Anthropic SDK Custom base_url: Python and TypeScript Setup with QCode
As of 2026-11-25, pointing the official Anthropic Python SDK (anthropic) or TypeScript SDK (@anthropic-ai/sdk) at QCode takes two settings: base_url="https://api.qcode.cc/api" (no /v1, no trailing slash) and your cr_-prefixed key as api_key. Everything else, including messages.create, streaming, tool use and prompt caching, is written exactly as in Anthropic's own examples. Claude models are served only on this Anthropic Messages endpoint; if you want GPT or Chinese models through the OpenAI SDK, see the OpenAI SDK multi-model guide.
QCode is an independent third-party API service. It is not operated by, endorsed by, or partnered with Anthropic. SDK behavior in this article comes from Anthropic's SDK source and documentation; QCode path rules come from the endpoints page on docs.qcode.cc.
Updated 2026-11-26
Key facts
- Base URL:
https://api.qcode.cc/api. The SDK appends/v1/messages, so requests go tohttps://api.qcode.cc/api/v1/messages. Alternate hosts:asia.qcode.cc(Asia) andus.qcode.cc(North America / Europe). The same key works on all three. - Auth: the SDK's
api_keysends anX-Api-Keyheader andauth_tokensendsAuthorization: Bearer(see_client.pyin the Anthropic Python SDK). QCode's docs show both headers in their examples. Use one, not both. - Model IDs:
claude-opus-5-5($4 / $20 per million tokens),claude-sonnet-5-5($2 / $10),claude-haiku-5-5($0.10 / $0.50 for prompts up to 100K tokens),claude-fable-5-2($8 / $40). Live prices are on /models. - Billing: QCode price = official API price × service multiplier. The multiplier for Anthropic models is currently ×1.0.
- Most common mistakes:
base_urlending in/api/v1(404), bothANTHROPIC_API_KEYandANTHROPIC_AUTH_TOKENset with a stale value (401), and disabling thinking or forcingtool_choiceon Opus 5.5 (400).
Before you start
- Create a key in the QCode dashboard. It looks like
cr_xxxxxxxx. Copy it without spaces or line breaks. - Install the SDK:
# Python
pip install anthropic
# Node.js / TypeScript
npm install @anthropic-ai/sdk
- Run one end-to-end curl test so you know the path and key work before you debug code. This is the same test the docs.qcode.cc endpoints page uses:
export QCODE_API_KEY="cr_your_key"
curl -sS https://api.qcode.cc/api/v1/messages \
-H "x-api-key: $QCODE_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model":"claude-haiku-5-5","max_tokens":64,"messages":[{"role":"user","content":"ping"}]}'
A JSON response with text in content means the path is good. If you get an HTML page with status 200, the request most likely went out without a key. That is not a success.
Python SDK: create the client
You can configure the Python SDK with explicit arguments or with environment variables.
Option A: explicit arguments (good for server code)
import os
import anthropic
client = anthropic.Anthropic(
base_url="https://api.qcode.cc/api", # not /api/v1, no trailing slash
api_key=os.environ["QCODE_API_KEY"], # sent as the X-Api-Key header
)
msg = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=2048,
messages=[{"role": "user", "content": "Explain idempotency in one sentence."}],
)
for block in msg.content:
if block.type == "text":
print(block.text)
print(msg.usage) # input_tokens, output_tokens and cache fields
Option B: environment variables (good for local scripts and CI)
export ANTHROPIC_BASE_URL="https://api.qcode.cc/api"
export ANTHROPIC_API_KEY="cr_your_key"
unset ANTHROPIC_AUTH_TOKEN # keep only one credential active
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY
x-api-key or Authorization: Bearer?
From the Anthropic Python SDK source: the api_key argument (or ANTHROPIC_API_KEY) produces an X-Api-Key header. The auth_token argument (or ANTHROPIC_AUTH_TOKEN) produces Authorization: Bearer <token>. If both are set, the request carries both headers. The SDK does not pick one for you.
That matters if you already use Claude Code with QCode, because Claude Code reads ANTHROPIC_AUTH_TOKEN (see the ANTHROPIC_BASE_URL setup guide). If an old ANTHROPIC_API_KEY is still exported in the same shell, the SDK sends it too, and a stale value can cause a 401. Run env | grep ANTHROPIC and keep one credential. QCode's docs use both x-api-key and Authorization: Bearer in their curl examples, so either style works for the key itself.
TypeScript SDK: create the client
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
baseURL: "https://api.qcode.cc/api", // note: baseURL, capital URL
apiKey: process.env.QCODE_API_KEY, // sent as X-Api-Key
});
const msg = await client.messages.create({
model: "claude-sonnet-5-5",
max_tokens: 2048,
messages: [{ role: "user", content: "Explain idempotency in one sentence." }],
});
for (const block of msg.content) {
if (block.type === "text") console.log(block.text);
}
The TypeScript SDK also reads ANTHROPIC_BASE_URL and ANTHROPIC_API_KEY, so new Anthropic() with no arguments works once they are exported. The Bearer-header option is authToken.
Streaming
Stream any request with long input, long output or a high max_tokens. It avoids HTTP timeouts and lets you show progress.
Python:
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=16000,
output_config={"effort": "high"}, # Opus 5.5 defaults to medium effort
messages=[{"role": "user", "content": "Review this function and suggest fixes: ..."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print("\n", final.usage)
TypeScript:
const stream = client.messages.stream({
model: "claude-opus-5-5",
max_tokens: 16000,
messages: [{ role: "user", content: "Review this function: ..." }],
});
stream.on("text", (t) => process.stdout.write(t));
const final = await stream.finalMessage();
console.log(final.usage);
Per QCode's docs, Opus 5.5 and Haiku 5.5 default to medium effort, and Fable 5.2 defaults to high. For coding and multi-step reasoning, set output_config.effort explicitly.
Tool use
Here is a minimal manual loop. Claude asks for a tool, you run it, you send back a tool_result, and you repeat until stop_reason is no longer tool_use.
import os
tools = [{
"name": "get_file_size",
"description": "Return the size in bytes of a file in the repository.",
"input_schema": {
"type": "object",
"properties": {"path": {"type": "string", "description": "Relative file path"}},
"required": ["path"],
"additionalProperties": False,
},
"strict": True, # tool input must match the schema exactly
}]
messages = [{"role": "user", "content": "How big is README.md?"}]
while True:
resp = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=4096,
tools=tools,
messages=messages,
)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
break
results = []
for block in resp.content:
if block.type == "tool_use":
try:
size = os.path.getsize(block.input["path"])
results.append({"type": "tool_result", "tool_use_id": block.id, "content": str(size)})
except OSError as e:
results.append({"type": "tool_result", "tool_use_id": block.id,
"content": f"error: {e}", "is_error": True})
messages.append({"role": "user", "content": results}) # all results in one user message
for block in resp.content:
if block.type == "text":
print(block.text)
Two rules. First, append the whole resp.content to history, not just the text. Second, on Opus 5.5, Sonnet 5.5 and Fable 5.2, tool_choice set to any or to a specific tool returns 400. Leave it at the default auto, use strict: true, and name the tool in your prompt.
Prompt caching with cache_control
Put large, stable content first (coding rules, project docs, tool definitions) and mark the last stable block with cache_control. When later requests hit the cache, that part is billed at the cache-read rate.
GUIDE = open("docs/coding-guidelines.md", encoding="utf-8").read()
resp = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=2048,
system=[
{"type": "text", "text": "You review code for this repository."},
{"type": "text", "text": GUIDE, "cache_control": {"type": "ephemeral"}},
],
messages=[{"role": "user", "content": "Review this diff: ..."}],
)
u = resp.usage
print("cache write:", u.cache_creation_input_tokens,
"cache read:", u.cache_read_input_tokens,
"uncached input:", u.input_tokens)
Per the /models page (read 2026-11-25), claude-sonnet-5-5 input is $2 per million tokens; cache reads and writes are billed at the rates shown on /models. Caching is a prefix match: if any byte earlier in the prompt changes (a timestamp in the system prompt, for example), everything after it misses. There is also a minimum cacheable length, so very short prefixes are not cached. If cache_read_input_tokens stays at 0 across repeated calls, find what is changing. More cost analysis: Claude Code prompt caching cost.
Claude model IDs on QCode
| Model ID | Input / output (per 1M tokens) | Typical use |
|---|---|---|
claude-opus-5-5 |
$4 / $20 | Complex coding, long agent runs |
claude-sonnet-5-5 |
$2 / $10 | Everyday coding, bulk review |
claude-haiku-5-5 |
$0.10 / $0.50 ($0.50 / $2.50 above 100K prompt) | Classification, extraction, subtasks |
claude-fable-5-2 |
$8 / $40 | Hardest reasoning and long tasks |
claude-opus-5 |
$5 / $25 | Legacy code paths |
Source: qcode.cc/models, read 2026-11-25. Check /models for live prices. All Claude models on /models have 1M context; in SDK code, use the plain model IDs. Watch Haiku 5.5's tier: when one request's prompt exceeds 100K tokens, the higher $0.50 / $2.50 rate applies.
Common errors and fixes
| Symptom | Usual cause | Fix |
|---|---|---|
| 404 Not Found | base_url set to https://api.qcode.cc/api/v1, so the request becomes /api/v1/v1/messages; or a trailing slash gives //v1/messages |
Stop at /api |
model_not_available_on_endpoint |
A Claude model sent to the OpenAI path (for example the OpenAI SDK pointed at /openai/v1) |
Use the Anthropic SDK with /api for Claude |
401 Invalid API key |
Key copied wrong or with a space; or ANTHROPIC_API_KEY and ANTHROPIC_AUTH_TOKEN both set, one stale |
Keep one credential, re-copy the key |
| 400 | thinking: {"type": "disabled"} or budget_tokens on Opus 5.5; tool_choice any/tool; assistant-message prefill |
Remove them; control depth with output_config.effort |
| 400 that appears after an SDK upgrade | Newer SDK majors send API version 2026-10-21, which rejects temperature, top_p and top_k |
Remove sampling parameters; see API version 2026-10-21 |
402 with daily_cost_limit_exceeded |
The plan's daily quota is used up | Resets at 00:00 Beijing time, or buy a top-up in the dashboard |
| 429 / 529 | Too much concurrency or upstream load | The SDK retries twice by default (max_retries); lower concurrency and back off |
In Python, catch errors from most specific to most general:
import anthropic
try:
msg = client.messages.create(model="claude-sonnet-5-5", max_tokens=512,
messages=[{"role": "user", "content": "ping"}])
except anthropic.AuthenticationError as e: # 401
print("Invalid key:", e.message)
except anthropic.NotFoundError as e: # 404
print("Wrong path or model ID:", e.message)
except anthropic.BadRequestError as e: # 400
print("Parameter rejected:", e.message)
except anthropic.RateLimitError: # 429
print("Too fast, retry later")
except anthropic.APIStatusError as e: # 402, 5xx and others
print(e.status_code, e.response.text)
except anthropic.APIConnectionError:
print("Network issue; try asia.qcode.cc or us.qcode.cc")
More 401 cases: 401 with a custom base URL.
Production tips
- Keep keys in environment variables or a secrets manager, never in the repository.
- Pick a host by region: try
asia.qcode.ccin Asia andus.qcode.ccin North America or Europe, and measure from your own network before you decide. - Log
usage: recordinput_tokens,output_tokensandcache_read_input_tokensper request so you can reconcile your bill. - Limit concurrency: use a queue or semaphore for batch jobs so you stay within the limits of your plan.
- Keep conversations append-only: on Opus 5.5 and other new models, thinking blocks are tied to the conversation. Rewriting earlier messages or the system prompt mid-conversation breaks both the cache and the thinking blocks.
Async client, timeouts and retries
In web services (FastAPI, aiohttp and similar), use the async client. It takes the same arguments; only the class name changes to AsyncAnthropic:
import os
import anthropic
aclient = anthropic.AsyncAnthropic(
base_url="https://api.qcode.cc/api",
api_key=os.environ["QCODE_API_KEY"],
timeout=120.0, # seconds (the TypeScript SDK uses milliseconds)
max_retries=3, # default is 2; retries 408/409/429/5xx and connection errors
)
async def summarize(text: str) -> str:
msg = await aclient.messages.create(
model="claude-haiku-5-5",
max_tokens=1024,
messages=[{"role": "user", "content": f"Summarize in three sentences:\n{text}"}],
)
return "".join(b.text for b in msg.content if b.type == "text")
The SDK timeout applies per attempt, so with retries the total wait can reach timeout × (max_retries + 1). Account for that if your own endpoint has a deadline. To change settings for one call without touching the shared client, use client.with_options(timeout=30, max_retries=0). For batch jobs, an asyncio.Semaphore that keeps in-flight requests under your key's concurrency limit is faster and easier to budget than waiting for 429s and backing off.
FAQ
What base_url do I use with the Anthropic SDK?
Use https://api.qcode.cc/api. The SDK adds /v1/messages itself, so do not add /v1 and do not end with a slash. Users in Asia or North America / Europe can swap the host for asia.qcode.cc or us.qcode.cc and keep the same path.
Should I use api_key or auth_token?
Both send your key. api_key sends X-Api-Key and auth_token sends Authorization: Bearer. QCode's docs use both styles, so pick one. Do not set both, because the request will carry both headers and a stale value can trigger a 401.
Can I call Claude through the OpenAI SDK?
Not on QCode. Claude models are served only on the Anthropic Messages endpoint, and a Claude request on the OpenAI path returns model_not_available_on_endpoint. GPT and Chinese models do work with the OpenAI SDK; see the OpenAI SDK multi-model guide.
Why do I get a 404 after adding /v1?
The SDK already appends /v1/messages. Adding it yourself gives /api/v1/v1/messages. Set base_url back to https://api.qcode.cc/api.
Does prompt caching work on QCode, and how do I confirm hits?
Add cache_control: {"type": "ephemeral"} to the last stable block and watch usage.cache_read_input_tokens. If it is above 0 from the second call on, the cache is working.
Opus 5.5 returns 400 saying thinking cannot be disabled. Why?
Opus 5.5 only runs adaptive thinking. Sending {"type": "disabled"} or budget_tokens returns 400. To spend fewer tokens, lower output_config.effort (for example to low) instead.
Is billing the same as the official API?
QCode bills official API price × service multiplier. As of 2026-11-25 the multiplier for Anthropic models is ×1.0. Per-model prices are on /models.
Can the SDK list the models available on QCode?
This guide does not rely on client.models.list(). Take model IDs from the qcode.cc/models page and set them in code.
Which plan fits SDK work
For scripts, one-off data jobs or evaluation runs, pay-as-you-go packs are the simplest: no subscription, 7-day validity, stackable, starting at $4 (see /pay-as-you-go). If SDK calls are part of daily work, such as an internal code-review bot or an agent that runs every day, the Daily-35 plan fits better: per /pricing as of 2026-11-25 it is $53.57 for 30 days with $35 of usage per day, reset at 00:00 Beijing time. Compare all plans on /pricing.