Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(examples): run the OpenCode example on self-hosted SIE with an OpenRouter upstream (#735)

Krisztian Gajdar17605365a172
diff --git a/examples/README.md b/examples/README.md
index 67fc94264..f0d0c8c4d 100644
--- a/examples/README.md
+++ b/examples/README.md
@@ -20,7 +20,7 @@ to a separately maintained repository (clone and run there).
| [Extract custom entities from primary sources](./named-entity-extraction) | Changing zero-shot labels across financial, healthcare, rail-safety and legal text, with the two labels that came back empty left visible | `extract` | SIE endpoint with GLiNER multi v2.1; `fetch.py` pulls the recorded run, `score.py` reproduces the counts with no key | Runnable recorded example |
| [Extract the entity types you name, with no model to train](./custom-entity-types) | Asking for the 85 entity types of seven zero-shot NER sets and scoring exact spans against GPT-6 Luna, GPT-6 Sol, Claude Haiku 4.5, SIE Qwen3.8 27B, AWS Comprehend and spaCy, with a paired bootstrap and the price of each | `extract` | SIE server with GLiNER BioMed Large; `fetch.py` pulls the recorded run, `score.py` reproduces the figures with no key | Runnable recorded example |
| [Answer a question from a passage, and quote the sentence you used](./chat) | Checking a generated answer for its citation, its length and whether it declines a question the passage cannot answer | `chat/completions` | SIE Cloud with Qwen3.8 27B; `fetch.py` pulls the recorded run, `score.py` reproduces the numbers with no key | Runnable recorded example |
-| [Run a coding agent on SIE with OpenCode](./coding-agent-opencode) | Pointing OpenCode at a laptop server, one 80 GB GPU, a self-hosted cluster or SIE Cloud, and checking the agent loop the way OpenCode drives it: streaming tool-call deltas, parallel calls, tool-result round trips, a 64K-plus prompt, a 64 KiB tool call, finish reasons, usage and the reasoning field; `session_load.py` measures how many agent sessions one endpoint holds | `chat/completions` | An SIE Cloud endpoint that lists GLM-5.3-Flash via SIE Relay, or a local server; the laptop recipe was run on Apple Silicon with Qwen3.5-4B, the GPU and cluster recipes on one H100 with Qwen3.8-27B-FP8; `conformance.py` reports every case, `run_gate.sh` makes OpenCode fix a seeded failing test | Runnable check, laptop, one-GPU and SIE Cloud results recorded |
+| [Run a coding agent on SIE with OpenCode](./coding-agent-opencode) | Pointing OpenCode at a laptop server, one 80 GB GPU, a self-hosted server with an OpenRouter upstream, a self-hosted cluster or SIE Cloud, and checking the agent loop the way OpenCode drives it: streaming tool-call deltas, parallel calls, tool-result round trips, a 64K-plus prompt, a 64 KiB tool call, finish reasons, usage and the reasoning field; `session_load.py` measures how many agent sessions one endpoint holds | `chat/completions` | An SIE Cloud endpoint that lists GLM-5.3-Flash via SIE Relay, or a local server, alone or with an OpenRouter key for GLM-5.3-Flash; the laptop recipe was run on Apple Silicon with Qwen3.5-4B, the GPU and cluster recipes on one H100 with Qwen3.8-27B-FP8; `conformance.py` reports every case, `run_gate.sh` makes OpenCode fix a seeded failing test | Runnable check, laptop, one-GPU and SIE Cloud results recorded |
| [Try a local System One model](./systemone-local) | Running unchanged TypeSafe SDK code against SIE by changing its base URL, and checking every SDK call that reaches the server: each question type, state shape, `models.list()`, the async client and the error classes | `systemone` | A local `sie-server` with GLiNER2.5-Decide on CPU, or SIE Serverless; `conformance.py` reports every case | Runnable check |
| [Route requests while skipping most generation calls](./request-routing) | Assigning support, banking and assistant requests to routes with an embedding classifier and conditional generation | `encode`, `chat/completions` | SIE server with Qwen3 Embedding 4B and Qwen3.8 27B; recorded 3,000-case verification needs no API key | Runnable recorded example |
| [Send each request to a cheap or a strong LLM](./request-routing/cost) | Cutting LLM spend with a bge-m3 nearest-neighbour router that picks GPT-6 Luna or GPT-6.1 Sol per request: 38.6% less than always using GPT-6.1 Sol at 95.8% of its quality on 728 held-out requests of a pre-registered study | `encode` | SIE Serverless with bge-m3; `fetch.py` pulls the recorded study, `score.py` reproduces the held-out table with no key | Runnable recorded example |
diff --git a/examples/coding-agent-opencode/README.md b/examples/coding-agent-opencode/README.md
index c5d234cbe..1a1426c16 100644
--- a/examples/coding-agent-opencode/README.md
+++ b/examples/coding-agent-opencode/README.md
@@ -5,17 +5,20 @@
[OpenCode](https://opencode.ai) is an open-source coding agent. It talks to
any OpenAI-compatible chat endpoint through a custom provider built on
`@ai-sdk/openai-compatible`, which targets `/v1/chat/completions`. This
-example points it at SIE four ways and checks that the agent loop holds up:
+example points it at SIE five ways and checks that the agent loop holds up:
- a laptop running `sie-server` with a small tools-capable model,
- one 80 GB NVIDIA GPU running `sie-server` with Qwen3.8-27B-FP8,
+- a self-hosted `sie-server` that serves `zai-org/GLM-5.3-Flash` through an
+ [OpenRouter](https://openrouter.ai) upstream, with your OpenRouter key,
- a self-hosted SIE cluster, reached through its gateway with a key,
- SIE Cloud, where `zai-org/GLM-5.3-Flash:relay` is served through SIE Relay.
Four pieces are in this directory:
-1. `recipes/<laptop|gpu|cluster|cloud>/opencode.json`, one OpenCode config per
- setup.
+1. `recipes/<laptop|gpu|openrouter|cluster|cloud>/opencode.json`, one
+ OpenCode config per setup. The OpenRouter recipe also holds the server's
+ `upstreams.yaml` and its `models/` directory.
2. `conformance.py`, an agent-loop conformance check. It drives
`/v1/chat/completions` the way OpenCode does, streaming, with tools declared
on every turn and tool results sent back as `role: tool` messages, and
@@ -152,6 +155,121 @@ with the recipe's `:long-context`. Both pass there (see
[the recorded result](#laptop-apple-silicon-recorded)). It has not been run on
an NVIDIA machine.
+### Self-hosted SIE with an OpenRouter upstream
+
+This recipe runs the open-source `sie-server` on your machine and serves
+`zai-org/GLM-5.3-Flash` as a remote-backed model: the server holds no weights
+and sends each chat request on to OpenRouter's `z-ai/glm-5.3-flash`. OpenCode
+talks only to the local server, and only the server needs your OpenRouter key.
+
+From the root of a checkout of this repository:
+
+```sh
+export OPENROUTER_API_KEY=sk-or-...
+mise exec -- uv run --frozen --project . --package sie-server sie-server serve \
+ --models-dir examples/coding-agent-opencode/recipes/openrouter/models \
+ --upstreams-file examples/coding-agent-opencode/recipes/openrouter/upstreams.yaml \
+ --device cpu --host 127.0.0.1
+```
+
+Then, from this directory:
+
+```sh
+uv sync
+uv run python conformance.py --base-url http://localhost:8080/v1 --model zai-org/GLM-5.3-Flash
+./run_gate.sh openrouter
+```
+
+The server reads the key from its own environment each time it sends a
+request, so it starts without one. When `OPENROUTER_API_KEY` is unset, it logs
+a `WARNING` at startup, `requests to upstream 'openrouter' fail until its
+credential is usable: environment variable OPENROUTER_API_KEY is not set`.
+Export the key in the shell that starts the server. When OpenRouter answers
+`429` or a `5xx` other than `501` and `505`, or cannot be reached, the server
+answers `503` with `Retry-After`. When OpenRouter refuses the request with
+`400` or `422`, the server answers `400 invalid_request`, `the upstream
+refused the chat input`, and logs `upstream 'openrouter' refused a generation
+request: the upstream refused the input (400)`, or `(422)`. A missing key, any
+other refusal from OpenRouter and an answer the server does not accept answer
+`502 upstream_error` before output, with a message and a `reason` field that
+name the class of the failure. After output, the stream ends with an error
+event instead. A request the server refuses itself answers `400` before
+anything is sent. For a `502` or an error event, the server log names the
+cause on a `WARNING` line, `remote chat for zai-org/GLM-5.3-Flash failed:
+<cause>`, or `failed after output: <cause>`:
+
+| Log | Message to the caller | Cause |
+|---|---|---|
+| `the upstream credential is unavailable` | `the server has no usable credential for its upstream` | `OPENROUTER_API_KEY` is not set in the server's environment, so nothing was sent |
+| `upstream answered 401` | `the upstream rejected the server's credential` | OpenRouter refused the key |
+| `upstream answered 402` | `the upstream account cannot pay for the request` | the OpenRouter account has no credits; GLM-5.3-Flash is a paid model on OpenRouter |
+| `upstream answered 404` | `the upstream has no route for the configured model` | OpenRouter found no endpoint for the request, for example under the account's provider or data-policy settings |
+| `upstream answered` another `4xx` | `the upstream refused the request` | OpenRouter refused the request with that status |
+| `upstream sent an error instead of a chat answer` | `the upstream could not be reached, timed out or failed` | OpenRouter accepted the request, then sent an error, as it does when the provider it picked fails. An error whose `code` is an HTTP status is logged as `upstream sent error <status> instead of a chat answer` and gets that status's message |
+| anything else | `the upstream answered with something the server cannot accept` | OpenRouter's answer broke a rule the server holds every upstream to, for example a call to a function the request did not declare, or usage above the request's `max_tokens` |
+
+Pointed at OpenRouter directly, OpenCode would get the same model. Through SIE
+it uses one API and one model name, `zai-org/GLM-5.3-Flash`, which the cluster
+recipe uses too and SIE Cloud serves as its `:relay` profile, so the same
+`conformance.py` and `run_gate.sh` check every setup, and the server adds the
+upstream's rate cap and circuit breaker and its checks of tool calls and usage.
+
+The two server files:
+
+- `upstreams.yaml` defines the `openrouter` upstream at
+ `https://openrouter.ai/api/v1`, offering `chat`. `api_key_secret` names the
+ environment variable the server reads the key from when it sends a request.
+ The key is in no file, and the recipe's `opencode.json` carries only a
+ placeholder `apiKey` for the local server. The server listens on `127.0.0.1`
+ because every request it serves spends that key.
+- `rate_cap` allows 60 requests a minute and 4 at a time. `breaker` stops
+ calls for 60 s after 5 calls in a row, within 30 s, found OpenRouter
+ unavailable. A request either one refuses gets `503` with `Retry-After`. Both
+ limits apply per server process.
+- `strip_params` removes `chat_template_kwargs`, which the server adds from
+ the model file and which only a local chat template reads.
+- The upstream sets no OpenRouter provider preference. On 2026-10-14 all 33
+ OpenRouter endpoints of `z-ai/glm-5.3-flash` listed every parameter the
+ server forwards for OpenCode and `conformance.py` (`max_tokens`,
+ `temperature`, `tools` and `tool_choice`), and OpenRouter sends a request
+ with tools only to providers that support tools, so `require_parameters`
+ would exclude no endpoint for them. An endpoint ignores a parameter it does
+ not list, such as `parallel_tool_calls` (listed by 1 of the 33), `logprobs`
+ (17) or `seed` (22); with `require_parameters` the request would go only to
+ endpoints that list it. Of the 33, 11 report no support for `tool_choice:
+ "required"`, and OpenRouter does not document whether it routes by that
+ value.
+- `models/zai-org__GLM-5.3-Flash.yaml` declares a remote-backed model
+ (`remote_backed: true`, `routing: {policy: remote_only}`) with one profile on
+ the `openrouter` upstream. It declares a 131,072-token window with up to
+ 32,768 tokens out, tool calling and text input. OpenRouter serves a larger
+ window; the declared one is what `/v1/models` reports and what the server
+ holds each answer's usage to. `chat_template_kwargs.enable_thinking: true`
+ declares the model as one that reasons, which is what lets
+ `include_reasoning` return its reasoning.
+
+On this path OpenRouter parses the model's tool calls and reasoning. The server
+checks that each streamed tool call arrives with an id, a function name and
+arguments, that the calls keep to the request's `tools`, `tool_choice` and
+`parallel_tool_calls`, that every answer finishes with exact usage inside the
+declared window and the request's output cap, and reports that usage. OpenRouter
+returns reasoning in a `reasoning` field; the server passes it on as
+`reasoning_content` when the request sets `include_reasoning`, as the recipe's
+`options` do, and drops it otherwise. OpenCode sends each earlier turn's
+reasoning back as `reasoning_content`, which the server forwards and OpenRouter
+accepts as an alias of `reasoning`. The server skips the SSE comment lines
+OpenRouter sends while a request waits (`: OPENROUTER PROCESSING`), and turns
+its closing usage event, which repeats the finished choice, into an OpenAI-form
+usage chunk.
+
+This recipe has been checked against a scripted stand-in for OpenRouter (see
+[Checked without a GPU](#checked-without-a-gpu)). A successful run with a real
+key is still [pending](#self-hosted-sie-with-an-openrouter-upstream-pending). To serve the
+model from a cluster instead, define the upstream for the chart's remote worker
+pool as
+[Serving a model through a remote backend](../../packages/sie_server/REMOTE_BACKENDS.md#cluster-deployment)
+describes.
+
### Against your cluster
`recipes/cluster/opencode.json` names `Qwen/Qwen3.8-27B-FP8:h100-256k-batch`,
@@ -742,6 +860,29 @@ with an output cap of 8,192 tokens and `tool_choice: "auto"`.
OpenAI-style function calling.
- One of the 600 requests failed with a `502` and is scored as a miss.
+### Self-hosted SIE with an OpenRouter upstream, pending
+
+`zai-org/GLM-5.3-Flash` through OpenRouter's `z-ai/glm-5.3-flash`, with the
+recipe's server files and a real OpenRouter key. `sie-server` from this
+repository at commit pending, OpenCode version pending, recorded on date
+pending.
+
+| Check | Result |
+|---|---|
+| `tool_choice_auto` | pending |
+| `streaming_tool_call_deltas` | pending |
+| `parallel_tool_calls` | pending |
+| `tool_result_round_trip` | pending |
+| `prompt_above_64k_tokens` | pending |
+| `finish_reason_stop` | pending |
+| `finish_reason_tool_calls` | pending |
+| `finish_reason_length` | pending |
+| `usage_on_final_chunk` | pending |
+| `include_reasoning` | pending |
+| `tool_choice_required` | pending |
+| `long_tool_call` | pending |
+| `./run_gate.sh openrouter` | pending |
+
## Checked without a GPU
`sie-server` ships a weightless `sie-fake` model for CI. Its
@@ -835,6 +976,29 @@ What runs anywhere, and in this repository's CI, is the test suite:
without a child that ignores TERM, two runs started in the same second, and
the key check, which applies only to a recipe that reads `SIE_BASE_URL` and
`SIE_API_KEY`.
+- `tests/test_openrouter_recipe.py` starts this repository's `sie-server`
+ with the OpenRouter recipe's `models/` directory and a copy of its
+ `upstreams.yaml` pointed at a scripted stand-in for OpenRouter on
+ `127.0.0.1`. The stand-in streams the way OpenRouter documents: SSE comment
+ lines, reasoning in a `reasoning` field, tool-call deltas and a closing usage
+ event that repeats the finished choice. `conformance.py` against the server
+ gives 11 pass, 0 fail and 1 recorded (`tool_choice_required`, supported).
+ The test pins each request the stand-in received, case by case: the model
+ `z-ai/glm-5.3-flash`, the key from `OPENROUTER_API_KEY` as a bearer token,
+ and exactly `messages`, `stream`, `max_tokens` and `temperature`, plus
+ `stream_options` when streamed and `tools` and `tool_choice` on a tools
+ turn. Asked for `require_parameters`, the stand-in answers `404` when no
+ endpoint of the model lists every request field that is one of the
+ parameter names in OpenRouter's public model list. That list does not hold
+ `stream` or `stream_options`; OpenRouter documents the preference in terms of
+ its parameters and does not say how it treats other fields.
+ `tests/openrouter_endpoints.json` holds the endpoints' lists and those names
+ as OpenRouter published them. The stand-in also answers `401`, `402`, `404`
+ and a stream whose only event is an error, and the test checks that each
+ comes back as a `502` with its class's message, and that the server log
+ names the cause and nothing the stand-in sent. It needs the
+ repository's environment, from `mise run sync` at the root, and is skipped
+ without it outside CI.
```sh
uv run pytest
@@ -842,8 +1006,9 @@ uv run pytest
`tests/test_conformance.py`, `tests/test_session_load.py` and
`tests/test_run_gate.py` check the checkers,
-and `tests/test_fake_engine.py` checks SIE's chat and Messages routes with a
-scripted model.
+`tests/test_fake_engine.py` checks SIE's chat and Messages routes with a
+scripted model, and `tests/test_openrouter_recipe.py` checks the OpenRouter
+recipe against a scripted stand-in for OpenRouter.
A model's endpoint is only checked by running `conformance.py` against it.
## What this does NOT establish
@@ -872,5 +1037,12 @@ A model's endpoint is only checked by running `conformance.py` against it.
- **Not a measure of how well Qwen3.8-27B codes.** BFCL scores single calls,
the seeded gate is a twenty-line fix, and the one real issue was not fixed
in either run.
+- **Not yet a run against OpenRouter.** Until the result above is recorded,
+ the OpenRouter recipe has been checked against a scripted stand-in only.
+ Which provider OpenRouter routes a request to, and how that provider streams
+ tool calls and reasoning, shows only in a real run. A provider without
+ `tool_choice: "required"` support can answer the `tool_choice_required` case
+ with text, which fails it, and a provider that reports more completion
+ tokens than `max_tokens` allows fails `finish_reason_length`.
- **One endpoint, one day.** The Cloud results were recorded once, on
2026-10-14.
diff --git a/examples/coding-agent-opencode/recipes/openrouter/models/zai-org__GLM-5.3-Flash.yaml b/examples/coding-agent-opencode/recipes/openrouter/models/zai-org__GLM-5.3-Flash.yaml
new file mode 100644
index 000000000..040268616
--- /dev/null
+++ b/examples/coding-agent-opencode/recipes/openrouter/models/zai-org__GLM-5.3-Flash.yaml
@@ -0,0 +1,31 @@
+sie_id: zai-org/GLM-5.3-Flash
+remote_backed: true
+routing:
+ policy: remote_only
+inputs:
+ text: true
+ image: false
+ audio: false
+ video: false
+tasks:
+ encode: null
+ score: null
+ extract: null
+ generate:
+ context_length: 131072
+ max_output_tokens: 32768
+ chat_template_kwargs:
+ enable_thinking: true
+ capabilities:
+ grammar: []
+ streaming: true
+ tools: true
+max_sequence_length: 131072
+profiles:
+ default:
+ adapter_path: sie_server.adapters.remote.openai:OpenAIUpstreamAdapter
+ max_batch_tokens: 131072
+ adapter_options:
+ loadtime:
+ upstream: openrouter
+ upstream_model: z-ai/glm-5.3-flash
diff --git a/examples/coding-agent-opencode/recipes/openrouter/opencode.json b/examples/coding-agent-opencode/recipes/openrouter/opencode.json
new file mode 100644
index 000000000..b82a00aaf
--- /dev/null
+++ b/examples/coding-agent-opencode/recipes/openrouter/opencode.json
@@ -0,0 +1,34 @@
+{
+ "$schema": "https://opencode.ai/config.json",
+ "model": "sie-local/zai-org/GLM-5.3-Flash",
+ "provider": {
+ "sie-local": {
+ "npm": "@ai-sdk/openai-compatible",
+ "name": "SIE on this machine",
+ "options": {
+ "baseURL": "http://localhost:8080/v1",
+ "apiKey": "local",
+ "timeout": 1800000,
+ "headerTimeout": 600000,
+ "chunkTimeout": 600000
+ },
+ "models": {
+ "zai-org/GLM-5.3-Flash": {
+ "name": "GLM-5.3-Flash via OpenRouter",
+ "limit": {
+ "context": 131072,
+ "output": 32768
+ },
+ "tool_call": true,
+ "reasoning": true,
+ "interleaved": {
+ "field": "reasoning_content"
+ },
+ "options": {
+ "include_reasoning": true
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/examples/coding-agent-opencode/recipes/openrouter/upstreams.yaml b/examples/coding-agent-opencode/recipes/openrouter/upstreams.yaml
new file mode 100644
index 000000000..4b028bf2e
--- /dev/null
+++ b/examples/coding-agent-opencode/recipes/openrouter/upstreams.yaml
@@ -0,0 +1,14 @@
+upstreams:
+ openrouter:
+ kind: openai
+ base_url: https://openrouter.ai/api/v1
+ api_key_secret: OPENROUTER_API_KEY
+ endpoints: [chat]
+ rate_cap:
+ requests_per_minute: 60
+ max_concurrency: 4
+ breaker:
+ failures: 5
+ window_s: 30
+ cooldown_s: 60
+ strip_params: [chat_template_kwargs]
diff --git a/examples/coding-agent-opencode/run_gate.sh b/examples/coding-agent-opencode/run_gate.sh
index 17957e3e1..411c2f19e 100755
--- a/examples/coding-agent-opencode/run_gate.sh
+++ b/examples/coding-agent-opencode/run_gate.sh
@@ -17,7 +17,7 @@ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RECIPE="${1:-cloud}"
CONFIG="$HERE/recipes/$RECIPE/opencode.json"
if [[ ! -f "$CONFIG" ]]; then
- echo "unknown recipe '$RECIPE'; pick laptop, gpu, cluster or cloud" >&2
+ echo "unknown recipe '$RECIPE'; pick laptop, gpu, openrouter, cluster or cloud" >&2
exit 2
fi
for tool in opencode uv; do
diff --git a/examples/coding-agent-opencode/tests/openrouter_endpoints.json b/examples/coding-agent-opencode/tests/openrouter_endpoints.json
new file mode 100644
index 000000000..e89bcfde4
--- /dev/null
+++ b/examples/coding-agent-opencode/tests/openrouter_endpoints.json
@@ -0,0 +1,42 @@
+{
+ "model": "z-ai/glm-5.3-flash",
+ "source": "https://openrouter.ai/api/v1/models/z-ai/glm-5.3-flash/endpoints",
+ "fetched": "2026-10-14",
+ "supported_parameters": [
+ ["frequency_penalty", "include_reasoning", "logit_bias", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "seed", "stop", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["include_reasoning", "logprobs", "max_tokens", "reasoning", "reasoning_effort", "response_format", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logprobs", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logprobs", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logprobs", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["include_reasoning", "max_tokens", "reasoning", "reasoning_effort", "response_format", "seed", "temperature", "tool_choice", "tools", "top_p"],
+ ["frequency_penalty", "include_reasoning", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "parallel_tool_calls", "presence_penalty", "reasoning", "reasoning_effort", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["include_reasoning", "logprobs", "max_tokens", "reasoning", "reasoning_effort", "response_format", "structured_outputs", "temperature", "tool_choice", "tools", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["include_reasoning", "logprobs", "max_tokens", "reasoning", "reasoning_effort", "response_format", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "response_format", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logprobs", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "seed", "stop", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "max_tokens", "reasoning", "reasoning_effort", "response_format", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "min_p", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "response_format", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_p"],
+ ["frequency_penalty", "include_reasoning", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "response_format", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["include_reasoning", "max_tokens", "reasoning", "reasoning_effort", "response_format", "temperature", "tool_choice", "tools", "top_k", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"],
+ ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_tokens", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_k", "top_logprobs", "top_p"]
+ ],
+ "catalog_source": "https://openrouter.ai/api/v1/models",
+ "catalog_parameters": ["frequency_penalty", "include_reasoning", "logit_bias", "logprobs", "max_completion_tokens", "max_tokens", "min_p", "parallel_tool_calls", "prediction", "presence_penalty", "reasoning", "reasoning_effort", "repetition_penalty", "response_format", "seed", "stop", "structured_outputs", "temperature", "tool_choice", "tools", "top_a", "top_k", "top_logprobs", "top_p", "verbosity", "web_search_options"]
+}
diff --git a/examples/coding-agent-opencode/tests/test_openrouter_recipe.py b/examples/coding-agent-opencode/tests/test_openrouter_recipe.py
new file mode 100644
index 000000000..e74189ff0
--- /dev/null
+++ b/examples/coding-agent-opencode/tests/test_openrouter_recipe.py
@@ -0,0 +1,402 @@
+"""The OpenRouter recipe end to end, with a scripted upstream standing in for OpenRouter.
+
+The repository's ``sie-server`` serves the recipe's models directory, with a
+copy of the recipe's upstreams file pointed at a loopback stub. The stub
+streams the way OpenRouter documents: SSE comment lines while it works,
+reasoning in a ``reasoning`` field, tool-call deltas, and a usage event that
+restates the finished choice. ``conformance.py`` then runs against the server,
+as the README tells a reader to, and the stub records what the server sent.
+
+OpenRouter documents ``require_parameters`` as routing only to providers that
+support every LLM parameter in the request, and names those parameters on its
+parameters page. The stub applies that rule to the parameter names OpenRouter's
+public model list uses, and answers 404 when no endpoint of the model lists
+every such name in the request. Other fields, such as ``stream_options``, do not
+count. ``openrouter_endpoints.json`` holds each endpoint's
+``supported_parameters`` from OpenRouter's public endpoints list, and the
+parameter names from its public model list.
+
+A request whose only user message is one of ``REFUSALS`` or ``ERROR_EVENT``
+gets that failure instead of an answer, the way OpenRouter sends it.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import socket
+import subprocess
+import threading
+import time
+from collections.abc import Iterator
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+import httpx
+import openai
+import pytest
+
+import conformance
+
+EXAMPLE = Path(__file__).resolve().parents[1]
+RECIPE = EXAMPLE / "recipes" / "openrouter"
+REPOSITORY = EXAMPLE.parents[1]
+SERVER = REPOSITORY / ".venv" / "bin" / "sie-server"
+MODEL = "zai-org/GLM-5.3-Flash"
+UPSTREAM_MODEL = "z-ai/glm-5.3-flash"
+OPENROUTER_URL = "https://openrouter.ai/api/v1"
+TEST_KEY = "sk-or-test-key"
+SERVER_START_TIMEOUT_S = 300.0
+REASONING = "Compare the tenths first: 9.9 has nine tenths and 9.11 has one tenth, so 9.9 is larger."
+COMMENT = b": OPENROUTER PROCESSING\n\n"
+PUBLISHED = json.loads(Path(__file__).with_name("openrouter_endpoints.json").read_text())
+ENDPOINTS = [frozenset(parameters) for parameters in PUBLISHED["supported_parameters"]]
+PARAMETERS = frozenset(PUBLISHED["catalog_parameters"])
+NO_ENDPOINTS = "No endpoints found that can handle the requested parameters."
+UPSTREAM_DETAIL = "stand-in upstream detail"
+REFUSALS = {"answer 401": 401, "answer 402": 402, "answer 404": 404}
+ERROR_EVENT = "answer with an error event"
+
+SEEN: list[dict[str, Any]] = []
+
+
+def _unroutable(body: dict[str, Any]) -> bool:
+ if not (body.get("provider") or {}).get("require_parameters"):
+ return False
+ parameters = set(body) & PARAMETERS
+ return not any(parameters <= supported for supported in ENDPOINTS)
+
+
+def _words(text: str) -> int:
+ return len(text.split())
+
+
+def _text(messages: list[dict[str, Any]], role: str) -> str:
+ return " ".join(m["content"] for m in messages if m["role"] == role and isinstance(m.get("content"), str))
+
+
+def _reply(body: dict[str, Any]) -> dict[str, Any]:
+ messages = body["messages"]
+ question = _text(messages, "user")
+ tools = body.get("tools")
+ paris = ("call_paris", "get_weather", {"city": "Paris"})
+ if tools and tools[0]["function"]["name"] == "write_file":
+ lines = range(1, conformance.LONG_CALL_LINES + 1)
+ content = "\n".join(conformance.long_call_line(number) for number in lines)
+ return {
+ "calls": [("call_file", "write_file", {"path": conformance.LONG_CALL_PATH, "content": content})],
+ "finish": "tool_calls",
+ }
+ if body.get("tool_choice") == "required":
+ return {"calls": [paris], "finish": "tool_calls"}
+ if tools and messages[-1]["role"] == "tool":
+ return {"content": "It is 18 degrees and overcast in Paris.", "finish": "stop"}
+ if tools and "Tokyo" in question:
+ tokyo = ("call_tokyo", "get_weather", {"city": "Tokyo"})
+ return {"calls": [paris, tokyo], "finish": "tool_calls", "reasoning": "Two cities, so two calls."}
+ if tools:
+ return {"calls": [paris], "finish": "tool_calls", "reasoning": "One call for Paris."}
+ if body.get("max_tokens") == 8:
+ return {"content": "The sea is", "finish": "length"}
+ if _words(question) > 10_000:
+ return {"content": "7741-ZEBRA", "finish": "stop"}
+ if "9.11" in question:
+ return {"content": "9.9", "finish": "stop", "reasoning": REASONING}
+ return {"content": "ready", "finish": "stop"}
+
+
+def _usage(body: dict[str, Any], reply: dict[str, Any]) -> dict[str, Any]:
+ prompt = sum(_words(m["content"]) for m in body["messages"] if isinstance(m.get("content"), str))
+ reasoning = _words(reply.get("reasoning") or "")
+ arguments = " ".join(json.dumps(args) for _, _, args in reply.get("calls") or [])
+ completion = max(1, _words(reply.get("content") or "") + reasoning + _words(arguments))
+ return {
+ "prompt_tokens": prompt,
+ "completion_tokens": completion,
+ "total_tokens": prompt + completion,
+ "cost": 0.0001,
+ "is_byok": False,
+ "prompt_tokens_details": {"cached_tokens": 0},
+ "completion_tokens_details": {"reasoning_tokens": reasoning},
+ }
+
+
+def _calls(reply: dict[str, Any]) -> list[dict[str, Any]]:
+ return [
+ {"index": index, "id": call_id, "type": "function", "function": {"name": name, "arguments": json.dumps(args)}}
+ for index, (call_id, name, args) in enumerate(reply.get("calls") or [])
+ ]
+
+
+class OpenRouterStub(BaseHTTPRequestHandler):
+ def log_message(self, *args: Any) -> None:
+ pass
+
+ def _event(self, choices: list[dict[str, Any]], **extra: Any) -> None:
+ payload = {
+ "id": "gen-stub",
+ "provider": "Stub",
+ "model": UPSTREAM_MODEL,
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "choices": choices,
+ **extra,
+ }
+ self.wfile.write(f"data: {json.dumps(payload)}\n\n".encode() + COMMENT)
+
+ def _delta(self, delta: dict[str, Any], finish: str | None = None) -> dict[str, Any]:
+ return {"index": 0, "delta": {"role": "assistant", "content": "", **delta}, "finish_reason": finish}
+
+ def _json(self, status: int, payload: dict[str, Any]) -> None:
+ raw = json.dumps(payload).encode()
+ self.send_response(status)
+ self.send_header("content-type", "application/json")
+ self.send_header("content-length", str(len(raw)))
+ self.end_headers()
+ self.wfile.write(raw)
+
+ def do_POST(self) -> None:
+ body = json.loads(self.rfile.read(int(self.headers["content-length"])))
+ SEEN.append({"path": self.path, "authorization": self.headers.get("authorization"), "body": body})
+ if _unroutable(body):
+ self._json(404, {"error": {"message": NO_ENDPOINTS, "code": 404}})
+ return
+ question = _text(body["messages"], "user")
+ if question in REFUSALS:
+ self._json(REFUSALS[question], {"error": {"message": UPSTREAM_DETAIL, "code": REFUSALS[question]}})
+ return
+ if question == ERROR_EVENT:
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.end_headers()
+ self.wfile.write(COMMENT)
+ error = {"code": "server_error", "message": UPSTREAM_DETAIL}
+ self._event([{"index": 0, "delta": {"content": ""}, "finish_reason": "error"}], error=error)
+ return
+ reply = _reply(body)
+ usage = _usage(body, reply)
+ if not body.get("stream"):
+ message: dict[str, Any] = {"role": "assistant", "content": reply.get("content") or "", "refusal": None}
+ if reply.get("reasoning"):
+ message["reasoning"] = reply["reasoning"]
+ message["reasoning_details"] = [{"type": "reasoning.text", "text": reply["reasoning"]}]
+ if reply.get("calls"):
+ message["tool_calls"] = _calls(reply)
+ choice = {"index": 0, "message": message, "finish_reason": reply["finish"]}
+ self._json(200, {"id": "gen-stub", "model": UPSTREAM_MODEL, "choices": [choice], "usage": usage})
+ return
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.end_headers()
+ self.wfile.write(COMMENT + COMMENT)
+ self._event([self._delta({})])
+ for piece in (reply.get("reasoning") or "").split(" "):
+ if piece:
+ details = [{"type": "reasoning.text", "text": piece + " "}]
+ self._event([self._delta({"reasoning": piece + " ", "reasoning_details": details})])
+ for call in _calls(reply):
+ head = {**call, "function": {"name": call["function"]["name"], "arguments": ""}}
+ self._event([self._delta({"tool_calls": [head]})])
+ arguments = call["function"]["arguments"]
+ for start in range(0, len(arguments), 4096):
+ tail = {"index": call["index"], "function": {"arguments": arguments[start : start + 4096]}}
+ self._event([self._delta({"tool_calls": [tail]})])
+ for word in (reply.get("content") or "").split(" "):
+ if word:
+ self._event([self._delta({"content": word + " "})])
+ finished = {**self._delta({}, reply["finish"]), "native_finish_reason": reply["finish"]}
+ self._event([finished])
+ self._event([finished], usage=usage)
+ self.wfile.write(b"data: [DONE]\n\n")
+
+
+def _free_port() -> int:
+ with socket.socket() as probe:
+ probe.bind(("127.0.0.1", 0))
+ return probe.getsockname()[1]
+
+
+def _wait_for_health(base: str, server: subprocess.Popen[bytes], log: Path) -> None:
+ deadline = time.monotonic() + SERVER_START_TIMEOUT_S
+ while time.monotonic() < deadline:
+ if server.poll() is not None:
+ pytest.fail(f"sie-server exited {server.returncode}:\n{log.read_text()[-4000:]}")
+ try:
+ if httpx.get(f"{base}/healthz", timeout=2.0).status_code == 200:
+ return
+ except httpx.HTTPError:
+ pass
+ time.sleep(0.5)
+ pytest.fail(f"sie-server did not answer /healthz within {SERVER_START_TIMEOUT_S}s:\n{log.read_text()[-4000:]}")
+
+
[email protected](scope="module")
+def server(tmp_path_factory: pytest.TempPathFactory) -> Iterator[SimpleNamespace]:
+ if not SERVER.exists():
+ message = f"{SERVER} is missing; run `mise run sync` at the repository root"
+ if os.environ.get("CI"):
+ pytest.fail(message)
+ pytest.skip(message)
+ stub = ThreadingHTTPServer(("127.0.0.1", 0), OpenRouterStub)
+ threading.Thread(target=stub.serve_forever, daemon=True).start()
+ work = tmp_path_factory.mktemp("openrouter")
+ recipe = (RECIPE / "upstreams.yaml").read_text()
+ assert recipe.count(OPENROUTER_URL) == 1
+ upstreams = work / "upstreams.yaml"
+ upstreams.write_text(recipe.replace(OPENROUTER_URL, f"http://127.0.0.1:{stub.server_address[1]}/api/v1"))
+ port = _free_port()
+ env = {key: value for key, value in os.environ.items() if key not in ("VIRTUAL_ENV", "SIE_REMOTE_SERVING")}
+ env["OPENROUTER_API_KEY"] = TEST_KEY
+ log = work / "sie-server.log"
+ command = [
+ str(SERVER),
+ "serve",
+ "--host",
+ "127.0.0.1",
+ "--port",
+ str(port),
+ "--device",
+ "cpu",
+ "--models-dir",
+ str(RECIPE / "models"),
+ "--upstreams-file",
+ str(upstreams),
+ ]
+ SEEN.clear()
+ with log.open("wb") as output:
+ server = subprocess.Popen(command, env=env, stdout=output, stderr=subprocess.STDOUT)
+ try:
+ base = f"http://127.0.0.1:{port}"
+ _wait_for_health(base, server, log)
+ yield SimpleNamespace(base=base, log=log)
+ finally:
+ server.terminate()
+ try:
+ server.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ server.kill()
+ server.wait()
+ stub.shutdown()
+
+
[email protected](scope="module")
+def report(server: SimpleNamespace) -> dict[str, Any]:
+ return conformance.run(f"{server.base}/v1", "", MODEL)
+
+
+def _cases(report: dict[str, Any]) -> dict[str, dict[str, Any]]:
+ return {case["name"]: case for case in report["cases"]}
+
+
+def test_every_case_passes_through_sie(report: dict[str, Any]) -> None:
+ cases = _cases(report)
+ assert {name for name, case in cases.items() if case["status"] != "pass"} == {"tool_choice_required"}, cases
+ assert cases["tool_choice_required"]["status"] == "recorded"
+ assert cases["tool_choice_required"]["observed"]["support"] == "supported"
+ assert report["served_by"] == "remote"
+ assert report["model_entry"]["max_sequence_length"] == 131072
+
+
+def test_reasoning_reaches_the_client_only_when_asked(report: dict[str, Any]) -> None:
+ observed = _cases(report)["include_reasoning"]["observed"]
+ assert observed["model_reasoned"] is True
+ assert observed["with_include_reasoning"]["reasoning_deltas"] > 0
+ assert observed["without_include_reasoning"]["reasoning_deltas"] == 0
+ assert observed["non_streamed_with_include_reasoning"]["reasoning_chars"] == len(REASONING)
+ assert report["tools_turn_params"] == {"tool_choice": "auto", "extra_body": {"include_reasoning": True}}
+
+
+def _conformance_requests() -> list[dict[str, Any]]:
+ return [r for r in SEEN if _text(r["body"]["messages"], "user") not in {*REFUSALS, ERROR_EVENT}]
+
+
+def test_each_case_reaches_the_upstream_with_exactly_these_fields(report: dict[str, Any]) -> None:
+ assert report["cases"]
+ ready = "Reply with the single word: ready."
+ paris = "What is the weather in Paris right now? Use the get_weather tool."
+ cities = "Get the current weather in Paris and in Tokyo. Call get_weather once per city, both in this turn."
+ long = f"Read this warehouse log, then answer.\n\n{conformance.long_prompt()}\n\nWhat is the access code? Reply with just the code."
+ budget = conformance.GENERATION_BUDGET
+ plain = {"model": UPSTREAM_MODEL, "stream": False, "temperature": 0, "max_tokens": budget}
+ streamed = {"model": UPSTREAM_MODEL, "stream": True, "stream_options": {"include_usage": True}, "temperature": 0}
+ tools = {**streamed, "max_tokens": budget, "tools": [conformance.WEATHER_TOOL], "tool_choice": "auto"}
+ expected = [
+ (ready, ["user"], {**streamed, "max_tokens": 4}),
+ (conformance.REASONING_QUESTION, ["user"], {**streamed, "max_tokens": budget}),
+ (conformance.REASONING_QUESTION, ["user"], {**streamed, "max_tokens": budget}),
+ (conformance.REASONING_QUESTION, ["user"], plain),
+ (paris, ["user"], tools),
+ (cities, ["user"], tools),
+ (paris, ["user", "assistant", "tool"], tools),
+ ("the long prompt", ["user"], {**streamed, "max_tokens": budget}),
+ (ready, ["user"], {**streamed, "max_tokens": budget}),
+ ("Write three paragraphs about the sea.", ["user"], {**streamed, "max_tokens": 8}),
+ ("Say hello.", ["user"], {**tools, "tool_choice": "required"}),
+ (
+ conformance.LONG_CALL_PROMPT,
+ ["user"],
+ {**tools, "max_tokens": conformance.LONG_CALL_BUDGET, "tools": [conformance.WRITE_TOOL]},
+ ),
+ ]
+ received = _conformance_requests()
+ sent = []
+ for request in received:
+ body = request["body"]
+ prompt = body["messages"][0]["content"]
+ roles = [message["role"] for message in body["messages"]]
+ fields = {name: value for name, value in body.items() if name != "messages"}
+ sent.append(("the long prompt" if prompt == long else prompt, roles, fields))
+ assert request["path"] == "/api/v1/chat/completions"
+ assert request["authorization"] == f"Bearer {TEST_KEY}"
+ assert not _unroutable({**body, "provider": {"require_parameters": True}})
+ assert sent == expected
+ assert received[6]["body"]["messages"][1]["reasoning_content"] == "One call for Paris. "
+
+
+def test_the_stand_in_counts_only_openrouter_parameters_for_require_parameters() -> None:
+ body = {
+ "model": UPSTREAM_MODEL,
+ "messages": [{"role": "user", "content": "hi"}],
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ "max_tokens": 4,
+ "temperature": 0,
+ "tools": [],
+ "tool_choice": "auto",
+ }
+ strict = {**body, "provider": {"require_parameters": True}}
+ assert len(ENDPOINTS) == 33
+ assert len(PARAMETERS) == 26
+ assert not _unroutable(strict)
+ assert not _unroutable({**strict, "n": 1})
+ assert not _unroutable({**strict, "parallel_tool_calls": True})
+ assert _unroutable({**strict, "parallel_tool_calls": True, "top_k": 20})
+ assert _unroutable({**strict, "max_completion_tokens": 8})
+ assert not _unroutable({**body, "max_completion_tokens": 8, "parallel_tool_calls": True, "top_k": 20})
+
+
+ ("question", "reason", "message"),
+ [
+ ("answer 401", "upstream answered 401", "the upstream rejected the server's credential"),
+ ("answer 402", "upstream answered 402", "the upstream account cannot pay for the request"),
+ ("answer 404", "upstream answered 404", "the upstream has no route for the configured model"),
+ (
+ ERROR_EVENT,
+ "upstream sent an error instead of a chat answer",
+ "the upstream could not be reached, timed out or failed",
+ ),
+ ],
+)
+def test_a_refusal_answers_502_and_the_server_log_names_why(
+ server: SimpleNamespace, question: str, reason: str, message: str
+) -> None:
+ client = openai.OpenAI(base_url=f"{server.base}/v1", api_key="none", max_retries=0)
+ result = conformance.stream_chat(client, MODEL, [{"role": "user", "content": question}], max_tokens=16)
+ assert result.error is not None
+ assert (result.error["status"], result.error["code"], result.error["message"]) == (502, "upstream_error", message)
+ log = server.log.read_text()
+ assert f"remote chat for {MODEL} failed: {reason}" in log
+ assert UPSTREAM_DETAIL not in log
diff --git a/examples/coding-agent-opencode/tests/test_run_gate.py b/examples/coding-agent-opencode/tests/test_run_gate.py
index 089b5f610..bf2786978 100644
--- a/examples/coding-agent-opencode/tests/test_run_gate.py
+++ b/examples/coding-agent-opencode/tests/test_run_gate.py
@@ -165,7 +165,9 @@ def test_a_run_past_its_deadline_is_stopped_and_fails(tmp_path: Path, ignores_te
pytest.fail(f"the agent's child process {pid} outlived the deadline")
[email protected](("recipe", "needs_sie_variables"), [("gpu", False), ("cluster", True), ("cloud", True)])
+ ("recipe", "needs_sie_variables"), [("gpu", False), ("openrouter", False), ("cluster", True), ("cloud", True)]
+)
def test_only_a_recipe_that_reads_the_sie_variables_requires_them(
tmp_path: Path, recipe: str, needs_sie_variables: bool
) -> None:
diff --git a/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py b/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py
index 22f200d84..f4afcc0ca 100644
--- a/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py
+++ b/packages/sie_server/src/sie_server/adapters/remote/_openai_chat.py
@@ -183,6 +183,18 @@ def _message(value: Any, *, stream: bool, keep_reasoning: bool = False) -> dict[
return clean
+def _restates_finish(choice: dict[str, Any], reason: str) -> bool:
+ """Whether a streamed ``choice`` repeats a finished choice's ``reason`` and carries nothing else."""
+ delta = choice.get("delta")
+ return (
+ choice.get("finish_reason") == reason
+ and choice.get("logprobs") is None
+ and isinstance(delta, dict)
+ and delta.get("role") in (None, "assistant")
+ and all(value in (None, "", []) for field, value in delta.items() if field != "role")
+ )
+
+
class ChatStreamParser:
"""Normalize chat events; require each choice to finish and exact final usage."""
@@ -195,7 +207,7 @@ class ChatStreamParser:
self.done = False
self._id = f"chatcmpl-{uuid.uuid4().hex}"
self._created = int(time.time())
- self._finished: set[int] = set()
+ self._finished: dict[int, str] = {}
self._usage: dict[str, Any] | None = None
self._tools: dict[int, dict[int, dict[str, Any]]] = {}
@@ -218,7 +230,7 @@ class ChatStreamParser:
self.done = True
return None
payload = _json(data, max_bytes=_MAX_EVENT_BYTES)
- choices = self._parse_choices(payload.get("choices"), stream=True)
+ choices = self._parse_choices(payload.get("choices"), stream=True, accounting=payload.get("usage") is not None)
clean = self._envelope(choices, stream=True)
# Upstreams may stream a running count on every chunk. Only the last
# usage after every choice finishes is the request's usage.
@@ -246,7 +258,7 @@ class ChatStreamParser:
if not self.done:
raise RemoteUpstreamError("upstream chat stream ended before its terminal event")
- def _parse_choices(self, value: Any, *, stream: bool) -> list[dict[str, Any]]:
+ def _parse_choices(self, value: Any, *, stream: bool, accounting: bool = False) -> list[dict[str, Any]]:
if not isinstance(value, list) or len(value) > self.choices:
raise _invalid()
seen: set[int] = set()
@@ -255,9 +267,14 @@ class ChatStreamParser:
if not isinstance(choice, dict):
raise _invalid()
index = _count(choice.get("index"), maximum=self.choices)
- if index in seen or index in self._finished:
+ if index in seen:
raise _invalid()
seen.add(index)
+ if index in self._finished:
+ # Some upstreams restate a finished choice on the event that carries usage.
+ if not (accounting and _restates_finish(choice, self._finished[index])):
+ raise _invalid()
+ continue
reason = choice.get("finish_reason")
if reason is not None and (not isinstance(reason, str) or reason not in _FINISH_REASONS):
raise _invalid()
@@ -280,7 +297,7 @@ class ChatStreamParser:
)
result["logprobs"] = None if has_reasoning else _logprobs(choice["logprobs"])
if reason is not None:
- self._finished.add(index)
+ self._finished[index] = reason
clean.append(result)
return clean
diff --git a/packages/sie_server/tests/adapters/test_remote_openai_chat.py b/packages/sie_server/tests/adapters/test_remote_openai_chat.py
index 9f4be0af0..d39224562 100644
--- a/packages/sie_server/tests/adapters/test_remote_openai_chat.py
+++ b/packages/sie_server/tests/adapters/test_remote_openai_chat.py
@@ -125,6 +125,53 @@ def test_duplicate_finished_choice_fails() -> None:
parser.parse(wire([choice(stream=True)]))
[email protected]("finish", ["stop", "tool_calls"])
+def test_usage_event_restating_the_finished_choice_is_accounting_only(finish: str) -> None:
+ parser = ChatStreamParser("model")
+ if finish == "tool_calls":
+ call = {"index": 0, "id": "call_1", "type": "function", "function": {"name": "f", "arguments": "{}"}}
+ parser.parse(wire([choice(stream=True, finish=None, content="", tool_calls=[call])]))
+ finished = parser.parse(wire([choice(stream=True, finish=finish, content="")]))
+ restated = {"content": "", "reasoning": None, "reasoning_details": [], "tool_calls": None}
+ trailing = parser.parse(wire([choice(stream=True, finish=finish, **restated)], usage=USAGE))
+ assert finished is not None
+ assert trailing is not None
+ assert trailing["choices"] == []
+ assert trailing["usage"] == USAGE
+ assert parser.parse(b"[DONE]") is None
+ parser.finish()
+
+
+ ("restated", "usage"),
+ [
+ ({"finish": "stop"}, None),
+ ({"finish": "length"}, USAGE),
+ ({"finish": None}, USAGE),
+ ({"content": "more"}, USAGE),
+ ({"reasoning": "more"}, USAGE),
+ ({"refusal": "no"}, USAGE),
+ ({"role": "tool"}, USAGE),
+ ({"tool_calls": [{"index": 1, "function": {"arguments": "{}"}}]}, USAGE),
+ ({"reasoning_details": [{"type": "reasoning.text", "text": "more"}]}, USAGE),
+ ],
+)
+def test_finished_choice_restated_with_anything_new_fails(restated: dict, usage: dict | None) -> None:
+ parser = ChatStreamParser("model")
+ parser.parse(wire([choice(stream=True)]))
+ fields = {"finish": "stop", "content": "", **restated}
+ with pytest.raises(RemoteUpstreamError):
+ parser.parse(wire([choice(stream=True, **fields)], **({} if usage is None else {"usage": usage})))
+
+
+def test_restated_choice_with_logprobs_fails() -> None:
+ parser = ChatStreamParser("model")
+ parser.parse(wire([choice(stream=True)]))
+ restated = {**choice(stream=True, content=""), "logprobs": {"content": []}}
+ with pytest.raises(RemoteUpstreamError):
+ parser.parse(wire([restated], usage=USAGE))
+
+
def test_running_usage_is_not_final_and_the_last_usage_after_every_finish_stands() -> None:
parser = ChatStreamParser("model")
running = {"prompt_tokens": 37, "completion_tokens": 1, "total_tokens": 38}