Pointing the Anthropic Python SDK at OpenRouter's Anthropic-compatible /api/v1/messages endpoint takes three fixes. Set base_url to https://openrouter.ai/api with no trailing /v1, or the request 404s at /v1/v1/messages. Return tool results as JSON strings, not dicts, or the follow-up request 400s with invalid_union. And prefix model IDs with anthropic/.

We hit all three while wiring a browser-driving agent into production. It uses the SDK's Tool Runner, and our org has no direct Anthropic account, so everything goes through OpenRouter. Each fix below was confirmed with a minimal repro against the live endpoint. The second bug is the one that killed our first real agent run.

Why does a base_url ending in /v1 404 at /v1/v1/messages?

The Anthropic SDK treats base_url as the API root and appends /v1/messages to it. OpenRouter documents its endpoint as https://openrouter.ai/api/v1/messages, so copying the "v1" base URL you'd use for the OpenAI-style API gives you .../api/v1/v1/messages, which 404s. The fix is base_url="https://openrouter.ai/api".

We found this in the SDK's debug log, not by guessing. To make it reproducible without spending tokens, we swapped in a mock transport and printed the URL the SDK actually built (anthropic-python 1.7.0):

import json, httpx2, anthropic

seen = []
def handler(req):
    seen.append(str(req.url))
    return httpx2.Response(200, json={
        "id": "msg_1", "type": "message", "role": "assistant", "model": "x",
        "content": [{"type": "text", "text": "ok"}],
        "stop_reason": "end_turn", "stop_sequence": None,
        "usage": {"input_tokens": 1, "output_tokens": 1}})

for base in ["https://openrouter.ai/api/v1", "https://openrouter.ai/api"]:
    client = anthropic.Anthropic(
        api_key="sk-test", base_url=base,
        http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))
    client.messages.create(model="anthropic/claude-opus-5", max_tokens=16,
                           messages=[{"role": "user", "content": "hi"}])
    print(base, "->", seen[-1])
https://openrouter.ai/api/v1 -> https://openrouter.ai/api/v1/v1/messages
https://openrouter.ai/api    -> https://openrouter.ai/api/v1/messages

One side note: recent SDK versions reject a plain httpx.Client passed as http_client, because the SDK now ships on httpx2. That's why the repro imports httpx2. OpenRouter's own Claude Code integration guide gives the same warning about the base URL for the same reason: the client adds /v1/messages itself.

How should the client be configured so it still works with a direct Anthropic key?

Read the key and an optional base URL from the environment, and only pass base_url when it's set. With ANTHROPIC_BASE_URL=https://openrouter.ai/api and an OpenRouter key in ANTHROPIC_API_KEY, traffic goes to OpenRouter. If you unset the base URL and supply a real Anthropic key, the same code calls api.anthropic.com without changes.

# .env
ANTHROPIC_API_KEY=$OPENROUTER_PROJECT_KEY
ANTHROPIC_BASE_URL=https://openrouter.ai/api   # NO trailing /v1

# agent_loop.py
MODEL_ID = "anthropic/claude-opus-5"           # OpenRouter needs the provider prefix

def _load_client_kwargs() -> dict:
    key = os.environ.get("ANTHROPIC_API_KEY")
    if not key:
        raise AgentLoopError("ANTHROPIC_API_KEY is not configured")
    kwargs = {"api_key": key}
    base_url = os.environ.get("ANTHROPIC_BASE_URL")
    if base_url:
        kwargs["base_url"] = base_url
    return kwargs

client = anthropic.Anthropic(**_load_client_kwargs())

The SDK also reads ANTHROPIC_BASE_URL by itself. In 1.7.0 the order of precedence is constructor kwarg, then the environment variable, then profile config. We still pass it explicitly. That way the missing-key check fails with a clear message instead of a generic 401 from deep inside the client, and the routing decision is visible in our own code.

Why does a @beta_tool that returns a dict fail with a 400 invalid_union on the follow-up request?

The Tool Runner puts whatever your tool returns, unchanged, into the content field of the tool_result block. The Messages schema allows a string or a list of content blocks there. A dict is neither, so OpenRouter's validator rejects the follow-up request with 400 invalid_union / invalid_type at messages[N].content. Fix: return json.dumps(...).

The confusing part is when it fails. The first request always succeeds: Claude reads your tool schema and sends back a clean tool_use block. Your tool runs, returns a dict, and the Tool Runner builds the next request. Only that second request carries the dict, so the 400 shows up one step after the code that caused it.

The SDK's type checking doesn't catch it either. The runner's declared result type is Union[str, Iterable[BetaContent]], and a Python dict is technically Iterable (over its keys), so nothing complains locally. Here is what the runner actually builds from a dict-returning tool:

from anthropic import beta_tool

