Skip to content

Claude API

Claude是Anthropic推出的大语言模型,以其强大的编程能力和安全性著称。本节介绍如何使用Claude API开发AI应用。

快速开始

获取API密钥

  1. 访问 console.anthropic.com
  2. 注册或登录账号
  3. 在API Keys页面创建密钥

安装SDK

bash
pip install anthropic

基本调用

python
import anthropic

client = anthropic.Anthropic(api_key="your-api-key")

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "你好!"}
    ]
)

print(message.content[0].text)

模型选择

可用模型(2025年)

模型特点适用场景价格(输入/输出)
claude-opus-4最强能力复杂任务$15/$75 每百万Token
claude-sonnet-4性价比高日常开发$3/$15 每百万Token
claude-haiku快速便宜简单任务$0.8/$4 每百万Token

Claude的优势

  • 编程能力强:在SWE-bench测试中领先
  • 上下文窗口大:支持高达1M Token
  • 安全性高:注重减少有害输出
  • 诚实性:不确定时会明确说明

高级功能

System Prompt

python
message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    system="你是一位专业的Python工程师,回答简洁专业。",
    messages=[
        {"role": "user", "content": "如何读取JSON文件?"}
    ]
)

流式输出

python
with client.messages.stream(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[{"role": "user", "content": "写一首诗"}]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

工具使用

python
message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=[
        {
            "name": "get_weather",
            "description": "获取城市天气",
            "input_schema": {
                "type": "object",
                "properties": {
                    "city": {"type": "string"}
                },
                "required": ["city"]
            }
        }
    ],
    messages=[{"role": "user", "content": "北京天气如何?"}]
)

if message.stop_reason == "tool_use":
    for block in message.content:
        if block.type == "tool_use":
            print(f"调用工具: {block.name}")
            print(f"参数: {block.input}")

提示缓存

python
message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "很长的文档内容...",
                    "cache_control": {"type": "ephemeral"}
                },
                {"type": "text", "text": "请总结这个文档"}
            ]
        }
    ]
)

与OpenAI API的区别

特性Claude APIOpenAI API
System Prompt独立参数在messages中
最大上下文1M Token128K Token
工具调用tool_usefunction_call
图像输入支持支持

小结

Claude API的核心要点:

要点说明
模型选择Sonnet性价比最高,Opus能力最强
System Prompt作为独立参数传入
工具使用支持AI调用外部函数
提示缓存可节省90%成本

下一步

继续学习 国内大模型APILangChain框架