Anthropic Messages
通过 Anthropic Messages API 用官方 SDK 调用 Claude。流式输出、扩展思考、工具调用、提示缓存和 token 计数均按 Anthropic 文档所述工作。
Lovely Router 完全按照 Anthropic 的定义提供 POST /v1/messages 和 POST /v1/messages/count_tokens。保留你现有的代码,把 base URL 改为 https://lovelyrouter.com,并使用你的 Lovely Router 密钥即可。请求体原样透传,因此每个参数都以 Anthropic 的文档为准。
配置 SDK#
Anthropic SDK 通过 x-api-key 发送密钥,Authorization: Bearer 同样可用。
curl https://lovelyrouter.com/v1/messages \
-H "x-api-key: $LOVELY_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5.5",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Explain HTTP caching in two sentences."}]
}'SDK 也会从环境变量读取 ANTHROPIC_BASE_URL 和 ANTHROPIC_API_KEY,所以对于创建默认客户端的代码,执行 export ANTHROPIC_BASE_URL=https://lovelyrouter.com 就够了。
目前可用的 Claude 模型:claude-fable-5.1、claude-opus-5.5、claude-sonnet-5.5、claude-haiku-5.5 以及更早的版本。GET /v1/models 提供当前的完整列表和价格。
流式接收响应#
设置 stream: true,或使用 SDK 的流式辅助方法。你会收到标准的事件序列:message_start、content_block_start、content_block_delta、content_block_stop、message_delta、message_stop。
with client.messages.stream(
model="claude-sonnet-5.5",
max_tokens=2048,
messages=[{"role": "user", "content": "Write a limerick about latency."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
final = stream.get_final_message()
print("\n", final.usage)网关会把流暂存到第一个 token 到达,因此早期失败的渠道会在你察觉不到的情况下被替换。详情请参阅流式输出。
使用扩展思考#
按照 Anthropic 针对你所调用模型的文档发送 thinking 和 output_config。当前模型使用带强度等级(effort)的自适应思考;较旧的模型(Claude 4.5 及更早版本)使用固定的 budget_tokens。各模型的具体规则请查看 Anthropic 的思考指南。
message = client.messages.create(
model="claude-opus-5.5",
max_tokens=16000,
thinking={"type": "adaptive", "display": "summarized"},
output_config={"effort": "high"},
messages=[{"role": "user", "content": "How many weekdays are there in 2027?"}],
)
for block in message.content:
if block.type == "thinking":
print("Thinking:", block.thinking)
elif block.type == "text":
print("Answer:", block.text)思考 token 计入 usage.output_tokens,按输出价格计费。在使用工具继续对话时,请把思考块原样传回。
使用工具#
用 JSON Schema 格式的 input_schema 定义工具。当响应带有 stop_reason: "tool_use" 时,运行该工具,并在 tool_result 块中把结果发回。
tools = [{
"name": "get_weather",
"description": "Current weather for a city.",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}]
messages = [{"role": "user", "content": "Do I need an umbrella in Lisbon?"}]
response = client.messages.create(
model="claude-sonnet-5.5", max_tokens=1024, tools=tools, messages=messages,
)
if response.stop_reason == "tool_use":
call = next(b for b in response.content if b.type == "tool_use")
result = {"city": call.input["city"], "forecast": "light rain"} # your code here
messages += [
{"role": "assistant", "content": response.content},
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": call.id, "content": str(result)},
]},
]
response = client.messages.create(
model="claude-sonnet-5.5", max_tokens=1024, tools=tools, messages=messages,
)
print(response.content[0].text)其他工具选项,例如 tool_choice 和 strict,都会原样透传。Anthropic 的工具调用指南对它们有详细说明。
缓存长提示词#
用 cache_control 标记提示词中稳定部分的末尾。第一个请求写入缓存;之后以相同前缀开头的请求会读取缓存,只需输入价格的一小部分。
response = client.messages.create(
model="claude-sonnet-5.5",
max_tokens=1024,
system=[{
"type": "text",
"text": LONG_REFERENCE_DOCUMENT,
"cache_control": {"type": "ephemeral"},
}],
messages=[{"role": "user", "content": "Summarize section 3."}],
)
u = response.usage
print(u.cache_creation_input_tokens, u.cache_read_input_tokens, u.input_tokens)以 claude-sonnet-5.5 为例,缓存写入每百万 token $2.50,缓存读取每百万 token $0.10,而未缓存输入为 $2.00。短于模型最低长度的前缀不会被缓存,两个字段都会报告为零。网关会让每个对话始终留在持有其缓存的渠道上;请参阅提示缓存。
计算 token 数#
POST /v1/messages/count_tokens 接受与消息请求相同的请求体(去掉 max_tokens),返回 input_tokens。它是免费的,余额为零时也能使用。
curl https://lovelyrouter.com/v1/messages/count_tokens \
-H "x-api-key: $LOVELY_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model": "claude-sonnet-5.5",
"messages": [{"role": "user", "content": "Hello, Claude"}]}'计数结果为近似值
用 count_tokens 检查提示词是否超出上下文窗口,或用来做预算。一次调用的扣费始终以模型在响应中报告的 usage 为准。
使用 Claude Code#
Claude Code 使用的就是这个 API。设置 ANTHROPIC_BASE_URL=https://lovelyrouter.com,并把 ANTHROPIC_AUTH_TOKEN 设为你的密钥,每个会话都会固定在一个渠道上,提示缓存因此持续生效。完整配置(包括模型设置)请参阅在你的工具中使用。
请求头#
| 请求头 | 说明 |
|---|---|
x-api-key 或 Authorization: Bearer | 你的 Lovely Router 密钥。必填。 |
anthropic-version | 会被转发。省略时默认为 2023-06-01。 |
anthropic-beta | 按原样转发。 |
x-lovely-group | 可选。当你的密钥未绑定渠道分组时,把请求锁定到指定的渠道分组。 |
x-session-id | 可选。把多个请求归为同一个对话,用于缓存感知路由。请求体中的 metadata.user_id 作用相同。 |
其他请求头不会被转发。错误采用 Anthropic 的格式 {"type": "error", "error": {"type": "...", "message": "..."}};请参阅错误。