1.3 从入门卷交付到实战仓库
本节先建立可离线执行的最小工程,再在第 2 章扩展配置与供应商,在第 3 章增加 HTTP。# file: / // file: 注释给出完整文件的写入位置,默认覆盖,不把示意目录当作已经存在的文件。
导入卷一的引擎
下载卷一目录中的 minagent-book.zip,解压后把其中 minagent/ 原样放入新的 researchcopilot/ 工作区。不要把 demo_*.py 当作服务入口。核心循环来自 minagent.loop.run,受控失败抛出 AgentLoopError,部分记录在异常的 result 中;不能把所有结束情况都记为成功。
本章只需要 Python 3.14 与 Node 26,不需要数据库、第三方 Python 包或包管理器。下面几个文件都相对 researchcopilot/ 根目录;第 2.1 节会覆盖基础 config.py,保留 load() 入口。
# file: researchcopilot/__init__.py | write
__version__ = "0.1.0"
# file: researchcopilot/config.py | write
from dataclasses import dataclass
@dataclass(frozen=True)
class Settings:
database_url: str = "postgresql://postgres:postgres@localhost:15435/research"
redis_url: str = "redis://localhost:16380/0"
max_steps: int = 8
use_fake_model: bool = True
def load() -> Settings:
return Settings()
# file: researchcopilot/engine.py | write
from minagent import Message, ModelResponse, ToolRegistry, run
class DemoModel:
# 演示响应直接标记;不能冒充真实检索或供应商结果。
def complete(self, messages, tools):
question = next(m.content for m in reversed(messages) if m.role == "user")
return ModelResponse(Message("assistant", "演示回答:" + question), "end_turn", {})
def answer(question: str):
# 每次请求构造独立模型和工具表,不能共享有游标的 ScriptedModel。
return run(DemoModel(), ToolRegistry(), question, max_steps=8)
# file: tests/test_smoke.py | write
import unittest
from researchcopilot import __version__
from researchcopilot.config import load
from researchcopilot.engine import answer
class SmokeTests(unittest.TestCase):
def test_version_and_config(self):
self.assertEqual(__version__, "0.1.0")
self.assertEqual(load().max_steps, 8)
def test_shared_engine(self):
result = answer("桥接测试")
self.assertEqual(result.final, "演示回答:桥接测试")
self.assertEqual(result.messages[-1].role, "assistant")
self.assertEqual(len(result.steps), 1)
if __name__ == "__main__": unittest.main()
运行:
python3 -m unittest discover -s tests -v
两个用例验证版本/基础配置和卷一真实循环的接入,未连接 Postgres 或 Redis。模型输出显式带「演示回答」,不宣称已经完成研究用例。
前端事件载荷与运行时校验
下面文件放在 web/。这是已分帧的 JSON 载荷解析器,字节分帧器参考卷一 17.3;类型断言不等于运行时校验。
// file: web/events.ts | write
export type AgentEvent =
| { type: "token"; text: string }
| { type: "tool_call"; name: string }
| { type: "final"; content: string };
export function parseSseFrame(frame: string): AgentEvent | null {
// 仅接收上游已经分帧的字符串;字节解码和分帧不能靠此函数处理。
const data = frame.split(/\r\n|\r|\n/).filter(l => l.startsWith("data:"))
.map(l => l.slice(5).replace(/^ /, "")).join("\n");
if (!data) return null;
const value: unknown = JSON.parse(data);
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error("invalid event");
const ev = value as Record<string, unknown>;
if (ev.type === "token" && typeof ev.text === "string") return { type: "token", text: ev.text };
if (ev.type === "tool_call" && typeof ev.name === "string") return { type: "tool_call", name: ev.name };
if (ev.type === "final" && typeof ev.content === "string") return { type: "final", content: ev.content };
throw new Error("unsupported event");
}
// file: web/events.test.ts | write
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseSseFrame } from "./events.ts";
test("Chinese and CRLF", () => assert.deepEqual(parseSseFrame('event: token\r\ndata: {"type":"token","text":"你好"}'), {type:"token",text:"你好"}));
test("empty heartbeat", () => assert.equal(parseSseFrame(": ping\n"), null));
test("reject malformed payload", () => {
for (const payload of ['null','[]','{"type":"token","text":3}','{"type":"error"}']) {
assert.throws(() => parseSseFrame("data: " + payload));
}
});
node --test web/events.test.ts
Node 直接运行可擦除 TypeScript 语法;这次检查不替代 tsc。引擎完整事件还包括 step、tool_result、error,本节三种载荷只为冒烟,不能作为完整前端协议。3.2 节补全生命周期和失败事件。
打包与 CI 的前提
最小阶段用当前目录 import,不承诺 pip install -e . 已经通过。需要发布 wheel 时再添加构建后端和显式包发现,把 minagent 与 researchcopilot 都纳入产物,并独立解压测试。不要给未声明的 [dev] extra 写安装命令;使用 npm ci 前必须先提交锁文件和真实依赖清单。
CI 应先复用上面两条实际运行命令,类型检查和 lint 在安装对应工具、配置规则后单独记录。工作流结构示意不等于远程 Actions 执行通过,章节标题里的 CI 是目标,当前交付为本地基础验证。
练习验收
- 修改 DemoModel 的输出,桥接测试必须随真实接口行为变化;不能替换
minagent.run为测试桩。 - 传入
null、数值text和未知事件类型,客户端应拒绝。 - 每请求使用独立模型;不要根据「无全局变量」推断注入对象可以安全共享。
阅读导航:上一节:1.2 架构总览:引擎 / 服务 / worker / 存储边界 · 下一节:2.1 分层配置:pydantic-settings 加载与校验 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。