@beta_tool
def navigate(target_url: str) -> dict:
    """Navigate the browser.
    Args:
        target_url: URL to open.
    """
    return {"title": "Hacker News", "url": target_url}

result = navigate.call({"target_url": "https://example.com"})
print({"type": "tool_result", "tool_use_id": "toolu_1", "content": result})
{"type": "tool_result", "tool_use_id": "toolu_1",
 "content": {"title": "Hacker News", "url": "https://example.com"}}

That content is a JSON object. The Claude tool-use docs define tool_result.content as "a string or a list of content blocks", and OpenRouter checks that union strictly. We have no direct Anthropic account, so we never tested whether api.anthropic.com is more lenient. That doesn't matter much: the payload breaks the documented contract, so no endpoint should be trusted to accept it.

What is the complete fix for tool results in 2026?

Route every tool's return value through one helper that always serializes to a JSON string and truncates large payloads into a JSON-string envelope. Annotate every @beta_tool as -> str. Serialize error paths too: an {"error": ...} dict returned from an except branch breaks the follow-up request exactly like a success dict does.

import json as _json
from anthropic import beta_tool

MAX_RESULT_CHARS = 6000

def _to_tool_result(obj, max_chars: int = MAX_RESULT_CHARS) -> str:
    """Every @beta_tool returns str (JSON), never a raw dict/list."""
    text = _json.dumps(obj)
    if len(text) <= max_chars:
        return text
    return _json.dumps({
        "truncated": True,
        "note": f"result was {len(text)} chars, truncated to {max_chars}",
        "preview": text[:max_chars],
    })

@beta_tool
def navigate(target_url: str) -> str:
    """Navigate the browser to a URL and return title, final URL, and a text summary.
    Args:
        target_url: The URL to open.
    """
    try:
        result = session.send("navigate", url=target_url)
    except ExplorerError as exc:
        return _to_tool_result({"error": str(exc)})   # error path serialized too
    return _to_tool_result(result)

We added the max_chars override later, for one tool whose reports regularly exceed 6,000 characters. The default truncation wraps the whole result as a flat preview string, which destroys its structure. For a tool whose output the agent has to parse field by field, raise that tool's cap instead of letting the envelope cut through the middle of the data.

We chose to always serialize rather than add a "dicts only for OpenRouter" switch. The project always runs through OpenRouter, and a code path that depends on an endpoint being lenient is a bug waiting for the next proxy change. A string costs nothing, and Claude reads JSON text in a tool_result as well as it reads structured content.

Why do model IDs need the anthropic/ prefix on OpenRouter?

OpenRouter picks the upstream provider from the model slug. The bare Claude API string claude-opus-5 isn't a valid OpenRouter model ID; anthropic/claude-opus-5 is. The Anthropic-messages emulation keeps the request shape but still uses OpenRouter's model namespace. So MODEL_ID changes when you switch endpoints, even though your SDK code doesn't.

Check the exact slug on OpenRouter's model page instead of adding a prefix to your old string. Version separators don't always match. OpenRouter's own issue tracker has an HTTP 400 report for claude-sonnet-4-6 versus anthropic/claude-sonnet-4.6. Before we committed to a model ID, we ran one real tool-call round trip through the Tool Runner with it. A plain chat completion only proves the model exists, not that tool use works through the emulation layer.

How did the dict bug show up in our first production run?

Our first real agent run used Hacker News' front page as the target and failed on its very first follow-up request. The browser tool returned a dict, the Tool Runner sent it back as tool_result.content, and OpenRouter returned the 400. The job didn't hang: the loop's hard budget stopped it and saved the real error.

That failure handling paid off. Because the 400 body was saved instead of being turned into a generic "agent failed", we reproduced it outside the agent loop within minutes. We used two otherwise identical tools, one returning a dict and one returning json.dumps of the same data. Only the dict version broke. We then checked the fix by calling BetaFunctionTool.call() directly against the live site and confirming navigate returned a real string.

The same browser agent produced another gotcha worth knowing about if you drive Chromium from tools: why time.sleep stalls your Playwright CDP screencast. And if you run Claude through OpenRouter for structured output, the other failure class to plan for is finish_reason='length' with null content, which hit 97 calls across 65 of our production runs.

What's the minimal checklist for the Anthropic SDK through OpenRouter?

There are four checks. base_url is https://openrouter.ai/api with no /v1. Every tool returns a str, including error branches and truncated output. The model ID is the exact OpenRouter slug with its anthropic/ prefix. And one real tool-call round trip passes before you trust it, because a single chat message never exercises the tool_result path.

None of these three bugs fails where you'd look first. The double /v1 only shows up in the SDK's debug log. The dict breaks the request after the one that produced it. And a model ID that works on the Claude API still fails on OpenRouter's routing. If your agent loop works in a one-shot test but dies on step two through OpenRouter, check the tool_result content type first.