Claude API怎么使用?使用Claude API有三种主流方案——Anthropic官方SDK直连、OpenAI兼容格式调用、以及通过聚合平台统一接入。如果你只是想最快跑通,往下翻到方案二,改个base_url五分钟就能出结果。
Claude API怎么使用:
环境准备
Python 3.10+,装两个包就行:
pip install anthropic openai
我用的是 Python 3.11.8,macOS Sonoma,测试日期 4 月 22 号。
方案一:Anthropic 官方 SDK 直连
最"正统"的方式。去 console.anthropic.com 注册账号,拿到 API Key。
import anthropic
client = anthropic.Anthropic(api_key="sk-ant-xxxxx")
message = client.messages.create(
model="claude-sonnet-4-20260514",
max_tokens=1024,
messages=[
{"role": "user", "content": "用一句话解释什么是 RAG"}
]
)
print(message.content[0].text)
跑起来没啥问题,但我第一次调的时候直接报了个错:
anthropic.AuthenticationError: Error code: 401 - {'type': 'error', 'error': {'type': 'authentication_error', 'message': 'invalid x-api-key'}}
原因很蠢——我把 Key 复制的时候多带了个换行符。strip 一下就好了。
Streaming 模式也很简单:
with client.messages.stream(
model="claude-sonnet-4-20260514",
max_tokens=1024,
messages=[{"role": "user", "content": "写一个 Python 快排"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
实测 Streaming 首 token 大概 180ms 出来,体感还行。但有个问题——如果你之前项目全是用 OpenAI SDK 写的,换 Anthropic SDK 意味着一堆代码要重构。接口格式不一样,返回结构也不一样。
方案二:OpenAI 兼容格式调用
这个方案是我最终选的。Claude 现在支持 OpenAI 兼容协议,你用 openai 这个 Python 包,改一下 base_url 和 model 名字就能调 Claude。
from openai import OpenAI
client = OpenAI(
api_key="your-key",
base_url="https://api.ofox.ai/v1"
)
response = client.chat.completions.create(
model="claude-sonnet-4-20260514",
messages=[
{"role": "system", "content": "你是一个合同助手"},
{"role": "user", "content": "请分析以下合同条款的风险点:..."}
],
max_tokens=2048,
stream=True
)
for chunk in response:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
好处很明显:如果你之前写了一堆 GPT-5.5 的调用代码,想试试 Claude 的效果,literally 只需要改 model 参数那一行。其他的 messages 格式、stream 处理、error handling 全部通用。
我那个合同的项目就是这么干的——先用 GPT-5.5 跑通了流程,然后把 model 换成 claude-sonnet-4 对比效果,发现 Claude 在长合同(8000+ 字)的条款理解上确实更稳。
方案三:带 Tool Use 的复杂调用
如果你要做 Agent 类的应用,Claude 的 Tool Use 绕不开。这里用 Anthropic 原生 SDK 演示:
import anthropic
import json
client = anthropic.Anthropic(api_key="sk-ant-xxxxx")
tools = [
{
"name": "search_contract",
"description": "在合同数据库中搜索相关条款",
"input_schema": {
"type": "object",
"properties": {
"keyword": {"type": "string", "description": "搜索关键词"},
"contract_type": {"type": "string", "enum": ["劳动合同", "采购合同", "租赁合同"]}
},
"required": ["keyword"]
}
}
]
response = client.messages.create(
model="claude-opus-4-20260514",
max_tokens=4096,
tools=tools,
messages=[
{"role": "user", "content": "帮我查一下我们采购合同里关于违约金的条款"}
]
)
# 处理 tool_use 响应
for block in response.content:
if block.type == "tool_use":
print(f"调用工具: {block.name}")
print(f"参数: {json.dumps(block.input, ensure_ascii=False)}")
Opus 4.7 的 Tool Use 准确率比之前高了不少,我测了 50 个 case,只有 2 个出现了参数格式错误。不过 Opus 贵啊——input 15/Mtokens,output15/M tokens,output 15/Mtokens,output75/M tokens。我那个私活预算有限,最后生产环境还是用的 Sonnet 4.6。
以上就是Claude API怎么使用的三种方法,从零开始写新项目并且重度依赖Claude特有功能,用Anthropic原生SDK。已有OpenAI格式的代码想快速切换,或者需要在多个模型之间测试,OpenAI兼容格式省事太多了。