Skip to content
Beijing QZ Technology Knowledge Base
🕸Knowledge Graph

07_AI编程与代码Agent

状态
标题 · 目录 · 标签 · 摘要(自动填写,可展开查看/修改)
基于后台配置的 AI 模型(智谱 GLM 等)
标题
目录
标签(逗号分隔)
摘要
Views 15 · Updated 2026-11-02
AI编程代码Agent代码生成模型Cursor/CopilotAST+LLM

本册介绍AI编程与代码Agent,涵盖代码生成模型原理、Cursor/Copilot架构、代码Agent工程化等内容。


领域七:AI 编程与代码 Agent

AI Agent 知识库 · 第七册 本册涵盖:代码生成模型原理、Cursor/Copilot 架构剖析、代码 Agent 工程化、AST+LLM 混合推理、代码评测体系


学习导航

前置知识自检(勾选你已掌握的):

  • 编程经验(至少一门语言,最好 Python + JavaScript)
  • 理解 IDE 的基本功能(补全、跳转定义、查找引用)
  • 知道什么是 AST(抽象语法树)——有帮助但非必需
  • 用过 GitHub Copilot 或类似代码补全工具

如果没用过代码补全工具:在 VS Code 中安装 Copilot/Cursor 感受一下

学习目标:读完本册你将能——

  1. 理解代码模型为什么需要 FIM(Fill-in-the-Middle)训练
  2. 剖析 Cursor/Copilot 的"代码索引 + 语义检索 + 上下文组装"架构
  3. 设计 AST + LLM 混合推理管道
  4. 构建带测试反馈循环的代码 Agent
  5. 用 pass@k 评测代码生成质量

本册难度:★★★★☆(需要编程经验,AST 概念稍有门槛) 前置册号:第一册(LLM 基础 → 代码模型)、第三册(Agent → 代码 Agent) 关联册号:第六册(代码模型微调)、第八册(多模态 → UI 理解 Agent)

术语速查(本册高频缩写):

缩写 全称 一句话解释
FIM Fill-in-the-Middle 训练模型在代码中间插入内容
AST Abstract Syntax Tree 抽象语法树,代码的结构化表示
CTAGS - 代码索引工具,提取函数/类定义
pass@k - 生成 k 个答案,至少一个通过测试的概率
LSP Language Server Protocol 语言服务器协议,提供代码智能提示

第一章 代码生成模型原理

1.1 代码模型的特殊挑战

代码生成 vs 自然语言生成的核心差异:

