Anthropic /v1/messages 傳輸協定解析:建構零延遲本機 Proxy 路由器與語義前綴快取
Inside Anthropic's /v1/messages Wire Protocol: Building Zero-Latency Local Proxy Routers and Semantic Prefix Caches
claude-code-router 透過本機 Proxy 將 Anthropic 的 /v1/messages 請求轉換為 OpenAI Chat Completions 格式,並以 SQLite WAL 快取重用語義前綴。它會在 1 毫秒內完成本機 token 計算,並將串流轉換為 Anthropic SSE 事件;命中快取時可重播 SSE 串流,無須推理。
By **Benni Alencar* — Chief AI Systems Architect at Benni OS. Canonical article & interactive benchmarks at benni-os.net.*
1. The Wire-Protocol Gap Between Claude Code and Local Inference
Pointing an Anthropic-native coding agent like Claude Code at a local inference server—whether benni-inference-engine, llama.cpp, or vLLM—fails immediately at the HTTP boundary if you only expose an OpenAI-compatible /v1/chat/completions endpoint. Even when local servers advertise an "Anthropic shim," subtle wire-level mismatches cause silent tool-call drops, broken context-window accounting, or stalled streams.
Anthropic's wire protocol is built around four distinct structural assumptions that do not map 1:1 to OpenAI Chat Completions:
-
Pre-flight Token Budgeting (
POST /v1/messages/count_tokens): Before dispatching heavy multi-file turns, Claude Code calls/v1/messages/count_tokenswith the exactsystem,tools, andmessagespayload to decide whether to compact history. A 404 or inaccurate estimate breaks automatic compaction. -
Top-Level
system& Typed Content Block Arrays: Unlike OpenAI's flat string orrole: "system"message, Anthropic passessystemas a top-level string or array of cache-annotated text blocks, and models every turn'scontentas a polymorphic list oftext,thinking,tool_use, andtool_resultblocks. -
Interleaved Tool Execution Loops: An assistant turn can emit multiple
tool_useblocks alongside reasoning text, and the subsequent user turn must return matchingtool_resultblocks keyed bytool_use_id—which OpenAI servers expect as separaterole: "tool"messages. -
Stateful SSE Frame Lifecycle: Anthropic streaming is an explicit state machine (
message_start→content_block_start→content_block_delta→content_block_stop→message_delta→message_stop) rather than statelessdata: {"choices":[{"delta":...}]}chunks.**Sovereign Routing Architecture:** **[Benni-OS/claude-code-router](https://github.com/Benni-OS/claude-code-router)** sits on `127.0.0.1` as a zero-latency wire-protocol proxy—terminating `/v1/messages` and `/v1/messages/count_tokens`, translating block graphs bidirectionally to `benni-inference-engine`, and short-circuiting repeated prefixes via an embedded SQLite WAL semantic cache.
2. End-to-End Wire Flow: Sequence Architecture
When Claude Code emits a turn with ANTHROPIC_BASE_URL=http://127.0.0.1:8787, every request traverses token counting, prefix-cache lookup, wire translation, and stateful SSE frame synthesis:
sequenceDiagram
autonumber
participant CC as Claude Code Client
participant PR as claude-code-router (Proxy)
participant DB as SQLite WAL Prefix Cache
participant IE as benni-inference-engine
CC->>PR: POST /v1/messages/count_tokens
PR-->>CC: 200 OK {input_tokens: 4820} (<1ms local)
CC->>PR: POST /v1/messages (stream=true, tools, system)
PR->>DB: Lookup normalized prefix SHA-256 + cosine sim
alt Semantic Prefix Cache Hit
DB-->>PR: Cached SSE frame sequence / KV hint
PR-->>CC: Replay Anthropic SSE stream (0ms inference)
else Cache Miss
PR->>PR: Translate system, tool_use, tool_result -> OpenAI JSON
PR->>IE: POST /v1/chat/completions (stream=true)
IE-->>PR: OpenAI SSE chunks (delta.content / delta.tool_calls)
PR-->>CC: Emit message_start -> block_start -> deltas -> message_stop
PR->>DB: Async WAL write (prefix_hash, response_blocks)
end3. Anatomy of Wire Translation: tool_use, tool_result, and count_tokens
Translating system and tools
In Anthropic's request schema, system may be either a plain string or a list of {"type": "text", "text": "...", "cache_control": {"type": "ephemeral"}} objects. The proxy flattens all system blocks into a leading {"role": "system", "content": "..."} message while extracting any cache_control boundaries as prefix-hash checkpoints for the local cache.
Similarly, each Anthropic tool definition ({"name", "description", "input_schema"}) maps to OpenAI's {"type": "function", "function": {"name", "description", "parameters"}} wrapper, while tool_choice translates {"type": "auto"}, {"type": "any"} (→ "required"), and {"type": "tool", "name": "..."} (→ {"type": "function", "function": {"name": "..."}}).
Splitting tool_use and tool_result Blocks
The hardest structural invariant is preserving multi-tool turns. An Anthropic assistant message can contain both a text block and two tool_use blocks. The router packs the text into content and converts each tool_use into an OpenAI tool_calls entry with json.dumps(block["input"]). On the next turn, an Anthropic user message containing tool_result blocks must be exploded into individual role: "tool" messages keyed by tool_call_id before any trailing user text block.
Local /v1/messages/count_tokens
Rather than returning a hardcoded dummy number—which causes Claude Code to either under-utilize context or crash past local KV-cache limits—claude-code-router runs a fast local tokenizer pass over the serialized system prompt, JSON-dumped tool schemas, and message blocks, returning {"input_tokens": count} in under 1 millisecond.
4. Python Wire Translator: Request & SSE State Machine
Below is the core bidirectional translation kernel in Python used inside claude-code-router—covering Anthropic-to-OpenAI payload translation and the zero-buffering SSE state machine that converts OpenAI stream chunks back into strict Anthropic event frames:
import hashlib
import json
from typing import Any, Iterator
def flatten_system_prompt(system: str | list[dict[str, Any]] | None) -> str:
"""Normalize Anthropic top-level system string or block list into plain text."""
if not system:
return ""
if isinstance(system, str):
return system
return "\n".join(b.get("text", "") for b in system if b.get("type") == "text")
def anthropic_to_openai_request(payload: dict[str, Any]) -> dict[str, Any]:
"""Translate an Anthropic /v1/messages payload to OpenAI /v1/chat/completions."""
oai_messages: list[dict[str, Any]] = []
sys_text = flatten_system_prompt(payload.get("system"))
if sys_text:
oai_messages.append({"role": "system", "content": sys_text})
for msg in payload.get("messages", []):
role = msg["role"]
content = msg["content"]
if isinstance(content, str):
oai_messages.append({"role": role, "content": content})
continue
text_parts: list[str] = []
tool_calls: list[dict[str, Any]] = []
tool_results: list[dict[str, Any]] = []
for block in content:
btype = block.get("type")
if btype == "text":
text_parts.append(block.get("text", ""))
elif btype == "tool_use":
tool_calls.append({
"id": block["id"],
"type": "function",
"function": {
"name": block["name"],
"arguments": json.dumps(block.get("input", {}), separators=(",", ":")),
},
})
elif btype == "tool_result":
raw = block.get("content", "")
serialized = raw if isinstance(raw, str) else json.dumps(raw)
tool_results.append({
"role": "tool",
"tool_call_id": block["tool_use_id"],
"content": serialized,
})
if role == "assistant":
oai_messages.append({
"role": "assistant",
"content": "\n".join(text_parts) if text_parts else None,
**({"tool_calls": tool_calls} if tool_calls else {}),
})
else:
# Anthropic puts tool_result inside user messages; OpenAI requires role="tool" first.
oai_messages.extend(tool_results)
if text_parts:
oai_messages.append({"role": "user", "content": "\n".join(text_parts)})
oai_tools = [
{
"type": "function",
"function": {
"name": t["name"],
"description": t.get("description", ""),
"parameters": t.get("input_schema", {"type": "object", "properties": {}}),
},
}
for t in payload.get("tools", [])
]
return {
"model": payload["model"],
"messages": oai_messages,
"max_tokens": payload.get("max_tokens", 4096),
"temperature": payload.get("temperature", 0.0),
"stream": payload.get("stream", False),
**({"tools": oai_tools} if oai_tools else {}),
}
def sse_frame(event: str, data: dict[str, Any]) -> str:
return f"event: {event}\ndata: {json.dumps(data, separators=(',', ':'))}\n\n"
def translate_openai_sse_to_anthropic(
chunks: Iterator[dict[str, Any]],
model: str,
msg_id: str = "msg_local_01",
) -> Iterator[str]:
"""Stateful zero-buffering translator from OpenAI delta chunks to Anthropic SSE."""
yield sse_frame("message_start", {
"type": "message_start",
"message": {
"id": msg_id, "type": "message", "role": "assistant",
"model": model, "content": [], "stop_reason": None,
"usage": {"input_tokens": 0, "output_tokens": 0},
},
})
block_idx = -1
active_type: str | None = None
saw_tool_calls = False
for chunk in chunks:
choice = chunk["choices"][0]
delta = choice.get("delta", {})
if delta.get("content"):
if active_type != "text":
if block_idx >= 0:
yield sse_frame("content_block_stop", {"type": "content_block_stop", "index": block_idx})
block_idx += 1
active_type = "text"
yield sse_frame("content_block_start", {
"type": "content_block_start", "index": block_idx,
"content_block": {"type": "text", "text": ""},
})
yield sse_frame("content_block_delta", {
"type": "content_block_delta", "index": block_idx,
"delta": {"type": "text_delta", "text": delta["content"]},
})
for tc in delta.get("tool_calls", []):
saw_tool_calls = True
if tc.get("id"):
if block_idx >= 0:
yield sse_frame("content_block_stop", {"type": "content_block_stop", "index": block_idx})
block_idx += 1
active_type = "tool_use"
yield sse_frame("content_block_start", {
"type": "content_block_start", "index": block_idx,
"content_block": {
"type": "tool_use", "id": tc["id"],
"name": tc["function"]["name"], "input": {},
},
})
args_part = tc.get("function", {}).get("arguments")
if args_part:
yield sse_frame("content_block_delta", {
"type": "content_block_delta", "index": block_idx,
"delta": {"type": "input_json_delta", "partial_json": args_part},
})
if choice.get("finish_reason"):
if block_idx >= 0:
yield sse_frame("content_block_stop", {"type": "content_block_stop", "index": block_idx})
stop_reason = "tool_use" if saw_tool_calls else "end_turn"
yield sse_frame("message_delta", {
"type": "message_delta",
"delta": {"stop_reason": stop_reason, "stop_sequence": None},
"usage": {"output_tokens": chunk.get("usage", {}).get("completion_tokens", 0)},
})
yield sse_frame("message_stop", {"type": "message_stop"})
break
5. SQLite WAL Semantic Prefix Caching
Agentic coding loops are overwhelmingly repetitive at the prefix level: the CLAUDE.md instructions, 20+ MCP tool schemas, and early repository exploration turns remain byte-identical across dozens of requests. Even when a trailing user prompt changes slightly (e.g., re-running a lint check or asking the same diagnostic question), the prefix hash and semantic embedding remain near-identical.
Benni-OS/claude-code-router pairs exact SHA-256 prefix hashing with a local SQLite Write-Ahead Logging (WAL) store:
-
Non-Blocking Concurrent Reads: Enabling
PRAGMA journal_mode=WAL;andPRAGMA synchronous=NORMAL;lets multiple parallel subagent workers read from the cache simultaneously without write-lock stalls. -
Two-Tier Lookup: First, an O(1) indexed lookup on
prefix_sha256(computed over canonicalizedsystem + tools + prefix_messagesup to the lastcache_controlbreakpoint). Second, for deterministic zero-temperature queries, a normalized cosine similarity check against quantized local embeddings of the trailing prompt. -
KV-Cache Alignment for
benni-inference-engine: Even on a semantic miss, the router passes the matchedprefix_sha256as a slot hint header tobenni-inference-engine, maximizing GPU KV-cache reuse across local llama.cpp / vLLM slots.
6. Wire Protocol Comparison: Anthropic vs. OpenAI vs. claude-code-router
| Protocol Dimension | Anthropic /v1/messages
|
OpenAI /v1/chat/completions
|
Benni-OS/claude-code-router |
|---|---|---|---|
| System Prompt | Top-level string or block array with cache_control
|
role: "system" message inside messages[]
|
Flattens blocks & extracts cache breakpoints |
| Tool Calls & Results |
tool_use & tool_result content blocks |
tool_calls[] + separate role: "tool" turns |
Lossless bidirectional block-to-turn splitter |
| Token Counting | POST /v1/messages/count_tokens |
Not standardized on local servers | Local sub-1ms tokenizer endpoint |
| SSE Streaming | 6-stage typed FSM (content_block_delta) |
Stateless choices[0].delta chunks |
Zero-buffer per-index SSE state machine |
| Prefix Caching | Cloud-side cache_control ephemeral TTL |
Implicit server KV-cache only | SQLite WAL semantic prefix cache + KV hints |
Route Claude Code Locally at Zero Latency
Deploy Benni-OS/claude-code-router in front of benni-inference-engine to translate /v1/messages, count_tokens, and SSE tool streams with SQLite WAL semantic prefix caching.
Frequently Asked Questions
Why can't Anthropic clients like Claude Code talk directly to OpenAI-compatible local servers?
Claude Code speaks Anthropic's /v1/messages and /v1/messages/count_tokens wire protocol, which uses top-level system arrays, typed content blocks (text, thinking, tool_use, tool_result), and a stateful Server-Sent Events (SSE) lifecycle. OpenAI-compatible local servers expect /v1/chat/completions with system messages inside messages[], stringified tool_calls arguments, and stateless chunk deltas.
How does claude-code-router handle /v1/messages/count_tokens locally?
Claude Code issues pre-flight `POST /v1/messages/count_tokens` requests to budget context windows before sending turns. `claude-code-router` intercepts this endpoint locally, serializes system prompts, tool schemas, and message blocks into canonical text, and computes deterministic token counts in sub-millisecond time without hitting an upstream cloud API.
How does SSE streaming translation preserve tool_use blocks without buffering the whole response?
`claude-code-router` maintains a per-request finite state machine that tracks the active `content_block_index`. As OpenAI-style delta chunks arrive from `benni-inference-engine`, text deltas emit `text_delta` events on index 0, while incremental `tool_calls` chunks lazily open a `tool_use` block via `content_block_start` and stream partial JSON arguments as `input_json_delta` frames until `finish_reason` triggers `content_block_stop` and `message_stop`.
Why use SQLite WAL for semantic prefix caching in a local proxy router?
SQLite in Write-Ahead Logging (WAL) mode gives a single-file, zero-daemon embedded cache with concurrent non-blocking reads and atomic prefix-hash lookups. By hashing normalized system prompts, tool schemas, and stable conversation prefixes alongside `cache_control` breakpoints, `claude-code-router` serves repeated pre-flight and deterministic turns in under 1 ms while keeping full local auditability.
Frequently Asked Questions
Why can't Anthropic clients like Claude Code talk directly to OpenAI-compatible local servers?
Claude Code speaks Anthropic's /v1/messages and /v1/messages/count_tokens wire protocol, which uses top-level system arrays, typed content blocks (text, thinking, tool_use, tool_result), and a stateful Server-Sent Events (SSE) lifecycle. OpenAI-compatible local servers expect /v1/chat/completions with system messages inside messages[], stringified tool_calls arguments, and stateless chunk deltas.
How does claude-code-router handle /v1/messages/count_tokens locally?
Claude Code issues pre-flight POST /v1/messages/count_tokens requests to budget context windows before sending turns. claude-code-router intercepts this endpoint locally, serializes system prompts, tool schemas, and message blocks into canonical text, and computes deterministic token counts in sub-millisecond time without hitting an upstream cloud API.
How does SSE streaming translation preserve tool_use blocks without buffering the whole response?
claude-code-router maintains a per-request finite state machine that tracks the active content_block_index. As OpenAI-style delta chunks arrive from benni-inference-engine, text deltas emit text_delta events on index 0, while incremental tool_calls chunks lazily open a tool_use block via content_block_start and stream partial JSON arguments as input_json_delta frames until finish_reason triggers content_block_stop and message_stop.
Why use SQLite WAL for semantic prefix caching in a local proxy router?
SQLite in Write-Ahead Logging (WAL) mode gives a single-file, zero-daemon embedded cache with concurrent non-blocking reads and atomic prefix-hash lookups. By hashing normalized system prompts, tool schemas, and stable conversation prefixes alongside cache_control breakpoints, claude-code-router serves repeated pre-flight and deterministic turns in under 1 ms while keeping full local auditability.
Explore the Benni Master OS Open-Source Ecosystem
- Portal & Articles: https://benni-os.net
- Operator Academy: https://benni-os.net/blog/academy.html
- GitHub Organization: https://github.com/Benni-OS & https://github.com/BenniAlencar
來源:DEV Community · dev.to