实战:用 Claude Agent SDK 构建多 Agent 系统自动修复 C++ 构建错误
实战:用 Claude Agent SDK 构建多 Agent 系统自动修复 C++ 构建错误
大型 C++ 项目的构建错误是每个开发者的噩梦。数千个文件、复杂的依赖关系、晦涩的编译器输出——当构建失败时,找到并修复错误往往需要数小时甚至数天。
但想象一下,如果有一个 AI 系统,能够:
- 自动分析编译器输出
- 定位错误源头
- 理解代码上下文
- 生成并应用修复
- 验证修复结果
这不再是科幻。基于最新的研究,LLM 驱动的系统可以自动解决高达 63% 的编译错误。本文将深入讲解如何使用 Claude Agent SDK 构建这样一个多 Agent 系统。
系统架构概览
核心设计理念
问题分解:C++ 构建错误修复是一个复杂的多步骤任务,需要:
1. 错误检测和分类
2. 代码上下文分析
3. 修复策略制定
4. 代码修改
5. 验证和迭代
单一 Agent vs 多 Agent:
- ❌ 单一 Agent:需要同时掌握所有技能,上下文过长,难以维护
- ✅ 多 Agent:专业化分工,清晰的职责边界,可扩展和可测试
Agent 系统架构
┌─────────────────────────────────────────────────────────────┐
│ Orchestrator Agent │
│ (协调者 - 总指挥) │
│ - 任务分解和分配 │
│ - Agent 之间的通信 │
│ - 决策何时迭代 │
└───────────┬─────────────────────────────────────────────────┘
│
├──────────────┬──────────────┬──────────────┐
▼ ▼ ▼ ▼
┌───────────┐ ┌───────────┐ ┌───────────┐ ┌───────────┐
│ Error │ │ Context │ │ Fixer │ │ Verifier │
│ Analyzer │ │ Analyzer │ │ Agent │ │ Agent │
│ (错误分析)│ │ (上下文) │ │ (修复者) │ │ (验证者) │
└───────────┘ └───────────┘ └───────────┘ └───────────┘
│ │ │ │
└──────────────┴──────────────┴──────────────┘
│
▼
┌─────────────────┐
│ Shared State │
│ (共享状态) │
│ - Build Log │
│ - File Cache │
│ - Fix History │
└─────────────────┘
Agent 详细设计
1. Orchestrator Agent(协调者)
职责:
- 解析构建日志,提取所有错误
- 将错误分组(相关错误一起处理)
- 分配任务给其他 Agent
- 协调 Agent 之间的工作流
- 决定何时继续迭代或放弃
设计重点:
# orchestrator_agent.yaml
role: Orchestrator
capabilities:
- parse_build_logs
- error_classification
- task_delegation
- workflow_orchestration
tools:
- log_parser: { format: "gcc|clang|msvc" }
- error_grouper: { strategy: "similarity_based" }
constraints:
- max_iterations: 3 # 最多尝试 3 次修复
- timeout_per_error: 300 # 每个错误最多 5 分钟
decision_logic:
- if error_count == 0: SUCCESS
- if iteration >= max_iterations: PARTIAL_SUCCESS
- if new_errors_introduced: ROLLBACK
实现示例:
from anthropic import Anthropic
from claude_agent_sdk import Agent
class OrchestratorAgent:
def __init__(self):
self.client = Anthropic()
self.error_analyzer = ErrorAnalyzerAgent()
self.context_analyzer = ContextAnalyzerAgent()
self.fixer_agent = FixerAgent()
self.verifier_agent = VerifierAgent()
async def fix_build_errors(self, build_log: str):
# 1. 解析构建日志
errors = self.parse_build_log(build_log)
# 2. 分组相关错误
error_groups = self.group_errors(errors)
# 3. 处理每组错误
results = []
for group in error_groups:
result = await self.process_error_group(group)
results.append(result)
return self.summarize_results(results)
async def process_error_group(self, error_group):
iteration = 0
max_iterations = 3
while iteration < max_iterations:
# 分析错误
error_analysis = await self.error_analyzer.analyze(error_group)
if error_analysis.is_fatal:
return {"status": "FAILED", "reason": error_analysis.reason}
# 收集上下文
context = await self.context_analyzer.collect(error_analysis)
# 生成修复
fixes = await self.fixer_agent.generate_fixes(error_analysis, context)
# 应用修复
await self.apply_fixes(fixes)
# 验证
verification = await self.verifier_agent.verify(fixes)
if verification.success:
return {"status": "SUCCESS", "fixes": fixes}
elif verification.new_errors:
# 引入了新错误,回滚
await self.rollback_fixes(fixes)
return {"status": "REGRESSION", "details": verification}
else:
# 修复失败,继续迭代
iteration += 1
error_group = verification.remaining_errors
return {"status": "PARTIAL", "iterations": iteration}
关键设计决策:
-
错误分组:相关的错误(如同一个文件的多个错误)一起处理,避免重复工作
-
迭代限制:最多 3 次迭代,避免无限循环
-
快速失败:致命错误(如循环依赖)立即返回,不浪费时间
-
状态管理:维护修复历史,支持回滚
2. Error Analyzer Agent(错误分析者)
职责:
- 解析编译器输出
- 提取关键信息:文件名、行号、错误类型、错误消息
- 分类错误类型
- 评估错误严重性
- 识别错误模式
设计重点:
# error_analyzer_agent.yaml
role: Error Analyzer
expertise:
- compiler_output_parsing
- error_classification
- pattern_recognition
error_categories:
syntax:
- missing_semicolon
- unmatched_braces
- invalid_tokens
linker:
- undefined_reference
- multiple_definition
type:
- implicit_conversion
- incompatible_types
- missing_include
template:
- template_instantiation_failed
- deduction_failed
output_format:
- file_path: string
- line_number: int
- column: int
- error_code: string
- error_type: enum
- severity: enum
- context_snippet: string
- suggested_fixes: list[string]
实现示例:
class ErrorAnalyzerAgent:
def __init__(self):
self.client = Anthropic()
async def analyze(self, error_group: List[str]) -> ErrorAnalysis:
# 使用 Claude 解析错误
prompt = f"""分析以下 C++ 编译错误,提取关键信息:
编译器输出:
{chr(10).join(error_group)}
请提供:
1. 错误类型(syntax/linker/type/template)
2. 严重性(fatal/error/warning)
3. 受影响的文件和行号
4. 错误的根本原因
5. 是否可以自动修复(是/否)
6. 如果是 fatal,说明原因
以 JSON 格式返回。"""
response = await self.client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=2000,
messages=[{"role": "user", "content": prompt}]
)
return self.parse_analysis(response.content)
def parse_analysis(self, content):
# 解析 Claude 的 JSON 输出
return ErrorAnalysis(
error_type=content["error_type"],
severity=content["severity"],
file_path=content["file_path"],
line_number=content["line_number"],
root_cause=content["root_cause"],
fixable=content["fixable"],
is_fatal=(not content["fixable"] and content["severity"] == "fatal")
)
关键设计决策:
-
使用 Claude 的结构化输出:确保解析一致性
-
错误分类:不同类型的错误需要不同的修复策略
-
可修复性评估:提前识别无法自动修复的错误,节省时间
-
模式识别:识别常见错误模式(如缺少分号、头文件)
3. Context Analyzer Agent(上下文分析者)
职责:
- 收集错误相关的代码上下文
- 分析代码结构和依赖
- 识别相关文件和函数
- 提取类型信息
- 理解代码意图
设计重点:
# context_analyzer_agent.yaml
role: Context Analyzer
capabilities:
- static_code_analysis
- dependency_tracing
- type_inference
- semantic_understanding
context_collection:
primary:
- error_line: 10 lines before/after
- function_body: complete function
- class_definition: complete class
secondary:
- included_headers: all #includes
- related_definitions: used types/functions
- call_sites: where this function is called
tertiary:
- build_config: CMakeLists.txt, Makefile
- compiler_flags: optimization, warnings
analysis_depth:
- shallow: only error location
- medium: + direct dependencies
- deep: + transitive dependencies (slow)
实现示例:
class ContextAnalyzerAgent:
def __init__(self):
self.client = Anthropic()
self.file_cache = {} # 文件缓存
async def collect(self, error_analysis: ErrorAnalysis) -> CodeContext:
# 1. 收集主要上下文
primary_context = await self.collect_primary_context(error_analysis)
# 2. 收集次要上下文
secondary_context = await self.collect_secondary_context(error_analysis)
# 3. 使用 Claude 理解代码意图
semantic_context = await self.analyze_semantics(
primary_context,
secondary_context
)
return CodeContext(
primary=primary_context,
secondary=secondary_context,
semantic=semantic_context
)
async def collect_primary_context(self, error: ErrorAnalysis):
file_path = error.file_path
line_no = error.line_number
# 读取文件
content = self.read_file(file_path)
# 提取上下文窗口(前后各 10 行)
lines = content.split('\n')
start = max(0, line_no - 10)
end = min(len(lines), line_no + 10)
context_window = '\n'.join(lines[start:end])
# 识别包含的函数/类
function_info = self.extract_function_info(content, line_no)
class_info = self.extract_class_info(content, line_no)
return {
"context_window": context_window,
"function": function_info,
"class": class_info
}
async def analyze_semantics(self, primary, secondary):
# 使用 Claude 理解代码意图
prompt = f"""分析以下 C++ 代码的语义和意图:
错误位置代码:
{primary['context_window']}
函数定义:
{primary.get('function', 'N/A')}
类定义:
{primary.get('class', 'N/A')}
相关依赖:
{secondary.get('dependencies', 'N/A')}
请分析:
1. 这段代码试图实现什么功能?
2. 错误可能的原因是什么?
3. 修复时需要注意哪些约束?
4. 相关的代码模式有哪些?
以 JSON 格式返回。"""
response = await self.client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=2000,
messages=[{"role": "user", "content": prompt}]
)
return self.parse_semantic_analysis(response.content)
关键设计决策:
-
分层上下文收集:主要、次要、三级,平衡速度和准确性
-
文件缓存:避免重复读取文件
-
语义理解:不仅收集代码,还理解意图,这对于生成正确的修复至关重要
-
依赖追踪:理解类型和函数的依赖关系
4. Fixer Agent(修复者)
职责:
- 基于错误分析和上下文生成修复
- 应用最佳实践
- 保持代码风格一致
- 生成多个候选修复(如果有多种方案)
- 解释修复理由
设计重点:
# fixer_agent.yaml
role: Fixer Agent
expertise:
- C++ best_practices
- design_patterns
- modern_cpp_standards
fix_strategies:
syntax_errors:
- add_missing_semicolon
- balance_braces
- fix_typos
type_errors:
- add_explicit_cast
- include_header
- fix_template_arguments
linker_errors:
- add_implementation
- fix_linkage_specification
- add_library_dependency
code_style:
follow_project_conventions: true
use_modern_cpp: C++17/20
preserve_formatting: true
add_comments: minimal
fix_generation:
num_candidates: 3 # 生成多个候选
rank_by:
- likelihood_of_success
- code_quality
- minimal_changes
实现示例:
class FixerAgent:
def __init__(self):
self.client = Anthropic()
async def generate_fixes(self, error: ErrorAnalysis, context: CodeContext) -> List[Fix]:
# 选择修复策略
strategy = self.select_strategy(error.error_type)
# 生成修复
prompt = self.build_fix_prompt(error, context, strategy)
response = await self.client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=4000,
messages=[{"role": "user", "content": prompt}],
tools=self.get_fixing_tools()
)
# 解析生成的修复
fixes = self.parse_fixes(response.content, error, context)
# 排序候选修复
fixes = self.rank_fixes(fixes)
return fixes[:3] # 返回前 3 个候选
def build_fix_prompt(self, error, context, strategy):
return f"""你是一个 C++ 专家,需要修复以下编译错误:
错误信息:
{error.error_message}
位置:{error.file_path}:{error.line_number}
错误类型:{error.error_type}
代码上下文:
{context.primary['context_window']}
语义分析:
{context.semantic['intent']}
约束条件:
{context.semantic['constraints']}
相关代码模式:
{context.semantic['patterns']}
请生成修复方案:
1. 解释错误的根本原因
2. 提供 3 个不同的修复方案
3. 对每个方案,说明:
- 具体的代码修改
- 为什么这样修复
- 潜在的风险
- 是否需要其他修改
以结构化格式返回。"""
def get_fixing_tools(self):
return [
{
"name": "apply_code_change",
"description": "Apply a code change to a file",
"input_schema": {
"type": "object",
"properties": {
"file_path": {"type": "string"},
"start_line": {"type": "integer"},
"end_line": {"type": "integer"},
"replacement": {"type": "string"},
"explanation": {"type": "string"}
},
"required": ["file_path", "start_line", "end_line", "replacement"]
}
},
{
"name": "add_include",
"description": "Add an #include directive",
"input_schema": {
"type": "object",
"properties": {
"file_path": {"type": "string"},
"header": {"type": "string"},
"position": {"type": "string", "enum": ["top", "after_includes"]}
},
"required": ["file_path", "header"]
}
}
]
关键设计决策:
-
多个候选修复:不是所有修复都正确,提供多个选项
-
使用 Tools:让 Claude 通过结构化的工具调用生成修复,而不是自由文本
-
代码风格保持:修复时保持项目的代码风格
-
风险意识:每个修复都包含潜在风险说明
5. Verifier Agent(验证者)
职责:
- 应用修复到代码
- 重新编译
- 分析编译结果
- 检测是否引入新错误
- 决定是否接受修复
设计重点:
# verifier_agent.yaml
role: Verifier Agent
capabilities:
- apply_patches
- incremental_compilation
- regression_detection
- fix_validation
verification_steps:
1. apply_fix:
method: git_diff # 使用 git diff 应用修改
backup: true # 自动备份
2. rebuild:
method: incremental # 增量编译
targets: affected_files
3. analyze:
check_new_errors: true
check_warnings: true
check_unchanged_errors: true
4. decision:
accept_if:
- original_error_fixed
- no_new_errors
- no_regression
reject_if:
- new_errors_introduced
- compilation_time_exceeded
rollback_strategy:
automatic: true
trigger:
- new_errors
- test_failures
实现示例:
class VerifierAgent:
def __init__(self):
self.client = Anthropic()
self.build_system = BuildSystem() # CMake/Make 抽象
async def verify(self, fix: Fix) -> VerificationResult:
# 1. 应用修复
applied = await self.apply_fix(fix)
if not applied.success:
return VerificationResult(success=False, reason=applied.error)
# 2. 增量编译
build_result = await self.rebuild(fix.affected_files)
# 3. 分析结果
analysis = await self.analyze_build_result(build_result, fix)
return analysis
async def apply_fix(self, fix: Fix):
# 使用 git apply
patch = self.generate_patch(fix)
result = subprocess.run(
["git", "apply", "--cached"],
input=patch.encode(),
capture_output=True
)
if result.returncode != 0:
return ApplyResult(success=False, error=result.stderr)
return ApplyResult(success=True)
async def rebuild(self, affected_files):
# 增量编译只编译受影响的文件
return await self.build_system.build_incremental(affected_files)
async def analyze_build_result(self, build_result, fix):
original_error = fix.original_error
new_errors = self.extract_errors(build_result)
# 检查原始错误是否修复
original_fixed = original_error not in new_errors
# 检查是否引入新错误
new_errors_introduced = self.has_new_errors(
new_errors,
fix.original_errors
)
# 检查是否有回退
regression = self.has_regression(new_errors)
if original_fixed and not new_errors_introduced and not regression:
return VerificationResult(
success=True,
remaining_errors=self.filter_errors(new_errors, fix.original_errors)
)
elif new_errors_introduced:
return VerificationResult(
success=False,
reason="引入新错误",
new_errors=new_errors_introduced
)
else:
return VerificationResult(
success=False,
reason="修复失败",
remaining_errors=new_errors
)
关键设计决策:
-
自动回滚:如果引入新错误,自动回滚修复
-
增量编译:只编译受影响的文件,加快验证速度
-
回归检测:确保没有破坏其他部分
-
详细的验证报告:为下一步决策提供充分信息
Agent 协作流程
完整工作流
async def fix_build_error_pipeline(build_log: str):
"""完整的错误修复流程"""
# 初始化 Orchestrator
orchestrator = OrchestratorAgent()
# 开始修复
result = await orchestrator.fix_build_errors(build_log)
return result
# 实际执行流程
"""
1. Orchestrator 接收构建日志
↓
2. Error Analyzer 解析错误
↓
3. Orchestrator 分组错误
↓
4. for each error_group:
├→ Context Analyzer 收集上下文
├→ Fixer Agent 生成修复
├→ Verifier Agent 验证修复
└→ if 验证失败:
返回 Fixer Agent 重新生成
↓
5. 汇总所有修复
↓
6. 返回最终结果
"""
通信协议
# Agent 之间的消息格式
@dataclass
class AgentMessage:
from_agent: str
to_agent: str
message_type: str # request/response/error
payload: dict
correlation_id: str
timestamp: datetime
# 示例:Error Analyzer → Context Analyzer
msg = AgentMessage(
from_agent="error_analyzer",
to_agent="context_analyzer",
message_type="context_request",
payload={
"error": {
"file_path": "src/foo.cpp",
"line_number": 42,
"error_type": "type_error"
}
},
correlation_id="req_001",
timestamp=datetime.now()
)
共享状态管理
class SharedState:
"""Agent 之间的共享状态"""
def __init__(self):
self.build_log = ""
self.errors = []
self.fixes = [] # 已应用的修复
self.file_cache = {} # 文件内容缓存
self.error_fix_map = {} # 错误 → 修复映射
def add_fix(self, fix):
"""记录修复"""
self.fixes.append(fix)
for error in fix.fixed_errors:
self.error_fix_map[error.id] = fix.id
def get_fix_history(self, error_id):
"""获取某个错误的所有修复尝试"""
fixes = []
for fix in self.fixes:
if error_id in [e.id for e in fix.fixed_errors]:
fixes.append(fix)
return fixes
实战示例
场景:修复缺少头文件错误
编译器输出:
src/parser.cpp:42:10: error: 'unique_ptr' is not a member of 'std'
42 | auto ptr = std::unique_ptr<Node>(new Node());
| ^~~
执行流程:
- Error Analyzer:
{
"error_type": "type_error",
"severity": "error",
"file_path": "src/parser.cpp",
"line_number": 42,
"root_cause": "std::unique_ptr 需要 <memory> 头文件",
"fixable": true,
"is_fatal": false
}
- Context Analyzer:
{
"primary": {
"context_window": "// ... 前面的代码\nauto ptr = std::unique_ptr<Node>(new Node());\n// ...",
"includes": ["#include <vector>", "#include <string>"],
"missing": ["<memory>"]
},
"semantic": {
"intent": "使用智能指针管理 Node 对象的生命周期",
"best_practice": "应该使用 std::make_unique",
"constraints": "不能改变 ptr 变量的类型"
}
}
- Fixer Agent:
# 候选修复 1(推荐)
{
"change": {
"file_path": "src/parser.cpp",
"position": "after_includes",
"action": "add_include",
"header": "#include <memory>"
},
"explanation": "添加 <memory> 头文件",
"risk": "无",
"additional_suggestions": "考虑使用 std::make_unique"
}
# 候选修复 2
{
"change": {
"file_path": "src/parser.cpp",
"line_number": 42,
"action": "replace",
"from": "std::unique_ptr<Node>(new Node())",
"to": "std::make_unique<Node>()"
},
"explanation": "使用 make_unique 并添加头文件",
"risk": "可能影响其他代码",
"requires": ["#include <memory>"]
}
- Verifier Agent:
# 应用修复 1
$ git apply patch_1.diff
$ cmake --build . --target parser.cpp.o
[100%] Building CXX object CMakeFiles/app.dir/src/parser.cpp.o
✅ 编译成功
# 结果
{
"success": true,
"original_error_fixed": true,
"new_errors": [],
"recommendation": "accept_fix"
}
场景:修复模板推导失败
编译器输出:
src/utils.hpp:120:15: error: no matching function for call to 'transform'
120 | return transform(begin, end, output);
| ^~~~~~~~
src/utils.hpp:120:15: note: candidate is:
template<class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt, InputIt, OutputIt, UnaryOperation);
多 Agent 协作:
-
Error Analyzer 识别为模板推导失败
-
Context Analyzer 分析:
-transform是自定义函数,不是std::transform
- 缺少第四个参数(转换函数) -
Fixer Agent 生成修复:
// 方案 1:提供转换函数
return transform(begin, end, output, [](const auto& x) { return x; });
// 方案 2:使用 std::transform
#include <algorithm>
return std::transform(begin, end, output, [](const auto& x) { return x; });
- Verifier Agent 验证并选择最佳方案
高级特性
1. 学习机制
class LearningModule:
"""从历史修复中学习"""
def __init__(self):
self.fix_database = {} # 错误模式 → 成功修复
def record_success(self, error_pattern, fix):
"""记录成功的修复"""
if error_pattern not in self.fix_database:
self.fix_database[error_pattern] = []
self.fix_database[error_pattern].append(fix)
def suggest_fix(self, error):
"""基于历史建议修复"""
pattern = self.extract_pattern(error)
if pattern in self.fix_database:
# 返回历史上最成功的修复
fixes = self.fix_database[pattern]
return max(fixes, key=lambda f: f.success_rate)
return None
2. 并行处理
async def parallel_fix(error_groups):
"""并行处理独立的错误组"""
tasks = []
for group in error_groups:
task = asyncio.create_task(process_error_group(group))
tasks.append(task)
results = await asyncio.gather(*tasks)
return results
3. 增量修复
class IncrementalFixer:
"""只修复新的或变化的错误"""
def __init__(self):
self.previous_errors = set()
def filter_new_errors(self, current_errors):
"""过滤出新的错误"""
current = set((e.file_path, e.line_number, e.error_msg) for e in current_errors)
new_errors = current - self.previous_errors
self.previous_errors = current
return new_errors
性能优化
1. 缓存策略
class CacheManager:
def __init__(self):
self.file_cache = LRUCache(maxsize=100)
self.analysis_cache = {} # (file, line) → analysis
def get_file(self, path):
if path not in self.file_cache:
self.file_cache[path] = self.read_file(path)
return self.file_cache[path]
def get_analysis(self, file_path, line_no):
key = (file_path, line_no)
if key not in self.analysis_cache:
# 分析并缓存
self.analysis_cache[key] = self.analyze(file_path, line_no)
return self.analysis_cache[key]
2. 智能错误过滤
def filter_fixable_errors(errors):
"""只处理可修复的错误"""
fixable = []
skip_patterns = [
"fatal error: .* no such file or directory", # 缺少系统文件
"internal compiler error", # 编译器 bug
"command terminated due to signal" # 系统问题
]
for error in errors:
if not any(re.search(pattern, error.msg) for pattern in skip_patterns):
fixable.append(error)
return fixable
3. 批量编译
async def batch_verify(fixes, batch_size=10):
"""批量验证修复"""
results = []
for i in range(0, len(fixes), batch_size):
batch = fixes[i:i+batch_size]
# 并行编译
batch_results = await asyncio.gather(
*[verify_fix(fix) for fix in batch]
)
results.extend(batch_results)
return results
部署和集成
CI/CD 集成
# .github/workflows/auto-fix.yml
name: Auto Fix Build Errors
on:
push:
branches: [main, develop]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build
run: cmake --build . 2>&1 | tee build.log
- name: Auto Fix
if: failure()
run: |
pip install claude-agent-sdk
python -m fixer_agent build.log --apply
- name: Rebuild
run: cmake --build .
- name: Create PR
if: success()
run: |
git config user.name "Auto Fixer"
git commit -am "Auto-fix build errors"
gh pr create --title "Auto-fix build errors" --body "Automatically fixed by AI"
配置文件
# fixer_config.yaml
project:
build_system: cmake
build_command: cmake --build .
source_dirs: [src, lib]
test_command: ctest
agents:
orchestrator:
max_iterations: 3
parallel_processing: true
error_analyzer:
compiler: gcc
error_db: ./error_patterns.json
context_analyzer:
context_lines: 10
include_headers: true
follow_includes: true
fixer:
num_candidates: 3
apply_style_check: true
run_format: true
verifier:
rebuild_strategy: incremental
auto_rollback: true
run_tests: true
performance:
cache_size: 100
parallel_jobs: 4
timeout_per_error: 300
logging:
level: INFO
file: fixer.log
评估和度量
成功指标
class Metrics:
"""修复系统的性能指标"""
def __init__(self):
self.total_errors = 0
self.fixed_errors = 0
self.failed_errors = 0
self.regressions = 0
self.avg_iterations = 0
@property
def success_rate(self):
return self.fixed_errors / self.total_errors
@property
def regression_rate(self):
return self.regressions / self.total_errors
def generate_report(self):
return f"""
修复系统报告
===========
总错误数: {self.total_errors}
成功修复: {self.fixed_errors} ({self.success_rate:.1%})
修复失败: {self.failed_errors}
引入回归: {self.regressions}
平均迭代次数: {self.avg_iterations:.1f}
"""
基准测试
基于研究数据,优秀的系统应该达到:
- 成功率: 60-70%(当前研究上限约 63%)
- 回归率: < 5%
- 平均修复时间: < 2 分钟/错误
- 准确率: > 95%(不破坏正确代码)
最佳实践
DO ✅
- 从简单开始:先实现单一功能,逐步扩展
- 充分测试:在真实项目上测试,收集反馈
- 保持透明:记录所有修复决策,便于审查
- 增量改进:基于失败案例持续优化
- 人类审查:自动修复后由开发者审查
DON'T ❌
- 不要信任 100%:AI 可能犯错,需要验证
- 不要忽略风格:修复应该符合项目规范
- 不要过度修复:只修复报告的错误
- 不要跳过测试:修复后必须运行测试
- 不要破坏构建:自动回滚失败的修复
总结
使用 Claude Agent SDK 构建多 Agent 系统来修复 C++ 构建错误,核心在于:
- 专业化分工:每个 Agent 专注于特定任务
- 清晰协议:定义良好的通信和状态管理
- 迭代改进:从失败中学习和优化
- 人类协作:AI 辅助,人类决策
这个系统不是要替代开发者,而是放大开发者的能力——让 AI 处理重复性的错误诊断和修复,让开发者专注于更复杂的问题。
根据研究,这样的系统可以自动解决 63% 的编译错误,这意味着开发者可以将精力集中在剩下的 37% 需要创造性思维的问题上。
这就是 AI Native Engineering 的真正力量。
参考资料
研究论文:
- Auto-repair without test cases: How LLMs fix compilation errors
- LLM-Based Repair of C++ Compiler Warnings
官方文档:
- Claude Agent SDK overview
- claude-agent-sdk-python
相关工具:
- AwesomeLLM4APR - LLM 自动化程序修复资源集合
本文展示了如何使用 Claude Agent SDK 构建生产级的多 Agent 系统,实际效果取决于具体项目的复杂度和代码质量。

浙公网安备 33010602011771号