1. 严格语法:代码必须通过编译器/解释器,一个符号错误就会失败
   自然语言:"我今天去银行" vs "我今天去银" → 仍可理解
   代码:print("hello") vs print("hello" → SyntaxError

2. 长程依赖:函数定义、变量声明、类型约束可能在数百行之外
   def calculate_tax(income: float) -> float:  # 第 10 行
       ...
   # 第 200 行使用 calculate_tax 的返回值
   # 模型需要记住函数签名和返回类型

3. 执行反馈:代码可以运行验证,自然语言不能
   → 这是代码 Agent 的核心优势:可以用编译器/测试验证生成结果

4. 上下文工程:代码仓库动辄数十万行,远超模型上下文窗口
   → 需要智能检索相关代码片段

1.2 主流代码模型

模型 参数量 许可证 代码能力 特点
DeepSeek-Coder-V2 16B (MoE) MIT 顶级 开源最强代码模型,支持 338 种语言
Qwen2.5-Coder-32B 32B Apache 2.0 顶级 阿里出品,中文+代码双强
CodeLlama-34B 34B Llama 2 License 良好 Meta 出品,社区生态丰富
StarCoder2-15B 15B BigCode OpenRAIL 良好 支持 600+ 语言
Copilot (GPT-4) 未公开 商用 顶级 GitHub Copilot 背后模型
Claude 3.5 Sonnet 未公开 商用 顶级 Anthropic,代码能力极强

1.3 代码模型训练流程

阶段 1:预训练(Pre-training)
  数据:The Stack(GitHub 开源代码,~3TB)
  目标:下一个 token 预测(与通用 LLM 相同)
  特殊处理:
    - 代码缩进敏感 → 使用特殊 tokenizer(保留缩进)
    - 文件路径信息 → <file_path> 标记
    - 仓库级别训练 → Fill-in-the-Middle (FIM) 目标

阶段 2:Fill-in-the-Middle 训练
  核心:让模型学会在代码中间插入内容(而非只续写)
  
  原始代码:
    def sort_list(items):
        result = []
        for item in items:
            # ↓ 这里是要补全的部分
            result.append(item)
        return result
  
  FIM 格式:
    <prefix>def sort_list(items):\n    result = []\n    for item in items:\n</prefix>
    <suffix>\n        return result</suffix>
    <middle>            result.append(item)</middle>
  
  这使得模型能做:
    - 代码补全(光标后插入)
    - 代码修改(替换中间部分)
    - Copilot 式的行内建议

阶段 3:指令微调(SFT)
  数据:代码指令-回答对
  目标:理解自然语言编程指令,生成正确的代码
  示例:
    {"instruction": "写一个 Python 函数实现快速排序", 
     "output": "def quicksort(arr):\n    ..."}

阶段 4:RLHF / DPO 对齐
  奖励信号:
    - 代码是否通过测试(编译+运行)
    - 代码质量(PEP8、复杂度)
    - 人类偏好(可读性、效率)

1.4 FIM(Fill-in-the-Middle)原理

# FIM 是代码补全的核心能力
# 将代码拆分为 prefix、middle、suffix 三部分训练

class FIMFormatter:
    """将完整代码转换为 FIM 训练格式"""
    
    def __init__(self, tokenizer):
        self.tokenizer = tokenizer
        # FIM 特殊标记
        self.prefix_token = "<|fim_prefix|>"
        self.middle_token = "<|fim_middle|>"
        self.suffix_token = "<|fim_suffix|>"
        self.end_token = "<|fim_end|>"
    
    def format_fim(self, code: str, split_point: int = None):
        """
        将代码转为 FIM 格式
        split_point: 中间部分的起始位置(字符偏移)
        """
        if split_point is None:
            # 随机选择分割点(偏向行首)
            lines = code.split('\n')
            split_line = random.randint(1, len(lines) - 1)
            prefix = '\n'.join(lines[:split_line])
            suffix = '\n'.join(lines[split_line + 1:])
            # middle 是被移除的那一行
            middle = lines[split_line]
        else:
            prefix = code[:split_point]
            suffix = code[split_point + 50:]  # suffix 取后续 50 字符
            middle = code[split_point:split_point + 50]
        
        # FIM 格式
        fim_text = (
            f"{self.prefix_token}{prefix}"
            f"{self.suffix_token}{suffix}"
            f"{self.middle_token}{middle}"
            f"{self.end_token}"
        )
        return fim_text
    
    def format_infill(self, prefix: str, suffix: str) -> str:
        """推理时使用:给定前后文,生成中间代码"""
        return (
            f"{self.prefix_token}{prefix}"
            f"{self.suffix_token}{suffix}"
            f"{self.middle_token}"
        )

第二章 Cursor / Copilot 架构剖析

2.1 GitHub Copilot 架构

┌──────────────────────────────────────────────────────────┐
│                    GitHub Copilot 架构                    │
├──────────────────────────────────────────────────────────┤
│                                                          │
│  IDE Plugin (VS Code / JetBrains)                        │
│  ┌──────────────────────────────────────────────────┐    │
│  │ 1. 上下文收集器                                   │    │
│  │    - 当前文件内容(光标前后)                      │    │
│  │    - 相邻文件(import 的模块)                     │    │
│  │    - 光标位置、语言类型                            │    │
│  │    - 最近编辑历史                                  │    │
│  │                                                   │    │
│  │ 2. 请求构建器                                     │    │
│  │    - FIM 格式封装                                 │    │
│  │    - Token 截断(保留 <2048 tokens)              │    │
│  │    - 去除敏感信息(密钥、密码)                    │    │
│  │                                                   │    │
│  │ 3. 响应处理器                                     │    │
│  │    - 流式渲染(逐 token 显示)                     │    │
│  │    - 后处理(缩进对齐、语法检查)                  │    │
│  │    - 置信度过滤(低概率 token 丢弃)               │    │
│  └──────────────────────────────────────────────────┘    │
│                         ↕ HTTPS                          │
│  Copilot Server                                          │
│  ┌──────────────────────────────────────────────────┐    │
│  │ 4. 上下文增强                                     │    │
│  │    - 代码片段检索(GitHub 代码库)                 │    │
│  │    - 相似代码检索                                  │    │
│  │                                                   │    │
│  │ 5. 模型推理                                       │    │
│  │    - GPT-4 / Codex 系列                           │    │
│  │    - 多模型路由(简单/复杂任务)                    │    │
│  │                                                   │    │
│  │ 6. 安全过滤                                       │    │
│  │    - 代码许可检查(排除 GPL 等受限许可)            │    │
│  │    - 敏感信息过滤                                  │    │
│  └──────────────────────────────────────────────────┘    │
│                                                          │
└──────────────────────────────────────────────────────────┘

2.2 Cursor 架构(AI-Native IDE)

Cursor 与 Copilot 的核心差异:
  Copilot = IDE 插件(在现有 IDE 上附加 AI)
  Cursor = AI-Native IDE(从底层重新设计,AI 为核心)

Cursor 的关键架构创新:

1. 全仓库上下文感知
   ┌────────────────────────────────────────┐
   │ Codebase Indexing                      │
   │  - 全仓库代码向量化(Embedding)        │
   │  - 语义检索:找到与当前任务相关的文件    │
   │  - 增量更新:文件修改后自动更新索引      │
   │  - 支持本地/远程仓库                    │
   └────────────────────────────────────────┘
   
2. Agent 模式
   ┌────────────────────────────────────────┐
   │ Agent Loop                             │
   │  - 理解用户意图                         │
   │  - 自动检索相关文件                     │
   │  - 生成代码修改方案                     │
   │  - 自动应用修改(diff)                 │
   │  - 运行测试验证                         │
   │  - 根据测试结果迭代修复                 │
   └────────────────────────────────────────┘
   
3. 多模型支持
   ┌────────────────────────────────────────┐
   │ Model Router                           │
   │  - Claude 3.5 Sonnet(代码生成强)      │
   │  - GPT-4o(通用能力强)                 │
   │  - DeepSeek-Coder(开源/低成本)        │
   │  - 自动选择或用户手动切换                │
   └────────────────────────────────────────┘

2.3 Cursor Agent 模式工作流

"""
Cursor Agent 模式的核心工作流(概念模型)
"""

class CodeAgent:
    """代码 Agent:理解意图 → 检索 → 修改 → 验证 → 迭代"""
    
    def __init__(self, repo_path: str, llm_client):
        self.repo_path = repo_path
        self.llm = llm_client
        self.indexer = CodebaseIndexer(repo_path)
        self.max_iterations = 10
    
    def execute(self, user_request: str) -> dict:
        """执行用户的代码修改请求"""
        
        # 1. 理解意图
        plan = self._understand_intent(user_request)
        
        # 2. 检索相关文件
        relevant_files = self._retrieve_relevant_code(plan)
        
        # 3. 迭代修改
        for i in range(self.max_iterations):
            # 生成代码修改
            modifications = self._generate_modifications(
                user_request, plan, relevant_files
            )
            
            # 应用修改
            self._apply_modifications(modifications)
            
            # 验证
            test_result = self._run_tests()
            
            if test_result["passed"]:
                return {"success": True, "changes": modifications}
            
            # 根据测试失败迭代修复
            error_context = self._analyze_failures(test_result)
            user_request = f"修复以下测试错误:\n{error_context}"
        
        return {"success": False, "reason": "达到最大迭代次数"}
    
    def _understand_intent(self, request: str) -> dict:
        """用 LLM 分析用户意图,生成执行计划"""
        prompt = f"""分析以下代码修改请求,生成执行计划:
        
请求:{request}

输出 JSON:
{{
  "task_type": "bug_fix|feature|refactor|test",
  "affected_modules": ["模块名"],
  "estimated_files": ["文件路径"],
  "steps": ["步骤1", "步骤2"]
}}"""
        response = self.llm.chat(prompt)
        return parse_json(response)
    
    def _retrieve_relevant_code(self, plan: dict) -> list:
        """从代码库检索相关代码片段"""
        # 语义检索
        query = " ".join(plan.get("estimated_files", []))
        results = self.indexer.search(query, top_k=10)
        
        # 补充:检索 import 关联文件
        for file_path in plan.get("estimated_files", []):
            imports = self.indexer.get_imports(file_path)
            for imp in imports:
                results.extend(self.indexer.search(imp, top_k=3))
        
        # 去重并截断到 token 预算
        return self._truncate_to_budget(results, max_tokens=8000)
    
    def _generate_modifications(self, request, plan, files) -> list:
        """生成代码修改(diff 格式)"""
        context = self._build_context(files)
        
        prompt = f"""基于以下代码上下文,修改代码以实现用户请求。

用户请求:{request}

相关代码:
{context}

输出修改后的文件内容,用 ```python 等代码块标注文件名。"""
        
        response = self.llm.chat(prompt)
        return self._parse_modifications(response)
    
    def _apply_modifications(self, modifications: list):
        """将修改应用到实际文件"""
        for mod in modifications:
            file_path = mod["file_path"]
            new_content = mod["content"]
            # 保存原始文件备份
            self._backup_file(file_path)
            # 写入新内容
            with open(file_path, 'w') as f:
                f.write(new_content)
    
    def _run_tests(self) -> dict:
        """运行测试套件"""
        import subprocess
        result = subprocess.run(
            ["python", "-m", "pytest", "--tb=short"],
            capture_output=True, text=True, cwd=self.repo_path
        )
        return {
            "passed": result.returncode == 0,
            "stdout": result.stdout,
            "stderr": result.stderr,
        }

2.4 代码索引与检索

"""
Codebase Indexing:代码库语义索引
"""
import os
from typing import List, Dict
import chromadb
from chromadb.utils import embedding_functions

class CodebaseIndexer:
    """代码库语义索引器"""
    
    def __init__(self, repo_path: str):
        self.repo_path = repo_path
        self.client = chromadb.PersistentClient(path=".code_index")
        self.embedder = embedding_functions.SentenceTransformerEmbeddingFunction(
            model_name="jinaai/jina-embeddings-v2-base-code"
        )
        self.collection = self.client.get_or_create_collection(
            name="codebase",
            embedding_function=self.embedder,
        )
    
    def index_repo(self):
        """索引整个代码仓库"""
        files = self._collect_code_files()
        
        for file_path in files:
            chunks = self._chunk_file(file_path)
            embeddings_data = []
            
            for i, chunk in enumerate(chunks):
                # 构建文档:包含文件路径和代码内容
                doc = f"File: {file_path}\n\n{chunk['content']}"
                metadata = {
                    "file_path": file_path,
                    "start_line": chunk["start_line"],
                    "end_line": chunk["end_line"],
                    "language": chunk["language"],
                }
                embeddings_data.append({
                    "id": f"{file_path}#{i}",
                    "document": doc,
                    "metadata": metadata,
                })
            
            # 批量插入
            self.collection.add(
                ids=[d["id"] for d in embeddings_data],
                documents=[d["document"] for d in embeddings_data],
                metadatas=[d["metadata"] for d in embeddings_data],
            )
        
        print(f"Indexed {len(files)} files")
    
    def search(self, query: str, top_k: int = 10) -> List[Dict]:
        """语义搜索代码"""
        results = self.collection.query(
            query_texts=[query],
            n_results=top_k,
        )
        
        return [
            {
                "content": doc,
                "file_path": meta["file_path"],
                "start_line": meta["start_line"],
                "end_line": meta["end_line"],
                "language": meta["language"],
            }
            for doc, meta in zip(
                results["documents"][0],
                results["metadatas"][0]
            )
        ]
    
    def _collect_code_files(self) -> List[str]:
        """收集所有代码文件"""
        code_extensions = {
            '.py', '.js', '.ts', '.tsx', '.jsx',
            '.java', '.go', '.rs', '.cpp', '.c', '.h',
            '.vue', '.svelte',
        }
        ignore_dirs = {
            'node_modules', '.git', '__pycache__',
            'dist', 'build', '.next', 'venv',
        }
        
        files = []
        for root, dirs, fnames in os.walk(self.repo_path):
            dirs[:] = [d for d in dirs if d not in ignore_dirs]
            for fname in fnames:
                if os.path.splitext(fname)[1] in code_extensions:
                    files.append(os.path.join(root, fname))
        return files
    
    def _chunk_file(self, file_path: str) -> List[Dict]:
        """按函数/类切分代码文件"""
        ext = os.path.splitext(file_path)[1]
        language = {
            '.py': 'python', '.js': 'javascript', '.ts': 'typescript',
            '.java': 'java', '.go': 'go', '.rs': 'rust',
        }.get(ext, 'unknown')
        
        with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
            lines = f.readlines()
        
        # 按函数/类定义切分
        chunks = []
        current_chunk = []
        chunk_start = 1
        
        for i, line in enumerate(lines, 1):
            current_chunk.append(line)
            # 检测函数/类定义(简化版)
            if self._is_definition(line, language):
                if current_chunk and len(current_chunk) > 5:
                    chunks.append({
                        "content": ''.join(current_chunk),
                        "start_line": chunk_start,
                        "end_line": i,
                        "language": language,
                    })
                    current_chunk = []
                    chunk_start = i + 1
        
        # 剩余部分
        if current_chunk:
            chunks.append({
                "content": ''.join(current_chunk),
                "start_line": chunk_start,
                "end_line": len(lines),
                "language": language,
            })
        
        return chunks
    
    def _is_definition(self, line: str, language: str) -> bool:
        """检测是否是函数/类定义行"""
        stripped = line.strip()
        if language == 'python':
            return stripped.startswith(('def ', 'class '))
        elif language in ('javascript', 'typescript'):
            return any(
                stripped.startswith(kw)
                for kw in ['function ', 'class ', 'const ', 'export ']
            )
        return False

第三章 AST + LLM 混合推理

3.1 为什么需要 AST

直觉理解:AST 是什么?

想象你要分析一句话"小明吃苹果"——

  • 纯文本视角:一串字符 "小明吃苹果",计算机不知道谁在做什么
  • 语法树视角(AST):把它分解为结构化的关系——
    动作:吃
    ├── 主语:小明
    └── 宾语:苹果
    

AST 就是代码版的"句子成分分析"。一段 Python 代码 result = add(1, 2) 的 AST 是:

赋值语句
├── 变量名:result
└── 值:函数调用
     ├── 函数名:add
     └── 参数:[1, 2]

有了 AST,计算机就能精确知道"result 是变量名"、"add 是函数"、"1 和 2 是参数",而不只是看到一串字符。LLM 生成代码时可能有语法错误,但 AST 一定是语法正确的——因为它就是语法规则的体现。

纯 LLM 代码生成的局限:
  1. 无法保证语法正确性(括号不匹配、缩进错误)
  2. 无法精确理解变量作用域
  3. 无法做静态分析(类型检查、未使用变量)
  4. 难以做大规模代码重构

AST(抽象语法树)的优势:
  1. 结构化表示代码,100% 语法正确
  2. 可以精确分析依赖关系
  3. 可以做静态分析和变换
  4. 可以做精确的代码修改(而非全文重写)

混合方案:
  LLM 负责理解意图和生成代码逻辑
  AST 负责验证、解析、精确修改
  → 两者协同:LLM 生成 → AST 验证 → LLM 修正 → AST 应用

3.2 AST + LLM 协同工作流

"""
AST + LLM 混合代码修改流水线
"""
import ast
import astor
from typing import Optional

class ASTLLMModifier:
    """使用 AST + LLM 进行精确代码修改"""
    
    def __init__(self, llm_client):
        self.llm = llm_client
    
    def modify_function(
        self,
        code: str,
        function_name: str,
        modification_request: str,
    ) -> str:
        """精确修改指定函数"""
        
        # 1. 解析为 AST
        try:
            tree = ast.parse(code)
        except SyntaxError as e:
            # 语法错误时用 LLM 修复
            code = self._fix_syntax(code, str(e))
            tree = ast.parse(code)
        
        # 2. 定位目标函数
        target_func = self._find_function(tree, function_name)
        if target_func is None:
            raise ValueError(f"Function '{function_name}' not found")
        
        # 3. 提取函数上下文
        func_source = astor.to_source(target_func)
        func_context = self._get_function_context(tree, target_func)
        
        # 4. LLM 生成修改后的函数
        new_func_code = self._llm_modify_function(
            func_source, func_context, modification_request
        )
        
        # 5. AST 验证修改后的函数
        try:
            new_func_ast = ast.parse(new_func_code)
            new_func_node = self._extract_function_node(
                new_func_ast, function_name
            )
        except SyntaxError as e:
            # 让 LLM 修复语法错误
            new_func_code = self._fix_syntax(new_func_code, str(e))
            new_func_ast = ast.parse(new_func_code)
            new_func_node = self._extract_function_node(
                new_func_ast, function_name
            )
        
        # 6. 替换 AST 中的函数节点
        new_tree = self._replace_function(tree, function_name, new_func_node)
        
        # 7. 生成最终代码
        return astor.to_source(new_tree)
    
    def analyze_code_structure(self, code: str) -> dict:
        """使用 AST 分析代码结构,为 LLM 提供上下文"""
        tree = ast.parse(code)
        
        analysis = {
            "functions": [],
            "classes": [],
            "imports": [],
            "variables": [],
        }
        
        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef):
                analysis["functions"].append({
                    "name": node.name,
                    "args": [a.arg for a in node.args.args],
                    "line": node.lineno,
                    "decorators": [
                        astor.to_source(d).strip()
                        for d in node.decorator_list
                    ],
                })
            elif isinstance(node, ast.ClassDef):
                methods = [
                    n.name for n in node.body
                    if isinstance(n, ast.FunctionDef)
                ]
                analysis["classes"].append({
                    "name": node.name,
                    "methods": methods,
                    "line": node.lineno,
                })
            elif isinstance(node, (ast.Import, ast.ImportFrom)):
                analysis["imports"].append(astor.to_source(node).strip())
        
        return analysis
    
    def _find_function(self, tree: ast.Module, name: str) -> Optional[ast.FunctionDef]:
        """在 AST 中查找指定函数"""
        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef) and node.name == name:
                return node
        return None
    
    def _get_function_context(self, tree: ast.Module, func_node: ast.FunctionDef) -> str:
        """获取函数的依赖上下文(imports, 调用的其他函数等)"""
        # 提取所有 import
        imports = [
            astor.to_source(node).strip()
            for node in ast.walk(tree)
            if isinstance(node, (ast.Import, ast.ImportFrom))
        ]
        
        # 提取函数内调用的其他函数名
        called_functions = set()
        for node in ast.walk(func_node):
            if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
                called_functions.add(node.func.id)
        
        # 查找被调用函数的定义
        func_defs = {}
        for node in ast.walk(tree):
            if isinstance(node, ast.FunctionDef) and node.name in called_functions:
                func_defs[node.name] = astor.to_source(node)
        
        context = "Imports:\n" + '\n'.join(imports)
        if func_defs:
            context += "\n\nCalled functions:\n"
            for name, src in func_defs.items():
                context += f"\n# {name}\n{src}"
        
        return context
    
    def _llm_modify_function(
        self, func_source: str, context: str, request: str
    ) -> str:
        """用 LLM 修改函数"""
        prompt = f"""修改以下 Python 函数。

修改请求:{request}

当前函数:
```python
{func_source}

依赖上下文: {context}

要求:

  1. 只输出修改后的函数,不要输出其他内容

  2. 保持函数名不变

  3. 保持函数签名兼容(除非请求要求改签名)

  4. 确保语法正确"""

     response = self.llm.chat(prompt)
     # 提取代码块
     if '```' in response:
         start = response.index('```python\n') + 10
         end = response.index('```', start)
         return response[start:end]
     return response
    

    def _replace_function( self, tree: ast.Module, name: str, new_node: ast.FunctionDef ) -> ast.Module: """替换 AST 中的函数节点""" for i, node in enumerate(tree.body): if isinstance(node, ast.FunctionDef) and node.name == name: tree.body[i] = new_node return tree # 检查类方法 if isinstance(node, ast.ClassDef): for j, method in enumerate(node.body): if isinstance(method, ast.FunctionDef) and method.name == name: node.body[j] = new_node return tree return tree

    def _extract_function_node( self, tree: ast.Module, name: str ) -> ast.FunctionDef: """从 AST 中提取指定函数节点""" node = self._find_function(tree, name) if node is None: raise ValueError(f"Function '{name}' not found in generated code") return node

    def _fix_syntax(self, code: str, error: str) -> str: """用 LLM 修复语法错误""" prompt = f"""以下 Python 代码有语法错误,请修复。

代码: {code}

错误信息: {error}

只输出修复后的完整代码。""" return self.llm.chat(prompt)


