欢迎回来

登录 EAKE AI,继续您的智能之旅

忘记密码?
还没有账号?立即注册

Anthropic Claude SDK 使用指南

2026-05-07 · Anthropic

概述

Anthropic Claude SDK for Python提供从Python应用程序访问Claude API的能力。

安装

pip install anthropic

快速开始

import os
from anthropic import Anthropic

client = Anthropic(
    api_key=os.environ.get("ANTHROPIC_API_KEY")
)

message = client.messages.create(
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": "Hello, Claude"
        }
    ],
    model="claude-opus-4-6",
)
print(message.content)

重要参数

模型选择

模型描述适合场景
claude-opus-4-6最强性能复杂推理
claude-sonnet-4-6平衡日常任务
claude-haiku-3-5最快简单任务

max_tokens

生成的最大token数。设置较大值可获得更长输出:

message = client.messages.create(
    max_tokens=4096,
    messages=[...],
    model="claude-opus-4-6"
)

系统提示词

message = client.messages.create(
    max_tokens=1024,
    system="你是一个专业的AI助手,擅长技术写作",
    messages=[
        {"role": "user", "content": "解释什么是机器学习"}
    ],
    model="claude-opus-4-6"
)

图像输入(Claude 3.5+)

message = client.messages.create(
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": "..."}},
                {"type": "text", "text": "这张图片里有什么?"}
            ]
        }
    ],
    model="claude-opus-4-6"
)

流式响应

with client.messages.stream(
    max_tokens=1024,
    messages=[{"role": "user", "content": "写一个故事"}],
    model="claude-sonnet-4-6"
) as stream:
    for text in stream.text_deltas:
        print(text, end="")

工具使用(Function Calling)

from anthropic import Anthropic

client = Anthropic()

tools = [
    {
        "name": "get_weather",
        "description": "获取指定城市的天气",
        "input_schema": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "城市名称"}
            },
            "required": ["city"]
        }
    }
]

message = client.messages.create(
    max_tokens=1024,
    tools=tools,
    messages=[
        {"role": "user", "content": "北京天气怎么样?"}
    ],
    model="claude-opus-4-6"
)

if message.stop_reason == "tool_use":
    tool_call = message.tool_calls[0]
    if tool_call.name == "get_weather":
        result = get_weather(tool_call.input["city"])

Thinking模式

Claude 4.0+支持思考过程:

message = client.messages.create(
    max_tokens=4096,
    thinking={"type": "enabled", "budget_tokens": 4096},
    messages=[{"role": "user", "content": "计算123*456"}],
    model="claude-opus-4-6"
)

print(message.thinking)
print(message.content)

错误处理

from anthropic import Anthropic, RateLimitError, APIStatusError

client = Anthropic()

try:
    message = client.messages.create(...)
except RateLimitError:
    print("速率超限")
except APIStatusError as e:
    print(f"API错误: {e.status_code} - {e.message}")

Python版本要求

Python 3.9+

相关链接

评论区

发表评论