← ClaudeAtlas

anthropic-sdk-via-openrouterlisted

Route Anthropic SDK calls through OpenRouter as a fallback when ANTHROPIC_API_KEY is absent but OPENROUTER_API_KEY is present. Pattern: anthropic.Anthropic(api_key=OPENROUTER_API_KEY, base_url="https://openrouter.ai/api/v1") + provider-prefixed model id "anthropic/claude-sonnet-4.6" (note dots, not dashes). The Anthropic SDK speaks Anthropic Messages API at the base_url; OpenRouter implements that contract at /v1/messages, so the same .messages.create(model=..., tools=..., tool_choice=...) call works without any code change beyond the constructor. Use when: (1) supporting users on Claude Code subscription auth (no direct ANTHROPIC_API_KEY but OPENROUTER_API_KEY available), (2) building any Python tool that uses the Anthropic SDK and wants to support OpenRouter-only environments without rewriting to use the OpenAI SDK or a different API contract, (3) implementing the symmetric fallback to a similar pattern on the OpenAI SDK side.
MrBinnacle/skills · ★ 0 · AI & Automation · score 65
Install: claude install-skill MrBinnacle/skills
# Anthropic SDK via OpenRouter (env-var fallback) ## Problem The Anthropic Python SDK constructor `anthropic.Anthropic()` resolves `ANTHROPIC_API_KEY` from the environment by default. When that env var is absent (e.g., on Claude Code subscription auth, on machines where the operator only has OpenRouter credentials, on CI where only an OpenRouter token is provisioned), the constructor raises before any call goes out. The naive workaround — rewriting the integration to use the OpenAI SDK against OpenRouter's chat completions endpoint — abandons the Anthropic Messages API contract (tool_use schema, system blocks, the content-block response shape, the `stop_reason` taxonomy, the cache control markers, etc.). For any non-trivial Anthropic integration, the rewrite cost is high. There is a much smaller move: keep the Anthropic SDK; just point it at OpenRouter's Anthropic-compatible endpoint via the `base_url` override. ## Solution Construct the Anthropic SDK with both `api_key` and `base_url` overrides: ```python import anthropic client = anthropic.Anthropic( api_key=os.environ["OPENROUTER_API_KEY"], base_url="https://openrouter.ai/api/v1", ) ``` Use a **provider-prefixed model id** with a DOT separator inside the model name (OpenRouter's slug convention, NOT Anthropic-direct's dash convention): ```python response = client.messages.create( model="anthropic/claude-sonnet-4.6", # dot before 6, not dash max_tokens=8192, system=SYSTEM_PROMPT, tools=[.