axor-openrouter 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. axor_openrouter-0.2.0/.github/workflows/ci.yml +128 -0
  2. axor_openrouter-0.2.0/.gitignore +8 -0
  3. axor_openrouter-0.2.0/CHANGELOG.md +51 -0
  4. axor_openrouter-0.2.0/PKG-INFO +177 -0
  5. axor_openrouter-0.2.0/README.md +158 -0
  6. axor_openrouter-0.2.0/axor_openrouter/__init__.py +152 -0
  7. axor_openrouter-0.2.0/axor_openrouter/_version.py +1 -0
  8. axor_openrouter-0.2.0/axor_openrouter/bus.py +45 -0
  9. axor_openrouter-0.2.0/axor_openrouter/caching/__init__.py +5 -0
  10. axor_openrouter-0.2.0/axor_openrouter/caching/breakpoints.py +67 -0
  11. axor_openrouter-0.2.0/axor_openrouter/caching/response_cache.py +26 -0
  12. axor_openrouter-0.2.0/axor_openrouter/caching/ttl_chooser.py +57 -0
  13. axor_openrouter-0.2.0/axor_openrouter/cascade/__init__.py +4 -0
  14. axor_openrouter-0.2.0/axor_openrouter/cascade/config.py +110 -0
  15. axor_openrouter-0.2.0/axor_openrouter/cascade/tiers.py +113 -0
  16. axor_openrouter-0.2.0/axor_openrouter/cli_extensions.py +72 -0
  17. axor_openrouter-0.2.0/axor_openrouter/envelope_codec.py +162 -0
  18. axor_openrouter-0.2.0/axor_openrouter/executor.py +317 -0
  19. axor_openrouter-0.2.0/axor_openrouter/governance/__init__.py +5 -0
  20. axor_openrouter-0.2.0/axor_openrouter/governance/adaptive_router.py +37 -0
  21. axor_openrouter-0.2.0/axor_openrouter/governance/budget_subscriber.py +42 -0
  22. axor_openrouter-0.2.0/axor_openrouter/governance/cache_health.py +62 -0
  23. axor_openrouter-0.2.0/axor_openrouter/loaders.py +39 -0
  24. axor_openrouter-0.2.0/axor_openrouter/normalizer.py +71 -0
  25. axor_openrouter-0.2.0/axor_openrouter/presets.py +203 -0
  26. axor_openrouter-0.2.0/axor_openrouter/rates/__init__.py +4 -0
  27. axor_openrouter-0.2.0/axor_openrouter/rates/catalog.py +83 -0
  28. axor_openrouter-0.2.0/axor_openrouter/rates/refresher.py +31 -0
  29. axor_openrouter-0.2.0/axor_openrouter/routing/__init__.py +5 -0
  30. axor_openrouter-0.2.0/axor_openrouter/routing/byok.py +22 -0
  31. axor_openrouter-0.2.0/axor_openrouter/routing/fallbacks.py +60 -0
  32. axor_openrouter-0.2.0/axor_openrouter/routing/provider_prefs.py +72 -0
  33. axor_openrouter-0.2.0/axor_openrouter/security.py +103 -0
  34. axor_openrouter-0.2.0/axor_openrouter/tools.py +144 -0
  35. axor_openrouter-0.2.0/axor_openrouter/transport.py +392 -0
  36. axor_openrouter-0.2.0/axor_openrouter/usage_codec.py +81 -0
  37. axor_openrouter-0.2.0/pyproject.toml +35 -0
  38. axor_openrouter-0.2.0/tests/__init__.py +0 -0
  39. axor_openrouter-0.2.0/tests/conftest.py +138 -0
  40. axor_openrouter-0.2.0/tests/fixtures/openai_compat/deepseek_thinking_tool_call.json +21 -0
  41. axor_openrouter-0.2.0/tests/fixtures/openai_compat/function_call_finish.json +11 -0
  42. axor_openrouter-0.2.0/tests/fixtures/openai_compat/kimi_thinking_tool_call.json +18 -0
  43. axor_openrouter-0.2.0/tests/fixtures/openai_compat/mistral_model_length.json +10 -0
  44. axor_openrouter-0.2.0/tests/fixtures/openai_compat/no_index_fragments.json +12 -0
  45. axor_openrouter-0.2.0/tests/fixtures/openai_compat/ollama_stop_with_tool_calls.json +15 -0
  46. axor_openrouter-0.2.0/tests/fixtures/openai_compat/openai_parallel_index_only.json +20 -0
  47. axor_openrouter-0.2.0/tests/fixtures/openai_compat/openrouter_cache_usage.json +11 -0
  48. axor_openrouter-0.2.0/tests/fixtures/openai_compat/qwen_thinking_tool_call.json +18 -0
  49. axor_openrouter-0.2.0/tests/test_bus.py +57 -0
  50. axor_openrouter-0.2.0/tests/test_caching.py +149 -0
  51. axor_openrouter-0.2.0/tests/test_cascade.py +71 -0
  52. axor_openrouter-0.2.0/tests/test_envelope_codec.py +123 -0
  53. axor_openrouter-0.2.0/tests/test_executor.py +161 -0
  54. axor_openrouter-0.2.0/tests/test_governance.py +114 -0
  55. axor_openrouter-0.2.0/tests/test_loaders.py +61 -0
  56. axor_openrouter-0.2.0/tests/test_make_session.py +77 -0
  57. axor_openrouter-0.2.0/tests/test_openai_compat.py +498 -0
  58. axor_openrouter-0.2.0/tests/test_rates.py +96 -0
  59. axor_openrouter-0.2.0/tests/test_routing.py +82 -0
  60. axor_openrouter-0.2.0/tests/test_security.py +140 -0
  61. axor_openrouter-0.2.0/tests/test_streaming.py +89 -0
  62. axor_openrouter-0.2.0/tests/test_tools.py +32 -0
  63. axor_openrouter-0.2.0/tests/test_usage_codec.py +74 -0
