源文件:chapter1/context/README.md 支持消融实验的上下文感知 AI Agent 一个进阶 AI Agent 实现,支持多种 LLM 提供方(SiliconFlow Qwen、字节跳动豆包、Moonshot Kimi、DeepSeek),通过系统化的消融实验直观展示上下文各组件的关键作用。 🎯 概览 本项目实现了一个上下文感知的 AI Agent,内置多种工具(PDF 解析、汇率换算、计算器、代码解释器),并提供完整的消融测试,用于探究不同上下文组件如何影响 Agent 的行为与表现。
源文件:chapter1/context/README.md
一个进阶 AI Agent 实现,支持多种 LLM 提供方(SiliconFlow Qwen、字节跳动豆包、Moonshot Kimi、DeepSeek),通过系统化的消融实验直观展示上下文各组件的关键作用。
本项目实现了一个上下文感知的 AI Agent,内置多种工具(PDF 解析、汇率换算、计算器、代码解释器),并提供完整的消融测试,用于探究不同上下文组件如何影响 Agent 的行为与表现。
--model deepseek-v4-pro)no_reasoning 消融时剥离 reasoning_contentdeepseek-chat / deepseek-reasoner 已弃用(2026-07-24);推荐使用 V4 系列 idparse_pdf(url) — 下载并提取 PDF 文档中的文本convert_currency(amount, from, to) — 实时汇率换算calculate(expression) — 简单数学表达式求值code_interpreter(code) — 执行 Python 代码,完成复杂计算、求和与数据处理系统内置 5 个预设示例任务,展示不同能力:
这些示例旨在展示 Agent 的能力以及上下文消融带来的影响。
# Clone the repository cd projects/week1/context # Install dependencies pip install -r requirements.txt # Copy and configure environment cp env.example .env # Edit .env and add your API key (SILICONFLOW_API_KEY or ARK_API_KEY)
# For Doubao (ByteDance) - Default export ARK_API_KEY=your_key_here python main.py # Uses Doubao by default # For SiliconFlow (Qwen) export SILICONFLOW_API_KEY=your_key_here python main.py --provider siliconflow # For Kimi (Moonshot) export MOONSHOT_API_KEY=your_key_here python main.py --provider kimi # For DeepSeek export DEEPSEEK_API_KEY=your_key_here python main.py --provider deepseek # Optional stronger model: python main.py --provider deepseek --model deepseek-v4-pro # Or specify a custom model python main.py --model doubao-seed-1-6-thinking-250715 # Universal OpenRouter fallback: if the provider key above is missing/invalid # but OPENROUTER_API_KEY is set, requests are routed through OpenRouter and the # model id is mapped automatically (bare gpt-*/o1-* -> openai/*, claude-* -> # anthropic/*, deepseek-* -> deepseek/*, other native ids -> OPENROUTER_MODEL # or openai/gpt-5.6-luna). export OPENROUTER_API_KEY=sk-or-v1-your-key-here python main.py # falls back to OpenRouter when ARK_API_KEY is unset python main.py --provider openrouter # or use OpenRouter directly
# Quick test of Kimi K3 model export MOONSHOT_API_KEY=your_key_here python test_kimi.py # Use Kimi in main script python main.py --provider kimi --mode interactive # Run ablation study with Kimi python main.py --provider kimi --mode ablation # Quick test of DeepSeek V4 export DEEPSEEK_API_KEY=your_key_here python test_deepseek.py # or: python quick_test_deepseek.py # Use DeepSeek in main script / ablation study python main.py --provider deepseek --mode interactive python main.py --provider deepseek --mode ablation
# Default (Doubao) python main.py --mode interactive # With SiliconFlow provider python main.py --mode interactive --provider siliconflow # In interactive mode, you can: # - Type 'samples' to see pre-defined tasks # - Type 'sample 3' to test PDF parsing # - Type 'providers' to list available providers # - Type 'provider kimi' to switch providers # - Type 'status' to see current configuration # - Type 'help' for all commands
# Run without arguments to select from samples python main.py --mode single # With specific provider python main.py --mode single --provider doubao # Or provide your own task python main.py --mode single \ --task "Convert $1000 USD to EUR, GBP, and JPY. Calculate the average." \ --context-mode full \ --provider siliconflow
# With default provider (single case, all five context modes) python main.py --mode ablation # With Doubao provider python main.py --mode ablation --provider doubao # Multi-case comparison across modes (stronger evidence for the book's point) python main.py --mode ablation --cases 3 # Compare only two modes and save raw results to a custom path python main.py --mode ablation --ablation-modes full no_history --output my_ablation.json
main.py 是唯一的 CLI 入口。运行 python main.py --help 可查看完整的(中文)参数说明。
关键参数:
| 参数 | 说明 |
|---|---|
--mode |
single / ablation / interactive(默认) |
--task |
single 模式下的任务文本 |
--context-mode |
single 模式下的上下文模式(full、no_history、no_reasoning、no_tool_calls、no_tool_results) |
--ablation-modes |
ablation 模式下要测试的子集(默认:全部五种) |
--cases |
ablation 模式下每个模式跑的用例数(默认:1) |
--provider / --model |
LLM 提供方及可选的模型覆盖 |
--output |
JSON 结果的输出路径(single)或原始结果(ablation) |
消融实验会系统性地移除上下文中的各组件,以理解其重要性:
一个复杂的财务分析任务,需要:
| 上下文模式 | 移除的组件(书 §实验 1.1) | 预期行为 | 影响 |
|---|---|---|---|
| full | 无(基线) | 完整成功执行 | 基线表现 |
| no_history | 历史消息 (history) | 冗余操作、低效 | 可能重复调用工具 |
| no_reasoning | 思考过程 (reasoning) | 缺乏章法、可能出错 | 缺少策略规划 |
| no_tool_calls | 工具定义 (tool definitions) | 完全失败 | 无法与外部世界交互 |
| no_tool_results | 工具执行结果 (tool results) | 得出错误结论 | 在没有反馈的情况下做决策 |
每种消融的具体实现(见 agent.py):
tools 参数,模型没有可供调用的工具定义。[Tool result hidden] 占位符。reasoning_content。_prepare_messages_for_api() 只向模型发送一个滑动窗口(系统提示 + 当前任务 + 最近一个 ReAct 步骤),因此早期步骤会被遗忘,Agent 倾向于重复调用工具。完整模式始终发送整条轨迹。# Run the full ablation study (single case, all five modes) python main.py --mode ablation # Run across multiple cases for a stronger comparison python main.py --mode ablation --cases 3 # This will generate: # - ablation_study_results.png (visualization, if matplotlib is installed) # - ablation_study_report.md (detailed report) # - ablation_results.json (raw data; override path with --output)
控制台会打印两张表:一张是每次运行的消融实验结果表,另一张是对比矩阵(上下文模式 × 用例),便于一眼读出各组件的效果。
ABLATION STUDY RESULTS ================================================================================ | Test Name | Success | Time | Iterations | Tool Calls | |--------------------------------|---------|--------|------------|------------| | Baseline - Full Context | ✓ | 12.3s | 5 | 8 | | No Historical Tool Calls | ✓ | 18.7s | 8 | 12 | | No Reasoning Process | ✗ | 25.4s | 10 | 15 | | No Tool Call Commands | ✗ | 3.2s | 2 | 0 | | No Tool Call Results | ✗ | 15.6s | 10 | 10 |
没有工具调用能力,Agent 无法与外部系统交互,任务根本无从完成。
看不到结果时,Agent 等于盲走,会得出错误结论并陷入死循环。
策略规划能减少迭代次数与工具调用次数,同时提升速度与准确性。
历史上下文能防止重复操作,并在多轮迭代中保持任务连贯性。
交互模式支持以下命令:
| 命令 | 说明 |
|---|---|
samples |
显示所有可用的示例任务 |
sample <n> |
运行第 n 个示例任务 |
providers |
列出所有可用的 LLM 提供方 |
provider <name> |
切换到其他提供方(如 provider kimi) |
modes |
列出可用于消融测试的上下文模式 |
mode <name> |
切换上下文模式(如 mode no_history) |
status |
显示当前配置(提供方、模型、模式等) |
reset |
重置 Agent 轨迹(清空历史) |
create_pdfs |
生成用于测试的示例 PDF 文件 |
quit |
退出交互模式 |
注意: 提示符会用方括号显示当前提供方,例如 [KIMI]> 或 [DOUBAO]>。
Agent 在整个交互会话中会保持会话历史:
reset 命令可清空历史并重新开始示例对话流程:
[DOUBAO]> Remember that our budget is $10,000. Calculate 15% of it. # Agent calculates and remembers the budget [DOUBAO]> Now convert that 15% amount to EUR # Agent uses the previously calculated amount without re-asking [DOUBAO]> What was our original budget? # Agent recalls the $10,000 mentioned earlier
创建你自己的测试场景:
from agent import ContextAwareAgent, ContextMode agent = ContextAwareAgent(api_key, ContextMode.FULL) result = agent.execute_task(""" Download the PDF from https://example.com/report.pdf, extract all monetary values, convert them to EUR, and calculate the total. """)
生成用于测试的示例 PDF:
python create_sample_pdf.py # Creates test_pdfs/ directory with sample financial reports
编辑 config.py 或设置环境变量:
export MODEL_TEMPERATURE=0.5 export MAX_ITERATIONS=15 export LOG_LEVEL=DEBUG
context/ ├── agent.py # Core agent implementation + context modes ├── main.py # Single CLI entry point (single / ablation / interactive) ├── config.py # Configuration management ├── create_sample_pdf.py # PDF generation utility ├── requirements.txt # Dependencies ├── env.example # Environment template └── README.md # This file
注意:消融实验位于
main.py(AblationTestSuite),通过python main.py --mode ablation运行。并不存在单独的ablation_tests.py。
本实现适用于:
欢迎贡献!可改进的方向:
MIT License - 详情见 LICENSE 文件。
如有疑问或反馈,请在 GitHub 上提 issue。
注意:这是一个演示 AI Agent 消融实验的教学项目。若用于生产环境,请实现完善的错误处理、限流与安全措施。