Claude API 简介
Anthropic Claude API 提供了强大的 AI 模型访问,以安全性和准确性著称。Claude 在编程、分析、写作等任务上表现出色,是构建企业级 AI 应用的理想选择。
#为什么使用 Claude API?
#1. 出色的代码能力
Claude 在编程任务上的优势:
- 代码生成准确率高
- 理解复杂代码逻辑
- 较少的"幻觉"问题
- 支持多种编程语言
#2. 超长上下文
| 模型 | 上下文长度 |
|---|---|
| Claude 3.5 Sonnet | 200K tokens |
| Claude 3 Opus | 200K tokens |
| Claude 3 Haiku | 200K tokens |
200K tokens ≈ 15 万字,可以一次处理完整代码库。
#3. 安全可靠
- Constitutional AI 技术
- 较少有害输出
- 企业级安全认证
- 数据隐私保护
#模型选择
| 模型 | 特点 | 适用场景 | 价格 |
|---|---|---|---|
| Claude 3.5 Sonnet | 最强综合性能 | 日常开发首选 | 中等 |
| Claude 3 Opus | 最强推理能力 | 复杂分析任务 | 较高 |
| Claude 3 Haiku | 最快响应 | 实时交互 | 最低 |
#快速开始
#1. 获取 API Key
- 注册 Anthropic 账号↗
- 进入 API Keys 页面
- 创建新的 API Key
#2. 安装 SDK
Python:
bashpip install anthropic
Node.js:
bashnpm install @anthropic-ai/sdk
#3. 第一次调用
Python:
pythonimport anthropic client = anthropic.Anthropic(api_key="your-api-key") message = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, messages=[ {"role": "user", "content": "用 Python 写一个快速排序算法"} ] ) print(message.content[0].text)
Node.js:
typescriptimport Anthropic from '@anthropic-ai/sdk'; const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, }); async function main() { const message = await anthropic.messages.create({ model: 'claude-3-5-sonnet-20241022', max_tokens: 1024, messages: [ { role: 'user', content: '用 TypeScript 写一个快速排序算法' }, ], }); console.log(message.content[0].text); } main();
#核心 API
#Messages API
主要的对话接口:
pythonmessage = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, system="你是一个专业的代码审查专家", messages=[ {"role": "user", "content": "审查这段代码..."}, {"role": "assistant", "content": "我来帮你审查..."}, {"role": "user", "content": "还有其他问题吗?"} ] )
#流式输出
实时返回生成内容:
pythonwith client.messages.stream( model="claude-3-5-sonnet-20241022", max_tokens=1024, messages=[{"role": "user", "content": "写一篇文章"}] ) as stream: for text in stream.text_stream: print(text, end="", flush=True)
#Tool Use (函数调用)
让 Claude 调用自定义工具:
pythontools = [ { "name": "get_weather", "description": "获取指定城市的天气信息", "input_schema": { "type": "object", "properties": { "city": { "type": "string", "description": "城市名称" } }, "required": ["city"] } } ] message = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, tools=tools, messages=[{"role": "user", "content": "北京天气怎么样?"}] ) # Claude 会返回 tool_use 请求 for block in message.content: if block.type == "tool_use": print(f"调用工具: {block.name}") print(f"参数: {block.input}")
#Vision (图像理解)
Claude 可以理解图像:
pythonimport base64 with open("image.png", "rb") as f: image_data = base64.standard_b64encode(f.read()).decode() message = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, messages=[ { "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": image_data } }, {"type": "text", "text": "描述这张图片"} ] } ] )
#高级功能
#Prompt Caching
缓存常用提示,节省成本:
pythonmessage = client.messages.create( model="claude-3-5-sonnet-20241022", max_tokens=1024, system=[ { "type": "text", "text": "你是一个代码专家...(很长的系统提示)", "cache_control": {"type": "ephemeral"} } ], messages=[{"role": "user", "content": "问题"}] )
#Batch API
批量处理请求:
pythonbatch = client.batches.create( requests=[ {"custom_id": "1", "params": {...}}, {"custom_id": "2", "params": {...}}, ] )
#API 定价
| 模型 | 输入 | 输出 |
|---|---|---|
| Claude 3.5 Sonnet | $3/M tokens | $15/M tokens |
| Claude 3 Opus | $15/M tokens | $75/M tokens |
| Claude 3 Haiku | $0.25/M tokens | $1.25/M tokens |
#最佳实践
#1. 使用系统提示
pythonmessage = client.messages.create( model="claude-3-5-sonnet-20241022", system="""你是一个 Python 专家。 - 使用类型提示 - 添加 docstring - 遵循 PEP 8 规范 """, messages=[...] )
#2. 错误处理
pythonimport anthropic try: message = client.messages.create(...) except anthropic.RateLimitError: print("达到速率限制,请稍后重试") except anthropic.APIError as e: print(f"API 错误: {e}")
#3. Token 管理
python# 检查响应的 token 使用 print(f"输入 tokens: {message.usage.input_tokens}") print(f"输出 tokens: {message.usage.output_tokens}")
#下一步
- 快速开始 - 详细入门教程
- Tool Use - 学习函数调用
- Prompt Caching - 优化成本
提示:Claude API 持续更新,查看 官方文档↗ 获取最新信息。