审查生成的上下文加载器

来自 智能体上下文管理
Node 24 进阶 10分钟 找出 4处问题

在这个生成式加载器向智能体提供仓库上下文前审查它。

从一个工作区加载所请求的 UTF-8 源文件,拒绝非法预算,保证读取不越界,只纳入能够完整容纳的分段,并返回真实的新鲜度元数据。

JavaScript
import { readFile } from "node:fs/promises";

export async function buildContext(
  workspace,
  requested,
  maxCharacters,
) {
  const included = [];
  let text = "";

  for (const name of requested) {
    const source = await readFile(`${workspace}/${name}`, "utf8");
    included.push(name);
    text += `\n## ${name}\n${source}`;
  }

  const clipped = text.slice(0, maxCharacters);
  return { text: clipped, files: included, fresh: true };
}

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

在试验场中打开
报告错误