Inside Anthropic's /v1/messages Wire Protocol: Building Zero-Latency Local Proxy Routers and Semantic Prefix Caches

How Benni-OS/claude-code-router translates Anthropic's /v1/messages, /v1/messages/count_tokens, tool_use/tool_result blocks, and stateful SSE streams into OpenAI-compatible payloads for benni-inference-engine—backed by a sub-millisecond SQLite WAL semantic prefix cache.

Inside Anthropic's /v1/messages Wire Protocol: Building Zero-Latency Local Proxy Routers and Semantic Prefix Caches

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:

Sovereign Routing Architecture: 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) end

3. 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:


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.

Explore Benni-OS/claude-code-router on GitHub →

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.