@@ -0,0 +1,128 @@
1
+ name: CI/CD
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ tags: ["v*.*.*"]
7
+ pull_request:
8
+ branches: [main]
9
+ repository_dispatch:
10
+ types: [axor-core-published]
11
+
12
+ jobs:
13
+ test:
14
+ name: Test (Python ${{ matrix.python-version }})
15
+ runs-on: ubuntu-latest
16
+ strategy:
17
+ matrix:
18
+ python-version: ["3.11", "3.12"]
19
+
20
+ steps:
21
+ - uses: actions/checkout@v4
22
+
23
+ - name: Checkout axor-core
24
+ if: github.event_name != 'repository_dispatch'
25
+ uses: actions/checkout@v4
26
+ with:
27
+ repository: ${{ github.repository_owner }}/axor-core
28
+ path: axor-core
29
+
30
+ - name: Log trigger context
31
+ if: github.event_name == 'repository_dispatch'
32
+ run: |
33
+ echo "Triggered by axor-core ${{ github.event.client_payload.version }}"
34
+
35
+ - uses: actions/setup-python@v5
36
+ with:
37
+ python-version: ${{ matrix.python-version }}
38
+ cache: pip
39
+
40
+ - name: Install axor-core from source
41
+ if: github.event_name != 'repository_dispatch'
42
+ run: pip install -e axor-core/
43
+
44
+ - name: Install axor-core from PyPI (pinned to triggering version)
45
+ if: github.event_name == 'repository_dispatch'
46
+ run: |
47
+ VERSION="${{ github.event.client_payload.version }}"
48
+ pip install "axor-core==${VERSION#v}"
49
+
50
+ - name: Install
51
+ run: pip install -e ".[dev]"
52
+
53
+ - name: Static analysis — no governance logic in adapter
54
+ run: |
55
+ python - << 'EOF'
56
+ import re, os, sys
57
+ # An adapter wires axor-core's public GovernedSession; it must not import
58
+ # core's internal governance machinery. Match import lines only (anchored)
59
+ # so prose/docstrings mentioning these names don't false-positive.
60
+ gov = re.compile(r"\b(PolicySelector|CapabilityResolver|IntentLoop|GovernedNode)\b")
61
+ issues = []
62
+ for root, dirs, files in os.walk("axor_openrouter"):
63
+ dirs[:] = [d for d in dirs if not d.startswith("__")]
64
+ for f in files:
65
+ if not f.endswith(".py"):
66
+ continue
67
+ path = os.path.join(root, f)
68
+ for line in open(path).read().splitlines():
69
+ if re.match(r"\s*(from|import)\s", line) and gov.search(line):
70
+ issues.append(f"GOV_INTERNAL_IMPORT: {path}: {line.strip()[:70]}")
71
+ if issues:
72
+ print("\n".join(issues))
73
+ sys.exit(1)
74
+ print("✓ adapter architecture clean")
75
+ EOF
76
+
77
+ - name: Run tests
78
+ run: pytest tests/ -v --tb=short
79
+
80
+ publish:
81
+ name: Publish to PyPI
82
+ needs: test
83
+ runs-on: ubuntu-latest
84
+ if: startsWith(github.ref, 'refs/tags/v')
85
+ environment: pypi
86
+
87
+ permissions:
88
+ id-token: write
89
+
90
+ steps:
91
+ - uses: actions/checkout@v4
92
+
93
+ - uses: actions/setup-python@v5
94
+ with:
95
+ python-version: "3.12"
96
+
97
+ - name: Verify tag matches package version
98
+ run: |
99
+ python - << 'EOF'
100
+ import pathlib
101
+ import re
102
+ import sys
103
+ import tomllib
104
+
105
+ ref = "${{ github.ref_name }}"
106
+ m = re.fullmatch(r"v(\d+\.\d+\.\d+)", ref)
107
+ if not m:
108
+ print(f"Tag {ref!r} must match vX.Y.Z")
109
+ sys.exit(1)
110
+
111
+ tag_version = m.group(1)
112
+ data = tomllib.loads(pathlib.Path("pyproject.toml").read_text(encoding="utf-8"))
113
+ pkg_version = data["project"]["version"]
114
+
115
+ if tag_version != pkg_version:
116
+ print(f"Version mismatch: tag={tag_version}, pyproject={pkg_version}")
117
+ sys.exit(1)
118
+
119
+ print(f"Version check passed: {pkg_version}")
120
+ EOF
121
+
122
+ - name: Build
123
+ run: |
124
+ pip install hatchling build
125
+ python -m build
126
+
127
+ - name: Publish to PyPI
128
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ dist/
5
+ build/
6
+ .venv/
7
+ .env
8
+ *.toml.local
@@ -0,0 +1,51 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 — 2026-12-06
4
+
5
+ First PyPI release.
6
+
7
+ ### Added
8
+ - Generic OpenAI-compatible adapter: `OpenAICompatTransport` (configurable base
9
+ URL, auth header/scheme, extra headers; no auth header when the key is None),
10
+ `OpenAICompatExecutor`, `make_executor(provider, ...)`.
11
+ - Provider presets (`presets.PRESETS`): openrouter, deepseek, kimi, kimi-cn,
12
+ qwen-intl, qwen-cn, glm, minimax, mistral, xai, groq, together, fireworks,
13
+ ollama, vllm, lmstudio, custom. Each records the doc page its URL and quirks
14
+ were checked against.
15
+ - Vendor quirks: reasoning carried back on the tool-call assistant message
16
+ (DeepSeek, Kimi, Qwen, GLM, MiniMax); Qwen `enable_thinking` and GLM
17
+ `thinking.type`; MiniMax `reasoning_split` and `max_completion_tokens`; Kimi
18
+ without `temperature`; `parallel_tool_calls` sent where documented and `False`
19
+ enforced client-side; per-preset max output tokens.
20
+ - `OpenAICompatNormalizer`, an axor-core `ProviderNormalizer` for OpenAI tool calls.
21
+ - Recorded-fixture tests (`tests/fixtures/openai_compat/`, hand-written from
22
+ vendor docs).
23
+
24
+ ### Changed
25
+ - `OpenRouterTransport` and `OpenRouterExecutor` are now the OpenRouter preset
26
+ of the generic classes (same constructor arguments).
27
+ - Fail-closed streaming: unknown chunk shapes, unknown `finish_reason`, invalid
28
+ tool-call JSON, missing tool-call id/name, a non-JSON SSE line or a mid-stream
29
+ error now end the run with an `ERROR` event (previously: arguments became `{}`,
30
+ bad lines were skipped, unknown finishes counted as a stop).
31
+ - Tool-call fragments are matched by index, id, or (without either) the latest
32
+ call; `finish_reason` `function_call` and `stop` with tool calls run the tools.
33
+ - `STOP` usage is summed over every model call of the run (was: last call only)
34
+ and carries `finish_reason` (`stop` or `length`).
35
+ - Usage: `prompt_tokens_details.cached_tokens` / `cache_write_tokens` are read;
36
+ DeepSeek `prompt_cache_miss_tokens` count as uncached input (were booked as
37
+ cache writes).
38
+
39
+ ### Fixed
40
+ - `make_session` works with the current axor-core contracts: it builds a
41
+ `GovernedSession` with a `CapabilityExecutor` holding the caller's `handlers`
42
+ (it used to pass arguments `OpenRouterExecutor` does not take and an
43
+ `ExecutionEnvelope` with fields that do not exist, and failed with TypeError on
44
+ every call). `task`/`context_text`/`byok`/`enable_cache`/`response_cache`/
45
+ `policy` are gone: run with `await session.run(task)`; other keyword arguments
46
+ go to `GovernedSession`. `model=` pins one model; without it the depth cascade
47
+ picks.
48
+ - Depend on `axor-core>=0.8.0,<0.14` (was `<0.9`); the suite passes on every
49
+ axor-core minor from 0.8.0 to 0.13.1.
50
+ - Depend on `httpx[http2]`: the transport opens an HTTP/2 client and failed with
51
+ ImportError without `h2`.
@@ -0,0 +1,177 @@
1
+ Metadata-Version: 2.5
2
+ Name: axor-openrouter
3
+ Version: 0.2.0
4
+ Summary: OpenAI-compatible backend adapter for axor-core: OpenRouter, DeepSeek, Kimi, Qwen, GLM, MiniMax, Mistral, xAI, Groq, Together, Fireworks, Ollama, vLLM, LM Studio
5
+ License: MIT
6
+ Requires-Python: >=3.11
7
+ Requires-Dist: axor-core<0.14,>=0.8.0
8
+ Requires-Dist: httpx[http2]>=0.27
9
+ Requires-Dist: tomli>=2.0; python_version < '3.11'
10
+ Provides-Extra: dev
11
+ Requires-Dist: anyio[trio]; extra == 'dev'
12
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
13
+ Requires-Dist: pytest>=8; extra == 'dev'
14
+ Requires-Dist: respx>=0.21; extra == 'dev'
15
+ Provides-Extra: security
16
+ Requires-Dist: axor-probe; extra == 'security'
17
+ Requires-Dist: axor-sentinel; extra == 'security'
18
+ Description-Content-Type: text/markdown
19
+
20
+ # axor-openrouter
21
+
22
+ [![CI](https://github.com/Bucha11/axor-openrouter/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/Bucha11/axor-openrouter/actions/workflows/ci.yml)
23
+ [![PyPI](https://img.shields.io/pypi/v/axor-openrouter?cacheSeconds=300)](https://pypi.org/project/axor-openrouter/)
24
+ [![Python](https://img.shields.io/pypi/pyversions/axor-openrouter?cacheSeconds=300)](https://pypi.org/project/axor-openrouter/)
25
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
26
+
27
+ **OpenAI-compatible backend adapter for [axor-core](https://github.com/Bucha11/axor-core)** —
28
+ OpenRouter, DeepSeek, Kimi, Qwen, GLM, MiniMax, Mistral, xAI, Groq, Together,
29
+ Fireworks, Ollama, vLLM, LM Studio, or any custom OpenAI-compatible endpoint.
30
+
31
+ Runs the model as a governed agent under axor-core's governance
32
+ kernel — streaming tool use, cost/rate tracking, and a full audit trail — while
33
+ keeping all governance logic in the kernel, never in the adapter.
34
+
35
+ ---
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install axor-openrouter
41
+ ```
42
+
43
+ Requires an [OpenRouter API key](https://openrouter.ai/keys).
44
+
45
+ Optional behavioral-security observers (axor-probe / axor-sentinel):
46
+
47
+ ```bash
48
+ pip install "axor-openrouter[security]"
49
+ ```
50
+
51
+ ---
52
+
53
+ ## Quick start
54
+
55
+ ```python
56
+ import asyncio
57
+ from axor_openrouter import make_session
58
+
59
+ session = make_session(
60
+ api_key="sk-or-...",
61
+ handlers=[MyReadHandler()], # axor_core ToolHandlers the model may call
62
+ )
63
+
64
+ async def main():
65
+ result = await session.run("explain this code")
66
+ print(result.output)
67
+
68
+ asyncio.run(main())
69
+ ```
70
+
71
+ Enable the optional observers (requires the `[security]` extra):
72
+
73
+ ```python
74
+ session = make_session(
75
+ api_key="sk-or-...",
76
+ enable_sentinel=True, # cross-session reputation (axor-sentinel)
77
+ probe_pipeline=my_pipeline, # behavioral drift probes (axor-probe)
78
+ )
79
+ # drain probe-flagged sessions for the sentinel audit cycle:
80
+ sessions = session.axor_security.drain_sentinel()
81
+ ```
82
+
83
+ ---
84
+
85
+ ## Other providers
86
+
87
+ Every OpenAI-compatible chat-completions endpoint is a preset; OpenRouter is one
88
+ of them. Pick one with `make_executor` (an axor-core `Invokable`):
89
+
90
+ ```python
91
+ from axor_openrouter import make_executor
92
+
93
+ executor = make_executor("deepseek", api_key=KEY, model="deepseek-chat")
94
+ executor = make_executor("qwen-intl", api_key=KEY, model="qwen-plus", thinking=True)
95
+ executor = make_executor("ollama", model="qwen3-coder") # local, no key
96
+ executor = make_executor(
97
+ "custom",
98
+ base_url="https://llm.internal/v1", # "/chat/completions" is appended
99
+ api_key=KEY,
100
+ model="my-model",
101
+ extra_headers={"X-Team": "core"},
102
+ )
103
+ ```
104
+
105
+ `base_url` and `extra_headers` override the preset's for any provider (e.g. a
106
+ Model Studio workspace domain, a proxy). For a non-`Authorization` key header
107
+ build the transport yourself:
108
+ `OpenAICompatTransport(base_url, auth_header="api-key", auth_scheme="")`.
109
+
110
+ Executor options: `max_tokens`, `thinking` (Qwen `enable_thinking`, GLM
111
+ `thinking.type`; refused on presets without a documented switch),
112
+ `parallel_tool_calls` (sent where the vendor documents it, and `False` is
113
+ enforced client-side everywhere), `extra_body` (merged into every request),
114
+ `tier_mapper`, and for OpenRouter `provider_prefs`.
115
+
116
+ | id | Base URL | Verified | Quirks set by the preset |
117
+ |---|---|---|---|
118
+ | `openrouter` | `https://openrouter.ai/api/v1` | yes | `HTTP-Referer`/`X-Title` headers |
119
+ | `deepseek` | `https://api.deepseek.com` | yes | reasoning echoed back; max output 393216 |
120
+ | `kimi` / `kimi-cn` | `https://api.moonshot.ai/v1` / `https://api.moonshot.cn/v1` | yes | reasoning echoed back; no `temperature`; `max_tokens` 16000 by default |
121
+ | `qwen-intl` / `qwen-cn` | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1` / `https://dashscope.aliyuncs.com/compatible-mode/v1` | yes (legacy domains; workspace domains preferred, pass `base_url`) | reasoning echoed back; `enable_thinking` |
122
+ | `glm` | `https://api.z.ai/api/paas/v4` | yes | reasoning echoed back; `thinking.type` |
123
+ | `minimax` | `https://api.minimax.io/v1` | yes | `reasoning_split: true`; reasoning echoed back; `max_completion_tokens` |
124
+ | `mistral` | `https://api.mistral.ai/v1` | yes | `parallel_tool_calls` param; `model_length` finish |
125
+ | `xai` | `https://api.x.ai/v1` | yes | `parallel_tool_calls` param |
126
+ | `groq` | `https://api.groq.com/openai/v1` | yes | — |
127
+ | `together` | `https://api.together.ai/v1` | yes | — |
128
+ | `fireworks` | `https://api.fireworks.ai/inference/v1` | yes | — |
129
+ | `ollama` | `http://localhost:11434/v1` | yes | no key |
130
+ | `vllm` | `http://localhost:8000/v1` | yes | no key (unless `--api-key`) |
131
+ | `lmstudio` | `http://localhost:1234/v1` | URL yes, keyless assumed | no key |
132
+ | `custom` | your `base_url` | — | none |
133
+
134
+ "Verified" = checked against the vendor's own docs on 2026-12-06; each preset
135
+ records its source page (`PRESETS[id].source`). Model names are never part of
136
+ a preset.
137
+
138
+ ### Fail-closed normalisation
139
+
140
+ The stream is validated chunk by chunk (`StreamAccumulator`) and every tool call
141
+ again before it reaches the kernel (`OpenAICompatNormalizer`, axor-core's
142
+ `ProviderNormalizer`). Unknown shapes — legacy `delta.function_call`,
143
+ non-function tool types, non-string arguments, unknown `finish_reason`, a
144
+ non-JSON SSE line, a mid-stream `error` — raise `UnknownProviderFormatError`;
145
+ malformed calls (bad JSON arguments, missing id or name, tool calls cut off by
146
+ `length`, several calls with `parallel_tool_calls=False`) raise
147
+ `NormalizerError`. The executor turns either into one `ERROR` event and stops;
148
+ nothing is passed through.
149
+
150
+ Handled vendor differences: tool-call fragments with id/name only in the first
151
+ fragment, repeated in every fragment, or without `index`; `finish_reason`
152
+ `tool_calls`, `function_call`, or `stop` with tool calls (Ollama); usage from
153
+ `prompt_tokens_details.cached_tokens` (OpenAI/OpenRouter/Mistral),
154
+ `cache_write_tokens`, and DeepSeek `prompt_cache_hit_tokens` /
155
+ `prompt_cache_miss_tokens` (misses are uncached input, not cache writes);
156
+ usage is summed over all model calls of a run.
157
+
158
+ ---
159
+
160
+ ## What it does
161
+
162
+ `axor-openrouter` is a thin **adapter** (Layer 1–4 integration): it speaks the
163
+ OpenAI-compatible HTTP/streaming API and presents the model to axor-core as a governed
164
+ executor. It does **not** contain policy, capability, or intent logic — those
165
+ live in axor-core, and CI enforces this separation.
166
+
167
+ - streaming tool-use interception via axor-core's `ToolResultBus`
168
+ - provider presets for OpenAI-compatible vendors (`presets`)
169
+ - per-model cost rates fetched from OpenRouter (`rates/catalog`)
170
+ - model cascade / routing (`cascade`)
171
+ - optional `[security]` wiring of axor-probe and axor-sentinel observers
172
+
173
+ ---
174
+
175
+ ## License
176
+
177
+ MIT.
@@ -0,0 +1,158 @@
1
+ # axor-openrouter
2
+
3
+ [![CI](https://github.com/Bucha11/axor-openrouter/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/Bucha11/axor-openrouter/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/axor-openrouter?cacheSeconds=300)](https://pypi.org/project/axor-openrouter/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/axor-openrouter?cacheSeconds=300)](https://pypi.org/project/axor-openrouter/)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ **OpenAI-compatible backend adapter for [axor-core](https://github.com/Bucha11/axor-core)** —
9
+ OpenRouter, DeepSeek, Kimi, Qwen, GLM, MiniMax, Mistral, xAI, Groq, Together,
10
+ Fireworks, Ollama, vLLM, LM Studio, or any custom OpenAI-compatible endpoint.
11
+
12
+ Runs the model as a governed agent under axor-core's governance
13
+ kernel — streaming tool use, cost/rate tracking, and a full audit trail — while
14
+ keeping all governance logic in the kernel, never in the adapter.
15
+
16
+ ---
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ pip install axor-openrouter
22
+ ```
23
+
24
+ Requires an [OpenRouter API key](https://openrouter.ai/keys).
25
+
26
+ Optional behavioral-security observers (axor-probe / axor-sentinel):
27
+
28
+ ```bash
29
+ pip install "axor-openrouter[security]"
30
+ ```
31
+
32
+ ---
33
+
34
+ ## Quick start
35
+
36
+ ```python
37
+ import asyncio
38
+ from axor_openrouter import make_session
39
+
40
+ session = make_session(
41
+ api_key="sk-or-...",
42
+ handlers=[MyReadHandler()], # axor_core ToolHandlers the model may call
43
+ )
44
+
45
+ async def main():
46
+ result = await session.run("explain this code")
47
+ print(result.output)
48
+
49
+ asyncio.run(main())
50
+ ```
51
+
52
+ Enable the optional observers (requires the `[security]` extra):
53
+
54
+ ```python
55
+ session = make_session(
56
+ api_key="sk-or-...",
57
+ enable_sentinel=True, # cross-session reputation (axor-sentinel)
58
+ probe_pipeline=my_pipeline, # behavioral drift probes (axor-probe)
59
+ )
60
+ # drain probe-flagged sessions for the sentinel audit cycle:
61
+ sessions = session.axor_security.drain_sentinel()
62
+ ```
63
+
64
+ ---
65
+
66
+ ## Other providers
67
+
68
+ Every OpenAI-compatible chat-completions endpoint is a preset; OpenRouter is one
69
+ of them. Pick one with `make_executor` (an axor-core `Invokable`):
70
+
71
+ ```python
72
+ from axor_openrouter import make_executor
73
+
74
+ executor = make_executor("deepseek", api_key=KEY, model="deepseek-chat")
75
+ executor = make_executor("qwen-intl", api_key=KEY, model="qwen-plus", thinking=True)
76
+ executor = make_executor("ollama", model="qwen3-coder") # local, no key
77
+ executor = make_executor(
78
+ "custom",
79
+ base_url="https://llm.internal/v1", # "/chat/completions" is appended
80
+ api_key=KEY,
81
+ model="my-model",
82
+ extra_headers={"X-Team": "core"},
83
+ )
84
+ ```
85
+
86
+ `base_url` and `extra_headers` override the preset's for any provider (e.g. a
87
+ Model Studio workspace domain, a proxy). For a non-`Authorization` key header
88
+ build the transport yourself:
89
+ `OpenAICompatTransport(base_url, auth_header="api-key", auth_scheme="")`.
90
+
91
+ Executor options: `max_tokens`, `thinking` (Qwen `enable_thinking`, GLM
92
+ `thinking.type`; refused on presets without a documented switch),
93
+ `parallel_tool_calls` (sent where the vendor documents it, and `False` is
94
+ enforced client-side everywhere), `extra_body` (merged into every request),
95
+ `tier_mapper`, and for OpenRouter `provider_prefs`.
96
+
97
+ | id | Base URL | Verified | Quirks set by the preset |
98
+ |---|---|---|---|
99
+ | `openrouter` | `https://openrouter.ai/api/v1` | yes | `HTTP-Referer`/`X-Title` headers |
100
+ | `deepseek` | `https://api.deepseek.com` | yes | reasoning echoed back; max output 393216 |
101
+ | `kimi` / `kimi-cn` | `https://api.moonshot.ai/v1` / `https://api.moonshot.cn/v1` | yes | reasoning echoed back; no `temperature`; `max_tokens` 16000 by default |
102
+ | `qwen-intl` / `qwen-cn` | `https://dashscope-intl.aliyuncs.com/compatible-mode/v1` / `https://dashscope.aliyuncs.com/compatible-mode/v1` | yes (legacy domains; workspace domains preferred, pass `base_url`) | reasoning echoed back; `enable_thinking` |
103
+ | `glm` | `https://api.z.ai/api/paas/v4` | yes | reasoning echoed back; `thinking.type` |
104
+ | `minimax` | `https://api.minimax.io/v1` | yes | `reasoning_split: true`; reasoning echoed back; `max_completion_tokens` |
105
+ | `mistral` | `https://api.mistral.ai/v1` | yes | `parallel_tool_calls` param; `model_length` finish |
106
+ | `xai` | `https://api.x.ai/v1` | yes | `parallel_tool_calls` param |
107
+ | `groq` | `https://api.groq.com/openai/v1` | yes | — |
108
+ | `together` | `https://api.together.ai/v1` | yes | — |
109
+ | `fireworks` | `https://api.fireworks.ai/inference/v1` | yes | — |
110
+ | `ollama` | `http://localhost:11434/v1` | yes | no key |
111
+ | `vllm` | `http://localhost:8000/v1` | yes | no key (unless `--api-key`) |
112
+ | `lmstudio` | `http://localhost:1234/v1` | URL yes, keyless assumed | no key |
113
+ | `custom` | your `base_url` | — | none |
114
+
115
+ "Verified" = checked against the vendor's own docs on 2026-12-06; each preset
116
+ records its source page (`PRESETS[id].source`). Model names are never part of
117
+ a preset.
118
+
119
+ ### Fail-closed normalisation
120
+
121
+ The stream is validated chunk by chunk (`StreamAccumulator`) and every tool call
122
+ again before it reaches the kernel (`OpenAICompatNormalizer`, axor-core's
123
+ `ProviderNormalizer`). Unknown shapes — legacy `delta.function_call`,
124
+ non-function tool types, non-string arguments, unknown `finish_reason`, a
125
+ non-JSON SSE line, a mid-stream `error` — raise `UnknownProviderFormatError`;
126
+ malformed calls (bad JSON arguments, missing id or name, tool calls cut off by
127
+ `length`, several calls with `parallel_tool_calls=False`) raise
128
+ `NormalizerError`. The executor turns either into one `ERROR` event and stops;
129
+ nothing is passed through.
130
+
131
+ Handled vendor differences: tool-call fragments with id/name only in the first
132
+ fragment, repeated in every fragment, or without `index`; `finish_reason`
133
+ `tool_calls`, `function_call`, or `stop` with tool calls (Ollama); usage from
134
+ `prompt_tokens_details.cached_tokens` (OpenAI/OpenRouter/Mistral),
135
+ `cache_write_tokens`, and DeepSeek `prompt_cache_hit_tokens` /
136
+ `prompt_cache_miss_tokens` (misses are uncached input, not cache writes);
137
+ usage is summed over all model calls of a run.
138
+
139
+ ---
140
+
141
+ ## What it does
142
+
143
+ `axor-openrouter` is a thin **adapter** (Layer 1–4 integration): it speaks the
144
+ OpenAI-compatible HTTP/streaming API and presents the model to axor-core as a governed
145
+ executor. It does **not** contain policy, capability, or intent logic — those
146
+ live in axor-core, and CI enforces this separation.
147
+
148
+ - streaming tool-use interception via axor-core's `ToolResultBus`
149
+ - provider presets for OpenAI-compatible vendors (`presets`)
150
+ - per-model cost rates fetched from OpenRouter (`rates/catalog`)
151
+ - model cascade / routing (`cascade`)
152
+ - optional `[security]` wiring of axor-probe and axor-sentinel observers
153
+
154
+ ---
155
+
156
+ ## License
157
+
158
+ MIT.
@@ -0,0 +1,152 @@
1
+ """axor-openrouter: OpenAI-compatible backend adapter for axor-core.
2
+
3
+ OpenRouter is one preset; DeepSeek, Kimi, Qwen, GLM, MiniMax, Mistral, xAI,
4
+ Groq, Together, Fireworks, Ollama, vLLM, LM Studio and any custom
5
+ OpenAI-compatible endpoint are the others (see ``presets.PRESETS``).
6
+
7
+ Any provider
8
+ ------------
9
+ from axor_openrouter import make_executor
10
+
11
+ executor = make_executor("deepseek", api_key="...", model="deepseek-chat")
12
+ executor = make_executor("custom", base_url="https://llm.internal/v1", model="m")
13
+
14
+ OpenRouter session
15
+ ------------------
16
+ from axor_openrouter import make_session
17
+
18
+ session = make_session(
19
+ api_key="sk-or-...",
20
+ handlers=[MyReadHandler()], # axor_core ToolHandlers the model may call
21
+ )
22
+ result = await session.run("explain this code")
23
+
24
+ Without ``model`` the depth cascade picks the model (``tier_config`` or the
25
+ default tiers); with ``model`` every call uses it. Routing preferences:
26
+ ``sort``, ``max_prompt_price``, ``fallback``. Other keyword arguments go to
27
+ ``GovernedSession`` (``soft_token_limit``, ``mode``, ``memory_provider``, ...).
28
+ """
29
+ from __future__ import annotations
30
+
31
+ from typing import Any
32
+
33
+ from axor_core.capability.executor import CapabilityExecutor, ToolHandler
34
+ from axor_core.worker.session import GovernedSession
35
+
36
+ from .cascade.tiers import DEFAULT_TIERS, TierMapper, load_cascade_config_if_exists
37
+ from .executor import OpenAICompatExecutor, OpenRouterExecutor
38
+ from .normalizer import OpenAICompatNormalizer
39
+ from .presets import PRESETS, ProviderPreset, get_preset
40
+ from .routing.provider_prefs import ProviderPrefs
41
+ from .security import SecurityObservers, build_observers
42
+ from .transport import OpenAICompatTransport, OpenRouterTransport
43
+
44
+ __all__ = [
45
+ "PRESETS",
46
+ "OpenAICompatExecutor",
47
+ "OpenAICompatNormalizer",
48
+ "OpenAICompatTransport",
49
+ "OpenRouterExecutor",
50
+ "OpenRouterTransport",
51
+ "ProviderPreset",
52
+ "SecurityObservers",
53
+ "build_observers",
54
+ "get_preset",
55
+ "make_executor",
56
+ "make_session",
57
+ ]
58
+
59
+
60
+ def make_executor(
61
+ provider: str,
62
+ *,
63
+ model: str,
64
+ api_key: str | None = None,
65
+ base_url: str | None = None,
66
+ extra_headers: dict[str, str] | None = None,
67
+ timeout: float = 120.0,
68
+ **options: Any,
69
+ ) -> OpenAICompatExecutor:
70
+ """Build an executor for a preset (``"custom"`` needs ``base_url``).
71
+
72
+ ``base_url`` and ``extra_headers`` override/extend the preset's. Other
73
+ keyword arguments go to the executor: ``max_tokens``, ``thinking``,
74
+ ``parallel_tool_calls``, ``extra_body``, ``tier_mapper``, and for
75
+ OpenRouter ``provider_prefs``.
76
+ """
77
+ preset = get_preset(provider)
78
+ transport = OpenAICompatTransport.from_preset(
79
+ preset, base_url=base_url, extra_headers=extra_headers, timeout=timeout,
80
+ )
81
+ cls = OpenRouterExecutor if preset.id == "openrouter" else OpenAICompatExecutor
82
+ return cls(api_key, model, transport, preset=preset, **options)
83
+
84
+
85
+ def make_session(
86
+ *,
87
+ api_key: str,
88
+ model: str | None = None,
89
+ handlers: list[ToolHandler] | tuple[ToolHandler, ...] = (),
90
+ # Routing / cascade
91
+ tier_config: str | None = None,
92
+ sort: str = "quality",
93
+ max_prompt_price: float | None = None,
94
+ fallback: bool = True,
95
+ transport: OpenAICompatTransport | None = None,
96
+ # Optional security observers (P-34: behind the [security] extra)
97
+ probe_pipeline=None,
98
+ enable_sentinel: bool = False,
99
+ **session_kwargs: Any,
100
+ ) -> GovernedSession:
101
+ """Build a GovernedSession backed by OpenRouter.
102
+
103
+ ``handlers`` are the ``ToolHandler``s the model may call; the built-in
104
+ read/write/bash/search/glob names have OpenAI schemas here. Run it
105
+ with ``await session.run(task)``.
106
+
107
+ Optional security observers are wired here — the adapter is the composition
108
+ root. Passing ``probe_pipeline`` enables an axor-probe context tap; setting
109
+ ``enable_sentinel=True`` enables an axor-sentinel session sink. Both require
110
+ the ``[security]`` extra (``pip install axor-openrouter[security]``) and an
111
+ axor-core whose ``GovernedSession`` takes ``context_taps`` / ``session_sink``.
112
+ """
113
+ preset = PRESETS["openrouter"]
114
+ if model is None:
115
+ tiers = load_cascade_config_if_exists(tier_config) if tier_config else DEFAULT_TIERS
116
+ tier_mapper: TierMapper | None = TierMapper(tiers)
117
+ model = tiers[0].model
118
+ else:
119
+ tier_mapper = None
120
+
121
+ executor = OpenRouterExecutor(
122
+ api_key,
123
+ model,
124
+ transport or OpenAICompatTransport.from_preset(preset),
125
+ tier_mapper,
126
+ ProviderPrefs(sort=sort, max_prompt_price=max_prompt_price, allow_fallbacks=fallback),
127
+ )
128
+
129
+ capability_executor = CapabilityExecutor()
130
+ for handler in handlers:
131
+ capability_executor.register(handler)
132
+
133
+ observers = build_observers(
134
+ probe_pipeline=probe_pipeline,
135
+ enable_sentinel=enable_sentinel,
136
+ )
137
+ if observers.context_tap is not None:
138
+ session_kwargs["context_taps"] = [
139
+ *(session_kwargs.get("context_taps") or []), observers.context_tap,
140
+ ]
141
+ if observers.session_sink is not None:
142
+ if session_kwargs.get("session_sink") is not None:
143
+ raise ValueError("pass either session_sink or enable_sentinel, not both")
144
+ session_kwargs["session_sink"] = observers.session_sink
145
+
146
+ session = GovernedSession(
147
+ executor=executor,
148
+ capability_executor=capability_executor,
149
+ **session_kwargs,
150
+ )
151
+ session.axor_security = observers
152
+ return session
@@ -0,0 +1 @@
1
+ __version__ = "0.2.0"