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(server): serve the Anthropic Messages API on sie-server (#815)

Krisztian Gajdarb80a0292fee2
diff --git a/conformance/anthropic_messages/request_vectors.json b/conformance/anthropic_messages/request_vectors.json
index 9ef8d3c99..b55d05a3c 100644
--- a/conformance/anthropic_messages/request_vectors.json
+++ b/conformance/anthropic_messages/request_vectors.json
@@ -301,6 +301,56 @@
"include_reasoning": false
}
},
+ {
+ "name": "tool result images come before the turn's own text and images",
+ "body": {
+ "model": "m",
+ "max_tokens": 16,
+ "messages": [
+ {"role": "user", "content": "Take a screenshot."},
+ {"role": "assistant", "content": [{"type": "tool_use", "id": "s1", "name": "screenshot", "input": {}}]},
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "s1",
+ "content": [
+ {"type": "text", "text": "shot.png"},
+ {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}}
+ ]
+ },
+ {"type": "text", "text": "Compare it with this one."},
+ {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "/9j/AA=="}}
+ ]
+ }
+ ]
+ },
+ "first_image": "messages.2.content.0.tool_result.content.1.image",
+ "chat": {
+ "model": "m",
+ "messages": [
+ {"role": "user", "content": "Take a screenshot."},
+ {
+ "role": "assistant",
+ "content": null,
+ "tool_calls": [{"id": "s1", "type": "function", "function": {"name": "screenshot", "arguments": "{}"}}]
+ },
+ {"role": "tool", "tool_call_id": "s1", "content": "shot.png"},
+ {
+ "role": "user",
+ "content": [
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="}},
+ {"type": "text", "text": "Compare it with this one."},
+ {"type": "image_url", "image_url": {"url": "data:image/jpeg;base64,/9j/AA=="}}
+ ]
+ }
+ ],
+ "max_tokens": 16,
+ "stream": false,
+ "include_reasoning": false
+ }
+ },
{
"name": "user image between text keeps its position",
"body": {
diff --git a/examples/coding-agent-claude-code/README.md b/examples/coding-agent-claude-code/README.md
index 4519227c2..a80cc8c3d 100644
--- a/examples/coding-agent-claude-code/README.md
+++ b/examples/coding-agent-claude-code/README.md
@@ -3,10 +3,11 @@
## What this shows
Claude Code talks to models through the Anthropic Messages API. The SIE
-gateway serves `POST /v1/messages`: it translates the request into a
-`/v1/chat/completions` request, serves it on the chat route with all of that
-route's limits, and translates the answer back, streamed or buffered. So Claude
-Code reaches a model served by SIE by changing its base URL.
+gateway and `sie-server`, the single-node server, both serve
+`POST /v1/messages`: each translates the request into a
+`/v1/chat/completions` request, serves it on its own chat route with all of
+that route's limits, and translates the answer back, streamed or buffered. So
+Claude Code reaches a model served by SIE by changing its base URL.
Anthropic does not support Claude Code with models other than Claude behind a
gateway. Nothing here is supported or endorsed by Anthropic. This example
@@ -15,8 +16,9 @@ agent loop closes.
The pieces:
-1. `recipes/cloud.sh` and `recipes/cluster.sh`, the environment Claude Code
- needs for SIE Cloud and for a self-hosted cluster's gateway.
+1. `recipes/cloud.sh`, `recipes/cluster.sh` and `recipes/laptop.sh`, the
+ environment Claude Code needs for SIE Cloud, for a self-hosted cluster's
+ gateway and for `sie-server` on this machine.
2. The conformance check of the OpenCode example, run with `--api messages`.
It drives `/v1/messages` the way Claude Code does and reports each case as
pass, fail or recorded.
@@ -24,9 +26,6 @@ The pieces:
package with two failing tests and the task "make the tests pass". Claude
Code works a copy headless, then pytest judges the result.
-`sie-server`, the single-node server, does not serve `/v1/messages`. This
-example needs an SIE gateway: a cluster's or SIE Cloud's.
-
## Run it
```sh
@@ -61,10 +60,49 @@ The seeded gate, which needs `claude` and `uv` on `PATH`:
```sh
./run_gate.sh # SIE Cloud
./run_gate.sh cluster # your gateway, with SIE_MODEL, SIE_CONTEXT_TOKENS and SIE_OUTPUT_TOKENS set
+./run_gate.sh laptop # sie-server on this machine, see below
+```
+
+The cloud and cluster recipes have not been run against a live endpoint yet.
+Their checks below were run against the gateway's own tests and against a
+recording stub.
+
+### On this machine
+
+From a checkout of this repository, start `sie-server` with the generation
+bundle:
+
+```sh
+mise run serve -- -b sglang # generation bundle; MLX on Apple Silicon
+```
+
+Then, from this directory:
+
+```sh
+source recipes/laptop.sh
+claude
```
-Neither recipe has been run against a live endpoint yet. The checks below were
-run against the gateway's own tests and against a recording stub.
+`recipes/laptop.sh` points Claude Code at `http://localhost:8080` and names
+`Qwen/Qwen3.5-4B:long-context`, the 32K-window profile of a 4B model that
+declares tool calling, with its 4,096-token output cap. `SIE_BASE_URL`,
+`SIE_API_KEY`, `SIE_MODEL`, `SIE_CONTEXT_TOKENS` and `SIE_OUTPUT_TOKENS`
+override those. A server with authentication off accepts any key. With
+authentication on, `SIE_API_KEY` is the server's token. A 32K window fits the
+gate's `--bare` session, which declares three tools and a short system prompt.
+An interactive session declares about twenty tools, so it reaches the window
+sooner and Claude Code compacts it earlier.
+
+The conformance check and the gate against it:
+
+```sh
+uv run --project ../coding-agent-opencode python ../coding-agent-opencode/conformance.py \
+ --api messages --base-url http://localhost:8080/v1 --model Qwen/Qwen3.5-4B:long-context
+./run_gate.sh laptop
+```
+
+Both were run on one Apple Silicon machine with the MLX backend; see
+[the recorded result](#laptop-apple-silicon-recorded).
## The recipe
@@ -89,9 +127,9 @@ export API_TIMEOUT_MS=1800000
- `ANTHROPIC_BASE_URL` is the gateway without `/v1`. Claude Code appends
`/v1/messages`.
- `ANTHROPIC_AUTH_TOKEN` arrives as `Authorization: Bearer ...`, and
- Claude Code sends `ANTHROPIC_API_KEY` as `x-api-key`. The gateway reads
- either one; when a request carries both, it uses `Authorization` and
- ignores `x-api-key`.
+ Claude Code sends `ANTHROPIC_API_KEY` as `x-api-key`. The gateway and
+ `sie-server` read either one; when a request carries both, they use
+ `Authorization` and ignore `x-api-key`.
- The model id is sent byte for byte, slash and colon included. The four
model variables keep every request, background tasks and subagents
included, on the SIE model. A request that names a model the gateway does
@@ -184,6 +222,78 @@ Busy refusals are retried as in the chat check: a `429` or `503`, or an
## What result to expect
+### Laptop, Apple Silicon, recorded
+
+`Qwen/Qwen3.5-4B:long-context` on an Apple M3 Max with 48 GB under macOS
+15.7, MLX backend (`mlx-community/Qwen3.5-4B-4bit`), `sie-server` from this
+repository started with `mise run serve -- -b sglang --host 127.0.0.1`, Claude
+Code 2.1.300, 2026-10-19.
+
+The conformance check:
+
+```
+ streaming_tool_use pass 1 tool_use: get_weather({"city": "Paris"}); 1 input_json_delta; stop_reason=tool_use
+ parallel_tool_use pass 2 tool_use in one turn: get_weather({"city": "Paris"}), get_weather({"city": "Tokyo"})
+ tool_result_round_trip pass final answer used the tool result: 'The weather in Paris is currently overcast with a temperature of 18°C.'
+ prompt_above_64k_tokens pass 74847 prompt tokens accepted and answered; needle found
+ stop_reason_end_turn pass stop_reason=end_turn after 'ready'
+ stop_reason_tool_use pass stop_reason=tool_use on the tool turn
+ stop_reason_max_tokens pass stop_reason=max_tokens at max_tokens=8 (output_tokens=8)
+ usage_on_message_delta pass message_delta carries usage {'input_tokens': 4, 'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 16, 'output_tokens': 2}
+ thinking_blocks recorded no thinking block came back; the model did not reason here or reasons privately
+ tool_choice_any recorded refused: 400 invalid_request_error: tool_choice: 'tool_choice' must be 'auto' or 'none' on this device, which cannot force a tool call
+ buffered_message pass stop_reason=end_turn, usage {'input_tokens': 20, 'cache_creation_input_tokens': 0, 'cache_read_input_tokens': 0, 'output_tokens': 2}
+ inert_fields_accepted pass metadata, cache_control and anthropic-beta accepted
+ effort_refusal pass 400 invalid_request_error: output_config.effort: Extra inputs are not permitted
+ system_turn_refusal pass 400 invalid_request_error: messages.1.role: role "system" is not supported in messages; use the top-level system parameter
+ unknown_model pass 404 not_found_error: Model 'sie-conformance/no-such-model' not found
+ event_grammar pass 9 streams: message_start, one block at a time, message_delta then message_stop
+ ping_events recorded 9 ping events across the streams
+ count_tokens recorded not served: 404; Claude Code then estimates locally
+
+14 pass, 0 fail, 4 recorded
+```
+
+- The profile does not ask the model to reason, so no thinking came back.
+- The MLX backend cannot force a tool call, so `tool_choice: any` is
+ refused. Claude Code does not send it.
+- The pings came during the 74,847-token prompt, which the server accepted
+ although the profile declares a 32,768-token window. Set
+ `CLAUDE_CODE_MAX_CONTEXT_TOKENS` to the declared window, as the recipe does,
+ so Claude Code compacts before that.
+- Prompt tokens served from the prefix cache come back as
+ `cache_read_input_tokens`.
+
+`./run_gate.sh laptop` passed three times out of three on the same server.
+The first run, Claude Code's JSON event lines left out:
+
+```
+== before: the seeded tests
+FAILED tests/test_amounts.py::test_credit_in_parentheses_is_negative - decima...
+FAILED tests/test_amounts.py::test_total_nets_credits - decimal.InvalidOperat...
+2 failed, 1 passed in 0.02s
+== claude run, recipe laptop, up to 50 turns and 1800 s
+== the run
+{
+ "turns": 5,
+ "duration_ms": 12443,
+ "usage": {"input_tokens": 2688, "cache_read_input_tokens": 8858, "output_tokens": 513},
+ "tool_uses": ["Bash", "Read", "Edit", "Bash"],
+ "api_retries": 0,
+ "problems": []
+}
+== after: the seeded tests must be untouched
+== after: pytest in a fresh environment, pinned to the seeded config and tests
+... [100%]
+3 passed in 0.01s
+GATE PASS (.../run-output/gate-20261019T105944Z-2izeas)
+```
+
+The other two took 5 turns each, in 12.1 s and 13.8 s. Each run's first
+request carried `output_config.effort`, which the server refused with the
+wording Claude Code retries on, and Claude Code sent it again without effort.
+That refusal is not an API retry, so `api_retries` stays 0.
+
### The gate against a recording stub, recorded
`run_gate.sh` with Claude Code 2.1.300 and a stub on `SIE_BASE_URL` that
@@ -223,11 +333,22 @@ nothing about a model.
request, serve `/v1/messages` through the real chat handler with a scripted
transport, and check that any chat chunk sequence yields a well-formed event
sequence.
+- `sie-server`'s tests replay the same vectors and captured requests, check
+ that the server's own chat validation accepts every translation, and check
+ the same event grammar. They also serve `/v1/messages` through the server's
+ app and chat route on the weightless fake: answers that match the chat
+ answer to the same conversation, buffered and streamed, thinking blocks
+ only on request, refusals in the Anthropic envelope, `Authorization` and
+ `x-api-key`, pings during a silent stretch, a failure after output, and a
+ client that goes away.
+- The OpenCode example's `tests/test_fake_engine.py` runs
+ `conformance.py --api messages` against this repository's `sie-server` on
+ the fake engine.
- `tests/test_run_gate.py` runs `run_gate.sh` with a scripted stand-in for
`claude`: a real fix, no change, a failed run, a run that ended in an error,
read no input tokens or took too few turns, edited tests, a run past its
- deadline, both recipes, and the arguments and environment Claude Code is
- started with.
+ deadline, the three recipes, and the arguments and environment Claude Code
+ is started with.
- The OpenCode example's `tests/test_messages_conformance.py` checks the
`--api messages` checker against a scripted Messages stub.
@@ -240,8 +361,16 @@ uv run pytest
- **Not supported by Anthropic.** Anthropic does not support Claude Code with
non-Claude models behind a gateway. A Claude Code release can change what it
sends. The capture above is how to re-check a new version.
-- **Not a live result yet.** Neither recipe has been run against a live
- endpoint, and no model has worked the fixture through `/v1/messages` here.
+- **Not a live result yet.** The cloud and cluster recipes have not been run
+ against a live endpoint.
+- **Not a claim about every laptop.** The laptop recipe was run on one Apple
+ Silicon machine with the MLX backend and one 4B model. It has not been run
+ on an NVIDIA machine.
- **Not a coding benchmark.** The fixture is two failing tests in a
twenty-line module.
-- **Not the single-node server.** `sie-server` does not serve `/v1/messages`.
+- **The single-node server answers in its chat route's words.** `sie-server`
+ translates the refusals its chat route makes. Its chat route does not
+ report the token counts of a prompt that does not fit on every backend, so
+ such a refusal can read `prompt is too long` without them. On a backend that
+ refuses media, an image is refused for the whole request rather than the
+ image block.
diff --git a/examples/coding-agent-claude-code/recipes/laptop.sh b/examples/coding-agent-claude-code/recipes/laptop.sh
new file mode 100644
index 000000000..7d39c2c17
--- /dev/null
+++ b/examples/coding-agent-claude-code/recipes/laptop.sh
@@ -0,0 +1,24 @@
+# Claude Code on this machine's sie-server, through its /v1/messages.
+#
+# mise run serve -- -b sglang # in a checkout of this repository; MLX on Apple Silicon
+# source recipes/laptop.sh && claude
+#
+# SIE_BASE_URL defaults to http://localhost:8080. A server with authentication off
+# accepts any key; with authentication on, set SIE_API_KEY to the server's token.
+# SIE_MODEL, SIE_CONTEXT_TOKENS and SIE_OUTPUT_TOKENS default to the 32K-window
+# profile of Qwen/Qwen3.5-4B and its 4,096-token output cap.
+export SIE_BASE_URL="${SIE_BASE_URL:-http://localhost:8080}"
+export SIE_API_KEY="${SIE_API_KEY:-local}"
+export ANTHROPIC_BASE_URL="$SIE_BASE_URL"
+export ANTHROPIC_AUTH_TOKEN="$SIE_API_KEY"
+export ANTHROPIC_MODEL="${SIE_MODEL:-Qwen/Qwen3.5-4B:long-context}"
+export ANTHROPIC_DEFAULT_OPUS_MODEL="$ANTHROPIC_MODEL"
+export ANTHROPIC_DEFAULT_SONNET_MODEL="$ANTHROPIC_MODEL"
+export ANTHROPIC_DEFAULT_HAIKU_MODEL="$ANTHROPIC_MODEL"
+export CLAUDE_CODE_SUBAGENT_MODEL="$ANTHROPIC_MODEL"
+export CLAUDE_CODE_MAX_CONTEXT_TOKENS="${SIE_CONTEXT_TOKENS:-32768}"
+export CLAUDE_CODE_MAX_OUTPUT_TOKENS="${SIE_OUTPUT_TOKENS:-4096}"
+export CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1
+export CLAUDE_CODE_ATTRIBUTION_HEADER=0
+export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1
+export API_TIMEOUT_MS=1800000
diff --git a/examples/coding-agent-claude-code/run_gate.sh b/examples/coding-agent-claude-code/run_gate.sh
index 9654b2d6b..7cc02b983 100755
--- a/examples/coding-agent-claude-code/run_gate.sh
+++ b/examples/coding-agent-claude-code/run_gate.sh
@@ -5,6 +5,7 @@
# SIE_BASE_URL=https://... SIE_API_KEY=sk-sie-... ./run_gate.sh # SIE Cloud (recipes/cloud.sh)
# SIE_BASE_URL=https://... SIE_API_KEY=... SIE_MODEL=... \
# SIE_CONTEXT_TOKENS=... SIE_OUTPUT_TOKENS=... ./run_gate.sh cluster # your gateway (recipes/cluster.sh)
+# ./run_gate.sh laptop # sie-server on this machine (recipes/laptop.sh)
#
# Needs claude and uv on PATH. The fixture is the OpenCode example's, unchanged. Writes
# run-output/gate-<timestamp>-<suffix>/ with the worked copy of the fixture, Claude Code's
@@ -12,8 +13,9 @@
#
# Claude Code runs with --bare and an empty config directory, so no user settings, hooks,
# MCP servers or CLAUDE.md files take part. Its key comes from an apiKeyHelper that prints
-# SIE_API_KEY. The run is bounded: GATE_TURNS turns (default 50), and a run still going
-# after GATE_DEADLINE_SECONDS (default 1800) is stopped and fails.
+# SIE_API_KEY, which the laptop recipe defaults. The run is bounded: GATE_TURNS turns
+# (default 50), and a run still going after GATE_DEADLINE_SECONDS (default 1800) is stopped
+# and fails.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
@@ -21,7 +23,7 @@ FIXTURE="$HERE/../coding-agent-opencode/fixture"
RECIPE="${1:-cloud}"
ENV_FILE="$HERE/recipes/$RECIPE.sh"
if [[ ! -f "$ENV_FILE" ]]; then
- echo "unknown recipe '$RECIPE'; pick cloud or cluster" >&2
+ echo "unknown recipe '$RECIPE'; pick cloud, cluster or laptop" >&2
exit 2
fi
for tool in claude uv; do
@@ -38,11 +40,12 @@ for var in GATE_TURNS GATE_DEADLINE_SECONDS; do
exit 2
fi
done
-REQUIRED=(SIE_BASE_URL SIE_API_KEY)
-if [[ "$RECIPE" == "cluster" ]]; then
- REQUIRED+=(SIE_MODEL SIE_CONTEXT_TOKENS SIE_OUTPUT_TOKENS)
-fi
-for var in "${REQUIRED[@]}"; do
+case "$RECIPE" in
+ cloud) REQUIRED=(SIE_BASE_URL SIE_API_KEY) ;;
+ cluster) REQUIRED=(SIE_BASE_URL SIE_API_KEY SIE_MODEL SIE_CONTEXT_TOKENS SIE_OUTPUT_TOKENS) ;;
+ *) REQUIRED=() ;;
+esac
+for var in ${REQUIRED[@]+"${REQUIRED[@]}"}; do
if [[ -z "${!var:-}" ]]; then
echo "$var is not set" >&2
exit 2
diff --git a/examples/coding-agent-claude-code/tests/test_run_gate.py b/examples/coding-agent-claude-code/tests/test_run_gate.py
index 9bb815371..f68277efe 100644
--- a/examples/coding-agent-claude-code/tests/test_run_gate.py
+++ b/examples/coding-agent-claude-code/tests/test_run_gate.py
@@ -67,7 +67,11 @@ env | grep -E '^(ANTHROPIC|CLAUDE_CODE|CLAUDE_CONFIG_DIR|API_TIMEOUT_MS)' | sort
def _gate(
- tmp_path: Path, agent: str, recipe: str = "cloud", extra_env: dict[str, str] | None = None
+ tmp_path: Path,
+ agent: str,
+ recipe: str = "cloud",
+ extra_env: dict[str, str] | None = None,
+ unset: tuple[str, ...] = (),
) -> tuple[int, str, Path]:
root = tmp_path / "examples"
example = root / "coding-agent-claude-code"
@@ -102,6 +106,8 @@ def _gate(
**(extra_env or {}),
}
)
+ for name in unset:
+ env.pop(name, None)
completed = subprocess.run(
["bash", str(example / "run_gate.sh"), recipe],
capture_output=True,
@@ -159,10 +165,44 @@ def test_the_cluster_recipe_needs_the_model_and_window(tmp_path: Path, missing:
assert f"{missing} is not set" in output
+def test_the_laptop_recipe_defaults_to_the_local_server_and_its_32k_profile(tmp_path: Path) -> None:
+ unset = ("SIE_BASE_URL", "SIE_API_KEY")
+ status, output, record = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{_events()}\nEOF", "laptop", unset=unset)
+ assert status == 0, output
+ env = dict(line.split("=", 1) for line in (record / "env").read_text().splitlines())
+ assert env["ANTHROPIC_BASE_URL"] == "http://localhost:8080"
+ assert env["ANTHROPIC_AUTH_TOKEN"] == "local"
+ assert env["ANTHROPIC_MODEL"] == "Qwen/Qwen3.5-4B:long-context"
+ assert env["ANTHROPIC_DEFAULT_HAIKU_MODEL"] == "Qwen/Qwen3.5-4B:long-context"
+ assert env["CLAUDE_CODE_SUBAGENT_MODEL"] == "Qwen/Qwen3.5-4B:long-context"
+ assert env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "32768"
+ assert env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "4096"
+ assert env["CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS"] == "1"
+ assert "ANTHROPIC_API_KEY" not in env
+
+
+def test_the_laptop_recipe_takes_the_server_key_and_model_from_the_environment(tmp_path: Path) -> None:
+ extra = {
+ "SIE_BASE_URL": "http://127.0.0.1:9000",
+ "SIE_API_KEY": "server-token",
+ "SIE_MODEL": "sie-fake:chat",
+ "SIE_CONTEXT_TOKENS": "131072",
+ "SIE_OUTPUT_TOKENS": "1024",
+ }
+ status, output, record = _gate(tmp_path, f"{FIX}\ncat <<'EOF'\n{_events()}\nEOF", "laptop", extra)
+ assert status == 0, output
+ env = dict(line.split("=", 1) for line in (record / "env").read_text().splitlines())
+ assert env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:9000"
+ assert env["ANTHROPIC_AUTH_TOKEN"] == "server-token"
+ assert env["ANTHROPIC_MODEL"] == "sie-fake:chat"
+ assert env["CLAUDE_CODE_MAX_CONTEXT_TOKENS"] == "131072"
+ assert env["CLAUDE_CODE_MAX_OUTPUT_TOKENS"] == "1024"
+
+
def test_an_unknown_recipe_is_refused(tmp_path: Path) -> None:
- status, output, _ = _gate(tmp_path, "exit 0", "laptop")
+ status, output, _ = _gate(tmp_path, "exit 0", "desktop")
assert status == 2
- assert "unknown recipe 'laptop'" in output
+ assert "unknown recipe 'desktop'; pick cloud, cluster or laptop" in output
def test_no_change_fails_on_the_seeded_tests(tmp_path: Path) -> None:
diff --git a/examples/coding-agent-opencode/README.md b/examples/coding-agent-opencode/README.md
index 6fea6e104..c5d234cbe 100644
--- a/examples/coding-agent-opencode/README.md
+++ b/examples/coding-agent-opencode/README.md
@@ -794,9 +794,11 @@ What runs anywhere, and in this repository's CI, is the test suite:
included, and what each case observed: the call's id and name on its first
delta, the tool result in the answer, reasoning only with the flag and the
same usage without it, the long prompt's size against the window, and
- `max_tokens: 8` spending exactly 8 tokens. It needs the repository's
- environment, from `mise run sync` at the root, and is skipped without it
- outside CI.
+ `max_tokens: 8` spending exactly 8 tokens. It also runs
+ `conformance.py --api messages` against the same server, whose
+ `/v1/messages` translates onto that chat route, and asserts that table. It
+ needs the repository's environment, from `mise run sync` at the root, and is
+ skipped without it outside CI.
- `tests/test_conformance.py` starts a scripted OpenAI-compatible stub that
plays a conforming wire, then breaks one thing per test: tool-call deltas
without ids, one call where two were asked for, `tool_choice: "required"`
@@ -840,7 +842,8 @@ 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 route with a scripted model.
+and `tests/test_fake_engine.py` checks SIE's chat and Messages routes with a
+scripted model.
A model's endpoint is only checked by running `conformance.py` against it.
## What this does NOT establish
diff --git a/examples/coding-agent-opencode/tests/test_fake_engine.py b/examples/coding-agent-opencode/tests/test_fake_engine.py
index 3779b9ae3..a0d9cacff 100644
--- a/examples/coding-agent-opencode/tests/test_fake_engine.py
+++ b/examples/coding-agent-opencode/tests/test_fake_engine.py
@@ -13,6 +13,11 @@ cap refuses the 32,000 tokens a 64 KiB call needs, so ``long_tool_call`` is
recorded as not run. The fake does not read
the long prompt, so the needle is never found; the case passes on the prompt
size and the answer, as it does for any model.
+
+The same server answers ``conformance.py --api messages``: ``/v1/messages``
+on ``sie-server`` translates each request onto the chat route above and the
+answer back, so the Messages cases check that translation over the same
+scripted turns.
"""
from __future__ import annotations
@@ -181,3 +186,73 @@ def test_tool_choice_required_forces_a_call(report: dict[str, Any]) -> None:
observed = _cases(report)["tool_choice_required"]["observed"]
assert observed["support"] == "supported"
assert json.loads(observed["tool_calls"][0]["arguments"]) == {"city": "Say hello."}
+
+
[email protected](scope="module")
+def messages_report(server: str) -> dict[str, Any]:
+ return conformance.run_messages(f"{server}/v1", "", MODEL)
+
+
+def test_each_messages_case_against_the_fake(messages_report: dict[str, Any]) -> None:
+ statuses = {name: case["status"] for name, case in _cases(messages_report).items()}
+ assert statuses == {
+ "streaming_tool_use": "pass",
+ "parallel_tool_use": "fail",
+ "tool_result_round_trip": "pass",
+ "prompt_above_64k_tokens": "pass",
+ "stop_reason_end_turn": "pass",
+ "stop_reason_tool_use": "pass",
+ "stop_reason_max_tokens": "pass",
+ "usage_on_message_delta": "pass",
+ "thinking_blocks": "pass",
+ "tool_choice_any": "recorded",
+ "buffered_message": "pass",
+ "inert_fields_accepted": "pass",
+ "effort_refusal": "pass",
+ "system_turn_refusal": "pass",
+ "unknown_model": "pass",
+ "event_grammar": "pass",
+ "ping_events": "recorded",
+ "count_tokens": "recorded",
+ }, messages_report["cases"]
+ assert messages_report["served_by"] == "local"
+ assert messages_report["warm_up"]["error"] is None
+
+
+def test_the_tool_use_block_streams_the_scripted_call(messages_report: dict[str, Any]) -> None:
+ observed = _cases(messages_report)["streaming_tool_use"]["observed"]
+ [call] = observed["tool_calls"]
+ question = "What is the weather in Paris right now? Use the get_weather tool."
+ assert call["first_delta_has_id_and_name"] is True
+ assert json.loads(call["arguments"]) == {"city": question}
+ assert observed["stop_reason"] == "tool_use"
+ assert observed["reasoning_deltas"] > 0
+
+
+def test_messages_usage_is_the_chat_usage_translated(messages_report: dict[str, Any]) -> None:
+ cases = _cases(messages_report)
+ usage = cases["usage_on_message_delta"]["observed"]["usage"]
+ long_prompt = cases["prompt_above_64k_tokens"]["observed"]["usage"]
+ assert usage["input_tokens"] > 0
+ assert usage["output_tokens"] > 0
+ assert usage["cache_creation_input_tokens"] == 0
+ assert cases["usage_on_message_delta"]["observed"]["message_start_usage"]["input_tokens"] == 0
+ assert conformance.LONG_PROMPT_MIN_TOKENS < long_prompt["input_tokens"] < WINDOW
+ assert cases["stop_reason_max_tokens"]["observed"]["usage"]["output_tokens"] == 8
+
+
+def test_thinking_blocks_come_back_only_when_asked(messages_report: dict[str, Any]) -> None:
+ observed = _cases(messages_report)["thinking_blocks"]["observed"]
+ assert observed["with_thinking"]["reasoning_deltas"] > 0
+ assert observed["without_thinking"]["reasoning_deltas"] == 0
+ assert observed["non_streamed_with_thinking"]["reasoning_chars"] == observed["with_thinking"]["reasoning_chars"]
+
+
+def test_the_messages_refusals_use_the_anthropic_wording(messages_report: dict[str, Any]) -> None:
+ cases = _cases(messages_report)
+ assert cases["effort_refusal"]["detail"] == (
+ "400 invalid_request_error: output_config.effort: Extra inputs are not permitted"
+ )
+ assert cases["unknown_model"]["observed"]["error"]["type"] == "not_found_error"
+ assert cases["count_tokens"]["observed"]["status"] == 404
+ assert cases["count_tokens"]["observed"]["body"]["error"]["type"] == "not_found_error"
diff --git a/packages/sie_server/src/sie_server/api/anthropic_messages.py b/packages/sie_server/src/sie_server/api/anthropic_messages.py
new file mode 100644
index 000000000..494495b36
--- /dev/null
+++ b/packages/sie_server/src/sie_server/api/anthropic_messages.py
@@ -0,0 +1,289 @@
+"""``POST /v1/messages``: the Anthropic Messages API on the single-instance server.
+
+The request is validated and translated into a chat completions body
+(:mod:`sie_server.api.anthropic_translation`), this server's own
+``/v1/chat/completions`` serves it in process, and the answer is translated
+back: a chat completion into a Message, chat SSE chunks into Messages events,
+and every error into the Anthropic envelope. Every chat gate, limit and timeout
+therefore applies unchanged. ``POST /v1/messages/count_tokens`` is not served.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import uuid
+from http import HTTPStatus
+from typing import Annotated, Any, cast
+
+from fastapi import APIRouter, Depends, Header, Request
+from fastapi.responses import JSONResponse, Response, StreamingResponse
+from starlette.types import ASGIApp, Message, Receive, Scope, Send
+
+from sie_server.api.anthropic_translation import (
+ PING_INTERVAL_S,
+ ErrorContext,
+ MessagesError,
+ StreamMachine,
+ anthropic_error,
+ chat_completion_to_message,
+ envelope,
+ error_type_for_status,
+ is_forwarded_header,
+ is_messages_path,
+ json_text,
+ messages_to_chat,
+ parse_json,
+ sie_code_for_status,
+ stream_events,
+)
+from sie_server.api.openai_local import _MAX_BODY_BYTES, serve_chat_completions
+from sie_server.api.routing import remote_routing
+
+logger = logging.getLogger(__name__)
+
+router = APIRouter(prefix="/v1", tags=["anthropic-compat"], dependencies=[Depends(remote_routing)])
+
+_MAX_ERROR_BODY_BYTES = 1024 * 1024
+_END = object()
+_INNER_SCOPE: Scope = {"type": "http", "asgi": {"version": "3.0", "spec_version": "2.4"}}
+
+
+class _ReleasedError(Exception):
+ """Ends a response that is closed before it was read."""
+
+
+async def _never() -> Message:
+ return await asyncio.get_running_loop().create_future()
+
+
+async def _refuse(_: Message) -> None:
+ raise _ReleasedError
+
+
+class _ResponseBody:
+ """The body of a response, read through the response's own ASGI call.
+
+ A chat answer releases what it holds, such as a generation slot or the
+ child's stream, when its ASGI call ends. Reading it through that call and
+ closing it by ending the call keeps that release with the chat route.
+ """
+
+ def __init__(self, response: Response) -> None:
+ self._response = response
+ self._chunks: asyncio.Queue[object] = asyncio.Queue(maxsize=1)
+ self._task: asyncio.Task[None] | None = None
+ self._closed = False
+
+ def __aiter__(self) -> _ResponseBody:
+ return self
+
+ async def __anext__(self) -> bytes:
+ if self._task is None:
+ self._task = asyncio.create_task(self._serve())
+ item = await self._chunks.get()
+ if item is _END:
+ raise StopAsyncIteration
+ if isinstance(item, BaseException):
+ raise item
+ return cast("bytes", item)
+
+ async def aclose(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ if self._task is None:
+ try:
+ await self._response(_INNER_SCOPE, _never, _refuse)
+ except _ReleasedError:
+ pass
+ except Exception: # noqa: BLE001 - closing must not mask the answer being sent
+ logger.warning("closing an unread chat answer failed", exc_info=True)
+ return
+ self._task.cancel()
+ await asyncio.wait({self._task})
+ if not self._task.cancelled():
+ self._task.exception()
+
+ async def _serve(self) -> None:
+ try:
+ await self._response(_INNER_SCOPE, _never, self._forward)
+ except Exception as error: # noqa: BLE001 - a broken chat stream is reported to the reader
+ await self._chunks.put(error)
+ return
+ await self._chunks.put(_END)
+
+ async def _forward(self, message: Message) -> None:
+ if message["type"] == "http.response.body" and message.get("body"):
+ await self._chunks.put(bytes(message["body"]))
+
+
+def _header_pairs(response: Response) -> list[tuple[str, str]]:
+ return [(name.decode("latin-1").lower(), value.decode("latin-1")) for name, value in response.raw_headers]
+
+
+async def _read(response: Response) -> bytes:
+ if not isinstance(response, StreamingResponse):
+ return bytes(response.body)
+ body = _ResponseBody(response)
+ try:
+ return b"".join([chunk async for chunk in body])
+ finally:
+ await body.aclose()
+
+
+def _json_answer(status: int, headers: list[tuple[str, str]], content: bytes) -> Response:
+ response = Response(content=content, status_code=status, media_type="application/json")
+ for name, value in headers:
+ if name != "content-type":
+ response.headers.append(name, value)
+ return response
+
+
+def _refusal(error: MessagesError) -> Response:
+ body = envelope(error_type_for_status(error.status), error.message, None)
+ headers = [("x-sie-error-code", sie_code_for_status(error.status))]
+ return _json_answer(error.status, headers, json_text(body).encode())
+
+
+async def _error_answer(answer: Response, context: ErrorContext) -> Response:
+ headers, content = anthropic_error(answer.status_code, _header_pairs(answer), await _read(answer), context)
+ return _json_answer(answer.status_code, headers, content)
+
+
+async def _read_body(request: Request) -> Any:
+ declared = request.headers.get("content-length")
+ if declared is not None and declared.isdigit() and int(declared) > _MAX_BODY_BYTES:
+ raise MessagesError(f"request body is larger than {_MAX_BODY_BYTES} bytes", status=413)
+ raw = bytearray()
+ async for chunk in request.stream():
+ if len(raw) + len(chunk) > _MAX_BODY_BYTES:
+ raise MessagesError(f"request body is larger than {_MAX_BODY_BYTES} bytes", status=413)
+ raw.extend(chunk)
+ try:
+ return parse_json(bytes(raw))
+ except ValueError as error:
+ raise MessagesError(f"body: invalid JSON: {error}") from None
+
+
+async def _buffered_message(answer: Response, model: str, request_id: str | None) -> Response:
+ content = await _read(answer)
+ try:
+ chat = parse_json(content)
+ except ValueError:
+ return _refusal(MessagesError("the chat completion is not valid JSON", status=500))
+ try:
+ message = chat_completion_to_message(chat, model, request_id or uuid.uuid4().hex)
+ except ValueError as error:
+ return _refusal(MessagesError(str(error), status=500))
+ headers = {name: value for name, value in _header_pairs(answer) if is_forwarded_header(name)}
+ if request_id:
+ headers["request-id"] = request_id
+ return JSONResponse(content=message, headers=headers)
+
+
+class _MessagesStream(StreamingResponse):
+ """A chat SSE answer served as Messages events. Ending this answer ends the chat answer."""
+
+ def __init__(self, chat: Response, machine: StreamMachine, request_id: str | None) -> None:
+ self._body = _ResponseBody(chat)
+ headers = {name: value for name, value in _header_pairs(chat) if name not in ("content-length", "content-type")}
+ if request_id:
+ headers["request-id"] = request_id
+ super().__init__(
+ stream_events(self._body, machine, PING_INTERVAL_S), media_type="text/event-stream", headers=headers
+ )
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ try:
+ await super().__call__(scope, receive, send)
+ finally:
+ await self._body.aclose()
+
+
+ "/messages",
+ response_model=None,
+ responses={
+ 400: {"description": "Invalid or unsupported request"},
+ 404: {"description": "Model not found"},
+ 413: {"description": "Request body is too large"},
+ 500: {"description": "Generation failed"},
+ 502: {"description": "The generation backend failed the request"},
+ 503: {"description": "Model loading or temporarily unavailable; retry after Retry-After"},
+ 504: {"description": "Generation timed out"},
+ },
+)
+async def messages(
+ http_request: Request,
+ x_machine_profile: Annotated[str | None, Header(alias="X-SIE-MACHINE-PROFILE")] = None,
+) -> Response:
+ """Anthropic Messages API, served by this server's chat completions route.
+
+ The request is translated into a ``/v1/chat/completions`` request, served
+ in process with all of that route's limits, and the answer is translated
+ back, as a Message or, with ``stream``, as Messages events. Errors use the
+ Anthropic envelope at the status the chat route answers.
+ """
+ try:
+ translation = messages_to_chat(await _read_body(http_request), http_request.headers.get("anthropic-version"))
+ except MessagesError as error:
+ return _refusal(error)
+ try:
+ answer = await serve_chat_completions(http_request, x_machine_profile, translation.chat)
+ if not HTTPStatus.OK <= answer.status_code < HTTPStatus.MULTIPLE_CHOICES:
+ return await _error_answer(answer, ErrorContext(first_image=translation.first_image))
+ request_id = next((value for name, value in _header_pairs(answer) if name == "x-sie-request-id"), None)
+ if translation.stream:
+ machine = StreamMachine(f"msg_{request_id or uuid.uuid4().hex}", translation.model)
+ return _MessagesStream(answer, machine, request_id)
+ return await _buffered_message(answer, translation.model, request_id)
+ except Exception:
+ logger.exception("the Messages translation of a chat answer failed")
+ return _refusal(MessagesError("internal server error", status=500))
+
+
+class AnthropicErrorEnvelopeMiddleware:
+ """Give every error answer on ``/v1/messages`` and the paths below it the Anthropic envelope.
+
+ Added outside the server's other middleware, so their refusals on these
+ paths, such as a missing credential, take the same shape. An answer that is
+ already in the Anthropic envelope passes through with ``Retry-After``
+ capped.
+ """
+
+ def __init__(self, app: ASGIApp) -> None:
+ self.app = app
+
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
+ if scope["type"] != "http" or not is_messages_path(scope["path"]):
+ await self.app(scope, receive, send)
+ return
+ held: Message | None = None
+ body = bytearray()
+ oversized = False
+
+ async def respond(message: Message) -> None:
+ nonlocal held, oversized
+ if message["type"] == "http.response.start" and message["status"] >= HTTPStatus.BAD_REQUEST:
+ held = message
+ return
+ if held is None or message["type"] != "http.response.body":
+ await send(message)
+ return
+ chunk = message.get("body", b"")
+ if len(body) + len(chunk) > _MAX_ERROR_BODY_BYTES:
+ oversized = True
+ elif not oversized:
+ body.extend(chunk)
+ if message.get("more_body", False):
+ return
+ status = held["status"]
+ inner = [(name.decode("latin-1"), value.decode("latin-1")) for name, value in held.get("headers", [])]
+ headers, content = anthropic_error(status, inner, b"" if oversized else bytes(body), ErrorContext())
+ raw = [(name.encode("latin-1"), value.encode("latin-1")) for name, value in headers]
+ raw.append((b"content-length", str(len(content)).encode()))
+ await send({"type": "http.response.start", "status": status, "headers": raw})
+ await send({"type": "http.response.body", "body": content})
+
+ await self.app(scope, receive, respond)
diff --git a/packages/sie_server/src/sie_server/api/anthropic_translation.py b/packages/sie_server/src/sie_server/api/anthropic_translation.py
new file mode 100644
index 000000000..7a41e5997
--- /dev/null
+++ b/packages/sie_server/src/sie_server/api/anthropic_translation.py
@@ -0,0 +1,1441 @@
+"""Anthropic Messages translation onto the chat completions wire.
+
+The Python twin of the gateway's ``handlers::messages``: a Messages request
+into a chat completions body, a chat completion into a Message, chat SSE
+``data`` payloads into Messages events, and an error answer into the Anthropic
+envelope. The shared vectors under ``conformance/anthropic_messages/`` pin both
+implementations, so a request is accepted, refused and answered the same way
+on ``sie-server`` and on the gateway.
+
+Validation happens here, in Anthropic terms, so a refusal names the field the
+caller sent. Unknown fields fail with ``<path>: Extra inputs are not
+permitted``. The accepted-but-inert set is ``metadata``, ``cache_control`` in
+every position, ``thinking.display: "summarized"`` and the tool flag
+``eager_input_streaming``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import math
+import re
+from collections.abc import AsyncIterator, Iterable
+from dataclasses import dataclass
+from http import HTTPStatus
+from typing import Any
+
+from fastapi import HTTPException
+
+from sie_server.api.generate import _parse_native_grammar
+
+SUPPORTED_ANTHROPIC_VERSION = "2023-06-01"
+MAX_TOOLS = 64
+THINKING_SIGNATURE = "sie-unsigned"
+MAX_RETRY_AFTER_S = 60
+PING_INTERVAL_S = 10.0
+SYSTEM_TURN_REFUSAL = 'role "system" is not supported in messages; use the top-level system parameter'
+CONTEXT_MANAGEMENT_REFUSAL = (
+ "context_management: Extra inputs are not permitted (Claude Code: set CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1)"
+)
+
+_MAX_TOOL_NAME_LEN = 64
+_MAX_USER_ID_CHARS = 512
+_MIN_THINKING_BUDGET = 1024
+_IMAGE_MEDIA_TYPES = ("image/jpeg", "image/png", "image/gif", "image/webp")
+_U32_MAX = (1 << 32) - 1
+_U64_MAX = (1 << 64) - 1
+_I64_MIN = -(1 << 63)
+_I64_MAX = (1 << 63) - 1
+_TOP_LEVEL_FIELDS = frozenset(
+ {
+ "model",
+ "max_tokens",
+ "messages",
+ "system",
+ "stop_sequences",
+ "temperature",
+ "top_p",
+ "top_k",
+ "stream",
+ "tools",
+ "tool_choice",
+ "thinking",
+ "metadata",
+ "cache_control",
+ }
+)
+_KNOWN_BLOCK_TYPES = frozenset(
+ {
+ "text",
+ "image",
+ "tool_result",
+ "tool_use",
+ "thinking",
+ "redacted_thinking",
+ "document",
+ "search_result",
+ "container_upload",
+ "server_tool_use",
+ "web_search_tool_result",
+ "web_fetch_tool_result",
+ "code_execution_tool_result",
+ "bash_code_execution_tool_result",
+ "text_editor_code_execution_tool_result",
+ "tool_search_tool_result",
+ "mcp_tool_use",
+ "mcp_tool_result",
+ }
+)
+# Unicode White_Space, the set Rust's ``str::trim`` strips.
+_WHITESPACE = frozenset(
+ chr(code)
+ for code in (
+ *range(0x09, 0x0E),
+ 0x20,
+ 0x85,
+ 0xA0,
+ 0x1680,
+ *range(0x2000, 0x200B),
+ 0x2028,
+ 0x2029,
+ 0x202F,
+ 0x205F,
+ 0x3000,
+ )
+)
+_LEADING_DIGITS = re.compile(r"[0-9]+")
+_FORWARDED_HEADERS = frozenset(
+ {
+ "x-sie-request-id",
+ "x-sie-served-by",
+ "x-sie-upstream",
+ "x-sie-fallback-reason",
+ "x-sie-fallback-error",
+ "x-sie-version",
+ "x-sie-server-version",
+ "x-sie-worker",
+ "x-queue-publish-time",
+ "x-queue-wait-time",
+ "x-queue-time",
+ "x-sie-model-revision",
+ "x-sie-execution-identity-sha256",
+ "x-sie-execution-binding-sha256",
+ "x-inference-time",
+ "x-tokenization-time",
+ "x-postprocessing-time",
+ "x-payload-fetch-time",
+ }
+)
+_ERROR_HEADERS = _FORWARDED_HEADERS | {"x-sie-error-code", "x-sie-error-version", "retry-after", "www-authenticate"}
+_ERROR_TYPES: dict[int, str] = {
+ HTTPStatus.UNAUTHORIZED: "authentication_error",
+ HTTPStatus.PAYMENT_REQUIRED: "billing_error",
+ HTTPStatus.FORBIDDEN: "permission_error",
+ HTTPStatus.NOT_FOUND: "not_found_error",
+ HTTPStatus.REQUEST_TIMEOUT: "timeout_error",
+ HTTPStatus.GATEWAY_TIMEOUT: "timeout_error",
+ HTTPStatus.REQUEST_ENTITY_TOO_LARGE: "request_too_large",
+ HTTPStatus.TOO_MANY_REQUESTS: "rate_limit_error",
+ HTTPStatus.SERVICE_UNAVAILABLE: "overloaded_error",
+ 529: "overloaded_error",
+}
+_SIE_CODES: dict[int, str] = {
+ HTTPStatus.UNAUTHORIZED: "UNAUTHORIZED",
+ HTTPStatus.FORBIDDEN: "FORBIDDEN",
+ HTTPStatus.NOT_FOUND: "NOT_FOUND",
+ HTTPStatus.REQUEST_ENTITY_TOO_LARGE: "PAYLOAD_TOO_LARGE",
+}
+
+
+class MessagesError(Exception):
+ """A refusal decided in Anthropic terms: the status and the client-facing message."""
+
+ def __init__(self, message: str, status: int = 400) -> None:
+ super().__init__(message)
+ self.status = status
+ self.message = message
+
+
+@dataclass(frozen=True)
+class ChatTranslation:
+ """A translated request."""
+
+ chat: dict[str, Any]
+ model: str
+ stream: bool
+ first_image: str | None
+ """Anthropic path of the first image block, named if the model refuses image input."""
+
+
+@dataclass(frozen=True)
+class ErrorContext:
+ """What the Messages route knows about a request that the chat route's error cannot say."""
+
+ first_image: str | None = None
+
+
+def is_forwarded_header(name: str) -> bool:
+ """Whether a chat answer header is copied onto the Messages answer."""
+ return name.lower() in _FORWARDED_HEADERS
+
+
+def json_text(value: Any) -> str:
+ """Compact JSON, as the gateway writes it."""
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
+
+
+def parse_json(text: str | bytes) -> Any:
+ """Parse strict JSON: no ``NaN`` or ``Infinity``, as the gateway parses it."""
+ return json.loads(text, parse_constant=_reject_constant)
+
+
+def _reject_constant(constant: str) -> Any:
+ raise ValueError(f"{constant} is not valid JSON")
+
+
+def _is_int(value: Any) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool)
+
+
+def _as_u64(value: Any) -> int | None:
+ return value if _is_int(value) and 0 <= value <= _U64_MAX else None
+
+
+def _as_i64(value: Any) -> int | None:
+ return value if _is_int(value) and _I64_MIN <= value <= _I64_MAX else None
+
+
+def _as_f64(value: Any) -> float | None:
+ if isinstance(value, bool) or not isinstance(value, int | float):
+ return None
+ try:
+ return float(value)
+ except OverflowError:
+ return None
+
+
+def _is_blank(text: str) -> bool:
+ return all(char in _WHITESPACE for char in text)
+
+
+def _invalid(message: str) -> MessagesError:
+ return MessagesError(message)
+
+
+def _extra(path: str) -> MessagesError:
+ return _invalid(f"{path}: Extra inputs are not permitted")
+
+
+def _required(path: str) -> MessagesError:
+ return _invalid(f"{path}: Field required")
+
+
+def _object(value: Any, path: str) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ raise _invalid(f"{path}: Input should be a valid dictionary")
+ return value
+
+
+def _only_keys(mapping: dict[str, Any], allowed: Iterable[str], path: str) -> None:
+ allowed_keys = frozenset(allowed)
+ for key in mapping:
+ if key not in allowed_keys:
+ raise _extra(f"{path}.{key}")
+
+
+def _string(mapping: dict[str, Any], key: str, path: str) -> str:
+ value = mapping.get(key)
+ if value is None:
+ raise _required(f"{path}.{key}")
+ if not isinstance(value, str):
+ raise _invalid(f"{path}.{key}: Input should be a valid string")
+ return value
+
+
+def _cache_control(mapping: dict[str, Any], path: str) -> None:
+ value = mapping.get("cache_control")
+ if value is not None and not isinstance(value, dict):
+ raise _invalid(f"{path}.cache_control: Input should be a valid dictionary")
+
+
+def _citations(mapping: dict[str, Any], path: str) -> None:
+ value = mapping.get("citations")
+ if value is None or value == []:
+ return
+ raise _invalid(f"{path}.citations: citations are not supported")
+
+
+class _Parts:
+ """Text accumulated in one turn, with image parts kept in order."""
+
+ def __init__(self) -> None:
+ self.items: list[tuple[str, str]] = []
+
+ def text(self, text: str) -> None:
+ if not text:
+ return
+ if self.items and self.items[-1][0] == "text":
+ self.items[-1] = ("text", self.items[-1][1] + text)
+ else:
+ self.items.append(("text", text))
+
+ def image(self, data_uri: str) -> None:
+ self.items.append(("image", data_uri))
+
+ def content(self) -> str | list[dict[str, Any]]:
+ if all(kind == "text" for kind, _ in self.items):
+ return "".join(value for _, value in self.items)
+ return [
+ {"type": "text", "text": value} if kind == "text" else {"type": "image_url", "image_url": {"url": value}}
+ for kind, value in self.items
+ ]
+
+
+def messages_to_chat(body: Any, anthropic_version: str | None) -> ChatTranslation:
+ """Translate an Anthropic Messages body into a chat completions body.
+
+ ``anthropic_version`` is the ``anthropic-version`` header, absent or
+ ``2023-06-01``.
+
+ Raises:
+ MessagesError: The request is refused, with the Anthropic wording.
+ """
+ if anthropic_version is not None and anthropic_version != SUPPORTED_ANTHROPIC_VERSION:
+ raise _invalid(f"anthropic-version: only {SUPPORTED_ANTHROPIC_VERSION} is supported")
+ if not isinstance(body, dict):
+ raise _invalid("body: Input should be a valid dictionary")
+ for key in body:
+ if key in _TOP_LEVEL_FIELDS:
+ continue
+ if key == "output_config":
+ _output_config(body[key])
+ elif key == "context_management":
+ raise _invalid(CONTEXT_MANAGEMENT_REFUSAL)
+ else:
+ raise _extra(key)
+
+ model = body.get("model")
+ if model is None:
+ raise _required("model")
+ if not isinstance(model, str):
+ raise _invalid("model: Input should be a valid string")
+ if not model:
+ raise _invalid("model: String should have at least 1 character")
+ max_tokens = _max_tokens(body.get("max_tokens"))
+ stream = body.get("stream")
+ if stream is None:
+ stream = False
+ elif not isinstance(stream, bool):
+ raise _invalid("stream: Input should be a valid boolean")
+ temperature = _bounded_number(body, "temperature", low_inclusive=True)
+ top_p = _bounded_number(body, "top_p", low_inclusive=False)
+ top_k = _top_k(body.get("top_k"))
+ stop = _stop_sequences(body)
+ _metadata(body)
+ cache_control = body.get("cache_control")
+ if cache_control is not None and not isinstance(cache_control, dict):
+ raise _invalid("cache_control: Input should be a valid dictionary")
+ include_reasoning = _thinking(body, max_tokens)
+ tools, tool_names = _tools(body)
+ tool_choice, parallel_tool_calls = _tool_choice(body, tool_names)
+
+ first_image: list[str] = []
+ chat_messages: list[dict[str, Any]] = []
+ system = _system(body)
+ if system is not None:
+ chat_messages.append({"role": "system", "content": system})
+ messages = body.get("messages")
+ if messages is None:
+ raise _required("messages")
+ if not isinstance(messages, list):
+ raise _invalid("messages: Input should be a valid list")
+ if not messages:
+ raise _invalid("messages: List should have at least 1 item")
+ for index, message in enumerate(messages):
+ _translate_message(message, index, chat_messages, first_image)
+ last = messages[-1]
+ if isinstance(last, dict) and last.get("role") == "assistant":
+ raise _invalid(
+ "messages: assistant message prefill is not supported; the conversation must end with a user message"
+ )
+
+ chat: dict[str, Any] = {"model": model, "messages": chat_messages, "max_tokens": max_tokens}
+ if stop is not None:
+ chat["stop"] = stop
+ if temperature is not None:
+ chat["temperature"] = temperature
+ if top_p is not None:
+ chat["top_p"] = top_p
+ if top_k is not None:
+ chat["top_k"] = top_k
+ chat["stream"] = stream
+ if stream:
+ chat["stream_options"] = {"include_usage": True}
+ if tools is not None:
+ chat["tools"] = tools
+ if tool_choice is not None:
+ chat["tool_choice"] = tool_choice
+ if parallel_tool_calls is not None:
+ chat["parallel_tool_calls"] = parallel_tool_calls
+ chat["include_reasoning"] = include_reasoning
+ return ChatTranslation(chat=chat, model=model, stream=stream, first_image=first_image[0] if first_image else None)
+
+
+def _output_config(value: Any) -> None:
+ if value is None:
+ return
+ for key in _object(value, "output_config"):
+ raise _extra(f"output_config.{key}")
+
+
+def _max_tokens(value: Any) -> int:
+ if value is None:
+ raise _required("max_tokens")
+ tokens = _as_u64(value)
+ if tokens == 0:
+ raise _invalid("max_tokens: Input should be greater than or equal to 1")
+ if tokens is not None and tokens <= _U32_MAX:
+ return tokens
+ signed = _as_i64(value)
+ if signed is not None and signed < 1:
+ raise _invalid("max_tokens: Input should be greater than or equal to 1")
+ raise _invalid("max_tokens: Input should be a valid integer")
+
+
+def _bounded_number(body: dict[str, Any], key: str, *, low_inclusive: bool) -> Any:
+ value = body.get(key)
+ if value is None:
+ return None
+ number = _as_f64(value)
+ if number is None or not math.isfinite(number):
+ raise _invalid(f"{key}: Input should be a valid number")
+ if low_inclusive and number < 0.0:
+ raise _invalid(f"{key}: Input should be greater than or equal to 0")
+ if not low_inclusive and number <= 0.0:
+ raise _invalid(f"{key}: Input should be greater than 0")
+ if number > 1.0:
+ raise _invalid(f"{key}: Input should be less than or equal to 1")
+ return value
+
+
+def _top_k(value: Any) -> int | None:
+ if value is None:
+ return None
+ k = _as_u64(value)
+ if k is not None:
+ if 1 <= k <= _U32_MAX:
+ return k
+ raise _invalid("top_k: Input should be greater than or equal to 1")
+ if _as_i64(value) is not None:
+ raise _invalid("top_k: Input should be greater than or equal to 1")
+ raise _invalid("top_k: Input should be a valid integer")
+
+
+def _stop_sequences(body: dict[str, Any]) -> list[str] | None:
+ value = body.get("stop_sequences")
+ if value is None:
+ return None
+ if not isinstance(value, list):
+ raise _invalid("stop_sequences: Input should be a valid list")
+ stop: list[str] = []
+ for index, item in enumerate(value):
+ if not isinstance(item, str):
+ raise _invalid(f"stop_sequences.{index}: Input should be a valid string")
+ stop.append(item)
+ return stop or None
+
+
+def _metadata(body: dict[str, Any]) -> None:
+ value = body.get("metadata")
+ if value is None:
+ return
+ metadata = _object(value, "metadata")
+ _only_keys(metadata, ("user_id",), "metadata")
+ user_id = metadata.get("user_id")
+ if user_id is None:
+ return
+ if not isinstance(user_id, str):
+ raise _invalid("metadata.user_id: Input should be a valid string")
+ if len(user_id) > _MAX_USER_ID_CHARS:
+ raise _invalid(f"metadata.user_id: String should have at most {_MAX_USER_ID_CHARS} characters")
+
+
+def _thinking(body: dict[str, Any], max_tokens: int) -> bool:
+ """Whether the request opts into public reasoning."""
+ value = body.get("thinking")
+ if value is None:
+ return False
+ thinking = _object(value, "thinking")
+ kind = thinking.get("type")
+ if kind is None:
+ raise _required("thinking.type")
+ if not isinstance(kind, str):
+ raise _invalid("thinking.type: Input should be a valid string")
+ path = f"thinking.{kind}"
+ if kind == "enabled":
+ _only_keys(thinking, ("type", "budget_tokens", "display"), path)
+ raw_budget = thinking.get("budget_tokens")
+ if raw_budget is None:
+ raise _required(f"{path}.budget_tokens")
+ budget = _as_u64(raw_budget)
+ if budget is None:
+ raise _invalid(f"{path}.budget_tokens: Input should be a valid integer")
+ if budget < _MIN_THINKING_BUDGET:
+ raise _invalid(f"{path}.budget_tokens: Input should be greater than or equal to {_MIN_THINKING_BUDGET}")
+ if budget >= max_tokens:
+ raise _invalid(f"{path}.budget_tokens: must be less than max_tokens")
+ elif kind == "adaptive":
+ _only_keys(thinking, ("type", "display"), path)
+ elif kind == "disabled":
+ _only_keys(thinking, ("type",), path)
+ return False
+ elif kind == "between_tools":
+ raise _invalid('"thinking.type.between_tools" is not supported for this model.')
+ else:
+ raise _invalid("thinking.type: Input should be 'enabled', 'adaptive' or 'disabled'")
+ display = thinking.get("display")
+ if display is None or display == "summarized":
+ return True
+ if display == "omitted":
+ return False
+ raise _invalid(f"{path}.display: Input should be 'summarized' or 'omitted'")
+
+
+def _system(body: dict[str, Any]) -> str | None:
+ value = body.get("system")
+ if value is None:
+ return None
+ if isinstance(value, str):
+ text = value
+ elif isinstance(value, list):
+ pieces: list[str] = []
+ for index, raw in enumerate(value):
+ path = f"system.{index}"
+ block = _object(raw, path)
+ kind = block.get("type")
+ if not isinstance(kind, str):
+ raise _required(f"{path}.type")
+ if kind != "text":
+ raise _invalid(f"{path}.type: Input should be 'text'")
+ _only_keys(block, ("type", "text", "cache_control", "citations"), path)
+ _cache_control(block, path)
+ _citations(block, path)
+ pieces.append(_string(block, "text", path))
+ text = "".join(pieces)
+ else:
+ raise _invalid("system: Input should be a valid string or list")
+ return text or None
+
+
+def _tools(body: dict[str, Any]) -> tuple[list[dict[str, Any]] | None, list[str]]:
+ value = body.get("tools")
+ if value is None:
+ return None, []
+ if not isinstance(value, list):
+ raise _invalid("tools: Input should be a valid list")
+ if len(value) > MAX_TOOLS:
+ raise _invalid(f"tools: at most {MAX_TOOLS} tools are supported, got {len(value)}")
+ tools: list[dict[str, Any]] = []
+ names: list[str] = []
+ for index, raw in enumerate(value):
+ path = f"tools.{index}"
+ tool = _object(raw, path)
+ kind = tool.get("type")
+ if kind is not None and kind != "custom":
+ if not isinstance(kind, str):
+ raise _invalid(f"{path}.type: Input should be a valid string")
+ raise _invalid(
+ f"{path}.type: tool type '{kind}' is not supported; only custom tools with an input_schema are"
+ )
+ _only_keys(
+ tool, ("type", "name", "description", "input_schema", "cache_control", "eager_input_streaming"), path
+ )
+ _cache_control(tool, path)
+ eager = tool.get("eager_input_streaming")
+ if eager is not None and not isinstance(eager, bool):
+ raise _invalid(f"{path}.eager_input_streaming: Input should be a valid boolean")
+ name = _string(tool, "name", path)
+ valid_chars = bool(name) and all(char.isascii() and (char.isalnum() or char in "_-") for char in name)
+ if valid_chars and len(name) > _MAX_TOOL_NAME_LEN:
+ raise _invalid(f"{path}.name: tool names longer than {_MAX_TOOL_NAME_LEN} characters are not supported")
+ if not valid_chars:
+ raise _invalid(f"{path}.name: String should match pattern '^[a-zA-Z0-9_-]{{1,{_MAX_TOOL_NAME_LEN}}}$'")
+ function: dict[str, Any] = {"name": name}
+ description = tool.get("description")
+ if description is not None:
+ if not isinstance(description, str):
+ raise _invalid(f"{path}.description: Input should be a valid string")
+ function["description"] = description
+ schema = tool.get("input_schema")
+ if schema is None:
+ raise _required(f"{path}.input_schema")
+ if not isinstance(schema, dict):
+ raise _invalid(f"{path}.input_schema: Input should be a valid dictionary")
+ try:
+ _parse_native_grammar({"json_schema": schema})
+ except HTTPException:
+ raise _invalid(
+ f"{path}.input_schema: the schema uses an unsupported JSON Schema keyword (if, then, else, "
+ "$dynamicRef, unevaluatedProperties, dependentSchemas) or exceeds the size or depth limits"
+ ) from None
+ function["parameters"] = schema
+ tools.append({"type": "function", "function": function})
+ names.append(name)
+ return (tools or None), names
+
+
+def _tool_choice(body: dict[str, Any], tool_names: list[str]) -> tuple[Any, bool | None]:
+ value = body.get("tool_choice")
+ if value is None:
+ return None, None
+ choice = _object(value, "tool_choice")
+ kind = choice.get("type")
+ if kind is None:
+ raise _required("tool_choice.type")
+ if not isinstance(kind, str):
+ raise _invalid("tool_choice.type: Input should be a valid string")
+ path = f"tool_choice.{kind}"
+ translated: Any
+ if kind in ("auto", "any", "none"):
+ _only_keys(choice, ("type", "disable_parallel_tool_use"), path)
+ translated = {"auto": "auto", "any": "required", "none": "none"}[kind]
+ elif kind == "tool":
+ _only_keys(choice, ("type", "name", "disable_parallel_tool_use"), path)
+ name = _string(choice, "name", path)
+ if name not in tool_names:
+ raise _invalid(f"{path}.name: tool '{name}' is not declared in tools")
+ translated = {"type": "function", "function": {"name": name}}
+ else:
+ raise _invalid("tool_choice.type: Input should be 'auto', 'any', 'tool' or 'none'")
+ disable = choice.get("disable_parallel_tool_use")
+ if disable is not None and not isinstance(disable, bool):
+ raise _invalid(f"{path}.disable_parallel_tool_use: Input should be a valid boolean")
+ parallel = False if disable is True else None
+ if not tool_names:
+ if kind in ("auto", "none"):
+ return None, None
+ raise _invalid(f"{path}: tool_choice requires tools")
+ return translated, parallel
+
+
+def _translate_message(message: Any, index: int, out: list[dict[str, Any]], first_image: list[str]) -> None:
+ path = f"messages.{index}"
+ message = _object(message, path)
+ role = message.get("role")
+ if role is None:
+ raise _required(f"{path}.role")
+ if not isinstance(role, str):
+ raise _invalid(f"{path}.role: Input should be a valid string")
+ if role == "system":
+ raise _invalid(f"{path}.role: {SYSTEM_TURN_REFUSAL}")
+ if role not in ("user", "assistant"):
+ raise _invalid(f"{path}.role: Input should be 'user' or 'assistant'")
+ _only_keys(message, ("role", "content"), path)
+ content = message.get("content")
+ if content is None:
+ raise _required(f"{path}.content")
+ if isinstance(content, str):
+ out.append({"role": role, "content": content})
+ return
+ if not isinstance(content, list):
+ raise _invalid(f"{path}.content: Input should be a valid string or list")
+ if not content:
+ raise _invalid(f"{path}.content: List should have at least 1 item")
+ if role == "user":
+ _user_blocks(content, path, out, first_image)
+ else:
+ _assistant_blocks(content, path, out)
+
+
+def _block_type(block: dict[str, Any], path: str) -> str:
+ kind = block.get("type")
+ if kind is None:
+ raise _required(f"{path}.type")
+ if not isinstance(kind, str):
+ raise _invalid(f"{path}.type: Input should be a valid string")
+ return kind
+
+
+def _unsupported_block(path: str, kind: str) -> MessagesError:
+ if kind in _KNOWN_BLOCK_TYPES:
+ return _invalid(f"{path}.{kind}: content blocks of type '{kind}' are not supported here")
+ return _invalid(f"{path}.type: Input tag '{kind}' found using 'type' does not match any of the expected tags")
+
+
+def _text_block(block: dict[str, Any], path: str) -> str:
+ path = f"{path}.text"
+ _only_keys(block, ("type", "text", "cache_control", "citations"), path)
+ _cache_control(block, path)
+ _citations(block, path)
+ return _string(block, "text", path)
+
+
+def _image_block(block: dict[str, Any], path: str) -> str:
+ path = f"{path}.image"
+ _only_keys(block, ("type", "source", "cache_control"), path)
+ _cache_control(block, path)
+ raw_source = block.get("source")
+ if raw_source is None:
+ raise _required(f"{path}.source")
+ source = _object(raw_source, f"{path}.source")
+ kind = source.get("type")
+ if kind in ("url", "file"):
+ raise _invalid(f"{path}.source: only base64 image sources are supported")
+ if kind != "base64":
+ raise _invalid(f"{path}.source.type: Input should be 'base64'")
+ base64_path = f"{path}.source.base64"
+ _only_keys(source, ("type", "media_type", "data"), base64_path)
+ media_type = _string(source, "media_type", base64_path)
+ if media_type not in _IMAGE_MEDIA_TYPES:
+ raise _invalid(
+ f"{base64_path}.media_type: Input should be 'image/jpeg', 'image/png', 'image/gif' or 'image/webp'"
+ )
+ data = _string(source, "data", base64_path)
+ return f"data:{media_type};base64,{data}"
+
+
+def _user_blocks(blocks: list[Any], path: str, out: list[dict[str, Any]], first_image: list[str]) -> None:
+ tool_messages: list[dict[str, Any]] = []
+ parts = _Parts()
+ tool_images = _Parts()
+ for index, raw in enumerate(blocks):
+ block_path = f"{path}.content.{index}"
+ block = _object(raw, block_path)
+ kind = _block_type(block, block_path)
+ if kind == "text":
+ parts.text(_text_block(block, block_path))
+ elif kind == "image":
+ parts.image(_image_block(block, block_path))
+ if not first_image:
+ first_image.append(f"{block_path}.image")
+ elif kind == "tool_result":
+ result_path = f"{block_path}.tool_result"
+ _only_keys(block, ("type", "tool_use_id", "content", "is_error", "cache_control"), result_path)
+ _cache_control(block, result_path)
+ tool_use_id = _string(block, "tool_use_id", result_path)
+ if not tool_use_id:
+ raise _invalid(f"{result_path}.tool_use_id: String should have at least 1 character")
+ is_error = block.get("is_error")
+ if is_error is not None and not isinstance(is_error, bool):
+ raise _invalid(f"{result_path}.is_error: Input should be a valid boolean")
+ text = _tool_result_content(block.get("content"), result_path, tool_images, first_image)
+ tool_messages.append({"role": "tool", "tool_call_id": tool_use_id, "content": text})
+ else:
+ raise _unsupported_block(block_path, kind)
+ out.extend(tool_messages)
+ combined = _Parts()
+ combined.items = tool_images.items + parts.items
+ if combined.items or not out or out[-1]["role"] != "tool":
+ out.append({"role": "user", "content": combined.content()})
+
+
+def _tool_result_content(content: Any, path: str, images: _Parts, first_image: list[str]) -> str:
+ if content is None:
+ return ""
+ if isinstance(content, str):
+ return content
+ if not isinstance(content, list):
+ raise _invalid(f"{path}.content: Input should be a valid string or list")
+ text: list[str] = []
+ for index, raw in enumerate(content):
+ block_path = f"{path}.content.{index}"
+ block = _object(raw, block_path)
+ kind = _block_type(block, block_path)
+ if kind == "text":
+ text.append(_text_block(block, block_path))
+ elif kind == "image":
+ images.image(_image_block(block, block_path))
+ if not first_image:
+ first_image.append(f"{block_path}.image")
+ else:
+ raise _unsupported_block(block_path, kind)
+ return "".join(text)
+
+
+def _assistant_blocks(blocks: list[Any], path: str, out: list[dict[str, Any]]) -> None:
+ text: list[str] = []
+ tool_calls: list[dict[str, Any]] = []
+ for index, raw in enumerate(blocks):
+ block_path = f"{path}.content.{index}"
+ block = _object(raw, block_path)
+ kind = _block_type(block, block_path)
+ if kind == "text":
+ text.append(_text_block(block, block_path))
+ elif kind == "tool_use":
+ use_path = f"{block_path}.tool_use"
+ _only_keys(block, ("type", "id", "name", "input", "cache_control"), use_path)
+ _cache_control(block, use_path)
+ call_id = _string(block, "id", use_path)
+ name = _string(block, "name", use_path)
+ if not call_id or not name:
+ field = "id" if not call_id else "name"
+ raise _invalid(f"{use_path}.{field}: String should have at least 1 character")
+ arguments = block.get("input")
+ if arguments is None:
+ raise _required(f"{use_path}.input")
+ if not isinstance(arguments, dict):
+ raise _invalid(f"{use_path}.input: Input should be a valid dictionary")
+ tool_calls.append(
+ {"id": call_id, "type": "function", "function": {"name": name, "arguments": json_text(arguments)}}
+ )
+ elif kind == "thinking":
+ _only_keys(block, ("type", "thinking", "signature"), f"{block_path}.thinking")
+ elif kind == "redacted_thinking":
+ _only_keys(block, ("type", "data"), f"{block_path}.redacted_thinking")
+ else:
+ raise _unsupported_block(block_path, kind)
+ joined = "".join(text)
+ if not tool_calls:
+ out.append({"role": "assistant", "content": joined})
+ else:
+ out.append({"role": "assistant", "content": joined or None, "tool_calls": tool_calls})
+
+
+def stop_reason(finish_reason: str | None, has_tool_use: bool) -> str:
+ """The Anthropic ``stop_reason`` for a chat ``finish_reason``."""
+ if finish_reason == "length":
+ return "max_tokens"
+ if finish_reason == "content_filter":
+ return "refusal"
+ if finish_reason in ("tool_calls", "function_call") or has_tool_use:
+ return "tool_use"
+ return "end_turn"
+
+
+def anthropic_usage(usage: Any) -> dict[str, int] | None:
+ """Anthropic usage from a chat usage block.
+
+ ``input_tokens`` excludes the prompt tokens served from the prefix cache,
+ which are reported as ``cache_read_input_tokens``, so the two add up to the
+ chat ``prompt_tokens``.
+ """
+ if not isinstance(usage, dict):
+ return None
+ prompt = _as_u64(usage.get("prompt_tokens"))
+ completion = _as_u64(usage.get("completion_tokens"))
+ if prompt is None or completion is None:
+ return None
+ details = usage.get("prompt_tokens_details")
+ cached = _as_u64(details.get("cached_tokens")) if isinstance(details, dict) else None
+ cached = min(cached or 0, prompt)
+ return {
+ "input_tokens": prompt - cached,
+ "cache_creation_input_tokens": 0,
+ "cache_read_input_tokens": cached,
+ "output_tokens": completion,
+ }
+
+
+def _zero_usage() -> dict[str, int]:
+ return {"input_tokens": 0, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 0}
+
+
+def tool_input(arguments: str) -> dict[str, Any]:
+ """The tool input a chat tool call's ``arguments`` string carries.
+
+ Raises:
+ ValueError: The arguments are not a JSON object.
+ """
+ if _is_blank(arguments):
+ return {}
+ try:
+ parsed = parse_json(arguments)
+ except ValueError:
+ raise ValueError("tool call arguments are not valid JSON") from None
+ if not isinstance(parsed, dict):
+ raise ValueError("tool call arguments are not a JSON object")
+ return parsed
+
+
+def chat_completion_to_message(chat: Any, model: str, request_id: str) -> dict[str, Any]:
+ """Translate a chat completion into a Message.
+
+ ``model`` is the model id the caller sent; ``request_id`` names the answer.
+
+ Raises:
+ ValueError: The chat completion cannot be translated.
+ """
+ choices = chat.get("choices") if isinstance(chat, dict) else None
+ if not isinstance(choices, list) or not choices:
+ raise ValueError("chat completion has no choices")
+ choice = choices[0]
+ if not isinstance(choice, dict) or "message" not in choice:
+ raise ValueError("chat completion choice has no message")
+ message = choice["message"] if isinstance(choice["message"], dict) else {}
+ content: list[dict[str, Any]] = []
+ reasoning = message.get("reasoning_content")
+ if isinstance(reasoning, str) and reasoning:
+ content.append({"type": "thinking", "thinking": reasoning, "signature": THINKING_SIGNATURE})
+ text = message.get("content")
+ if isinstance(text, str) and not _is_blank(text):
+ content.append({"type": "text", "text": text})
+ has_tool_use = False
+ tool_calls = message.get("tool_calls")
+ for call in tool_calls if isinstance(tool_calls, list) else []:
+ call_id = call.get("id") if isinstance(call, dict) else None
+ if not isinstance(call_id, str):
+ raise ValueError("tool call has no id")
+ if "function" not in call:
+ raise ValueError("tool call has no function")
+ function = call["function"]
+ name = function.get("name") if isinstance(function, dict) else None
+ if not isinstance(name, str):
+ raise ValueError("tool call has no name")
+ arguments = function.get("arguments")
+ content.append(
+ {
+ "type": "tool_use",
+ "id": call_id,
+ "name": name,
+ "input": tool_input(arguments if isinstance(arguments, str) else ""),
+ }
+ )
+ has_tool_use = True
+ usage = anthropic_usage(chat.get("usage"))
+ if usage is None:
+ raise ValueError("chat completion has no usage")
+ finish_reason = choice.get("finish_reason")
+ return {
+ "id": f"msg_{request_id}",
+ "type": "message",
+ "role": "assistant",
+ "model": model,
+ "content": content,
+ "stop_reason": stop_reason(finish_reason if isinstance(finish_reason, str) else None, has_tool_use),
+ "stop_sequence": None,
+ "usage": usage,
+ }
+
+
+@dataclass(frozen=True)
+class Event:
+ """One Anthropic SSE event."""
+
+ name: str
+ data: dict[str, Any]
+
+ def encode(self) -> bytes:
+ return f"event: {self.name}\ndata: {json_text(self.data)}\n\n".encode()
+
+
+PING = Event("ping", {"type": "ping"})
+
+
+def _status_for_code(code: str) -> int:
+ """The HTTP status a mid-stream chat error code stands for, which decides the Anthropic error type."""
+ if code in ("invalid_request", "unsupported_field", "context_exceeded", "INPUT_TOO_LONG", "grammar_invalid"):
+ return 400
+ if code == "PAYLOAD_TOO_LARGE":
+ return 413
+ if code in ("rate_limit_exceeded", "COLD_START_RATE_LIMITED"):
+ return 429
+ if code in (
+ "RESOURCE_EXHAUSTED",
+ "QUEUE_FULL",
+ "MODEL_LOADING",
+ "LORA_LOADING",
+ "transport_failure",
+ "provisioning",
+ "QUEUE_UNAVAILABLE",
+ ):
+ return 503
+ if code in (
+ "first_chunk_timeout",
+ "inter_chunk_timeout",
+ "overall_timeout",
+ "GATEWAY_TIMEOUT",
+ "cancelled",
+ "generation_timeout",
+ ):
+ return 504
+ return 500
+
+
+class StreamMachine:
+ """The chat-chunk to Anthropic-event state machine.
+
+ One block is open at a time and block indices are contiguous from 0.
+ """
+
+ def __init__(self, message_id: str, model: str) -> None:
+ self._message_id = message_id
+ self._model = model
+ self._next_index = 0
+ self._open: tuple[str, int, int | None] | None = None
+ self._held_whitespace = ""
+ self._tool_indices: list[int] = []
+ self._finish_reason: str | None = None
+ self._usage: dict[str, int] | None = None
+ self._started = False
+ self.done = False
+ """Whether ``message_stop`` or an ``error`` event has been produced."""
+
+ def start(self) -> list[Event]:
+ """The ``message_start`` event, sent as soon as the chat stream opens."""
+ if self._started:
+ return []
+ self._started = True
+ message = {
+ "id": self._message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": self._model,
+ "content": [],
+ "stop_reason": None,
+ "stop_sequence": None,
+ "usage": _zero_usage(),
+ }
+ return [Event("message_start", {"type": "message_start", "message": message})]
+
+ def on_data(self, data: str) -> list[Event]:
+ """Feed one chat SSE ``data`` payload."""
+ events = self.start()
+ if self.done:
+ return events
+ if data == "[DONE]":
+ self._finish(events)
+ return events
+ try:
+ chunk = parse_json(data)
+ except ValueError:
+ self._fail(events, "api_error", "the generation stream sent a malformed chunk")
+ return events
+ if not isinstance(chunk, dict):
+ chunk = {}
+ error = chunk.get("error")
+ if isinstance(error, dict):
+ code = error.get("code")
+ status = _status_for_code(code if isinstance(code, str) else "")
+ error_type, message, _ = translate_error_body(status, {"error": error}, ErrorContext())
+ self._fail(events, error_type, message)
+ return events
+ choices = chunk.get("choices")
+ if isinstance(choices, list) and choices:
+ choice = choices[0] if isinstance(choices[0], dict) else {}
+ delta = choice.get("delta")
+ delta = delta if isinstance(delta, dict) else {}
+ reasoning = delta.get("reasoning_content")
+ if isinstance(reasoning, str) and reasoning:
+ self._thinking(reasoning, events)
+ text = delta.get("content")
+ if isinstance(text, str) and text:
+ self._text(text, events)
+ calls = delta.get("tool_calls")
+ for call in calls if isinstance(calls, list) else []:
+ problem = self._tool_call(call, events)
+ if problem is not None:
+ self._fail(events, "api_error", problem)
+ return events
+ finish_reason = choice.get("finish_reason")
+ if isinstance(finish_reason, str):
+ self._close(events)
+ self._held_whitespace = ""
+ self._finish_reason = finish_reason
+ usage = anthropic_usage(chunk.get("usage"))
+ if usage is not None:
+ self._usage = usage
+ if self._finish_reason is not None and self._usage is not None:
+ self._complete(events)
+ return events
+
+ def on_end(self) -> list[Event]:
+ """The chat stream ended. A stream that reported a finish completes; any other ending is an ``error``."""
+ events = self.start()
+ if not self.done:
+ self._finish(events)
+ return events
+
+ def on_transport_error(self) -> list[Event]:
+ """The chat stream broke before it ended."""
+ events = self.start()
+ if not self.done:
+ self._fail(events, "api_error", "the generation stream ended unexpectedly")
+ return events
+
+ def _finish(self, events: list[Event]) -> None:
+ if self._finish_reason is not None:
+ self._complete(events)
+ else:
+ self._fail(events, "api_error", "the generation stream ended without a finish reason")
+
+ def _complete(self, events: list[Event]) -> None:
+ self._close(events)
+ delta = {"stop_reason": stop_reason(self._finish_reason, bool(self._tool_indices)), "stop_sequence": None}
+ usage = self._usage if self._usage is not None else _zero_usage()
+ events.append(Event("message_delta", {"type": "message_delta", "delta": delta, "usage": usage}))
+ events.append(Event("message_stop", {"type": "message_stop"}))
+ self.done = True
+
+ def _fail(self, events: list[Event], error_type: str, message: str) -> None:
+ events.append(Event("error", {"type": "error", "error": {"type": error_type, "message": message}}))
+ self.done = True
+
+ def _open_block(
+ self, kind: str, chat_index: int | None, content_block: dict[str, Any], events: list[Event]
+ ) -> None:
+ index = self._next_index
+ self._next_index += 1
+ self._open = (kind, index, chat_index)
+ events.append(
+ Event(
+ "content_block_start", {"type": "content_block_start", "index": index, "content_block": content_block}
+ )
+ )
+
+ def _delta(self, delta: dict[str, Any], events: list[Event]) -> None:
+ if self._open is not None:
+ index = self._open[1]
+ events.append(Event("content_block_delta", {"type": "content_block_delta", "index": index, "delta": delta}))
+
+ def _close(self, events: list[Event]) -> None:
+ if self._open is None:
+ return
+ kind, index, _ = self._open
+ self._open = None
+ if kind == "thinking":
+ signature = {"type": "signature_delta", "signature": THINKING_SIGNATURE}
+ events.append(
+ Event("content_block_delta", {"type": "content_block_delta", "index": index, "delta": signature})
+ )
+ events.append(Event("content_block_stop", {"type": "content_block_stop", "index": index}))
+
+ def _thinking(self, text: str, events: list[Event]) -> None:
+ if self._open is None or self._open[0] != "thinking":
+ self._held_whitespace = ""
+ self._close(events)
+ self._open_block("thinking", None, {"type": "thinking", "thinking": "", "signature": ""}, events)
+ self._delta({"type": "thinking_delta", "thinking": text}, events)
+
+ def _text(self, text: str, events: list[Event]) -> None:
+ if self._open is None or self._open[0] != "text":
+ if _is_blank(text):
+ self._held_whitespace += text
+ return
+ self._close(events)
+ self._open_block("text", None, {"type": "text", "text": ""}, events)
+ first = self._held_whitespace + text
+ self._held_whitespace = ""
+ self._delta({"type": "text_delta", "text": first}, events)
+ return
+ self._delta({"type": "text_delta", "text": text}, events)
+
+ def _tool_call(self, call: Any, events: list[Event]) -> str | None:
+ call = call if isinstance(call, dict) else {}
+ chat_index = _as_u64(call.get("index"))
+ chat_index = 0 if chat_index is None else chat_index
+ function = call.get("function")
+ function = function if isinstance(function, dict) else {}
+ call_id = call.get("id")
+ name = function.get("name")
+ if chat_index not in self._tool_indices:
+ if not isinstance(call_id, str) or not isinstance(name, str):
+ return "a tool call arrived without its id and name"
+ self._held_whitespace = ""
+ self._close(events)
+ self._open_block(
+ "tool_use", chat_index, {"type": "tool_use", "id": call_id, "name": name, "input": {}}, events
+ )
+ self._tool_indices.append(chat_index)
+ arguments = function.get("arguments")
+ if not isinstance(arguments, str) or not arguments:
+ return None
+ if self._open is None or self._open[0] != "tool_use" or self._open[2] != chat_index:
+ return "tool call arguments arrived after another content block started"
+ self._delta({"type": "input_json_delta", "partial_json": arguments}, events)
+ return None
+
+
+class FrameParser:
+ """Splits an SSE byte stream into the ``data`` payloads of its events."""
+
+ def __init__(self) -> None:
+ self._buffer = bytearray()
+
+ def push(self, chunk: bytes) -> list[str]:
+ self._buffer.extend(chunk.replace(b"\r", b""))
+ payloads: list[str] = []
+ while (end := self._buffer.find(b"\n\n")) >= 0:
+ frame = bytes(self._buffer[: end + 2]).decode("utf-8", errors="replace")
+ del self._buffer[: end + 2]
+ data: str | None = None
+ for line in frame.split("\n"):
+ if not line.startswith("data:"):
+ continue
+ rest = line[len("data:") :].removeprefix(" ")
+ data = rest if data is None else f"{data}\n{rest}"
+ if data is not None:
+ payloads.append(data)
+ return payloads
+
+
+async def stream_events(
+ chunks: AsyncIterator[bytes], machine: StreamMachine, ping_interval: float = PING_INTERVAL_S
+) -> AsyncIterator[bytes]:
+ """The Anthropic SSE body for a chat SSE body.
+
+ A ``ping`` goes out whenever no event was sent for ``ping_interval``
+ seconds. An ``error`` event ends the body and closes ``chunks``, so a
+ stream the translation cannot follow stops generating, as a client that
+ goes away does.
+ """
+ loop = asyncio.get_running_loop()
+ parser = FrameParser()
+ pending: asyncio.Future[bytes] | None = None
+ try:
+ for event in machine.start():
+ yield event.encode()
+ deadline = loop.time() + ping_interval
+ while True:
+ if pending is None:
+ pending = asyncio.ensure_future(anext(chunks))
+ timeout = None if machine.done else max(deadline - loop.time(), 0.0)
+ done, _ = await asyncio.wait({pending}, timeout=timeout)
+ if not done:
+ yield PING.encode()
+ deadline = loop.time() + ping_interval
+ continue
+ arrived, pending = pending, None
+ try:
+ chunk = arrived.result()
+ except StopAsyncIteration:
+ for event in machine.on_end():
+ yield event.encode()
+ return
+ except Exception: # noqa: BLE001 - any failure of the chat body ends the stream with an error event
+ for event in machine.on_transport_error():
+ yield event.encode()
+ return
+ for payload in parser.push(chunk):
+ events = machine.on_data(payload)
+ for event in events:
+ yield event.encode()
+ deadline = loop.time() + ping_interval
+ if any(event.name == "error" for event in events):
+ return
+ finally:
+ if pending is not None:
+ pending.cancel()
+ await asyncio.wait({pending})
+ if not pending.cancelled():
+ pending.exception()
+ close = getattr(chunks, "aclose", None)
+ if close is not None:
+ await close()
+
+
+def error_type_for_status(status: int) -> str:
+ """The Anthropic ``error.type`` for an HTTP status."""
+ known = _ERROR_TYPES.get(status)
+ if known is not None:
+ return known
+ if HTTPStatus.BAD_REQUEST <= status < HTTPStatus.INTERNAL_SERVER_ERROR:
+ return "invalid_request_error"
+ return "api_error"
+
+
+def sie_code_for_status(status: int) -> str:
+ """The ``X-SIE-Error-Code`` of a refusal this module decides."""
+ known = _SIE_CODES.get(status)
+ if known is not None:
+ return known
+ if HTTPStatus.BAD_REQUEST <= status < HTTPStatus.INTERNAL_SERVER_ERROR:
+ return "INVALID_REQUEST"
+ return "INTERNAL_SERVER_ERROR"
+
+
+def _default_message(status: int) -> str:
+ messages = {
+ 400: "invalid request",
+ 401: "invalid or missing credential",
+ 402: "payment required",
+ 403: "permission denied",
+ 404: "not found",
+ 405: "method not allowed",
+ 408: "request timed out",
+ 504: "request timed out",
+ 413: "request too large",
+ 429: "rate limited",
+ 503: "overloaded",
+ 529: "overloaded",
+ }
+ return messages.get(status, "internal server error")
+
+
+def envelope(error_type: str, message: str, request_id: str | None) -> dict[str, Any]:
+ """The Anthropic error body."""
+ return {"type": "error", "error": {"type": error_type, "message": message}, "request_id": request_id}
+
+
+def translate_error_body(status: int, body: Any, context: ErrorContext) -> tuple[str, str, str | None]:
+ """The ``(type, message, SIE code)`` an inner error answer becomes.
+
+ ``body`` is the inner answer as JSON: the OpenAI ``{error}`` envelope, the
+ SIE ``{detail}`` envelope, or anything else. Messages are rewritten only
+ where Anthropic clients match the wording: the output cap, a prompt that
+ does not fit, and media the model cannot read.
+ """
+ error_type = error_type_for_status(status)
+ body = body if isinstance(body, dict) else {}
+ inner = body.get("error") if isinstance(body.get("error"), dict) else None
+ if inner is None and isinstance(body.get("detail"), dict):
+ inner = body["detail"]
+ code = inner.get("code") if inner is not None and isinstance(inner.get("code"), str) else None
+ inner_type = inner.get("type") if inner is not None else None
+ param = inner.get("param") if inner is not None and isinstance(inner.get("param"), str) else None
+ message: str | None = None
+ if inner is not None and isinstance(inner.get("message"), str):
+ message = inner["message"]
+ elif isinstance(body.get("detail"), str):
+ message = body["detail"]
+ elif isinstance(body.get("message"), str):
+ message = body["message"]
+ if not message:
+ message = _default_message(status)
+ if status != HTTPStatus.BAD_REQUEST:
+ return error_type, message, code
+ cap = _output_cap(message)
+ if cap is not None:
+ requested, limit = cap
+ return (
+ error_type,
+ f"max_tokens: {requested} > {limit}, which is the maximum allowed number of output tokens for this model",
+ code,
+ )
+ if code in ("context_exceeded", "INPUT_TOO_LONG") or inner_type == "context_length_exceeded":
+ size = _prompt_size(message)
+ if size is None:
+ return error_type, "prompt is too long", code
+ return error_type, f"prompt is too long: {size[0]} tokens > {size[1]} maximum", code
+ if "does not support image input" in message and context.first_image is not None:
+ return error_type, f"{context.first_image}: {message}", code
+ if "does not support tool calling" in message:
+ return error_type, f"tools: {message}", code
+ message = message.replace("max_completion_tokens", "max_tokens")
+ if param is not None:
+ path = _anthropic_param(param)
+ if not message.startswith(f"{path}:"):
+ return error_type, f"{path}: {message}", code
+ return error_type, message, code
+
+
+def _anthropic_param(param: str) -> str:
+ if param == "max_completion_tokens":
+ return "max_tokens"
+ if param == "stop":
+ return "stop_sequences"
+ if param.startswith("tools["):
+ index, separator, field = param[len("tools[") :].partition("].function.")
+ if separator:
+ return f"tools.{index}.{'input_schema' if field == 'parameters' else field}"
+ return param
+
+
+def _leading_number(text: str) -> tuple[int, str] | None:
+ match = _LEADING_DIGITS.match(text)
+ if match is None:
+ return None
+ value = int(match.group())
+ if value > _U64_MAX:
+ return None
+ return value, text[match.end() :]
+
+
+def _output_cap(message: str) -> tuple[int, int] | None:
+ """``(requested, cap)`` from the chat route's or the worker's output-cap refusal."""
+ for prefix in ("max_completion_tokens (", "max_tokens (", "max_new_tokens ("):
+ if not message.startswith(prefix):
+ continue
+ requested = _leading_number(message[len(prefix) :])
+ if requested is None:
+ return None
+ rest = requested[1]
+ for middle in (") exceeds model max_output_tokens (", ") exceeds model cap ("):
+ if rest.startswith(middle):
+ rest = rest[len(middle) :]
+ break
+ else:
+ return None
+ cap = _leading_number(rest)
+ if cap is None or cap[1] != ")":
+ return None
+ return requested[0], cap[0]
+ return None
+
+
+def _prompt_size(message: str) -> tuple[int, int] | None:
+ """``(tokens, limit)`` from ``... = T exceeds context_length (C) ...`` or ``prompt_tokens (T) exceeds ...``."""
+ before, separator, after = message.partition(" exceeds context_length (")
+ if not separator:
+ return None
+ limit = _leading_number(after)
+ if limit is None:
+ return None
+ _, equals, total = before.rpartition("= ")
+ if equals:
+ tokens = _leading_number(total)
+ elif before.startswith("prompt_tokens ("):
+ tokens = _leading_number(before[len("prompt_tokens (") :])
+ else:
+ return None
+ if tokens is None:
+ return None
+ return tokens[0], limit[0]
+
+
+def _is_anthropic_envelope(body: Any) -> bool:
+ return (
+ isinstance(body, dict)
+ and body.get("type") == "error"
+ and isinstance(body.get("error"), dict)
+ and isinstance(body["error"].get("type"), str)
+ )
+
+
+def anthropic_error(
+ status: int, headers: Iterable[tuple[str, str]], body: bytes, context: ErrorContext
+) -> tuple[list[tuple[str, str]], bytes]:
+ """Re-render a non-2xx answer in the Anthropic envelope.
+
+ Returns the answer's headers and body; the status is kept. ``Retry-After``
+ is kept and capped at :data:`MAX_RETRY_AFTER_S`, the longest wait Anthropic
+ clients keep retrying through, and the SIE headers are kept.
+ """
+ try:
+ parsed = parse_json(body) if body else None
+ except (ValueError, UnicodeDecodeError):
+ parsed = None
+ kept = [(name.lower(), value) for name, value in headers if name.lower() in _ERROR_HEADERS]
+ request_id = next((value for name, value in kept if name == "x-sie-request-id"), None) or None
+ if _is_anthropic_envelope(parsed):
+ rendered = body
+ else:
+ error_type, message, code = translate_error_body(status, parsed, context)
+ if code is not None and not any(name == "x-sie-error-code" for name, _ in kept):
+ kept.append(("x-sie-error-code", code))
+ rendered = json_text(envelope(error_type, message, request_id)).encode()
+ retry_after = next((value for name, value in kept if name == "retry-after"), None)
+ kept = [(name, value) for name, value in kept if name != "retry-after"]
+ seconds = _retry_after_seconds(retry_after)
+ if seconds is not None:
+ kept = [(name, value) for name, value in kept if name != "x-should-retry"]
+ kept += [("retry-after", str(seconds)), ("x-should-retry", "true")]
+ kept.append(("content-type", "application/json"))
+ if request_id is not None:
+ kept.append(("request-id", request_id))
+ return kept, rendered
+
+
+def _retry_after_seconds(value: str | None) -> int | None:
+ if value is None:
+ return None
+ text = value.strip()
+ digits = text.removeprefix("+")
+ if not digits or not digits.isascii() or not digits.isdigit() or int(digits) > _U64_MAX:
+ return None
+ return min(max(int(digits), 1), MAX_RETRY_AFTER_S)
+
+
+def is_messages_path(path: str) -> bool:
+ """Whether a path is ``/v1/messages`` or below it."""
+ return path == "/v1/messages" or path.startswith("/v1/messages/")
diff --git a/packages/sie_server/src/sie_server/api/openai_local.py b/packages/sie_server/src/sie_server/api/openai_local.py
index 39f68fadb..55983f2f0 100644
--- a/packages/sie_server/src/sie_server/api/openai_local.py
+++ b/packages/sie_server/src/sie_server/api/openai_local.py
@@ -1562,9 +1562,22 @@ async def chat_completions(
Errors are emitted as top-level OpenAI ``{"error": {...}}`` envelopes
(never FastAPI's ``{"detail": ...}`` wrapper), matching ``/v1/completions``.
"""
+ return await serve_chat_completions(http_request, x_machine_profile)
+
+
+async def serve_chat_completions(
+ http_request: Request,
+ x_machine_profile: str | None,
+ body: dict[str, Any] | None = None,
+) -> Response | StreamingResponse:
+ """Answer a chat completions request exactly as ``/v1/chat/completions`` does.
+
+ ``body`` is the chat request to serve in place of the request's own body,
+ for a route that translates its request onto this one in process.
+ """
async with AsyncExitStack() as lifetime:
try:
- response = await _chat_completions(http_request, x_machine_profile, lifetime)
+ response = await _chat_completions(http_request, x_machine_profile, lifetime, body)
if isinstance(response, JSONResponse) and response.status_code >= status.HTTP_400_BAD_REQUEST:
payload = json.loads(bytes(response.body))
code = payload.get("error", {}).get("code")
@@ -1582,10 +1595,11 @@ async def _chat_completions(
http_request: Request,
x_machine_profile: str | None,
lifetime: AsyncExitStack,
+ chat_body: dict[str, Any] | None = None,
) -> Response | StreamingResponse:
validate_machine_profile_header(x_machine_profile)
- body = await _read_json_body(http_request)
+ body = await _read_json_body(http_request) if chat_body is None else chat_body
model = body.get("model")
if not isinstance(model, str) or not model.strip():
diff --git a/packages/sie_server/src/sie_server/app/app_factory.py b/packages/sie_server/src/sie_server/app/app_factory.py
index 494687320..a66a21a70 100644
--- a/packages/sie_server/src/sie_server/app/app_factory.py
+++ b/packages/sie_server/src/sie_server/app/app_factory.py
@@ -9,6 +9,8 @@ import torch
from fastapi import FastAPI
from sie_server import __version__
+from sie_server.api.anthropic_messages import AnthropicErrorEnvelopeMiddleware
+from sie_server.api.anthropic_messages import router as anthropic_messages_router
from sie_server.api.decisions import router as decisions_router
from sie_server.api.encode import router as encode_router
from sie_server.api.extract import router as extract_router
@@ -99,6 +101,7 @@ class AppFactory:
app.add_middleware(ServerAuthMiddleware, tokens=server_tokens(os.environ))
elif config.bind_host and is_loopback_host(config.bind_host):
app.add_middleware(LoopbackHostMiddleware, allowed_hosts=loopback_host_allowlist(config.bind_host))
+ app.add_middleware(AnthropicErrorEnvelopeMiddleware)
install_upstreams(
load_upstreams(config.upstreams_file) if config.upstreams_file else {},
@@ -139,6 +142,7 @@ class AppFactory:
# Local-only convenience (single-node/dev); intentionally NOT in the published
# openapi.json — see cli.openapi_export. The Rust gateway is the prod API authority.
app.include_router(openai_local_router) # local /v1/chat/completions + /v1/rerank
+ app.include_router(anthropic_messages_router) # local /v1/messages over /v1/chat/completions
setup_custom_openapi_schema(app)
return app
diff --git a/packages/sie_server/src/sie_server/cli.py b/packages/sie_server/src/sie_server/cli.py
index ad9b2b1d7..b60eb1241 100644
--- a/packages/sie_server/src/sie_server/cli.py
+++ b/packages/sie_server/src/sie_server/cli.py
@@ -424,7 +424,8 @@ def openapi_export(
# init, model registry, telemetry, or NATS). NOTE: the direct-container convenience routes
# are intentionally excluded from the committed openapi.json — the ``openai_local`` router
# (/v1/chat/completions + /v1/rerank) proxies managed MLX/SGLang children for single-node
- # serving, while the Rust gateway owns the published production chat contract. The
+ # serving, and /v1/messages is translated onto it, while the Rust gateway owns the
+ # published production chat and Messages contracts. The
# SIE-native ``generate`` route is part of the worker contract and is published here.
app_ = FastAPI(
title="SIE Server",
diff --git a/packages/sie_server/tests/api/test_anthropic_messages_route.py b/packages/sie_server/tests/api/test_anthropic_messages_route.py
new file mode 100644
index 000000000..f64b29c79
--- /dev/null
+++ b/packages/sie_server/tests/api/test_anthropic_messages_route.py
@@ -0,0 +1,457 @@
+"""``POST /v1/messages`` through the server's own app and chat route, on the weightless fake.
+
+The app comes from :class:`AppFactory`, so its middleware, routers and the
+Messages envelope run as ``sie-server serve`` runs them. The model configs and
+the fake adapter come from the catalog; only the registry is a stub. So each
+request is translated, served by the real ``/v1/chat/completions`` code and
+translated back.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from collections.abc import AsyncIterator
+from contextlib import AsyncExitStack
+from functools import cache
+from pathlib import Path
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from fastapi.responses import StreamingResponse
+from fastapi.testclient import TestClient
+from sie_server.adapters.remote._http import RemoteUpstreamError
+from sie_server.api import anthropic_messages
+from sie_server.api.anthropic_translation import StreamMachine
+from sie_server.api.lora import LeasedStreamingResponse
+from sie_server.app.app_factory import AppFactory
+from sie_server.app.app_state_config import AppStateConfig
+from sie_server.config.model import ModelConfig
+from sie_server.core.loader import load_adapter, load_model_configs
+
+MODELS_DIR = Path(__file__).resolve().parents[2] / "models"
+MODEL = "sie-fake:chat"
+QUESTION = "What is the weather in Paris?"
+WEATHER = {
+ "name": "get_weather",
+ "description": "Current weather for a city.",
+ "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
+}
+HEADERS = {"anthropic-version": "2023-06-01", "anthropic-beta": "claude-code-20250219,interleaved-thinking-2025-05-14"}
+TOKEN = "messages-route-token" # noqa: S105 - a test credential
+
+
+@cache
+def _configs() -> dict[str, ModelConfig]:
+ return load_model_configs(MODELS_DIR)
+
+
+def _registry(loading: frozenset[str] = frozenset()) -> MagicMock:
+ configs = {name: _configs()[name] for name in ("sie-fake", MODEL)}
+ adapters = {}
+ for name, config in configs.items():
+ adapter = load_adapter(config, MODELS_DIR, device="cpu")
+ adapter.load("cpu")
+ adapters[name] = adapter
+ registry = MagicMock()
+ registry.device = "cpu"
+ registry.model_names = list(configs)
+ registry.has_model.side_effect = configs.__contains__
+ registry.get_config.side_effect = configs.__getitem__
+ registry.get.side_effect = adapters.__getitem__
+ registry.is_failed.return_value = False
+ registry.is_unloading.return_value = False
+ registry.is_loading.side_effect = loading.__contains__
+ registry.is_loaded.return_value = True
+ registry.adapters = adapters
+ return registry
+
+
+def registry() -> MagicMock:
+ return _registry()
+
+
+def _client(registry: MagicMock, monkeypatch: pytest.MonkeyPatch, *, token: str | None = None) -> TestClient:
+ if token is not None:
+ monkeypatch.setenv("SIE_AUTH_TOKEN", token)
+ app = AppFactory.create_app(AppStateConfig(auth_mode="token" if token else "none"))
+ app.state.registry = registry
+ return TestClient(app)
+
+
+def client(registry: MagicMock, monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ return _client(registry, monkeypatch)
+
+
+def _body(text: str = "Which is larger, 9.11 or 9.9?", **fields: Any) -> dict[str, Any]:
+ return {"model": MODEL, "max_tokens": 64, "messages": [{"role": "user", "content": text}], **fields}
+
+
+def _post(client: TestClient, body: dict[str, Any], headers: dict[str, str] | None = None) -> Any:
+ return client.post("/v1/messages?beta=true", json=body, headers=headers if headers is not None else HEADERS)
+
+
+def _events(response: Any) -> list[dict[str, Any]]:
+ assert response.status_code == 200, response.text
+ assert response.headers["content-type"].startswith("text/event-stream")
+ events = []
+ for frame in response.text.split("\n\n"):
+ if not frame.strip():
+ continue
+ lines = dict(line.split(": ", 1) for line in frame.splitlines())
+ data = json.loads(lines["data"])
+ assert data["type"] == lines["event"]
+ events.append(data)
+ return events
+
+
+def _names(events: list[dict[str, Any]]) -> list[str]:
+ return [event["type"] for event in events]
+
+
+def _chat_events(response: Any) -> list[dict[str, Any]]:
+ assert response.status_code == 200, response.text
+ data = [block.removeprefix("data: ") for block in response.text.split("\n\n") if block.startswith("data: ")]
+ assert data[-1] == "[DONE]"
+ return [json.loads(item) for item in data[:-1]]
+
+
+def _error(response: Any, status: int, error_type: str) -> str:
+ assert response.status_code == status, response.text
+ assert response.headers["content-type"] == "application/json"
+ body = response.json()
+ assert body["type"] == "error"
+ assert body["error"]["type"] == error_type
+ assert body["request_id"] is None
+ return body["error"]["message"]
+
+
+def test_a_buffered_message_matches_the_chat_answer_to_the_same_conversation(client: TestClient) -> None:
+ body = _body(
+ "Reply with a word.",
+ metadata={"user_id": "opaque"},
+ system=[{"type": "text", "text": "Be brief.", "cache_control": {"type": "ephemeral"}}],
+ cache_control={"type": "ephemeral"},
+ )
+ body["messages"][0]["content"] = [
+ {"type": "text", "text": "Reply with a word.", "cache_control": {"type": "ephemeral"}}
+ ]
+ response = _post(client, body)
+ chat = client.post(
+ "/v1/chat/completions",
+ json={
+ "model": MODEL,
+ "max_tokens": 64,
+ "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "Reply with a word."}],
+ },
+ ).json()
+
+ assert response.status_code == 200, response.text
+ assert response.headers["x-sie-served-by"] == "local"
+ assert "request-id" not in response.headers
+ message = response.json()
+ assert message["id"].startswith("msg_")
+ assert len(message["id"]) > len("msg_")
+ assert message["type"] == "message"
+ assert message["role"] == "assistant"
+ assert message["model"] == MODEL
+ assert message["content"] == [{"type": "text", "text": chat["choices"][0]["message"]["content"]}]
+ assert message["stop_reason"] == "end_turn"
+ assert message["stop_sequence"] is None
+ assert message["usage"] == {
+ "input_tokens": chat["usage"]["prompt_tokens"],
+ "cache_creation_input_tokens": 0,
+ "cache_read_input_tokens": 0,
+ "output_tokens": chat["usage"]["completion_tokens"],
+ }
+
+
+def test_a_streamed_tool_turn_opens_thinking_then_tool_use_with_the_chat_usage(client: TestClient) -> None:
+ response = _post(
+ client,
+ _body(QUESTION, stream=True, tools=[WEATHER], tool_choice={"type": "auto"}, thinking={"type": "adaptive"}),
+ )
+ chat = _chat_events(
+ client.post(
+ "/v1/chat/completions",
+ json={
+ "model": MODEL,
+ "max_tokens": 64,
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ "include_reasoning": True,
+ "tools": [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": WEATHER["description"],
+ "parameters": WEATHER["input_schema"],
+ },
+ }
+ ],
+ "tool_choice": "auto",
+ "messages": [{"role": "user", "content": QUESTION}],
+ },
+ )
+ )
+ events = _events(response)
+ starts = [event for event in events if event["type"] == "content_block_start"]
+ deltas = [event["delta"] for event in events if event["type"] == "content_block_delta"]
+ [message_delta] = [event for event in events if event["type"] == "message_delta"]
+
+ assert _names(events)[0] == "message_start"
+ assert events[0]["message"]["usage"]["input_tokens"] == 0
+ assert [start["content_block"]["type"] for start in starts] == ["thinking", "tool_use"]
+ assert starts[1]["content_block"]["id"].startswith("call_")
+ assert starts[1]["content_block"]["name"] == "get_weather"
+ assert "".join(delta["thinking"] for delta in deltas if delta["type"] == "thinking_delta").startswith(
+ "Tools are declared"
+ )
+ assert {"type": "signature_delta", "signature": "sie-unsigned"} in deltas
+ arguments = "".join(delta["partial_json"] for delta in deltas if delta["type"] == "input_json_delta")
+ assert json.loads(arguments) == {"city": QUESTION}
+ assert message_delta["delta"] == {"stop_reason": "tool_use", "stop_sequence": None}
+ assert message_delta["usage"]["input_tokens"] == chat[-1]["usage"]["prompt_tokens"]
+ assert message_delta["usage"]["output_tokens"] == chat[-1]["usage"]["completion_tokens"]
+ assert _names(events)[-2:] == ["message_delta", "message_stop"]
+
+
+def test_a_tool_result_is_answered_in_text_and_replayed_thinking_does_not_reach_the_model(client: TestClient) -> None:
+ result = '{"city": "Paris", "temperature_c": 18}'
+ response = _post(
+ client,
+ _body(
+ tools=[WEATHER],
+ messages=[
+ {"role": "user", "content": QUESTION},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "I should call it.", "signature": "sie-unsigned"},
+ {"type": "tool_use", "id": "call_1", "name": "get_weather", "input": {"city": "Paris"}},
+ ],
+ },
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": result}]},
+ ],
+ ),
+ )
+
+ assert response.status_code == 200, response.text
+ message = response.json()
+ assert message["content"] == [{"type": "text", "text": f"Tool result: {result}"}]
+ assert message["stop_reason"] == "end_turn"
+
+
[email protected]("thinking", [None, {"type": "disabled"}, {"type": "adaptive", "display": "omitted"}])
+def test_reasoning_stays_private_without_the_opt_in(client: TestClient, thinking: dict[str, Any] | None) -> None:
+ fields = {} if thinking is None else {"thinking": thinking}
+ streamed = _events(_post(client, _body(stream=True, **fields)))
+ buffered = _post(client, _body(**fields)).json()
+
+ assert all(event.get("content_block", {}).get("type") != "thinking" for event in streamed)
+ assert [block["type"] for block in buffered["content"]] == ["text"]
+
+
+def test_thinking_opts_into_the_reasoning_on_both_paths(client: TestClient) -> None:
+ streamed = _events(_post(client, _body(stream=True, thinking={"type": "adaptive"})))
+ buffered = _post(client, _body(thinking={"type": "enabled", "budget_tokens": 1024}, max_tokens=2048)).json()
+ reasoning = "".join(
+ event["delta"]["thinking"]
+ for event in streamed
+ if event["type"] == "content_block_delta" and event["delta"]["type"] == "thinking_delta"
+ )
+
+ assert reasoning == "No tool call applies, so answer in text."
+ assert buffered["content"][0] == {"type": "thinking", "thinking": reasoning, "signature": "sie-unsigned"}
+ assert buffered["content"][1]["type"] == "text"
+
+
+def test_max_tokens_cuts_the_answer_with_a_max_tokens_stop(client: TestClient) -> None:
+ message = _post(client, _body("Write a long answer.", max_tokens=3)).json()
+
+ assert message["stop_reason"] == "max_tokens"
+ assert message["usage"]["output_tokens"] == 3
+
+
+def test_a_translation_refusal_reaches_no_engine(client: TestClient, registry: MagicMock) -> None:
+ registry.get.reset_mock()
+ response = _post(client, _body(output_config={"effort": "high"}))
+
+ assert _error(response, 400, "invalid_request_error") == "output_config.effort: Extra inputs are not permitted"
+ assert response.headers["x-sie-error-code"] == "INVALID_REQUEST"
+ registry.get.assert_not_called()
+
+
+ ("body", "status", "error_type", "message"),
+ [
+ (_body(model="sie-conformance/no-such-model"), 404, "not_found_error", None),
+ (
+ _body(max_tokens=5000),
+ 400,
+ "invalid_request_error",
+ "max_tokens: 5000 > 4096, which is the maximum allowed number of output tokens for this model",
+ ),
+ (_body(" ".join(["w"] * 600), model="sie-fake"), 400, "invalid_request_error", "prompt is too long"),
+ (
+ _body(messages=[{"role": "user", "content": "hi"}, {"role": "system", "content": "short answers"}]),
+ 400,
+ "invalid_request_error",
+ 'messages.1.role: role "system" is not supported in messages; use the top-level system parameter',
+ ),
+ ({"model": MODEL, "messages": [{"role": "user", "content": "hi"}]}, 400, "invalid_request_error", None),
+ ],
+ ids=["unknown model", "output cap", "prompt too long", "system turn", "missing max_tokens"],
+)
+def test_refusals_come_back_in_the_anthropic_envelope(
+ client: TestClient, body: dict[str, Any], status: int, error_type: str, message: str | None
+) -> None:
+ for stream in (False, True):
+ refused = _error(_post(client, {**body, "stream": stream}), status, error_type)
+ if message is not None:
+ assert refused.startswith(message), refused
+
+
+def test_a_loading_model_is_overloaded_with_its_retry_after(monkeypatch: pytest.MonkeyPatch) -> None:
+ client = _client(_registry(loading=frozenset({MODEL})), monkeypatch)
+ response = _post(client, _body(stream=True))
+
+ assert _error(response, 503, "overloaded_error") == f"Model '{MODEL}' is loading, please retry"
+ assert response.headers["retry-after"] == "5"
+ assert response.headers["x-should-retry"] == "true"
+ assert response.headers["x-sie-error-code"] == "MODEL_LOADING"
+
+
+def test_paths_below_messages_take_the_envelope_and_other_paths_do_not(client: TestClient) -> None:
+ count = client.post("/v1/messages/count_tokens", json=_body(), headers=HEADERS)
+ wrong_method = client.get("/v1/messages")
+ other = client.post("/v1/unknown", json=_body())
+
+ assert _error(count, 404, "not_found_error") == "Not Found"
+ assert _error(wrong_method, 405, "invalid_request_error") == "Method Not Allowed"
+ assert other.status_code == 404
+ assert other.json() == {"detail": "Not Found"}
+
+
+def test_token_auth_takes_either_header_and_refuses_in_the_anthropic_envelope(
+ registry: MagicMock, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ client = _client(registry, monkeypatch, token=TOKEN)
+ missing = _post(client, _body())
+ chat_missing = client.post(
+ "/v1/chat/completions", json={"model": MODEL, "messages": [{"role": "user", "content": "hi"}]}
+ )
+
+ assert _error(missing, 401, "authentication_error").startswith("Missing credentials")
+ assert missing.headers["www-authenticate"] == "Bearer"
+ assert missing.headers["x-sie-error-code"] == "UNAUTHORIZED"
+ assert chat_missing.status_code == 401
+ assert chat_missing.json()["detail"]["code"] == "UNAUTHORIZED"
+ for credentials in (
+ {"x-api-key": TOKEN},
+ {"authorization": f"Bearer {TOKEN}"},
+ {"authorization": f"Bearer {TOKEN}", "x-api-key": "wrong"},
+ ):
+ assert _post(client, _body(), {**HEADERS, **credentials}).status_code == 200, credentials
+ wrong = _post(client, _body(), {**HEADERS, "authorization": "Bearer wrong", "x-api-key": TOKEN})
+ assert _error(wrong, 401, "authentication_error") == "Invalid token"
+
+
+def _delayed_stream(adapter: Any, delay_s: float, *, after: int = 1, fail: bool = False) -> None:
+ original = adapter.chat_completion_stream
+
+ async def stream(*args: Any, **kwargs: Any) -> AsyncIterator[dict[str, Any]]:
+ sent = 0
+ async for payload in original(*args, **kwargs):
+ if sent == after:
+ await asyncio.sleep(delay_s)
+ if fail:
+ raise RemoteUpstreamError("the scripted engine failed", upstream_reason="upstream_unavailable")
+ sent += 1
+ yield payload
+
+ adapter.chat_completion_stream = stream
+
+
+def test_a_silent_stream_is_kept_alive_with_pings(
+ registry: MagicMock, client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setattr(anthropic_messages, "PING_INTERVAL_S", 0.02)
+ _delayed_stream(registry.adapters[MODEL], 0.2)
+ events = _events(_post(client, _body(stream=True)))
+ names = _names(events)
+
+ assert names[0] == "message_start"
+ assert names.count("ping") >= 2, names
+ assert names[-2:] == ["message_delta", "message_stop"]
+
+
+def test_a_failure_after_output_is_an_error_event(registry: MagicMock, client: TestClient) -> None:
+ _delayed_stream(registry.adapters[MODEL], 0.0, after=2, fail=True)
+ events = _events(_post(client, _body(stream=True, thinking={"type": "adaptive"})))
+
+ assert _names(events)[:2] == ["message_start", "content_block_start"]
+ assert _names(events)[-1] == "error"
+ assert events[-1]["error"]["type"] == "api_error"
+ assert "message_stop" not in _names(events)
+
+
+class _Lease:
+ def __init__(self) -> None:
+ self.released = False
+ self.body_closed = False
+
+ async def body(self) -> AsyncIterator[bytes]:
+ try:
+ yield b'data: {"choices":[{"index":0,"delta":{"content":"x"},"finish_reason":null}]}\n\n'
+ await asyncio.get_running_loop().create_future()
+ finally:
+ self.body_closed = True
+
+ async def answer(self) -> LeasedStreamingResponse:
+ lifetime = AsyncExitStack()
+ lifetime.callback(setattr, self, "released", True)
+ inner = StreamingResponse(self.body(), media_type="text/event-stream")
+ return LeasedStreamingResponse(inner, lifetime)
+
+
+async def _serve(response: Any, *, fail_on: str, after: int = 0) -> list[dict[str, Any]]:
+ sent: list[dict[str, Any]] = []
+
+ async def send(message: dict[str, Any]) -> None:
+ if message["type"] == fail_on and sum(m["type"] == fail_on for m in sent) >= after:
+ raise OSError("the client went away")
+ sent.append(message)
+
+ async def receive() -> dict[str, Any]:
+ await asyncio.get_running_loop().create_future()
+ return {}
+
+ scope = {"type": "http", "asgi": {"version": "3.0", "spec_version": "2.4"}}
+ with pytest.raises(Exception): # noqa: B017, PT011 - Starlette reports the disconnect in its own type
+ await asyncio.wait_for(response(scope, receive, send), 5)
+ return sent
+
+
+async def test_a_client_that_goes_away_mid_stream_ends_the_chat_answer() -> None:
+ lease = _Lease()
+ stream = anthropic_messages._MessagesStream(await lease.answer(), StreamMachine("msg_c", "m"), None)
+
+ sent = await _serve(stream, fail_on="http.response.body", after=2)
+
+ assert any(b"content_block_start" in message.get("body", b"") for message in sent)
+ assert lease.body_closed
+ assert lease.released
+
+
+async def test_a_stream_never_read_still_releases_the_chat_answer() -> None:
+ lease = _Lease()
+ stream = anthropic_messages._MessagesStream(await lease.answer(), StreamMachine("msg_n", "m"), None)
+
+ await _serve(stream, fail_on="http.response.start")
+
+ assert lease.released
diff --git a/packages/sie_server/tests/api/test_anthropic_translation.py b/packages/sie_server/tests/api/test_anthropic_translation.py
new file mode 100644
index 000000000..08fc0749d
--- /dev/null
+++ b/packages/sie_server/tests/api/test_anthropic_translation.py
@@ -0,0 +1,370 @@
+"""The Messages translation replays the vectors the gateway replays.
+
+Every file under ``conformance/anthropic_messages/`` is read by the gateway's
+tests and by these, so a request is accepted, refused and answered the same
+way on both topologies. A translated request must also pass this server's own
+chat validation, as the gateway checks it against its chat seam.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from collections.abc import AsyncIterator
+from pathlib import Path
+from typing import Any
+
+import pytest
+from sie_server.api.anthropic_translation import (
+ MAX_TOOLS,
+ ErrorContext,
+ FrameParser,
+ MessagesError,
+ StreamMachine,
+ anthropic_error,
+ chat_completion_to_message,
+ messages_to_chat,
+ stream_events,
+)
+from sie_server.api.openai_local import (
+ _validate_chat_message_media,
+ _validate_chat_messages,
+ _validate_cuda_chat_body,
+)
+
+VECTORS = Path(__file__).resolve().parents[4] / "conformance" / "anthropic_messages"
+
+
+def _vectors(name: str) -> Any:
+ return json.loads((VECTORS / name).read_text(encoding="utf-8"))
+
+
+def _chat_route_accepts(chat: dict[str, Any]) -> None:
+ _validate_chat_messages(chat["messages"])
+ _validate_chat_message_media(chat["messages"])
+ _validate_cuda_chat_body(chat)
+
+
+def _frames(case: dict[str, Any]) -> list[str]:
+ return [frame if isinstance(frame, str) else json.dumps(frame) for frame in case["frames"]]
+
+
+def _named(events: list[Any]) -> list[dict[str, Any]]:
+ return [{"event": event.name, "data": event.data} for event in events]
+
+
+def _parse_events(body: bytes) -> list[dict[str, Any]]:
+ parsed = []
+ for frame in body.decode().split("\n\n"):
+ if not frame.strip():
+ continue
+ name, data = "", None
+ for line in frame.splitlines():
+ if line.startswith("event: "):
+ name = line[len("event: ") :]
+ elif line.startswith("data: "):
+ data = json.loads(line[len("data: ") :])
+ assert data is not None, frame
+ assert data["type"] == name, frame
+ parsed.append({"event": name, "data": data})
+ return parsed
+
+
+async def _drain(body: AsyncIterator[bytes]) -> bytes:
+ return b"".join([chunk async for chunk in body])
+
+
[email protected]("case", _vectors("request_vectors.json")["accepted"], ids=lambda case: case["name"])
+def test_an_accepted_request_vector_translates_onto_the_chat_body(case: dict[str, Any]) -> None:
+ translation = messages_to_chat(case["body"], case.get("anthropic_version"))
+
+ assert translation.chat == case["chat"]
+ assert translation.first_image == case.get("first_image")
+ _chat_route_accepts(translation.chat)
+
+
[email protected]("case", _vectors("request_vectors.json")["rejected"], ids=lambda case: case["name"])
+def test_a_rejected_request_vector_is_refused_with_its_wording(case: dict[str, Any]) -> None:
+ with pytest.raises(MessagesError) as refused:
+ messages_to_chat(case["body"], case.get("anthropic_version"))
+
+ assert refused.value.status == 400
+ assert refused.value.message == case["message"]
+
+
[email protected]("case", _vectors("claude_code_requests.json")["cases"], ids=lambda case: case["name"])
+def test_a_captured_claude_code_request_translates_or_fails_with_the_recovery_wording(case: dict[str, Any]) -> None:
+ expect = case["expect"]
+ version = case["headers"].get("anthropic-version")
+ if "error" in expect:
+ with pytest.raises(MessagesError) as refused:
+ messages_to_chat(case["body"], version)
+ assert refused.value.message == expect["error"]
+ return
+ translation = messages_to_chat(case["body"], version)
+ chat = expect["chat"]
+ assert [message["role"] for message in translation.chat["messages"]] == chat["roles"]
+ assert translation.chat["stream"] == chat["stream"]
+ assert translation.chat["max_tokens"] == chat["max_tokens"]
+ assert translation.chat["include_reasoning"] == chat["include_reasoning"]
+ assert len(translation.chat.get("tools") or []) == chat["tool_count"]
+ assert translation.chat.get("stop") == chat.get("stop")
+ _chat_route_accepts(translation.chat)
+
+
+def test_tool_count_over_the_limit_is_refused() -> None:
+ tools = [{"name": f"tool_{index}", "input_schema": {"type": "object"}} for index in range(MAX_TOOLS + 1)]
+ body = {"model": "m", "max_tokens": 1, "tools": tools, "messages": [{"role": "user", "content": "x"}]}
+
+ with pytest.raises(MessagesError) as refused:
+ messages_to_chat(body, None)
+
+ assert refused.value.message == "tools: at most 64 tools are supported, got 65"
+
+
[email protected]("case", _vectors("response_vectors.json")["translated"], ids=lambda case: case["name"])
+def test_a_response_vector_translates_the_chat_completion(case: dict[str, Any]) -> None:
+ assert chat_completion_to_message(case["chat"], case["model"], case["request_id"]) == case["message"]
+
+
[email protected]("case", _vectors("response_vectors.json")["faults"], ids=lambda case: case["name"])
+def test_a_faulty_chat_completion_is_not_translated(case: dict[str, Any]) -> None:
+ with pytest.raises(ValueError, match=r"^(chat completion|tool call)"):
+ chat_completion_to_message(case["chat"], "m", "r")
+
+
[email protected]("case", _vectors("stream_vectors.json")["streams"], ids=lambda case: case["name"])
+def test_a_stream_vector_drives_the_state_machine(case: dict[str, Any]) -> None:
+ machine = StreamMachine(case["message_id"], case["model"])
+ events = machine.start()
+ for frame in _frames(case):
+ events += machine.on_data(frame)
+ events += machine.on_end()
+
+ assert _named(events) == case["events"]
+
+
[email protected]("case", _vectors("stream_vectors.json")["streams"], ids=lambda case: case["name"])
+async def test_a_stream_vector_survives_the_sse_body_split_at_any_byte(case: dict[str, Any]) -> None:
+ sse = "".join(f"data: {frame}\n\n:\n\n" for frame in _frames(case)).encode()
+
+ async def chunks() -> AsyncIterator[bytes]:
+ for start in range(0, len(sse), 7):
+ yield sse[start : start + 7]
+
+ body = stream_events(chunks(), StreamMachine(case["message_id"], case["model"]), ping_interval=60.0)
+
+ assert _parse_events(await _drain(body)) == case["events"]
+
+
+def test_the_frame_parser_joins_multi_line_data_and_skips_comments() -> None:
+ parser = FrameParser()
+
+ assert parser.push(b': keep-alive\r\n\r\ndata: {"a"') == []
+ assert parser.push(b":1}\r\n\r\nevent: x\ndata: one\ndata: two\n\n") == ['{"a":1}', "one\ntwo"]
+
+
[email protected]("case", _vectors("error_vectors.json")["errors"], ids=lambda case: case["name"])
+def test_an_error_vector_renders_the_anthropic_envelope(case: dict[str, Any]) -> None:
+ body = b"" if case["body"] is None else json.dumps(case["body"]).encode()
+ headers, content = anthropic_error(
+ case["status"],
+ list((case.get("headers") or {}).items()),
+ body,
+ ErrorContext(first_image=case.get("first_image")),
+ )
+ expect = case["expect"]
+ first = {}
+ for name, value in headers:
+ first.setdefault(name, value)
+
+ assert case["status"] == expect["status"]
+ assert first["content-type"] == "application/json"
+ for name, value in (expect.get("headers") or {}).items():
+ assert first.get(name) == value, name
+ for name in expect.get("absent_headers") or []:
+ assert name not in first, name
+ rendered = json.loads(content)
+ assert rendered["type"] == "error"
+ assert rendered["error"]["type"] == expect["type"]
+ assert rendered["error"]["message"] == expect["message"]
+ assert rendered["request_id"] == expect.get("request_id")
+
+
+_STEPS: dict[str, str] = {
+ "role": json.dumps({"choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": None}]}),
+ "text a": json.dumps({"choices": [{"index": 0, "delta": {"content": "a"}, "finish_reason": None}]}),
+ "text space": json.dumps({"choices": [{"index": 0, "delta": {"content": " "}, "finish_reason": None}]}),
+ "text newline": json.dumps({"choices": [{"index": 0, "delta": {"content": "\n"}, "finish_reason": None}]}),
+ "reasoning": json.dumps({"choices": [{"index": 0, "delta": {"reasoning_content": "r"}, "finish_reason": None}]}),
+ **{
+ f"tool start {index}": json.dumps(
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {
+ "tool_calls": [
+ {
+ "index": index,
+ "id": f"c{index}",
+ "type": "function",
+ "function": {"name": "f", "arguments": ""},
+ }
+ ]
+ },
+ "finish_reason": None,
+ }
+ ]
+ }
+ )
+ for index in (0, 1)
+ },
+ **{
+ f"tool args {index}": json.dumps(
+ {
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"tool_calls": [{"index": index, "function": {"arguments": "{}"}}]},
+ "finish_reason": None,
+ }
+ ]
+ }
+ )
+ for index in (0, 1)
+ },
+ **{
+ f"finish {reason}": json.dumps({"choices": [{"index": 0, "delta": {}, "finish_reason": reason}]})
+ for reason in ("stop", "tool_calls", "length")
+ },
+ "usage": json.dumps({"choices": [], "usage": {"prompt_tokens": 3, "completion_tokens": 2, "total_tokens": 5}}),
+ "error": json.dumps(
+ {
+ "choices": [],
+ "error": {"message": "m", "type": "server_error", "param": None, "code": "RESOURCE_EXHAUSTED"},
+ }
+ ),
+ "done": "[DONE]",
+}
+
+
+def _assert_event_grammar(events: list[dict[str, Any]], context: str) -> None:
+ """Check the event grammar Anthropic clients parse.
+
+ ``message_start``, one block at a time with contiguous indices and matching
+ deltas, then ``message_delta`` and ``message_stop`` or one ``error``, and
+ nothing after.
+ """
+ assert events[0]["event"] == "message_start", context
+ open_block: tuple[int, str] | None = None
+ next_index = 0
+ ended = False
+ for position, event in enumerate(events[1:], start=1):
+ assert not ended, f"{context}: event after the end at {position}"
+ data = event["data"]
+ name = event["event"]
+ if name == "content_block_start":
+ assert open_block is None, f"{context}: two open blocks"
+ assert data["index"] == next_index, context
+ next_index += 1
+ open_block = (data["index"], data["content_block"]["type"])
+ elif name == "content_block_delta":
+ assert open_block is not None, f"{context}: delta without an open block"
+ assert data["index"] == open_block[0], context
+ allowed = {
+ "text": {"text_delta"},
+ "thinking": {"thinking_delta", "signature_delta"},
+ "tool_use": {"input_json_delta"},
+ }[open_block[1]]
+ assert data["delta"]["type"] in allowed, context
+ elif name == "content_block_stop":
+ assert open_block is not None, context
+ assert data["index"] == open_block[0], context
+ open_block = None
+ elif name == "message_delta":
+ assert open_block is None, f"{context}: message_delta with an open block"
+ assert events[position + 1]["event"] == "message_stop", context
+ elif name in ("message_stop", "error"):
+ ended = True
+ else:
+ assert name == "ping", f"{context}: unexpected event {name}"
+ assert ended, f"{context}: no terminal event"
+
+
+def test_any_chat_chunk_sequence_yields_a_valid_event_grammar() -> None:
+ alphabet = list(_STEPS)
+ seed = 0x9E3779B97F4A7C15
+ mask = (1 << 64) - 1
+ for round_number in range(4000):
+ steps = []
+ for _ in range(round_number % 12 + 1):
+ seed ^= (seed << 13) & mask
+ seed ^= seed >> 7
+ seed ^= (seed << 17) & mask
+ steps.append(alphabet[seed % len(alphabet)])
+ machine = StreamMachine("msg_x", "m")
+ events = machine.start()
+ for step in steps:
+ events += machine.on_data(_STEPS[step])
+ events += machine.on_end()
+ _assert_event_grammar(_named(events), f"round {round_number}: {steps}")
+
+
+async def test_a_silent_stream_sends_pings_until_output_arrives() -> None:
+ async def slow() -> AsyncIterator[bytes]:
+ await asyncio.sleep(0.15)
+ yield b'data: {"choices":[{"index":0,"delta":{"content":"x"},"finish_reason":"stop"}]}\n\n'
+ yield b'data: {"choices":[],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2}}\n\n'
+ yield b"data: [DONE]\n\n"
+
+ events = _parse_events(await _drain(stream_events(slow(), StreamMachine("msg_p", "m"), ping_interval=0.02)))
+ names = [event["event"] for event in events]
+ first_block = names.index("content_block_start")
+
+ assert names[0] == "message_start"
+ assert names.count("ping") >= 2, names
+ assert set(names[1:first_block]) == {"ping"}
+ assert names[-1] == "message_stop"
+ _assert_event_grammar(events, "pings")
+
+
+class _Source:
+ """A chat body that records whether it was closed."""
+
+ def __init__(self, chunks: list[bytes]) -> None:
+ self._chunks = list(chunks)
+ self.closed = False
+
+ def __aiter__(self) -> _Source:
+ return self
+
+ async def __anext__(self) -> bytes:
+ if self._chunks:
+ return self._chunks.pop(0)
+ await asyncio.get_running_loop().create_future()
+ raise AssertionError("unreachable")
+
+ async def aclose(self) -> None:
+ self.closed = True
+
+
+async def test_an_error_event_ends_the_body_and_closes_the_chat_body() -> None:
+ source = _Source([b"data: {not json\n\n"])
+
+ body = await asyncio.wait_for(_drain(stream_events(source, StreamMachine("msg_e", "m"), ping_interval=60.0)), 5)
+
+ assert [event["event"] for event in _parse_events(body)] == ["message_start", "error"]
+ assert source.closed
+
+
+async def test_closing_the_messages_body_closes_the_chat_body() -> None:
+ source = _Source([])
+ body = stream_events(source, StreamMachine("msg_d", "m"), ping_interval=60.0)
+
+ first = await anext(body)
+ assert first.startswith(b"event: message_start")
+ assert not source.closed
+ await body.aclose()
+
+ assert source.closed