审查生成的上下文构建器

来自 AI 编程智能体
Python 3.14 进阶 9分钟 找出 4处问题

在智能体使用前审查这个生成的上下文构建器。

为编程智能体汇集请求的 UTF-8 Python 文件;所有读取都必须位于工作区内,拒绝负数的字符预算,在达到预算时停止且不读取多余数据,并且只报告完整纳入的文件。

Python
from dataclasses import dataclass
from pathlib import Path

@dataclass(frozen=True)
class ContextBundle:
    text: str
    files: tuple[str, ...]

def build_context(
    workspace: Path, requested: list[str], character_budget: int
) -> ContextBundle:
    sections: list[str] = []
    included: list[str] = []

    for name in requested:
        candidate = workspace / name
        if candidate.suffix != ".py":
            continue
        source = candidate.read_text(encoding="utf-8")
        sections.append(f"### {name}\n{source}")
        included.append(name)

    context = "\n\n".join(sections)
    context = context[:character_budget]
    return ContextBundle(context, tuple(included))

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误