---

## 第四章 代码 Agent 工程化 «kb-section-id:section-e207de7d89689b3eeed0acf0»

### 4.1 代码 Agent 架构设计 «kb-section-id:section-02ec263d9279aa052c10f94d»

┌─────────────────────────────────────────────────────────┐ │ 代码 Agent 系统架构 │ ├─────────────────────────────────────────────────────────┤ │ │ │ ┌─────────────┐ ┌──────────────┐ ┌────────────┐ │ │ │ 意图理解 │──→│ 上下文检索 │──→│ 代码生成 │ │ │ │ (LLM) │ │ (Vector DB) │ │ (LLM) │ │ │ └─────────────┘ └──────────────┘ └──────┬─────┘ │ │ │ │ │ ┌──────────────────────┘ │ │ ▼ │ │ ┌─────────────┐ ┌──────────────┐ ┌────────────┐ │ │ │ 测试验证 │←──│ AST 分析 │←──│ 代码应用 │ │ │ │ (执行) │ │ (Parse) │ │ (Diff) │ │ │ └──────┬──────┘ └──────────────┘ └────────────┘ │ │ │ │ │ ▼ │ │ ┌─────────────┐ │ │ │ 结果反馈 │──→ 失败则回到「代码生成」迭代 │ │ └─────────────┘ │ │ │ └─────────────────────────────────────────────────────────┘


