Claude API 简介
Claude API 允许开发者将 Claude 的能力集成到自己的应用中。本文介绍如何使用 Claude API。
快速开始
1. 获取 API Key
首先需要在 Anthropic 官网注册并获取 API Key。
2. 安装 SDK
Python:
pip install anthropic
Node.js:
npm install @anthropic-ai/sdk
3. 基础调用
Python 示例:
import anthropic
client = anthropic.Anthropic(
api_key="your-api-key"
)
message = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[
{"role": "user", "content": "你好,请介绍一下你自己"}
]
)
print(message.content[0].text)
Node.js 示例:
import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic({
apiKey: 'your-api-key',
});
async function main() {
const message = await client.messages.create({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 1024,
messages: [
{ role: 'user', content: '你好,请介绍一下你自己' }
],
});
console.log(message.content[0].text);
}
main();
API 参数说明
主要参数
| 参数 | 说明 | 示例 |
|---|---|---|
| model | 模型名称 | claude-sonnet-4-5-20250929 |
| max_tokens | 最大输出 token 数 | 1024 |
| messages | 对话消息列表 | [{“role”: “user”, “content”: “…”}] |
| temperature | 随机性(0-1) | 0.7 |
| system | 系统提示词 | “你是一个专业的助手” |
模型选择
| 模型 | 特点 | 适用场景 |
|---|---|---|
| claude-sonnet-4-5-20250929 | 最新最强 | 复杂任务 |
| claude-3-opus | 深度思考 | 研究分析 |
| claude-3-haiku | 快速响应 | 简单查询 |
高级用法
流式输出
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=[{"role": "user", "content": "写一首诗"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
多轮对话
messages = [
{"role": "user", "content": "我想学习 Python"},
{"role": "assistant", "content": "很好!Python 是一门很棒的编程语言..."},
{"role": "user", "content": "应该从哪里开始?"}
]
response = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
messages=messages
)
系统提示词
response = client.messages.create(
model="claude-sonnet-4-5-20250929",
max_tokens=1024,
system="你是一个专业的 Python 开发专家,回答要简洁专业。",
messages=[
{"role": "user", "content": "如何处理异常?"}
]
)
错误处理
import anthropic
try:
response = client.messages.create(...)
except anthropic.APIError as e:
print(f"API 错误: {e}")
except anthropic.AuthenticationError as e:
print(f"认证错误: {e}")
except anthropic.RateLimitError as e:
print(f"速率限制: {e}")
不想用 API?试试这些平台
如果你不想自己接入 API,可以直接使用这些平台:
- Claude 官网镜像 - 无需开发,直接使用
- Claude 中文版 - 中文界面,开箱即用
- Claude 镜像站 - 多模型支持
总结
Claude API 功能强大,接入简单。无论是构建聊天机器人、内容生成工具还是智能助手,Claude API 都是理想的选择。
🔗 推荐 Claude 访问方式
想要体验 Claude Sonnet 4.5 的强大功能?试试以下国内可用的访问方式:
- Claude 官网镜像 - 原汁原味的 Claude 体验
- Claude 中文版 - 中文优化版本
- Claude 镜像站 - 稳定快速访问