Patterns to Avoid
【免费下载链接】Agent-Skills-for-Context-EngineeringA comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems. Use when building, optimizing, or debugging agent systems that require effective context management.项目地址: https://gitcode.com/GitHub_Trending/ag/Agent-Skills-for-Context-Engineering
- Missing Validation: Accepting tool responses at face value without verifying the actual state change occurred.
- Hallucinating Sources: Citing sources that failed to load.
- Ignoring Contradictions: Proceeding when tool results conflict.
Recommended Practices
- After every tool call, state the outcome explicitly
- Track sources separately: 'attempted' vs 'successful'
- Implement error recovery with alternative approaches
- Cross-reference key claims against multiple sources
SKILL.md 的模板结构固定为:YAML frontmatter(`name` + `description`)→ `# 标题` → intro → When to Activate → Core Concepts → Patterns to Avoid → Recommended Practices → Guidelines → Examples → Skill Metadata(生成日期、来源、优化迭代次数、分数提升)。 ## API 参考 ### TraceCapture ```python capture = TraceCapture( api_key="...", # MiniMax API key base_url="https://api.minimax.io/anthropic", # API 端点 model="MiniMax-M2.1" # 使用的模型 ) trace = capture.run( task="...", # 要执行的任务 system_prompt="...", # 系统提示词 tools=[...], # 工具定义(Anthropic 格式) tool_executor=fn, # 执行工具的函数 max_turns=10, # 最大对话轮次 max_tokens=4096 # 每次响应的最大 token 数 )源码层面的默认值与限制(capture.py):
api_key缺省时读取环境变量ANTHROPIC_API_KEY;base_url默认国际端点;model可选MiniMax-M2.1、MiniMax-M2.1-lightning、MiniMax-M2(CLI 的--model也提供这三个选项);system_prompt默认"You are a helpful assistant.";max_turns默认 10,超出未完成时记录success=False与错误信息Reached maximum turns (10) without completion。
TraceAnalyzer
analyzer = TraceAnalyzer( api_key="...", base_url="https://api.minimax.io/anthropic", model="MiniMax-M2.1" ) analysis = analyzer.analyze(trace) # 返回: AnalysisResult,包含 patterns、scores、recommendations quick_score = analyzer.quick_score(trace) # 返回: float (0-100),用于快速反馈analyze()的max_tokens默认 8192;analyze_batch()支持批量分析。分析器本身也使用 M2.1 的交错思考来"思考如何分析"——ANALYSIS_SYSTEM_PROMPT把分析器设定为"专家级 AI Agent 调试器",最终AnalysisResult.analyzer_thinking会保留分析器自身的推理过程,实现"用推理分析推理"的可解释闭环。
OptimizationLoop 与 LoopConfig
config = LoopConfig( # 迭代控制 max_iterations=5, # 最大优化迭代次数 convergence_threshold=3.0, # 改进幅度低于该百分比则停止 min_score_threshold=75.0, # 分数超过该值则停止 regression_threshold=8.0, # 分数回落超过该值则告警 # 优化行为 use_best_prompt=True, # 使用表现最好的提示词,而非最后一轮的 max_prompt_growth=5.0, # 提示词最大膨胀倍数(相对原始)5x # 输出选项 save_artifacts=True, # 保存轨迹与分析 artifacts_dir="./artifacts" # 保存位置 ) loop = OptimizationLoop(config=config) result = loop.run(task, initial_prompt, tools, tool_executor) # 返回: LoopResult,包含 iterations、final_prompt、scores从 loop.py 可以看到 LoopConfig 还包含三个评分权重参数:success_weight=0.4、score_weight=0.4、error_weight=0.2,以及verbose=True输出控制。OptimizationLoop.run()每轮迭代执行四步:捕获轨迹 → 分析 → 按_check_convergence()判断是否收敛(分数达标 / 连续两次回归 / 改进小于阈值 / 达到最大迭代数四类停止条件)→ 若继续则调用PromptOptimizer.optimize()生成新提示词,并在新提示词超过initial_prompt × max_prompt_growth时回退保留当前提示词。
优化保护机制:
- 最佳提示词跟踪:保留产生最高分数的提示词(
use_best_prompt=True时最终结果使用它); - 提示词膨胀限制:通过
max_prompt_growth限制体积膨胀; - 回归检测:分数下降时告警,连续回归后停止。
分数预期(README 中的经验值,供设定阈值参考):
| 任务复杂度 | 典型分数区间 | 说明 |
|---|---|---|
| 简单(1-2 个工具) | 80-95 | 直接任务快速收敛 |
| 中等(3-5 个工具) | 70-85 | 多工具协同带来波动 |
| 复杂(6+ 个工具、多步骤) | 60-75 | 长推理链固有方差 |
多工具多步骤的复杂研究任务通常稳定在65-75分,原因是工具输出可变性影响推理路径、多种有效路径导致评分差异、多步 Agent 执行的随机性。因此优化器关注的是相对提升与模式消除,而非追求某个绝对分数。
SkillGenerator
generator = SkillGenerator() skill_path = generator.generate( result=loop_result, # 来自 OptimizationLoop skill_name="my-skill", # 小写加连字符 output_dir="./generated_skills", title="Human Readable Title" )此外,SkillGenerator.generate_from_analysis()支持在未运行完整优化循环的情况下,仅凭多份分析结果聚合生成 Skill(analysis.overall_score的平均值写入元数据)。
CLI 用法
# 捕获推理轨迹 rto capture "Explain interleaved thinking" -s "You are an AI researcher." # 分析任务并输出结果 rto analyze "Debug this code snippet" -o analysis.txt # 运行完整优化循环 rto optimize "Research AI papers" --max-iterations 5 --generate-skill # 从历史优化产物生成 Skill rto generate-skill my-skill-name --artifacts-dir ./optimization_artifacts对应 cli.py 的四个子命令,全局参数包括:
--api-key:MiniMax API key(或使用ANTHROPIC_API_KEY环境变量);--base-url:默认https://api.minimax.io/anthropic;--model:可选MiniMax-M2.1/MiniMax-M2.1-lightning/MiniMax-M2。
optimize子命令特有参数:--max-iterations(默认 5)、--convergence-threshold(默认 5.0)、--min-score(默认 80.0)、--artifacts-dir(默认./optimization_artifacts)、--generate-skill、--skill-name、--skills-dir(默认./generated_skills);generate-skill子命令会从summary.json重建LoopResult再生成 Skill。
鲁棒性设计:解析韧性
LLM 响应不总是产出合法 JSON,系统对此做了优雅降级(README 归纳 + 源码验证):
| 组件 | 降级行为 |
|---|---|
| Analyzer | JSON 解析失败时用正则提取分数,兜底默认 50/100(而非 0) |
| Optimizer | 多策略提示词提取:JSON → 正则 → 标记检测 → 代码块 |
| Loop | 最终提示词未变化时给出告警,并跟踪最优迭代 |
具体实现:
- analyzer.py:
_parse_analysis_response()先剥离 markdown 代码围栏再json.loads;失败时_fallback_parse_analysis()用 4 组正则(overall["\s:]+(\d+)、Overall Score[:\s]+(\d+)等)提取分数,仍失败则返回中性分 50 并附上"解析失败、分析可能不完整"的提示;若最终分数为 0 且无任何模式,还会追加 WARNING 说明并尝试二次提取。 - optimizer.py:
_fallback_extract_prompt()依次尝试"optimized_prompt": "..."正则、四组起始/结束标记(## Optimized Prompt、**Optimized Prompt**、OPTIMIZED PROMPT:、Here is the improved prompt:)、以及长度大于 100 的非 JSON 代码块。
10 轮扩展测试结果(README 记录的实测经验)
Iteration Score Patterns Tool Calls Notes ──────────────────────────────────────────────── 1 69/100 4 22 Baseline 2 66/100 3 14 - 3 61/100 3 17 - 4 72/100 3 20 ← Best score 5 59/100 4 16 - 6 50/100* 0 15 *Parser fallback activated 7 70/100 3 12 Recovery 8 64/100 3 14 - 9 64/100 3 18 - 10 70/100 3 19 Final * Iteration 6: JSON parsing failed, fallback returned neutral score关键经验:
- 分数在迭代之间因模型随机行为波动 ±15 分;
- 最优分数(72)出现在运行中途而非末尾;
use_best_prompt=True正确选中了 iteration 4 的提示词;- 解析失败现在被优雅处理,不再返回 0 分。
架构总览
reasoning_trace_optimizer/ ├── __init__.py # 公共 API 导出 ├── models.py # 数据模型 │ ├── ThinkingBlock # 单段推理 │ ├── ToolCall # 工具调用记录 │ ├── ReasoningTrace # 完整执行轨迹 │ ├── Pattern # 检测到的失败模式 │ ├── AnalysisResult # 完整分析输出 │ └── LoopResult # 优化循环结果 ├── capture.py # TraceCapture - M2.1 API 包装 ├── analyzer.py # TraceAnalyzer - 模式检测(含降级解析) ├── optimizer.py # PromptOptimizer - 提示词改进(含降级提取) ├── loop.py # OptimizationLoop - 完整循环(含最优分数跟踪) ├── skill_generator.py # SkillGenerator - 创建 Skill └── cli.py # 命令行接口此外 models.py 还定义了PromptDiff(提示词差异:section / original / optimized / reason)与OptimizationResult(原始提示词、优化提示词、diffs、预期提升百分比、置信度、优化器自身的推理过程),为审计"每次优化改了什么、为什么改"提供了结构化支撑。
与 Claude Code 集成
项目自带 Claude Code Skill(SKILL.md,frontmatter 中name: reasoning-trace-optimizer),支持三种激活方式:
- 失败自动触发:Agent 任务失败时自动分析原因;
- 按需分析:使用
/reasoning-trace-optimizer命令; - 会话分析:分析当前对话中的思考过程。
在 Claude Code 中配置钩子,实现工具错误后自动分析:
{ "hooks": { "post_tool_error": { "command": "rto analyze-session --last-error" } } }作为 Python 库使用
from reasoning_trace_optimizer import ( TraceCapture, TraceAnalyzer, PromptOptimizer, OptimizationLoop, LoopConfig, SkillGenerator, )【免费下载链接】Agent-Skills-for-Context-EngineeringA comprehensive collection of Agent Skills for context engineering, multi-agent architectures, and production agent systems. Use when building, optimizing, or debugging agent systems that require effective context management.项目地址: https://gitcode.com/GitHub_Trending/ag/Agent-Skills-for-Context-Engineering
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考