> 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)。

> **版本提示（核验日期：2026-06-10）**：模型 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-4-6..."):::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-4-6",
    max_tokens=1024,
    system="You are a helpful assistant.",
    messages=[
        {"role": "user", "content": "Explain quantum computing."}
    ]
)
print(message.content[0].text)
```

### TypeScript

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

const client = new Anthropic();

const message = await client.messages.create({
  model: 'claude-sonnet-4-6',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello, Claude' }],
});
console.log(message.content[0].text);
```

### 关键参数说明

* `model`: 模型 ID。示例模型包括 `claude-opus-4-8`、`claude-sonnet-4-6`、`claude-haiku-4-5-20251001`；Haiku 4.5 也有便捷别名 `claude-haiku-4-5`。实际可用列表以官方模型文档、Models API 和账号权限为准。
* `max_tokens`: 最多生成多少 Token。**必须指定**。
* `temperature`: 控制采样随机性的可选参数。`0` 会降低随机性，但不保证完全确定性；部分新模型（例如 Opus 4.7）对非默认采样参数支持更严格，迁移前应查当前 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-4-6",
) 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-4-6",
    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-4-6",
    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`      | 负载过高  | 临时繁忙，稍后重试。                      |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://yeasy.gitbook.io/claude_guide/fu-lu/12_appendix/12.1_api_ref.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
