Anthropic 是 AI 安全领域的先行者,由前 OpenAI 研究人员于 2021 年创立。其 Claude 系列模型以长上下文窗口(200K tokens)、Constitutional AI 对齐技术、出色的文档理解能力和原生计算机使用(Computer Use)能力著称。自 Claude 3 系列发布以来,Anthropic 在多个基准测试中与 OpenAI GPT-4o 和 Google Gemini 形成三足鼎立之势,尤其在代码生成、长文档分析和安全对齐领域表现突出。
| 属性 | 值 |
|---|---|
| 官网 | https://www.anthropic.com |
| API 文档 | https://docs.anthropic.com |
| API 控制台 | https://console.anthropic.com |
| 基础 URL | https://api.anthropic.com/v1 |
| 认证方式 | x-api-key Header |
| SDK | Python (anthropic), TypeScript (@anthropic-ai/sdk) |
| OpenAI-compatible | ⚠️ 部分兼容(Messages API 类似但非完全兼容) |
Anthropic 的模型经历了三代演进:
| 代际 | 模型 | 发布时间 | 关键突破 |
|---|---|---|---|
| Claude 1 | claude-1、claude-instant-1 |
2023 Q1-Q2 | 首批基于 Constitutional AI 的助手模型 |
| Claude 2 | claude-2、claude-2.1 |
2023 Q3-Q4 | 100K 上下文窗口、文件上传支持 |
| Claude 3 | claude-3-opus、claude-3-sonnet、claude-3-haiku |
2024 Q1 | 200K 上下文、多模态(Vision)、三档定位 |
| Claude 3.5 | claude-3.5-sonnet、claude-3.5-haiku |
2024 Q2-Q3 | 代码能力大幅提升、Computer Use |
| Claude 4 | claude-4-sonnet、claude-4-opus |
2025 Q1 | 原生多模态、更强推理、更长上下文 |
| 模型 | 上下文 | 特点 | 适用场景 | 价格(输入/输出 per M tokens) |
|---|---|---|---|---|
claude-3-5-sonnet-20241022 |
200K | 最佳性价比,代码能力强 | 日常开发、文档分析、内容生成 | $3 / $15 |
claude-3-5-haiku-20241022 |
200K | 快速轻量,低延迟 | 实时对话、分类、简单问答 | $0.80 / $4 |
claude-3-opus-20240229 |
200K | 最强推理能力 | 复杂分析、数学证明、研究 | $15 / $75 |
claude-3-sonnet-20240229 |
200K | 平衡型(上一代) | 兼容性需求 | $3 / $15 |
性能对比:在 HumanEval 代码生成测试中,Claude 3.5 Sonnet 得分约 92%,接近 GPT-4o 的 93%;在 MATH 数学推理中,Claude 3 Opus 得分 73%,与 GPT-4o 的 76% 相当。而在长文档理解(ZeroSCROLLS)上,Claude 3.5 以 89% 的准确率领先行业。
Anthropic 使用 x-api-key 自定义 Header 进行认证,与 OpenAI 的 Authorization: Bearer 不同:
# 获取 API Key:https://console.anthropic.com/ > API Keys
curl -X POST https://api.anthropic.com/v1/messages \
-H "x-api-key: sk-ant-xxxxxxxxxxxx" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Hello, Claude!"}]
}'
| Header | 必填 | 说明 |
|---|---|---|
x-api-key |
✅ | API Key |
anthropic-version |
✅ | API 版本,推荐 2023-06-01 |
Content-Type |
✅ | application/json |
anthropic-beta |
❌ | 实验性功能(如 Computer Use 需要 computer-use-2024-10-22) |
{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 4096,
"messages": [
{"role": "user", "content": "Hello, Claude!"}
],
"system": "You are a helpful assistant built by Anthropic. Answer concisely."
}
与 OpenAI 的核心差异在于 system 作为独立顶层参数、max_tokens 为必填项、以及响应格式使用 content blocks。
{
"id": "msg_01ABCDEF123456",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello! How can I help you today?"
}
],
"model": "claude-3-5-sonnet-20241022",
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 12,
"output_tokens": 10
}
}
关键字段说明:
content:始终为数组,每个元素是一个 content block(可包含 text、tool_use、thinking 等类型)stop_reason:end_turn(正常结束)、max_tokens(达到上限)、stop_sequence(命中停止序列)、tool_use(工具调用)usage:包含输入和输出 token 计数,用于监控成本| 参数 | 类型 | 范围 | 默认值 | 行为说明 |
|---|---|---|---|---|
model |
string | 模型 ID | 必填 | 指定使用的模型 |
max_tokens |
integer | 1-8192 | 必填 | 最大生成 token 数 |
messages |
array | user/assistant | 必填 | 对话消息列表 |
system |
string | - | null | 系统提示 |
temperature |
float | 0-1 | 1.0 | 控制随机性 |
top_p |
float | 0-1 | 1.0 | Nucleus sampling 阈值 |
top_k |
integer | ≥1 | - | 仅考虑概率最高的 K 个 token |
stop_sequences |
array | string[] | [] | 停止生成的自定义序列 |
metadata |
object | - | {} | 用户标识等元数据 |
stream |
boolean | true/false | false | 是否返回流式响应 |
tools |
array | tool 定义 | [] | 定义可用工具 |
thinking |
object | type/budget_tokens | null | 扩展思维(experimental) |
这是与 OpenAI 最关键的差异之一:OpenAI 的 max_tokens 可选(默认无限),而 Anthropic 必须显式指定,否则 API 返回 400 错误。
不同场景的推荐值:
| 场景 | 推荐 max_tokens | 说明 |
|---|---|---|
| 简单问答 | 256-512 | "今天天气怎么样"类问题 |
| 代码生成 | 1024-2048 | 生成单个函数或方法 |
| 文档总结 | 2048-4096 | 总结长文档 |
| 代码库分析 | 4096-8192 | 分析整个文件或模块 |
| 内容创作 | 2048-4096 | 写文章、报告 |
具体数值示例:以 "写一首关于 AI 的诗" 为 prompt,不同 temperature 的效果:
| temperature | 输出特点 | 示例开头 |
|---|---|---|
| 0.0 | 几乎完全确定性,每次相同 | "硅基之心跳动着智慧的火焰,数据之海翻涌着知识的浪花" |
| 0.3 | 较保守,略有变化 | "在硅基的世界里,神经网络编织着智慧的梦想" |
| 0.7 | 创意丰富,多样性好 | "电流如诗流淌在芯片间,算法如舞者在数据中旋转" |
| 1.0 | 高度随机,可能有异常 | "量子森林里,一个晶体管思考着存在的意义" |
最佳实践:
从累计概率达到 top_p 的最小 token 集合中采样。与 temperature 通常二选一使用,不建议同时调整。
| top_p | 行为 | 示例效果 |
|---|---|---|
| 1.0 | 考虑所有 token(默认) | 最大多样性 |
| 0.9 | 考虑占 90% 概率的 token | 排除低概率异常 token |
| 0.1 | 只考虑概率最高的 10% token | 非常保守 |
对比示例:生成词语 "太阳从东方" 的续写
| 参数设置 | 续写结果 |
|---|---|
| temperature=1.0, top_p=1.0 | "升起,照亮了沉睡的大地" |
| temperature=0.5, top_p=0.9 | "升起。" |
| temperature=0.0, top_p=0.1 | "升起来了" |
| temperature=1.0, top_p=0.5 | "升起。光线穿过薄雾" |
| 特性 | Anthropic | OpenAI | 迁移注意事项 |
|---|---|---|---|
| System 消息 | 独立 system 参数(字符串) |
messages 数组中的 system role |
需要从 messages 中移出 |
| 认证 Header | x-api-key |
Authorization: Bearer |
HTTP 请求 Header 不同 |
| 流式字段 | delta.text |
delta.content |
解析逻辑需要修改 |
| 工具调用 | tool_use / tool_result |
tool_calls / tool |
content block vs. 顶层字段 |
| 最大 tokens | 必须指定 max_tokens |
可选,有默认值 | 必须增加显式参数 |
| 温度范围 | 0-1 | 0-2 | 值域不同,注意映射 |
| 角色支持 | user、assistant |
system、user、assistant、tool |
无内建 system role |
| 频率惩罚 | ❌ 不支持 | frequency_penalty |
需用 system prompt 替代 |
| 存在惩罚 | ❌ 不支持 | presence_penalty |
需用 system prompt 替代 |
| 种子参数 | ❌ 不支持 | seed |
无法保证确定性输出 |
| 响应格式 | content blocks array | choices array | 解析路径不同 |
| logprobs | ❌ 不支持 | ✅ 支持 | 无法获取 token 概率 |
Anthropic 的 SSE(Server-Sent Events)流式输出使用 event-based 协议,与 OpenAI 的 data-only 格式不同。
event: message_start
data: {"type":"message_start","message":{"id":"msg_xxx","type":"message","role":"assistant","content":[],"model":"claude-3-5-sonnet-20241022","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":1}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: ping
data: {"type": "ping"}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hello"}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"! How can I"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":10}}
event: message_stop
data: {"type":"message_stop"}
每个事件包含 event 行和 data 行。完整的消息流程如下:
message_start → content_block_start → content_block_delta(×N) → content_block_stop → message_delta → message_stop
message_start:标记流开始,包含消息元数据content_block_start:每个 content block(文本、工具调用等)开始content_block_delta:增量内容,文本在 delta.text 中content_block_stop:content block 结束message_delta:消息级别元数据更新(token 计数)message_stop:整个消息结束from anthropic import Anthropic
client = Anthropic(api_key="sk-ant-xxx")
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Write a short poem about AI."}]
) as stream:
for chunk in stream:
if chunk.type == "content_block_delta":
print(chunk.delta.text, end="", flush=True)
# 从 OpenAI 迁移时的适配层
def process_anthropic_stream(stream):
collected_text = ""
for chunk in stream:
if chunk.type == "message_start":
print(f"[Message started, id={chunk.message.id}]")
elif chunk.type == "content_block_delta":
# 对应 OpenAI 的 delta.content
text = chunk.delta.text
collected_text += text
print(text, end="", flush=True)
elif chunk.type == "message_delta":
print(f"\n[Stop reason: {chunk.delta.stop_reason}]")
elif chunk.type == "message_stop":
print(f"\n[Complete, usage: {collected_text} chars]")
return collected_text
Anthropic 的 content 字段始终为数组,支持多种 content block 类型:
| Content Block 类型 | 用途 | 可以出现在 |
|---|---|---|
text |
纯文本 | user、assistant |
image |
图片(base64 编码) | user |
image_url |
图片(URL) | user |
document |
PDF 等文档 | user |
tool_use |
工具调用请求 | assistant |
tool_result |
工具调用结果 | user |
thinking |
模型推理过程 | assistant |
{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "/9j/4AAQSkZJRg..."
}
},
{
"type": "text",
"text": "What's in this image?"
}
]
}
图片限制:
Claude 的原生文档理解是其核心优势之一:
{
"role": "user",
"content": [
{
"type": "document",
"source": {
"type": "base64",
"media_type": "application/pdf",
"data": "JVBERi0xLjQK..."
}
},
{
"type": "text",
"text": "请用中文总结这份文档的要点"
}
]
}
文档处理能力:
| 能力 | 说明 | 典型场景 |
|---|---|---|
| 文本提取 | 从 PDF 中提取所有文本内容 | 论文分析、合同审查 |
| 表格识别 | 理解表格结构和数据 | 财报分析、数据报表 |
| 图像元素 | 识别 PDF 中的图片和图表 | 技术报告分析 |
| 长文档 | 一次性处理百页级文档 | 研究报告、书籍分析 |
| 多文档 | 在一次对话中处理多个文档 | 对比分析、文献综述 |
实际应用案例:使用 Claude 3.5 Sonnet 分析 300 页的招股说明书,提取所有财务数据和法律风险点,准确率约 95%,耗时不到 30 秒。
Anthropic 使用 input_schema(而非 OpenAI 的 parameters)定义工具参数:
{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"tools": [
{
"name": "get_weather",
"description": "Get current weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g. 'Beijing'"
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["city"]
}
},
{
"name": "search_web",
"description": "Search the web for information",
"input_schema": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"max_results": {"type": "integer", "description": "Max results to return"}
},
"required": ["query"]
}
}
]
}
User: "Paris的天气和最新新闻是什么?"
↓
Claude: {"type": "tool_use", "name": "get_weather", "input": {"city": "Paris", "units": "celsius"}}
↓
系统执行 get_weather,返回结果
↓
User: {"type": "tool_result", "tool_use_id": "xxx", "content": "15°C, Sunny"}
↓
Claude: {"type": "tool_use", "name": "search_web", "input": {"query": "Paris latest news 2026", "max_results": 5}}
↓
系统执行 search_web,返回结果
↓
User: {"type": "tool_result", "tool_use_id": "yyy", "content": "..."}
↓
Claude: {"type": "text", "text": "巴黎天气是15°C晴天..."}
关键区别:
tool_use 和 tool_result 是 content block type,作为 content 数组的元素tool_calls 是消息的顶层字段id 字段),在返回的 tool_use block 中from anthropic import Anthropic
client = Anthropic(api_key="sk-ant-xxx")
def get_weather(city: str, units: str = "celsius"):
"""Mock weather function"""
return f"The weather in {city} is 22° {'C' if units == 'celsius' else 'F'}"
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=[{
"name": "get_weather",
"description": "Get weather for a city",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"units": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}],
messages=[{"role": "user", "content": "What's the weather in Beijing?"}]
)
# 处理工具调用
for block in response.content:
if block.type == "tool_use":
# 执行工具
result = get_weather(**block.input)
# 将结果返回给模型
final_response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
tools=[...],
messages=[
{"role": "user", "content": "What's the weather in Beijing?"},
{"role": "assistant", "content": response.content},
{"role": "user", "content": [{
"type": "tool_result",
"tool_use_id": block.id,
"content": result
}]}
]
)
print(final_response.content[0].text)
Anthropic 的扩展思维功能允许模型在回答复杂问题时内部"思考"更长时间,类似于 OpenAI 的 o1 模型的推理模式。
{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 8192,
"thinking": {
"type": "enabled",
"budget_tokens": 4096
},
"messages": [
{"role": "user", "content": "证明 √2 是无理数"}
]
}
{
"content": [
{
"type": "thinking",
"thinking": "我们假设 √2 = p/q(最简分数),则 2 = p²/q²,p² = 2q²,说明 p 是偶数...",
"signature": "sig_xyz"
},
{
"type": "text",
"text": "√2 是无理数。证明如下:\n\n假设 √2 是有理数..."
}
]
}
| 问题复杂度 | 推荐 budget_tokens | 预期思考深度 |
|---|---|---|
| 简单问答 | 512 | 基本事实确认 |
| 代码评审 | 1024-2048 | 分析代码逻辑、检查边缘情况 |
| 数学证明 | 2048-4096 | 构造证明过程 |
| 复杂推理 | 4096-8192 | 深度推理、多步骤验证 |
| 长文档分析 | 4096+ | 全面分析文档内容 |
Claude 的 200K 上下文大约可以容纳 150,000 个英文单词或约 100,000 个中文字符。这相当于:
Anthropic 提供了 Prompt Caching 功能,用于降低长上下文场景的成本:
{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 1024,
"system": [
{"type": "text", "text": "You are a code review assistant.", "cache_control": {"type": "ephemeral"}}
],
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "请审查以下代码",
"cache_control": {"type": "ephemeral"}
},
{
"type": "text",
"text": "# 5000 行代码内容..."
}
]
}
]
}
缓存定价对比(以数百万 token 输入为例):
| 场景 | 无缓存 | 有缓存 | 节省 |
|---|---|---|---|
| 一次性分析 | $15(100K tokens, Sonnet) | - | - |
| 多次同一文档分析 | $15 × 10 次 = $150 | $1.5(首次读取)+ $1.5 × 9 = $15 | 节省 90% |
| 批量代码审查 | $30 × 100 = $3000 | $3 + $3 × 99 = $300 | 节省 90% |
Claude 3.5 Sonnet 的 Computer Use 功能是业界首创——AI 不仅能理解和生成文本,还能直接操作图形界面。
{
"model": "claude-3-5-sonnet-20241022",
"max_tokens": 4096,
"tools": [{
"type": "computer_20241022",
"name": "computer",
"display_width_px": 1920,
"display_height_px": 1080,
"display_number": 1
}],
"messages": [{
"role": "user",
"content": "打开浏览器,访问 example.com,截图给我看"
}]
}
需要添加 Beta Header:
anthropic-beta: computer-use-2024-10-22
| 操作 | 描述 | 参数 |
|---|---|---|
mouse_move |
移动鼠标到坐标 | (x, y) |
left_click |
左键点击 | (x, y) |
right_click |
右键点击 | (x, y) |
type |
键盘输入文本 | text |
keypress |
按键 | key_sequence |
screenshot |
截取屏幕 | - |
cursor_position |
获取鼠标位置 | - |
实际应用场景:
| HTTP 状态码 | 错误码 | 原因 | 处理方案 |
|---|---|---|---|
| 400 | invalid_request_error |
请求参数错误 | 检查请求格式 |
| 401 | authentication_error |
API Key 无效 | 检查 API Key |
| 403 | permission_error |
权限不足 | 检查 API Key 权限 |
| 404 | not_found_error |
模型或端点不存在 | 检查模型名称 |
| 429 | rate_limit_error |
速率限制 | 退避重试 |
| 500 | api_error |
服务端错误 | 退避重试 |
| 529 | overloaded_error |
服务过载 | 退避重试 |
import time
import random
from anthropic import Anthropic, RateLimitError, APIError
def retry_with_backoff(func, max_retries=5, base_delay=1.0):
"""指数退避重试"""
for attempt in range(max_retries):
try:
return func()
except RateLimitError as e:
wait = base_delay * (2 ** attempt) + random.uniform(0, 1)
print(f"速率限制,等待 {wait:.1f} 秒后重试(第 {attempt+1}/{max_retries} 次)")
time.sleep(wait)
except APIError as e:
if e.status_code == 529: # Overloaded
wait = base_delay * (2 ** attempt) + random.uniform(0, 2)
print(f"服务过载,等待 {wait:.1f} 秒后重试")
time.sleep(wait)
else:
raise
except Exception as e:
print(f"未知错误: {e}")
raise
raise Exception(f"重试 {max_retries} 次后仍然失败")
# 使用示例
client = Anthropic(api_key="sk-ant-xxx")
def call_claude():
return client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}]
)
response = retry_with_backoff(call_claude)
不同账户层级的速率限制差异显著:
| 层级 | RPM | TPM | 并发请求数 | 价格模型 |
|---|---|---|---|---|
| Free | 5 | 25K | 1 | 免费额度 |
| Build($5) | 50 | 50K | 2 | 按量付费 |
| Build($50) | 100 | 100K | 3 | 按量付费 |
| Build($200) | 500 | 500K | 5 | 按量付费 |
| Scale($1000+) | 1000 | 2M | 10 | 按量付费 |
| Enterprise | 自定义 | 自定义 | 自定义 | 合同定价 |
假设每天 10,000 次请求,每次平均输入 2000 tokens,输出 500 tokens:
| 模型 | 每日输入成本 | 每日输出成本 | 月成本 |
|---|---|---|---|
| Claude 3.5 Sonnet | $60 $75 | ~$4050 | |
| Claude 3.5 Haiku | $16 $20 | ~$1080 | |
| Claude 3 Opus | $300 $375 | ~$20250 |
| 策略 | 节省 | 实现方式 |
|---|---|---|
| Prompt Caching | 高达 90% | 对长上下文复用启用缓存 |
| 模型选择 | 可节省 80% | 简单任务使用 Haiku 而非 Opus |
| Batch API | 可节省 50% | 批量处理非实时任务 |
| 输入压缩 | 10-30% | 精简 prompt、移除冗余 |
| 输出限制 | 可变 | 设置合理的 max_tokens |
| 能力级别 | Anthropic 模型 | Anthropic 价格 (per M tokens) | OpenAI 模型 | OpenAI 价格 (per M tokens) |
|---|---|---|---|---|
| 经济型 | Haiku | $0.80 / $4 | GPT-4o Mini | $0.15 / $0.60 |
| 标准型 | Sonnet | $3 / $15 | GPT-4o | $2.50 / $10 |
| 旗舰型 | Opus | $15 / $75 | GPT-4o Turbo | $10 / $30 |
import anthropic
client = anthropic.Anthropic(api_key="sk-ant-xxx")
def chat_with_claude(
system_prompt: str,
messages: list,
max_tokens: int = 1024,
temperature: float = 0.7
):
"""与 Claude 对话的封装函数"""
try:
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=max_tokens,
temperature=temperature,
system=system_prompt,
messages=messages
)
return {
"text": response.content[0].text,
"usage": response.usage.input_tokens + response.usage.output_tokens
}
except Exception as e:
return {"error": str(e), "text": None}
# 多轮对话
messages = [
{"role": "user", "content": "Python 中 '== '和 'is' 有什么区别?"}
]
response = chat_with_claude("你是一个 Python 导师", messages)
print(response["text"])
# 继续对话
messages.append({
"role": "assistant",
"content": response["text"]
})
messages.append({
"role": "user",
"content": "能给我一个具体的例子吗?"
})
response = chat_with_claude("你是一个 Python 导师", messages)
print(response["text"])
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: 'sk-ant-xxx',
});
async function chatCompletion() {
const response = await client.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 1024,
system: 'You are a helpful TypeScript developer assistant.',
messages: [
{ role: 'user', content: 'Explain TypeScript generics with examples' }
]
});
console.log(response.content[0].text);
}
Anthropic 提供了 OpenAI-compatible 端点(有限支持):
from openai import OpenAI
client = OpenAI(
api_key="your-anthropic-api-key",
base_url="https://api.anthropic.com/v1"
)
# ⚠️ 注意:
# 1. 只支持 Messages API,不支持 Completions
# 2. system 参数需要特殊处理
# 3. 建议使用官方 Anthropic SDK 获取完整功能
# === OpenAI (旧) ===
import openai
openai.api_key = "sk-xxx"
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[
{"role": "system", "content": "Be concise."},
{"role": "user", "content": "Explain AI"}
],
max_tokens=100, # 可选
temperature=0.7,
stream=True
)
for chunk in response:
print(chunk.choices[0].delta.content or "")
# === Anthropic (新) ===
import anthropic
client = anthropic.Anthropic(api_key="sk-ant-xxx")
with client.messages.stream(
model="claude-3-5-sonnet-20241022",
max_tokens=100, # 必填!
system="Be concise.", # 独立参数
messages=[
{"role": "user", "content": "Explain AI"}
],
temperature=0.7
) as stream:
for chunk in stream:
if chunk.type == "content_block_delta" and chunk.delta.type == "text_delta":
print(chunk.delta.text, end="")
| 功能 | OpenAI 语法 | Anthropic 语法 |
|---|---|---|
| 认证 | Authorization: Bearer |
x-api-key |
| 系统提示 | messages[0].role = "system" |
system 顶层参数 |
| 消息 | messages 数组 |
messages 数组 |
| 模型 | gpt-4, gpt-3.5-turbo |
claude-3-5-sonnet-xxx |
| 流式 | stream=True |
stream=True |
| 工具 | tools + tool_choice |
tools + tool_choice |
| 响应解析 | choices[0].message.content |
content[0].text |
| Token 计数 | usage.prompt_tokens |
usage.input_tokens |
Anthropic 的核心差异在于其 Constitutional AI(CAI)训练方法:
实际效果对比:
| 测试维度 | Claude 3.5 Sonnet | GPT-4o | 说明 |
|---|---|---|---|
| 有害请求拒绝率 | 98.5% | 96.2% | 安全基准测试 |
| 拒绝精度 | 95.1% | 92.8% | 不误伤合法请求 |
| 政策合规 | 94.7% | 91.3% | 遵循使用政策 |
| 偏见检测 | 低偏见 | 中等 | BBQ 测试 |