☰ 速查表
关键 API、参数、模式一览 · 支持搜索 · 可打印
API 认证 & 基础
Base URL
https://api.anthropic.com/v1/messages
必须 Headers
x-api-key: <YOUR_API_KEY>
anthropic-version: 2023-06-01
content-type: application/json
必须 Body 参数
model (string) — 模型 ID,如 claude-opus-4-5
max_tokens (int) — 最大输出 token 数
messages (array) — 对话消息列表
常用模型 ID
claude-opus-4-5
claude-sonnet-4-5
claude-haiku-3-5
(最新列表见 docs.anthropic.com/models)
Python 基础示例
使用 anthropic SDK 发送单条消息
import anthropic
client = anthropic.Anthropic(api_key="YOUR_API_KEY") # 也可读取环境变量 ANTHROPIC_API_KEY
message = client.messages.create(
model="claude-opus-4-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude!"}
]
)
print(message.content[0].text)
# message.stop_reason -> "end_turn" | "max_tokens" | "tool_use" | "stop_sequence"
# message.usage.input_tokens / output_tokens响应对象关键字段
id — 消息唯一 ID
type — "message"
role — "assistant"
content — 内容块列表
stop_reason — 停止原因
usage.input_tokens / output_tokens
消息格式 & 对话
role 取值
"user" — 用户消息
"assistant" — 助手消息
(messages 数组必须以 user 开头,角色交替出现)
content 格式
字符串形式: "Hello!"
数组形式(多模态):
[{type:"text", text:"..."}, {type:"image", source:{...}}]
图片 source 支持 base64 或 URL
System Prompt 放置位置
system 是 messages.create() 的顶级参数,不放入 messages 数组。
可以是字符串,也可以是带 cache_control 的数组。
message = client.messages.create(
model="claude-opus-4-5",
max_tokens=1024,
system="You are a helpful assistant.", # 顶级参数
messages=[{"role": "user", "content": "Hi"}]
)多轮对话 — 手动累积
SDK 不自动保存历史,需将 assistant 回复追加到 messages 列表后再发起下一轮请求。
messages = []
# 第一轮
messages.append({"role": "user", "content": "What is 2+2?"})
resp = client.messages.create(model="claude-opus-4-5", max_tokens=256, messages=messages)
messages.append({"role": "assistant", "content": resp.content[0].text})
# 第二轮
messages.append({"role": "user", "content": "Multiply that by 3."})
resp2 = client.messages.create(model="claude-opus-4-5", max_tokens=256, messages=messages)
print(resp2.content[0].text)流式输出 (Streaming)
使用 client.messages.stream() 上下文管理器逐 token 输出。
with client.messages.stream(
model="claude-opus-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Tell me a story"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)Tool Use (工具调用)
工具定义结构
name (string) — 工具名称(字母/数字/下划线)
description (string) — 详细描述,模型据此决定是否调用
input_schema (object) — JSON Schema,定义参数结构
tools = [
{
"name": "get_weather",
"description": "Get current weather for a city. Returns temperature and conditions.",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}
]tool_choice 参数
{"type": "auto"} — 模型自主决定(默认)
{"type": "any"} — 必须调用某个工具
{"type": "tool", "name": "get_weather"} — 强制调用指定工具
完整工具调用流程
1. 发送请求(含 tools 定义)
2. 若 stop_reason=="tool_use",提取 tool_use 块
3. 执行工具,获取结果
4. 将 tool_result 追加到 messages 中
5. 再次调用 API 获取最终回复
import anthropic, json
client = anthropic.Anthropic()
def get_weather(city: str, unit: str = "celsius") -> str:
return json.dumps({"city": city, "temp": 22, "conditions": "sunny", "unit": unit})
tools = [{
"name": "get_weather",
"description": "Get current weather for a city.",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["city"]
}
}]
messages = [{"role": "user", "content": "What's the weather in Tokyo?"}]
# 第一次调用
resp = client.messages.create(
model="claude-opus-4-5", max_tokens=1024,
tools=tools, messages=messages
)
if resp.stop_reason == "tool_use":
# 提取 tool_use 块
tool_block = next(b for b in resp.content if b.type == "tool_use")
tool_name = tool_block.name
tool_input = tool_block.input
# 执行工具
result = get_weather(**tool_input)
# 构建 tool_result 消息
messages.append({"role": "assistant", "content": resp.content})
messages.append({
"role": "user",
"content": [{
"type": "tool_result",
"tool_use_id": tool_block.id,
"content": result
}]
})
# 第二次调用获取最终答案
final = client.messages.create(
model="claude-opus-4-5", max_tokens=1024,
tools=tools, messages=messages
)
print(final.content[0].text)并行工具调用
同一轮模型可返回多个 tool_use 块。应并行执行所有工具,然后一次性将所有 tool_result 放入同一个 user 消息的 content 数组中。
错误处理
tool_result 中设置 "is_error": true 可通知模型工具调用失败。
content 填入错误信息,模型会尝试恢复或提示用户。
Prompt Caching
cache_control 语法
在内容块中添加 "cache_control": {"type": "ephemeral"} 标记缓存断点。
Cache TTL
5 分钟(默认 ephemeral)
每个 API key 最多 4 个缓存断点同时有效。
可以缓存的位置
1. system prompt(整个系统提示或其中一段)
2. messages 中靠前的大段文本(如长文档、工具定义)
3. 原则:把稳定的、大的内容放在前面并加缓存断点
缓存命中指标
usage.cache_creation_input_tokens — 首次写入缓存的 token 数
usage.cache_read_input_tokens — 命中缓存读取的 token 数(约 10% 成本)
Python 示例 — 系统提示缓存
对大型系统提示启用缓存,减少重复 token 计费
import anthropic
client = anthropic.Anthropic()
LONG_SYSTEM_PROMPT = "..." * 500 # 假设很长的系统提示
message = client.messages.create(
model="claude-opus-4-5",
max_tokens=1024,
system=[
{
"type": "text",
"text": LONG_SYSTEM_PROMPT,
"cache_control": {"type": "ephemeral"} # 缓存断点
}
],
messages=[{"role": "user", "content": "Summarize your instructions."}]
)
print(message.usage)
# cache_creation_input_tokens: N (首次)
# cache_read_input_tokens: N (后续命中)Python 示例 — 工具定义缓存
工具定义量大时缓存可显著降低成本
tools_with_cache = [
{
"name": "tool_one",
"description": "...",
"input_schema": {"type": "object", "properties": {}}
},
# ... 更多工具
{
"name": "last_tool",
"description": "...",
"input_schema": {"type": "object", "properties": {}},
"cache_control": {"type": "ephemeral"} # 在最后一个工具后打断点
}
]Extended Thinking
什么是 Extended Thinking
模型在生成最终回复前进行内部推理(chain-of-thought),适合数学、逻辑、复杂分析等任务。思考过程以 thinking 内容块返回。
启用方式
在请求中传入 thinking 参数:
{"type": "enabled", "budget_tokens": N}
budget_tokens 控制最大思考 token 数(建议 1024–10000+)
thinking 内容块
type: "thinking"
thinking: 内部推理文本(对用户透明)
最终回复仍是 type: "text" 块
注意:thinking 块不计入 output_tokens 费用
适用场景
- 数学证明 / 竞赛题
- 多步逻辑推理
- 代码调试(复杂 bug)
- 策略规划
- 不适合:简单问答、创意写作(浪费 token)
Python 示例
启用 thinking 模式解决数学题
import anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-opus-4-5",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000 # 允许最多 10k token 用于思考
},
messages=[{
"role": "user",
"content": "Prove that sqrt(2) is irrational."
}]
)
for block in response.content:
if block.type == "thinking":
print("=== Internal Thinking ===")
print(block.thinking)
elif block.type == "text":
print("=== Final Answer ===")
print(block.text)注意事项
- 启用 thinking 后 temperature 自动为 1,不可修改
- 不支持 top_p / top_k
- streaming 支持(thinkingDelta 事件)
- thinking 内容在多轮对话中需原样传回
RAG & 向量搜索
RAG 完整流程
1. 文档分块 (Chunking)
2. 向量化 (Embedding)
3. 存入向量数据库
4. 用户 Query 向量化
5. 检索 Top-K 相似块
6. 构建 Prompt(Query + 检索结果)
7. Claude 生成最终答案
分块策略
固定大小:每块 N token,overlap M token(简单通用)
语义分块:按段落/章节边界切分(保语义完整性)
递归分块:先大后小,保留层级结构
推荐:256–512 token/块,10–15% overlap
余弦相似度公式
cos(θ) = (A · B) / (‖A‖ × ‖B‖)
范围 [-1, 1],越接近 1 越相似。
向量数据库(FAISS/Pinecone/Weaviate)内置此计算。
BM25 稀疏检索
BM25 是经典词频-逆文档频率算法,不需要 embedding。
优点:精确关键词匹配、无需 GPU、可解释
缺点:不理解语义同义词
Elasticsearch 默认使用 BM25
混合检索 (Hybrid Search)
同时运行向量检索(语义)+ BM25(关键词),用 RRF(倒数排名融合)或加权求和合并排名。
RRF score = Σ 1/(k + rank_i),k 通常取 60。
Contextual Retrieval(Anthropic 方案)
在分块前让 Claude 为每个 chunk 生成简短上下文描述,然后将"描述 + chunk"一起 embed。
可使检索准确率提升 ~49%。
结合 BM25 + Contextual Embedding 效果最佳。
# 为每个 chunk 生成上下文
def contextualize_chunk(full_doc: str, chunk: str) -> str:
resp = client.messages.create(
model="claude-haiku-3-5",
max_tokens=100,
system="Generate a concise context (1-2 sentences) for the following chunk within the full document.",
messages=[{
"role": "user",
"content": f"<document>{full_doc}</document>\n<chunk>{chunk}</chunk>"
}]
)
context = resp.content[0].text
return f"{context}\n\n{chunk}" # 上下文 + 原文Reranking
检索 Top-20 后用 Cross-Encoder 重排,取最终 Top-5 传给 LLM。
Cross-Encoder 计算 Query-Chunk 对的精确相似度,比 Bi-Encoder 准确但慢。
常用:Cohere Rerank API、BGE-Reranker
Agent 架构模式
并行化 (Parallelization)
将独立子任务同时发送给多个 Claude 实例,最后汇总结果。
适用:批量处理、多文档分析、A/B 评估
实现:asyncio.gather() 或 ThreadPoolExecutor
import asyncio
import anthropic
client = anthropic.AsyncAnthropic()
async def analyze(text: str) -> str:
resp = await client.messages.create(
model="claude-haiku-3-5", max_tokens=256,
messages=[{"role": "user", "content": f"Summarize: {text}"}]
)
return resp.content[0].text
async def main(documents: list[str]):
results = await asyncio.gather(*[analyze(doc) for doc in documents])
return results链式调用 (Chaining)
前一步输出作为下一步输入,形成流水线。
适用:翻译→润色→格式化、提取→验证→存储
注意:错误会沿链传播,需每步校验输出质量
路由 (Routing)
分类器(轻量 Claude 或规则)判断请求类型,路由到专门处理该类型的子 Agent 或 prompt。
适用:客服系统(技术/账单/销售)、多语言路由
Orchestrator-Workers 模式
Orchestrator(Claude)负责分解任务、调度 Worker、汇总结果。
Worker 可以是:Claude 实例、外部 API、数据库查询、代码执行器
适用:复杂研究、自动化编码、多步骤数据处理
停止条件设计
避免无限循环,需明确定义:
- 最大迭代次数(硬限制)
- 任务完成信号(模型输出特定 token)
- 超时机制
- 人工干预触发点(HITL)
最小化上下文原则
每次 API 调用只传入当前步骤所需的上下文,避免 context window 被历史信息占满。
使用外部存储(向量库、KV store)存放长期记忆,按需检索注入。
MCP 核心架构
什么是 MCP
Model Context Protocol — 开放协议,标准化 AI 模型与外部数据源/工具的连接方式。
类比:AI 领域的"USB-C 接口"
客户端-服务器模型
MCP Host(Claude Desktop / Claude Code)
└─ MCP Client(1:1 连接 Server)
└─ MCP Server(暴露工具/资源/提示)
Host 管理多个 Client,每个 Client 对应一个 Server。
Transport 类型
stdio — 标准输入/输出,本地进程间通信(最常用于本地 Server)
SSE (Server-Sent Events) — HTTP 长连接,用于远程 Server
Streamable HTTP — 新一代传输,支持双向流
三大原语 (Primitives)
Tools(工具)— 模型可调用的函数,有副作用(API 调用、写文件)
Resources(资源)— 模型可读取的数据,无副作用(文件、数据库记录)
Prompts(提示)— 预定义的提示模板,用户可触发
请求-响应流程
1. Host 初始化 → Client 发送 initialize 请求
2. Server 返回 capabilities(声明支持哪些原语)
3. Client 发送 initialized 通知
4. 正常使用:tools/list → tools/call → result
5. 使用 JSON-RPC 2.0 协议
安全模型
Server 只暴露明确定义的能力
Host 控制 Client 可访问哪些 Server
用户需在 Host 中授权 Server 连接
工具调用需用户确认(Host 决策)
MCP Python SDK
安装
pip install mcp
或在 pyproject.toml 中添加 mcp 依赖
Server 基础结构
使用 FastMCP 快速创建服务器
from mcp.server.fastmcp import FastMCP
# 创建 MCP Server 实例
mcp = FastMCP("my-server")
if __name__ == "__main__":
mcp.run() # 默认使用 stdio transport@mcp.tool() — 定义工具
工具有副作用,模型主动调用,需要 JSON Schema 描述参数
from mcp.server.fastmcp import FastMCP
import httpx
mcp = FastMCP("weather-server")
@mcp.tool()
async def get_weather(city: str, unit: str = "celsius") -> str:
"""Get current weather for a city.
Args:
city: Name of the city
unit: Temperature unit (celsius or fahrenheit)
"""
# FastMCP 自动从类型注解生成 JSON Schema
async with httpx.AsyncClient() as client:
resp = await client.get(f"https://api.weather.example.com/{city}")
data = resp.json()
return f"{city}: {data['temp']}°{unit[0].upper()}, {data['conditions']}"@mcp.resource() — 定义资源
资源只读,URI 唯一标识,模型可读取但不修改
from mcp.server.fastmcp import FastMCP
from mcp.types import Resource
mcp = FastMCP("file-server")
# 静态资源
@mcp.resource("file://config.json")
def get_config() -> str:
"""Return application configuration."""
with open("config.json") as f:
return f.read()
# 动态资源(模板)
@mcp.resource("user://{user_id}/profile")
def get_user_profile(user_id: str) -> str:
"""Fetch user profile by ID."""
return f"Profile for user {user_id}"@mcp.prompt() — 定义提示模板
用户可在 Host UI 触发的预定义提示,支持参数
from mcp.server.fastmcp import FastMCP
from mcp.types import GetPromptResult, PromptMessage, TextContent
mcp = FastMCP("prompt-server")
@mcp.prompt()
def code_review(language: str, code: str) -> list[PromptMessage]:
"""Generate a code review prompt."""
return [
PromptMessage(
role="user",
content=TextContent(
type="text",
text=f"Please review this {language} code:\n\n```{language}\n{code}\n```"
)
)
]完整服务器示例(stdio + SSE)
stdio 用于本地,SSE 用于远程部署
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("demo")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers."""
return a + b
if __name__ == "__main__":
import sys
if "--sse" in sys.argv:
mcp.run(transport="sse", host="0.0.0.0", port=8080)
else:
mcp.run(transport="stdio")Resources & Prompts
Resource URI 规范
直接 URI:file://path/to/doc.txt
模板 URI:user://{user_id}/profile
(RFC 6570 URI Template 语法)
MIME 类型:text/plain、application/json、image/png 等
Resource vs Tool 的区别
Resource — 只读数据源,幂等,无副作用。模型"读取"资源。
Tool — 可执行操作,有副作用(写入/API调用)。模型"调用"工具。
经验法则:能只读就用 Resource,需要操作用 Tool。
Resource 返回类型
TextResourceContents — 文本内容(type: "text")
BlobResourceContents — 二进制内容(type: "blob",base64 编码)
通过 mimeType 字段声明内容类型
Prompt 参数定义
Prompt 支持带参数的模板,参数在 arguments 数组中定义。
参数包含:name、description、required 字段。
Host 会向用户展示参数表单让用户填写后触发。
Prompt 返回格式
返回 GetPromptResult,包含:
- description(可选)
- messages:PromptMessage 列表
每条消息有 role(user/assistant)和 content
Roots — 工作目录声明
Server 可声明 roots(根目录列表),告知 Client 服务器操作的文件范围。
Client 可通过 roots/list 请求获取。
用途:IDE 集成时让 Host 知道 Server 关注哪些路径。
在 Claude Desktop 中注册 Server
编辑 ~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"my-weather": {
"command": "python",
"args": ["/path/to/weather_server.py"],
"env": {
"WEATHER_API_KEY": "your-key"
}
},
"remote-server": {
"url": "http://localhost:8080/sse"
}
}
}Skill 文件结构
SKILL.md 完整 Frontmatter 字段
name — 技能名称(对应斜杠命令,如 /my-skill)
description — 触发时机描述,模型据此判断何时激活
allowed-tools — 此技能允许使用的工具列表(白名单)
argument-hint — 参数提示,显示在命令输入框中
version — 版本号
完整 SKILL.md 示例
技能文件由 YAML frontmatter + Markdown 正文组成
---
name: code-review
description: |
Perform a comprehensive code review of the current file or selection.
Trigger when user asks to review code, check code quality, or find bugs.
allowed-tools:
- Read
- Bash
argument-hint: "[file path or 'current']"
version: "1.0.0"
---
# Code Review Skill
When activated, perform the following steps:
1. Read the target file(s) using the Read tool
2. Analyze for: bugs, security issues, performance, style
3. Run linting if available: `npm run lint` or `ruff check`
4. Output findings in this format:
## Critical Issues
[List blocking bugs]
## Suggestions
[List improvements]
## Summary
[Overall assessment]Frontmatter 字段详解
name: 全小写,连字符分隔,对应 /name 触发
description: 详细描述触发场景,越具体越好
allowed-tools: 仅列出技能实际需要的工具
argument-hint: 如 "[查询词]" 或 "[文件路径]"
技能正文编写要点
正文是给 Claude 的指令,用清晰 Markdown 写。
- 分步骤列出操作流程
- 说明输出格式
- 包含边界条件处理
- 可内嵌示例输入/输出
- 保持简洁,避免歧义
技能存放路径
项目级:.claude/skills/<skill-name>.md
用户级:~/.claude/skills/<skill-name>.md
插件级:通过 npm/pip 包分发,自动注册
技能分发 & 管理
仓库共享
在项目 .claude/skills/ 目录下添加技能文件,随 Git 仓库一起分发。
团队成员 clone 后即可使用,适合项目专属工作流。
插件分发
npm 包或 pip 包形式发布,package.json/pyproject.toml 中声明 claude-skills 字段。
用户安装包后技能自动注册,无需手动配置。
适合:通用工具技能、跨项目复用。
企业 Managed Settings
通过 settings.json 的 managedSettings 字段统一下发配置。
可强制启用/禁用特定技能,控制 allowed-tools 范围。
优先级:Managed > Project > User
allowed-tools 的作用
限制技能可使用的工具,遵循最小权限原则。
未在列表中的工具即使正文中提到也不会执行。
可用工具标识符:Read、Write、Edit、Bash、Glob、Grep、WebFetch、WebSearch 等
settings.json 技能配置示例
在项目 .claude/settings.json 中管理技能权限
{
"skills": {
"code-review": {
"enabled": true,
"allowed-tools": ["Read", "Bash", "Glob", "Grep"]
},
"deploy": {
"enabled": false // 在此项目中禁用部署技能
}
},
"permissions": {
"allow": [
"Bash(npm run lint)",
"Bash(ruff check *)"
]
}
}技能触发方式
斜杠命令:/skill-name [args]
自然语言:系统根据 description 自动匹配
快捷键:可在 keybindings.json 中绑定技能到快捷键
Claude Code 核心功能
上下文管理
/clear — 清除对话历史,释放 context window
/compact — 压缩历史为摘要(保留关键信息)
#file — 在消息中引用文件(自动读取内容注入上下文)
@symbol — 引用代码符号(函数/类)
自定义命令 (Custom Commands)
在 .claude/commands/<name>.md 中定义。
文件名即命令名:/name
正文是 Markdown 格式的指令模板。
支持 $ARGUMENTS 变量接收用户输入。
# .claude/commands/fix-tests.md
Find all failing tests, diagnose the root cause, and fix them.
Arguments: $ARGUMENTS
Steps:
1. Run: npm test 2>&1 | tail -50
2. Identify failing test files
3. Read the failing tests and related source files
4. Fix the implementation (not the tests unless tests are wrong)
5. Verify: npm testGitHub 集成
gh CLI 自动可用,Claude 可:
- 读取 PR / Issue 详情
- 创建/更新 PR
- 查看 CI 状态
- 自动修复 PR review 意见
触发词:"review this PR", "fix CI"
MCP 集成
在 .claude/settings.json 中配置 mcpServers。
支持:stdio(本地)、SSE(远程)。
Claude Code 会自动连接并将 MCP 工具注入 session。
使用 /mcp 命令查看已连接的服务器和工具列表。
CLAUDE.md — 项目记忆
CLAUDE.md 在每次会话开始时自动注入上下文。
适合存放:项目架构说明、编码规范、常用命令、重要约定。
支持分层:根目录 + 子目录各自的 CLAUDE.md 自动合并。
权限模型
Claude Code 默认安全:
- 破坏性操作(rm、git reset)需确认
- 网络请求需声明
- 敏感文件自动拒绝
可在 settings.json 中通过 permissions.allow 白名单自动批准特定命令。
最佳实践
何时使用 Extended Thinking
适用:
- 复杂架构设计决策
- 难以重现的 bug 分析
- 算法复杂度分析
- 安全漏洞审查
不适用:
- 简单代码格式化
- 常规 CRUD 实现
- 文档生成(浪费 token)
多工具组合策略
Glob + Read — 先定位文件,再读取内容(比盲目 Read 高效)
Grep + Read — 先搜索模式,再读取命中文件
Bash(git) + Read — 查看 diff 后读取完整文件了解上下文
避免:不必要的 cat/find(用专用工具代替)
Context Window 优化
- 用 /compact 而非 /clear 保留关键历史
- 引用具体文件而非整个目录
- 将长文档放入 MCP Resource 而非直接粘贴
- 任务结束后 /clear,避免污染下一个任务
- CLAUDE.md 只放真正通用的信息
高效提问技巧
- 提供具体错误信息(完整 stack trace)
- 说明已尝试过的方案
- 指定期望的输出格式
- 给出约束条件(不改变公共 API、保持向后兼容)
- 一次专注一个任务
Git 工作流集成
- 让 Claude 在实现前先写测试(TDD)
- 每个逻辑单元让 Claude commit 一次(原子提交)
- PR 前让 Claude 自查:/review
- 复杂重构:先让 Claude 生成计划,确认后执行
- 保持 .gitignore 包含 .claude/settings.local.json
调试工作流
1. 提供完整错误信息(含文件名+行号)
2. 让 Claude 先解释可能原因(不急于修改)
3. 确认诊断方向后再修复
4. 修复后让 Claude 运行测试验证
5. 复杂 bug 启用 thinking 模式
安全注意事项
- 不将 .env 文件或 API Key 粘贴到对话
- 仔细审查 Bash 命令(尤其是 rm/curl/pipe 组合)
- 对外部输入做 injection 检查(prompt injection 风险)
- 生产变更前在暂存环境验证
- settings.json 的 allow 列表用具体命令而非通配符
显示 14 / 14 个章节 ·84 个知识点