Claude 支持高达 200K token 的上下文窗口(约 15 万个汉字,或 25 万个英文单词)。 这意味着你可以把整个代码库、完整书籍或几十份文档一次性交给 Claude 分析。 本文讲解如何高效利用这个能力。
200K Token 能装多少内容?
| 内容类型 | 大约数量 |
|---|---|
| 中文字符 | ~15 万字 |
| 英文单词 | ~15 万词 |
| Python 代码行 | ~2 万行 |
| A4 页面(密排) | ~400 页 |
| 中等规模 React 项目 | 完整源码 |
| 技术书籍 | 1-2 本 |
何时用长上下文 vs 分块处理
用长上下文(一次性发送所有内容)
适合:
- 需要理解全局架构的任务(代码重构、架构审查)
- 需要跨文档关联的分析(多份合同对比、法律文书审查)
- 需要维持完整上下文的对话(读完全书再问问题)
不适合:
- 纯粹的批量处理(每份文档独立,用 Batch API 更省钱)
- 超过 200K token 的内容(必须分块)
决策树
内容 < 200K token?
├── 是 → 任务需要理解多个部分之间的关联?
│ ├── 是 → 用长上下文(一次发送全部)
│ └── 否 → 考虑分块处理(更省钱)
└── 否 → 必须分块处理 + 结果合并
场景 1:整个代码库分析
python
import os, anthropic
def load_codebase(root_dir: str, extensions: list[str]) -> str:
# 把代码库所有文件合并成一个字符串
files_content = []
for dirpath, _, filenames in os.walk(root_dir):
# 跳过不需要的目录
if any(skip in dirpath for skip in ['.git', 'node_modules', '__pycache__', '.venv']):
continue
for filename in filenames:
if any(filename.endswith(ext) for ext in extensions):
filepath = os.path.join(dirpath, filename)
try:
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
relative_path = os.path.relpath(filepath, root_dir)
files_content.append(f"=== {relative_path} ===
{content}")
except Exception:
pass
return "
".join(files_content)
client = anthropic.Anthropic()
# 加载整个项目
codebase = load_codebase("./my-project", [".py", ".ts", ".tsx", ".json"])
token_estimate = len(codebase) // 4 # 粗略估算
print(f"代码库大小:{len(codebase):,} 字符,约 {token_estimate:,} tokens")
# 整体分析
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=4096,
system="你是一位资深架构师,请分析以下完整代码库。",
messages=[{
"role": "user",
"content": f"{codebase}
---
请分析:
1. 整体架构模式
2. 主要模块和职责
3. 潜在的技术债务
4. 安全隐患
5. 改进建议(按优先级)"
}]
)
print(response.content[0].text)场景 2:长文档精准问答
python
def analyze_document(doc_path: str, questions: list[str]) -> dict:
# 对长文档进行多个问题的批量问答
with open(doc_path, 'r') as f:
document = f.read()
# 用 Prompt Caching 缓存文档(节省重复问题的成本)
all_questions = "
".join(f"{i+1}. {q}" for i, q in enumerate(questions))
response = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=4096,
system=[
{"type": "text", "text": "你是文档分析助手,请仔细阅读以下文档并回答问题。"},
{
"type": "text",
"text": document,
"cache_control": {"type": "ephemeral"} # 缓存长文档
}
],
messages=[{
"role": "user",
"content": f"请逐一回答以下问题:
{all_questions}"
}],
extra_headers={"anthropic-beta": "prompt-caching-2024-07-31"}
)
return response.content[0].text
# 使用示例:分析技术规范文档
questions = [
"系统支持的最大并发用户数是多少?",
"数据备份策略是什么?",
"有哪些安全认证要求?",
"SLA 要求响应时间是多少?"
]
result = analyze_document("technical-spec.pdf", questions)场景 3:多文件对比分析
我有三份竞品的 API 文档,请对比分析:
[文件1: OpenAI API 文档摘录]
...
[文件2: Anthropic API 文档摘录]
...
[文件3: Google Gemini API 文档摘录]
...
请对比:
1. 支持的模型和定价模式
2. 上下文窗口大小
3. 流式输出的实现方式
4. 工具调用(Function Calling)的设计差异
5. 各自的独特功能
6. 哪个最适合[描述你的使用场景]
场景 4:大型 PR 代码审查
bash
# 获取完整 diff(可能很大)
git diff main...feature/big-refactor > full_diff.txt
# 发给 Claude 完整审查
cat full_diff.txt | claude -p "
Perform a comprehensive code review of this entire PR diff.
Review for:
1. Logic errors and bugs
2. Security vulnerabilities
3. Performance issues (N+1 queries, unnecessary re-renders)
4. Code style inconsistencies
5. Missing error handling
6. Test coverage gaps
7. Breaking API changes
Format output as:
## Critical Issues (must fix before merge)
## Suggestions (nice to have)
## Positive observations
"上下文优先级管理技巧
当内容接近 200K 限制时,信息位置很重要:
python
# Claude 对上下文首尾的注意力最强(中间会有衰减)
# 重要规则放开头(system prompt)
# 最相关的内容放最后(接近问题)
# 次要的背景信息放中间
messages = [
{
"role": "user",
"content": (
"以下是完整的项目代码库:
"
f"{background_code}
" # 背景代码放中间
f"最相关的文件:
{key_files}
" # 关键文件放后面
"问题:解释 authenticate() 函数的完整调用链" # 问题放最后
)
}
]成本控制
200K token 的一次调用成本不低,几个优化技巧:
- Prompt Caching:文档/代码库不变时,缓存后每次只需 10% 的读取费用
- 先用 Haiku 筛选:用便宜的 Haiku 先找到相关段落,再用 Sonnet 深入分析
- 精准选择内容:不要把整个
node_modules放进去,只放你写的代码
python
# 成本估算
content_tokens = len(content) // 4
cost_sonnet = content_tokens / 1_000_000 * 3.0 # $3/M tokens
print(f"预计单次调用成本:${cost_sonnet:.4f}")
print(f"使用 Prompt Cache 后(第 2 次起):${cost_sonnet * 0.1:.4f}")来源:Context Windows - Anthropic 官方文档