[ PROMPT_NODE_23832 ]
Claude API 说明文档
[ SKILL_DOCUMENTATION ]
# Claude API — Python
## 安装
bash
pip install anthropic
## 客户端初始化
python
import anthropic
# 默认(使用 ANTHROPIC_API_KEY 环境变量)
client = anthropic.Anthropic()
# 显式 API 密钥
client = anthropic.Anthropic(api_key="your-api-key")
# 异步客户端
async_client = anthropic.AsyncAnthropic()
---
## 基础消息请求
python
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
messages=[
{"role": "user", "content": "What is the capital of France?"}
]
)
# response.content 是内容块对象(TextBlock, ThinkingBlock, ToolUseBlock 等)的列表。
# 在访问 .text 之前请检查 .type。
for block in response.content:
if block.type == "text":
print(block.text)
---
## 系统提示词 (System Prompts)
python
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
system="You are a helpful coding assistant. Always provide examples in Python.",
messages=[{"role": "user", "content": "How do I read a JSON file?"}]
)
---
## 视觉能力 (Images)
### Base64
python
import base64
with open("image.png", "rb") as f:
image_data = base64.standard_b64encode(f.read()).decode("utf-8")
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
messages=[{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/png",
"data": image_data
}
},
{"type": "text", "text": "What's in this image?"}
]
}]
)
### URL
python
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=16000,
messages=[{
"role": "user",
"content": [
{
"type": "image",
"source": {
"type": "url",
"url": "https://example.com/image.png"
}
},
{"type": "text", "text": "Describe this image"}
]
}]
)
---
## 提示词缓存 (Prompt Caching)
缓存大上下文以降低成本(最高可节省 90%)。**缓存是前缀匹配** — 前缀中任何位置的字节更改都会使之后的所有内容失效。关于放置模式、架构指导(固定的系统提示词、确定性的工具顺序、易变内容的位置)以及静默失效 au