> For the complete documentation index, see [llms.txt](https://yeasy.gitbook.io/claude_guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://yeasy.gitbook.io/claude_guide/fu-lu/12_appendix/12.1_api_ref.md).

# 附录 A：API 参考手册

本手册涵盖了 Python SDK 和 TypeScript SDK 的高频用法。 完整的 API 文档请参考 [platform.claude.com/docs](https://platform.claude.com/docs)。

> **版本提示**：模型 ID、上下文窗口、beta header 和工具能力会随 Anthropic 发布节奏变化。生产代码应把模型名和 beta 开关放在配置中，并在升级前按官方文档和回归测试确认。

```mermaid
graph TD
    classDef core fill:#2a4b7c,stroke:#fff,stroke-width:2px,color:#fff;
    classDef feature fill:#4a6b9c,stroke:#fff,stroke-width:2px,color:#fff;
    classDef param fill:#e6f2ff,stroke:#2a4b7c,stroke-width:1px,color:#333;

    A[Anthropic API]:::core --> B(Messages API):::core

    B --> C1[核心参数]:::feature
    B --> C2[高级功能]:::feature

    C1 --> P1("model (必填)<br>claude-sonnet-5-5..."):::param
    C1 --> P2("max_tokens (必填)<br>最大生成长度"):::param
    C1 --> P3("messages (必填)<br>[{role: 'user', content: '...'}]"):::param
    C1 --> P4("system (可选)<br>系统提示词"):::param
    C1 --> P5("temperature (可选)<br>0.0 - 1.0, 默认 1.0"):::param

    C2 --> F1["流式输出 (Streaming)"]:::feature
    C2 --> F2["工具使用 (Tool Use)"]:::feature
    C2 --> F3["视觉能力 (Vision)"]:::feature
    C2 --> F4["提示词缓存 (Prompt Caching)"]:::feature

    F1 -.-> |"stream=True"| S1("Server-Sent Events (SSE)"):::param
    F2 -.-> |"tools=[{...}]"| S2("定义 schema, 处理 tool_use 停止原因"):::param
    F3 -.-> |"type: image"| S3("传递 base64 编码的图像数据"):::param
    F4 -.-> |"cache_control"| S4("ephemeral 标记, 降低长上下文成本"):::param
```

## 12.1.1 基础消息

所有交互的核心。

### Python

```python
import anthropic

client = anthropic.Anthropic() # 自动读取 ANTHROPIC_API_KEY

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    system="You are a helpful assistant.",
    messages=[
        {"role": "user", "content": "Explain quantum computing."}
    ]
)
print("".join(b.text for b in message.content if b.type == "text"))
```

### TypeScript

```typescript
import Anthropic from '@anthropic-ai/sdk';

const client = new Anthropic();

const message = await client.messages.create({
  model: 'claude-sonnet-5-5',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello, Claude' }],
});
console.log(
  message.content
    .filter((b): b is Anthropic.TextBlock => b.type === 'text')
    .map((b) => b.text)
    .join(''),
);
```

### 关键参数说明

* `model`: 模型 ID。示例模型包括 `claude-sonnet-5-5`、`claude-opus-5-5`、`claude-haiku-4-5-20251001`；Haiku 4.5 也有便捷别名 `claude-haiku-4-5`。实际可用列表以官方模型文档、Models API 和账号权限为准。
* `max_tokens`: 最多生成多少 Token。**必须指定**。
* `temperature`: 控制采样随机性的可选参数。`0` 会降低随机性，但不保证完全确定性。Sonnet 5 与 Sonnet 5.5 默认使用 Adaptive Thinking，手动 extended thinking 和非默认采样参数会返回 HTTP 400；迁移时应删除这些参数并按当前 API 文档处理。
* `system`: 系统提示词。

## 12.1.2 流式输出

提高首字响应速度 (TTFT)。

### Python

```python
with client.messages.stream(
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a long story..."}],
    model="claude-sonnet-5-5",
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
```

## 12.1.3 工具使用

### Tool Definition

```python
tools = [{
    "name": "get_weather",
    "description": "Get current weather",
    "input_schema": {
        "type": "object",
        "properties": {
            "location": {"type": "string"}
        },
        "required": ["location"]
    }
}]
```

### Handling Tool Calls

```python
response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    tools=tools,
    messages=[{"role": "user", "content": "How is weather in Tokyo?"}]
)

if response.stop_reason == "tool_use":
    tool_results = []
    for block in response.content:
        if block.type != "tool_use":
            continue
        # ... 根据 block.name / block.input 执行工具逻辑 ...
        tool_results.append({
            "type": "tool_result",
            "tool_use_id": block.id,
            "content": "...工具执行结果..."
        })

    messages = [
        {"role": "user", "content": "How is weather in Tokyo?"},
        {"role": "assistant", "content": response.content},
        {"role": "user", "content": tool_results},
    ]
```

## 12.1.4 图像理解

支持 JPEG, PNG, GIF, WEBP。单张图片建议压缩在 5MB 以内。

```python
import base64

with open("image.jpg", "rb") as image_file:
    image_data = base64.b64encode(image_file.read()).decode("utf-8")

message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/jpeg",
                        "data": image_data,
                    },
                },
                {"type": "text", "text": "Describe this image."}
            ],
        }
    ],
)
```

## 12.1.5 提示缓存

提示缓存已正式发布（GA），无需额外的 beta header，直接在内容块中添加 `cache_control` 即可。

```python
system_message = [
    {
        "type": "text",
        "text": "Huge context text...",
        "cache_control": {"type": "ephemeral"} # 标记缓存点
    }
]
```

## 12.1.6 错误代码对照表

| Error Code                  | 含义    | 解决方案                            |
| --------------------------- | ----- | ------------------------------- |
| `400 invalid_request_error` | 参数错误  | 检查 JSON Schema 或 Token 限制。      |
| `401 authentication_error`  | 鉴权失败  | 检查 API Key 是否正确/过期。             |
| `403 permission_error`      | 权限不足  | 检查账号是否被封禁或地区限制。                 |
| `429 rate_limit_error`      | 速率限制  | 实现指数退避重试 (Exponential Backoff)。 |
| `500 api_error`             | 服务器错误 | Anthropic 侧故障，稍后重试。             |
| `529 overloaded_error`      | 负载过高  | 临时繁忙，稍后重试。                      |

## 12.1.7 可执行 Messages API 参考

[`examples/messages_api.py`](https://github.com/yeasy/claude_guide/tree/main/examples/messages_api.py) 将请求构造与传输函数分离，可用 fake transport 离线验证 Messages schema、文本块拼接与 `stop_reason: "refusal"` 分支。安装锁定依赖后直接运行该文件，真实凭据只通过 SDK 默认环境配置读取。
