LLM APITechnical Deep Dive
Claude API 实战:Anthropic 模型完全指南
发布时间2025/12/10
分类LLM API
预计阅读8 分钟
作者吴长龙
*
Claude API 以长上下文和高质量输出著称。本文介绍 Claude API 的使用方法、消息格式、工具调用等。
01.内容
# Claude API 实战:Anthropic 模型完全指南
Claude API 是 Anthropic 提供的 LLM 服务,以高质量和长上下文著称。
02.1. 基础调用
1.1 安装与配置
python snippetpython
pip install anthropic
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."1.2 简单调用
python snippetpython
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "你好"}
]
)
print(message.content[0].text)03.2. 消息格式
2.1 多轮对话
python snippetpython
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "什么是 AI?"},
{"role": "assistant", "content": "AI 是人工智能..."},
{"role": "user", "content": "它能做什么?"}
]
)2.2 系统提示
python snippetpython
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
system="你是一个专业的技术作家",
messages=[
{"role": "user", "content": "写一篇博客"}
]
)04.3. 流式响应
python snippetpython
with client.messages.stream(
model="claude-sonnet-4-20250514",
messages=[{"role": "user", "content": "写一个故事"}]
) as stream:
for text in stream.text_stream:
print(text, end="")05.4. 工具调用
python snippetpython
client = anthropic.Anthropic(
default_headers={"anthropic-beta": "tools-2024-01-15"}
)
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
messages=[{"role": "user", "content": "北京天气"}],
tools=[{
"name": "get_weather",
"description": "获取天气",
"input_schema": {
"type": "object",
"properties": {
"location": {"type": "string"}
}
}
}]
)06.5. Claude vs OpenAI
| 特性 | Claude | OpenAI |
|---|---|---|
| 上下文 | 200K | 128K |
| 价格 | 更便宜 | 较贵 |
| 工具调用 | 原生支持 | Function Calling |
| 输出质量 | 详细、结构化 | 快 |
07.6. 总结
Claude API 是高质量选择,上下文更长。
(未完待续...)