### 4.2 多文件修改管理 «kb-section-id:section-3be91cfd47657a41173ef363»

```python
"""
多文件代码修改管理器
"""
from dataclasses import dataclass, field
from typing import List, Optional
import difflib
import os

@dataclass
class FileChange:
    """单个文件的修改"""
    file_path: str
    original_content: str
    new_content: str
    change_type: str = "modify"  # modify | create | delete
    
    @property
    def diff(self) -> str:
        """生成 unified diff"""
        original_lines = self.original_content.splitlines(keepends=True)
        new_lines = self.new_content.splitlines(keepends=True)
        diff = difflib.unified_diff(
            original_lines, new_lines,
            fromfile=f"a/{self.file_path}",
            tofile=f"b/{self.file_path}",
        )
        return ''.join(diff)

@dataclass 
class ChangeSet:
    """一次修改涉及的所有文件变更"""
    changes: List[FileChange] = field(default_factory=list)
    
    def add_change(self, change: FileChange):
        self.changes.append(change)
    
    def apply(self, base_dir: str = "."):
        """应用所有修改"""
        for change in self.changes:
            full_path = os.path.join(base_dir, change.file_path)
            
            if change.change_type == "delete":
                if os.path.exists(full_path):
                    os.remove(full_path)
            elif change.change_type == "create":
                os.makedirs(os.path.dirname(full_path), exist_ok=True)
                with open(full_path, 'w', encoding='utf-8') as f:
                    f.write(change.new_content)
            else:  # modify
                with open(full_path, 'w', encoding='utf-8') as f:
                    f.write(change.new_content)
    
    def rollback(self, base_dir: str = "."):
        """回滚所有修改"""
        for change in reversed(self.changes):
            full_path = os.path.join(base_dir, change.file_path)
            
            if change.change_type == "create":
                if os.path.exists(full_path):
                    os.remove(full_path)
            else:  # modify or delete → restore original
                if change.original_content is not None:
                    with open(full_path, 'w', encoding='utf-8') as f:
                        f.write(change.original_content)
    
    def summary(self) -> str:
        """生成修改摘要"""
        lines = [f"Changes ({len(self.changes)} files):"]
        for change in self.changes:
            symbol = {"modify": "M", "create": "+", "delete": "-"}[change.change_type]
            lines.append(f"  {symbol} {change.file_path}")
        return '\n'.join(lines)

第五章 代码评测体系

5.1 代码生成评测基准

基准 说明 评测方式
HumanEval 164 个 Python 编程题 函数级,单元测试验证
MBPP 974 个 Python 编程题 入门级,单元测试验证
LiveCodeBench 实时更新(LeetCode/Codeforces) 防数据泄露
SWE-bench 真实 GitHub Issue 修复 仓库级,测试套件验证
CodeXGLUE 多任务(补全/翻译/摘要/缺陷检测) 综合评测

5.2 pass@k 指标

"""
pass@k:代码生成的核心评测指标
含义:生成 k 个候选解,至少 1 个通过测试的概率
"""
import math
from typing import List

def pass_at_k(n: int, c: int, k: int) -> float:
    """
    计算 pass@k
    
    n: 总生成样本数
    c: 通过测试的样本数
    k: 取前 k 个样本
    """
    if n - c < k:
        return 1.0
    # 1 - C(n-c, k) / C(n, k)
    return 1.0 - math.comb(n - c, k) / math.comb(n, k)

# 示例:
# 生成 10 个解,其中 3 个通过
# pass@1 = 3/10 = 0.3
# pass@5 = 1 - C(7,5)/C(10,5) = 1 - 21/252 ≈ 0.917
# pass@10 = 1.0(全部取)

# 实践含义:
# pass@1 高 → 单次生成质量好(适合 Copilot 行内补全)
# pass@10 高 → 多次生成有解(适合 Agent 模式,可以多试几次)

5.3 代码质量多维评估

"""
代码质量多维度评估框架
"""
from dataclasses import dataclass
from typing import Optional

@dataclass
class CodeEvaluation:
    """代码评估结果"""
    correctness: float      # 正确性(是否通过测试)
    efficiency: float       # 效率(时间/空间复杂度)
    readability: float      # 可读性(命名、注释、结构)
    security: float         # 安全性(有无漏洞)
    style: float            # 风格(是否符合 lint 规范)
    
    @property
    def overall(self) -> float:
        weights = {
            "correctness": 0.4,
            "efficiency": 0.15,
            "readability": 0.2,
            "security": 0.15,
            "style": 0.1,
        }
        return sum(getattr(self, k) * v for k, v in weights.items())

class CodeEvaluator:
    """代码质量评估器"""
    
    def evaluate(self, code: str, test_cases: list, language: str = "python") -> CodeEvaluation:
        return CodeEvaluation(
            correctness=self._eval_correctness(code, test_cases, language),
            efficiency=self._eval_efficiency(code),
            readability=self._eval_readability(code),
            security=self._eval_security(code),
            style=self._eval_style(code, language),
        )
    
    def _eval_correctness(self, code: str, test_cases: list, lang: str) -> float:
        """通过测试用例评估正确性"""
        passed = 0
        for tc in test_cases:
            try:
                # 执行代码并检查输出
                result = self._run_code(code, tc["input"], lang)
                if result == tc["expected"]:
                    passed += 1
            except Exception:
                pass
        return passed / len(test_cases) if test_cases else 0.0
    
    def _eval_efficiency(self, code: str) -> float:
        """评估时间/空间复杂度"""
        # 鮸鱼分析:循环嵌套深度、数据结构选择等
        # 也可通过实际运行时间 benchmark
        # 简化版:检查嵌套循环深度
        import ast
        try:
            tree = ast.parse(code)
        except:
            return 0.5
        
        max_depth = 0
        def count_loop_depth(node, current_depth=0):
            nonlocal max_depth
            for child in ast.iter_child_nodes(node):
                if isinstance(child, (ast.For, ast.While)):
                    max_depth = max(max_depth, current_depth + 1)
                    count_loop_depth(child, current_depth + 1)
                else:
                    count_loop_depth(child, current_depth)
        
        count_loop_depth(tree)
        
        # 深度越大效率越低
        if max_depth <= 1: return 1.0
        elif max_depth == 2: return 0.8
        elif max_depth == 3: return 0.5
        else: return 0.3
    
    def _eval_readability(self, code: str) -> float:
        """评估可读性(LLM-as-Judge)"""
        # 简化版:基于启发式规则
        score = 1.0
        lines = code.split('\n')
        
        # 检查注释比例
        comment_lines = sum(1 for l in lines if l.strip().startswith('#'))
        comment_ratio = comment_lines / len(lines) if lines else 0
        if comment_ratio < 0.05:
            score -= 0.2  # 注释太少
        
        # 检查函数长度
        if len(lines) > 50:
            score -= 0.2  # 函数太长
        
        # 检查命名
        import re
        single_char_vars = len(re.findall(r'\b[a-z]\b', code))
        if single_char_vars > 10:
            score -= 0.1  # 单字符变量太多
        
        return max(score, 0.0)
    
    def _eval_security(self, code: str) -> float:
        """评估安全性"""
        dangerous_patterns = [
            ("eval(", 0.3),
            ("exec(", 0.3),
            ("os.system(", 0.2),
            ("subprocess.call(", 0.1),
            ("__import__", 0.2),
            ("pickle.loads", 0.2),
        ]
        
        score = 1.0
        for pattern, penalty in dangerous_patterns:
            if pattern in code:
                score -= penalty
        
        return max(score, 0.0)
    
    def _eval_style(self, code: str, language: str) -> float:
        """评估代码风格"""
        if language == "python":
            # 用 pycodestyle 检查 PEP8 合规
            import subprocess
            result = subprocess.run(
                ["pycodestyle", "--count", "-"],
                input=code, capture_output=True, text=True
            )
            try:
                violations = int(result.stdout.strip().split('\n')[-1])
                return max(1.0 - violations * 0.05, 0.0)
            except:
                return 0.8
        return 0.8

本章总结

知识点 重要度 实践频率
FIM(Fill-in-the-Middle)原理 核心 中频
代码模型训练流程 重要 中频
Copilot / Cursor 架构 重要 高频
代码索引与语义检索 核心 高频
AST + LLM 混合推理 核心 中频
代码 Agent 工作流 核心 高频
多文件修改管理(Diff/Changeset) 实践 中频
pass@k 评测指标 重要 高频
代码质量多维评估 实践 中频
SWE-bench 等评测基准 了解 低频
目录与内容权限

无规则时继承上级;配置规则后,本级只允许匹配的所有人、用户或用户组。用户和组可按名称搜索选择;章节仅控制查看权限。