API是同一个Claude,但计费方式不同且没有界面。当你想要自动化重复任务、将Claude集成到某个东西中,或者你的使用量波动很大以至于订阅会为闲置周收费时,请使用它。如果你只是想聊天,那就跳过它——一个好的客户端需要花费金钱和时间,而Pro更简单。
第一次调用的三个步骤
- 1
获取密钥
在Anthropic Console创建一个账户,添加少量信用额度,并创建一个API密钥。同时设置月度消费限额;这是你能买到的最便宜的保险。
- 2
发送消息
所有请求都通过一个端点
POST /v1/messages。你选择一个模型,设置最大输出长度,然后发送一系列消息。 - 3
查看使用量
每个响应都会报告输入和输出 token 数量。乘以模型的费率,你就能精确到分地知道这次调用的成本。
curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "In three bullets, when is an API cheaper than a chat subscription?"}
]
}'import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "In three bullets, when is an API cheaper than a chat subscription?"}
],
)
for block in response.content:
if block.type == "text":
print(block.text)
u = response.usage
print(f"input={u.input_tokens} output={u.output_tokens}")
# Sonnet 5 at the time of writing: $2 / 1M input, $10 / 1M output
print(f"cost ≈ ${u.input_tokens * 2 / 1e6 + u.output_tokens * 10 / 1e6:.5f}")那次调用只需几分之一美分。usage 对象就是完整的成本控制故事:第 8 课中的每一项优化都是为了缩小这两个数字,或者降低输入 token 的成本。
构建任何东西之前需要了解的两个功能
- 提示缓存。 在请求的稳定部分(系统提示、大文档、工具列表)添加
cache_control,重复调用会从缓存中读取,价格约为正常输入价格的 10%。对于重复发送同一份 50,000 token 文档的工作负载,这相当于账单与舍入误差的区别。详情请参阅:Anthropic 的提示缓存文档。 - 消息批次。 将多达数千个请求作为一批发送,一天内获得结果,支付半价。任何不需要即时回答的内容——夜间报告、批量分类、评估——都属于此。详情请参阅:批处理文档。
知识检查
你的应用程序随每个用户问题发送相同的 40,000 token 策略文档。什么最能削减账单?