目标:从零建项目骨架,写出一个可交互的 CLI Agent——能扫 docs/ 目录、读文件、回答问题。 这是后面所有章节的地基:llm 客户端、工具层、Agent Loop 的接口形状在这里定型,10b 起只在其上扩展。
前置:03、04 篇已学。预计 2~3 小时。建议手敲代码,复制只留给 tsconfig 这类配置。
1. 项目初始化
mkdir kb-agent && cd kb-agent
mkdir server && cd server
npm init -y
npm i -D typescript tsx @types/node
package.json 手工补充三处(type: "module" 用 ESM,脚本省得敲长命令):
{
"type": "module",
"scripts": {
"cli": "tsx --env-file=../../.env src/cli.ts"
}
}
.env放在仓库根kb-agent/.env(从总览章的环境凭据复制)。--env-file路径是相对 cwd 的,从server/目录执行所以带../../。
tsconfig.json(极简,tsx 不做类型检查但编辑器需要):
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}
建目录:
mkdir -p src/tools docs
docs/ 放 3~5 篇 markdown 作为语料(公司 wiki 导出、README 均可)。
2. 类型定义
src/types.ts——先定类型再写实现,后面所有文件都引用它:
// 消息模型与 OpenAI 兼容协议对齐
export type Msg =
| { role: "system"; content: string }
| { role: "user"; content: string }
| { role: "assistant"; content: string; tool_calls?: ToolCall[] }
| { role: "tool"; tool_call_id: string; content: string };
export interface ToolCall {
id: string;
type: "function";
function: { name: string; arguments: string }; // arguments 是 JSON 字符串
}
export interface ToolDef {
type: "function";
function: {
name: string;
description: string;
parameters: Record<string, unknown>; // JSON Schema
};
}
// 模型返回的 LLM 响应(带 usage 供 10e 评测用)
export interface LLMResult {
message: { role: "assistant"; content: string | null; tool_calls?: ToolCall[] };
finish_reason: "stop" | "tool_calls" | "length" | string;
usage?: { prompt_tokens: number; completion_tokens: number };
}
// 工具轨迹:M5 评测要断言"它调了什么"
export interface ToolTraceItem {
name: string;
args: Record<string, unknown>;
ok: boolean;
}
3. LLM 客户端
src/llm.ts——裸 fetch 封装,全项目唯一的模型出入口(10b 会在这里加流式版本):
import type { LLMResult, Msg, ToolDef } from "./types.js";
const BASE_URL = process.env.LLM_BASE_URL!;
const API_KEY = process.env.LLM_API_KEY!;
const MODEL = process.env.LLM_MODEL!;
// Node 22 原生支持顶层 await 之前的环境变量校验放函数里
function assertEnv() {
for (const [k, v] of Object.entries({ BASE_URL, API_KEY, MODEL })) {
if (!v) throw new Error(`缺少环境变量,检查 kb-agent/.env:${k}`);
}
}
export async function chat(messages: Msg[], tools?: ToolDef[]): Promise<LLMResult> {
assertEnv();
const res = await fetch(`${BASE_URL}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
body: JSON.stringify({
model: MODEL,
messages,
tools,
temperature: 0.2,
}),
});
if (!res.ok) {
// 把网关的错误信息带出来——401/404 时你能立刻分辨是 key 还是模型名的问题
throw new Error(`LLM 网关返回 ${res.status}: ${(await res.text()).slice(0, 500)}`);
}
const data = await res.json();
return data.choices[0];
}
注意两处细节,都是 03 篇踩过的坑固化成代码:
- 工具定义是可选参数——M4 之前没有 RAG 工具时也能跑;
- 非 200 直接抛出但截断错误体(500 行足够定位,没必要全量打印)。
验证:src/smoke.ts 单发一条消息确认连通:
import { chat } from "./llm.js";
const r = await chat([{ role: "user", content: "回复两个字:连通" }]);
console.log(r.message.content);
npx tsx --env-file=../../.env src/smoke.ts
4. 工具层
src/tools/index.ts——声明与实现分离,实现用统一签名方便 loop 统一分发(04 篇原则的落地):
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import type { ToolDef } from "../types.js";
// ============ 声明(给模型看) ============
export const toolDefs: ToolDef[] = [
{
type: "function",
function: {
name: "list_docs",
description:
"列出 docs 目录下所有文档文件名。回答知识内容问题前,先调用它了解有哪些文档。",
parameters: { type: "object", properties: {}, required: [] },
},
},
{
type: "function",
function: {
name: "read_file",
description:
"读取 docs 目录下指定文件的全文。返回文件内容;文件过长会被截断并提示可继续读取的位置。",
parameters: {
type: "object",
properties: {
name: { type: "string", description: "docs 目录下的文件名,如 报销制度.md" },
offset: { type: "number", description: "截断续读的起始字符位置,首次调用不传" },
},
required: ["name"],
},
},
},
];
// ============ 实现(你的代码执行) ============
const DOCS_DIR = path.resolve(process.cwd(), "../../docs");
// 统一签名:所有工具实现都是 (args: any) => Promise<string>
// 返回值一律是字符串——直接成为 role:"tool" 消息的 content
export type ToolImpl = (args: any) => Promise<string>;
export const toolImpls: Record<string, ToolImpl> = {
async list_docs() {
const entries = await readdir(DOCS_DIR);
const files = entries.filter((f) => f.endsWith(".md"));
return files.length ? files.join("\n") : "(docs 目录为空)";
},
async read_file({ name, offset = 0 }: { name: string; offset?: number }) {
// 路径安全:拼进 DOCS_DIR 后校验仍然落在 docs 内,防模型构造 ../ 逃逸
const full = path.resolve(DOCS_DIR, name);
if (!full.startsWith(DOCS_DIR)) return "ERROR: 只允许读取 docs 目录内的文件";
const content = await readFile(full, "utf-8");
const MAX = 4000;
if (content.length > MAX) {
return (
content.slice(offset, offset + MAX) +
`\n...[已截断,全文 ${content.length} 字符。可用 offset=${offset + MAX} 继续读取,或判断已够用则停止]`
);
}
return content;
},
};
路径校验那两行不是多余的偏执——模型的参数来自概率采样,name: "../server/src/llm.ts" 是真实会发生的事。
验证:不动模型,直接测工具实现:
npx tsx -e "import('./src/tools/index.js').then(async m => console.log(await m.toolImpls.list_docs({})))"
能看到 docs 下的文件名列表即为正确。
5. Agent Loop
src/agent.ts——03 篇 loop 的整理版,新增两点:轨迹记录(M5 用)、工具执行回调(10b 换成发 SSE 事件):
import { chat } from "./llm.js";
import { toolDefs, toolImpls } from "./tools/index.js";
import type { Msg, ToolTraceItem } from "./types.js";
const MAX_ROUNDS = 10;
export const SYSTEM_PROMPT =
"你是知识库问答助手,docs 目录中有公司文档。" +
"回答前先调用 list_docs 了解文档,再用 read_file 阅读相关内容,基于真实内容回答。" +
"docs 中没有的信息要明确说「文档中没有相关内容」,不要编造。";
export interface AgentRunResult {
reply: string;
trace: ToolTraceItem[];
usage: { promptTokens: number; completionTokens: number };
}
export interface AgentHandlers {
// 10b 会传入 onToolEvent 往 SSE 推事件;CLI 版不传即可
onToolEvent?: (e: { name: string; args?: Record<string, unknown>; status: "start" | "done"; summary?: string }) => void;
}
export async function runAgent(messages: Msg[], handlers: AgentHandlers = {}): Promise<AgentRunResult> {
const trace: ToolTraceItem[] = [];
const usage = { promptTokens: 0, completionTokens: 0 };
// 循环直接在传入的 messages 上追加——调用方持有会话历史,本函数只管推进
for (let round = 0; round < MAX_ROUNDS; round++) {
const result = await chat(messages, toolDefs);
usage.promptTokens += result.usage?.prompt_tokens ?? 0;
usage.completionTokens += result.usage?.completion_tokens ?? 0;
messages.push(result.message as Msg);
if (result.finish_reason !== "tool_calls") {
return { reply: result.message.content ?? "", trace, usage };
}
for (const call of result.message.tool_calls ?? []) {
const name = call.function.name;
let args: Record<string, unknown> = {};
try {
args = JSON.parse(call.function.arguments || "{}");
} catch {
messages.push({
role: "tool",
tool_call_id: call.id,
content: "ERROR: 参数不是合法 JSON,请检查参数格式后重试",
});
continue;
}
handlers.onToolEvent?.({ name, args, status: "start" });
let content: string;
let ok = true;
const impl = toolImpls[name];
if (!impl) {
// 工具名不存在也要回填——模型才知道这条路不通
content = `ERROR: 工具 ${name} 不存在,可用工具:${Object.keys(toolImpls).join(", ")}`;
ok = false;
} else {
try {
content = await impl(args);
} catch (err: any) {
content = `ERROR: ${err.message}`;
ok = false;
}
}
trace.push({ name, args, ok });
handlers.onToolEvent?.({ name, status: "done", summary: content.slice(0, 80) });
messages.push({ role: "tool", tool_call_id: call.id, content });
}
}
return { reply: "(达到最大轮数,强制停止)", trace, usage };
}
逐块确认你理解了再往下走:
messages由调用方传入并在其上追加——这是刻意的设计,10b 的 HTTP 会话直接把session.messages传进来,Agent 不需要知道"会话"是什么;- 参数 JSON 解析失败也走
role:"tool"回填——所有失败都是信息; onToolEvent现在没有消费者,10b 的 SSE 版本会把它接到响应流上。
6. CLI 入口
src/cli.ts——readline REPL,把会话历史接进 loop:
import { createInterface } from "node:readline";
import { runAgent, SYSTEM_PROMPT } from "./agent.js";
import type { Msg } from "./types.js";
const rl = createInterface({ input: process.stdin });
const session: Msg[] = [{ role: "system", content: SYSTEM_PROMPT }];
process.stdout.write("❓ ");
for await (const line of rl) {
const question = line.trim();
if (!question) { process.stdout.write("❓ "); continue; }
if (question === "/exit") break;
session.push({ role: "user", content: question });
// CLI 里用 stderr 打轨迹,stdout 留给回答
const t0 = Date.now();
const { reply, trace, usage } = await runAgent(session, {
onToolEvent: (e) => {
if (e.status === "start") console.error(` ⚙ ${e.name}(${JSON.stringify(e.args)})`);
},
});
console.log(reply);
console.error(` ─ ${trace.length} 次工具调用 · ${(Date.now() - t0) / 1000}s · in:${usage.promptTokens} out:${usage.completionTokens}`);
process.stdout.write("❓ ");
}
7. 运行验证
npm run cli
依次测三类问题(这三类就是 10e 评测集的原型):
- 命中语料:
报销流程是什么?——回答应引用 docs 中真实内容 - 多文档综合:
docs 里都有哪些主题?分别讲什么?——应先 list_docs 再逐个 read - 拒答:
公司团建去哪了?——应明确说文档中没有,而不是编造
M1 验收清单
- smoke 跑通,网关连通
- 三类问题行为符合预期(命中引用真实内容 / 多步工具链 / 拒答不编造)
- stderr 能看到工具调用轨迹与 token 统计
- 能解释:为什么
messages由调用方持有(提示:10b 会话化后 Agent 代码不变) - 能解释:
read_file的路径校验防的是什么
下一章:10b · 服务化 + SSE 流式——把 CLI 变成 HTTP 服务,Agent Loop 升级为真流式,重点攻克含 tool_calls 的流式增量解析。