name: claude-agent-sdk-context-management description: 使用Agent SDK管理Claude AI代理的上下文、内存和对话状态时使用。 allowed-tools:
- Read
- Write
- Edit
- Bash
- Grep
- Glob
Claude Agent SDK - 上下文管理
在Claude Agent SDK中管理代理内存、上下文和对话状态。
设置来源
项目内存
import { Agent } from '@anthropic-ai/claude-agent-sdk';
// 从.claude/CLAUDE.md加载项目特定上下文
const agent = new Agent({
settingSources: ['project'],
});
用户内存
// 从~/.claude/CLAUDE.md加载用户偏好
const agent = new Agent({
settingSources: ['user'],
});
组合来源
// 加载用户和项目设置
const agent = new Agent({
settingSources: ['user', 'project'],
});
CLAUDE.md 文件
项目上下文 (.claude/CLAUDE.md)
# 项目上下文
这是一个使用React和Next.js的TypeScript Web应用程序。
## 代码风格
- 使用函数式组件
- 优先使用钩子而非类组件
- 使用TypeScript严格模式
## 架构
- API路由在/pages/api
- 组件在/components
- 工具在/lib
用户偏好 (~/.claude/CLAUDE.md)
# 用户偏好
## 沟通风格
- 简洁
- 展示代码示例
- 解释推理过程
## 开发环境
- 主要编辑器:VS Code
- Node版本:20.x
- 包管理器:pnpm
系统提示
直接系统提示
const agent = new Agent({
systemPrompt: `你是一位TypeScript开发专家。
遵循以下指南:
- 使用严格类型检查
- 优先不变性
- 编写全面的测试`,
});
动态系统提示
const projectType = detectProjectType();
const agent = new Agent({
systemPrompt: `你是一位${projectType}专家。
当前项目:${process.cwd()}
Node版本:${process.version}`,
});
对话状态
单轮对话
const agent = new Agent({
settingSources: ['project'],
});
const response = await agent.chat('这个项目是关于什么的?');
console.log(response);
多轮对话
const agent = new Agent({
settingSources: ['project'],
});
// 第一轮
const response1 = await agent.chat('列出所有API端点');
// 第二轮 - 代理记住之前的上下文
const response2 = await agent.chat('为登录端点添加身份验证');
// 第三轮
const response3 = await agent.chat('为你刚刚做的更改编写测试');
对话历史
import { query } from '@anthropic-ai/claude-agent-sdk';
const conversation = query({
prompt: '帮助我重构这段代码',
options: {
settingSources: ['project'],
},
});
// 访问对话历史
for await (const message of conversation) {
console.log('角色:', message.role);
console.log('内容:', message.content);
}
上下文限制
管理上下文大小
const agent = new Agent({
model: 'claude-3-5-sonnet-20241022',
systemPrompt: '你是一位代码审查员',
// 代理自动管理上下文窗口
});
// 对于非常大的文件,分块内容
const largeFile = await readFile('huge-file.ts');
const chunks = chunkContent(largeFile, 10000);
for (const chunk of chunks) {
await agent.chat(`审查这个部分:
${chunk}`);
}
上下文摘要
// 代理可以总结之前的上下文以适应窗口
const agent = new Agent({
settingSources: ['project'],
});
// 长对话
await agent.chat('解释身份验证系统');
await agent.chat('会话管理如何工作?');
await agent.chat('密码哈希呢?');
// 代理自动维护相关上下文
await agent.chat('更新登录端点以使用bcrypt');
内存持久性
存储对话状态
import { query } from '@anthropic-ai/claude-agent-sdk';
const conversationFile = './conversation-state.json';
// 加载之前的对话
let messages = [];
if (existsSync(conversationFile)) {
messages = JSON.parse(readFileSync(conversationFile, 'utf8'));
}
const conversation = query({
prompt: '继续我们上次停止的地方',
options: {
settingSources: ['project'],
// 如果API支持,传递之前的消息
},
});
// 保存对话状态
const newMessages = [];
for await (const message of conversation) {
newMessages.push(message);
}
writeFileSync(
conversationFile,
JSON.stringify([...messages, ...newMessages], null, 2),
);
最佳实践
分离项目和用户上下文
// 好:清晰分离
const agent = new Agent({
settingSources: ['user', 'project'],
systemPrompt: `额外任务特定上下文`,
});
// 避免:在系统提示中混合上下文
const agent = new Agent({
systemPrompt: `
用户偏好:简洁
项目:TypeScript + React
任务:审查代码
`, // 难以维护
});
保持CLAUDE.md文件聚焦
<!-- 好:聚焦的项目上下文 -->
# 项目上下文
## 技术栈
- Next.js 14
- TypeScript 5
- Tailwind CSS
## 关键约定
- 默认使用服务器组件
- 仅在需要时使用客户端组件
- API路由遵循REST约定
<!-- 避免:太多细节 -->
# 项目上下文
## 技术栈
- Next.js 14.2.3
- TypeScript 5.4.2
- Tailwind CSS 3.4.1
- ...50多个依赖
## 每个文件
- src/app/page.tsx: 主页
- src/app/about/page.tsx: 关于页面
- ...200多个文件
随着项目发展更新上下文
# 当架构变化时更新.claude/CLAUDE.md
echo "## 新功能
- 添加了GraphQL API
- 迁移到PostgreSQL" >> .claude/CLAUDE.md
反模式
不要重复上下文
// 坏:在系统提示中重复项目信息
const agent = new Agent({
settingSources: ['project'], // 已经加载.claude/CLAUDE.md
systemPrompt: `这是一个使用TypeScript的React应用`, // 冗余
});
// 好:让settingSources处理它
const agent = new Agent({
settingSources: ['project'],
systemPrompt: `额外任务特定指导`,
});
不要硬编码路径
// 坏:硬编码路径
const agent = new Agent({
systemPrompt: `项目位置:/Users/me/projects/myapp`,
});
// 好:使用相对或动态路径
const agent = new Agent({
systemPrompt: `项目根目录:${process.cwd()}`,
});
不要在CLAUDE.md中存储秘密
<!-- 坏:上下文中的秘密 -->
# 项目上下文
数据库:postgresql://user:password@localhost/db
API密钥:sk-secret-key-here
<!-- 好:引用环境变量 -->
# 项目上下文
数据库:通过DATABASE_URL环境变量配置
API密钥:设置OPENAI_API_KEY环境变量
高级模式
上下文注入
const agent = new Agent({
settingSources: ['project'],
systemPrompt: `
当前分支:${execSync('git branch --show-current').toString().trim()}
未提交的更改:${execSync('git status --short').toString()}
`,
});
基于角色的上下文
function createSpecializedAgent(role: 'reviewer' | 'implementer' | 'tester') {
const rolePrompts = {
reviewer: '专注于代码质量和最佳实践',
implementer: '编写生产就绪的代码',
tester: '创建全面的测试覆盖',
};
return new Agent({
settingSources: ['project'],
systemPrompt: rolePrompts[role],
});
}
const reviewer = createSpecializedAgent('reviewer');
const implementer = createSpecializedAgent('implementer');
相关技能
- agent-creation: 代理初始化和配置
- tool-integration: 与工具和MCP服务器工作