模式 1:托管智能体运行时
最高级别的路径。你将用户消息交给 Sonzai,Sonzai 返回流式回复,记忆、情绪、人格和工具执行全在我们这一侧完成。
你将应用指向 client.agents.chat(或用 sessions.start → 聊天回合 → sessions.end
显式打开会话)。Sonzai 从智能体身份组装系统提示词,召回相关记忆,运行 LLM,
流式返回 token,执行已注册的工具,并更新状态 — 全部在一次调用中完成。
这是代码量最少的模式。 适用于陪伴、客服智能体,以及任何可以让 Sonzai
拥有完整智能体循环的场景,是默认推荐的路径。
何时使用
- 你希望每回合一次 HTTP 调用,零记忆管线代码。
- 你接受 Sonzai 选择(或通过覆盖参数指定)LLM 提供商。
- 你希望人格、情绪、记忆、语音、知识库搜索、主动通知等"开箱即用", 不必自己编排。
何时切换
- 必须使用自己的 LLM — 切换到 模式 4:独立实时。
- 对话已在平台外发生(录音、转录、批量摄入)— 切换到 模式 5:独立批处理。
- 运行在 Claude Desktop / Cursor / 兼容 MCP 的 IDE 中 — 切换到 模式 2:MCP。
- 已使用 OpenClaw — 切换到 模式 3:OpenClaw。
架构
┌─────────────┐ ┌───────────────────────────────────┐
│ Your App │ │ Sonzai │
└──────┬──────┘ └──────────────────┬────────────────┘
│ │
│ agents.chat({ messages }) │
│───────────────────────────────>│ • assemble context
│ │ (memory, mood,
│ │ personality, KB,
│ │ relationship)
│ │ • run LLM (your choice
│ │ of provider/model)
│ │ • execute registered
│ │ tools (if any)
│ <── SSE stream ───────────────│ • write back: facts,
│ tokens + done │ mood, personality,
│ │ goals, habits
│ │
│ (optional) sessions.end │
│───────────────────────────────>│ • consolidate, dedup,
│ │ diary, clustering
端到端示例
最简完整流程:显式打开会话、驱动流式聊天、结束会话。
import { Sonzai } from "@sonzai-labs/agents";
const sonzai = new Sonzai({ apiKey: process.env.SONZAI_API_KEY! });
const AGENT_ID = "agent-uuid";
const USER_ID = "user-123";
const SESSION_ID = crypto.randomUUID();
// 1. Start an explicit session (optional — agents.chat will auto-create one
// if you don't, but explicit sessions let you scope tools and lifecycle).
await sonzai.agents.sessions.start(AGENT_ID, {
userId: USER_ID,
sessionId: SESSION_ID,
});
// 2. Drive turns. Sonzai owns context assembly, the LLM call, tool exec,
// and writeback. You stream the reply straight to your UI.
for await (const event of sonzai.agents.chatStream({
agent: AGENT_ID,
sessionId: SESSION_ID,
userId: USER_ID,
messages: [{ role: "user", content: "Hi! How's your day going?" }],
language: "en",
})) {
process.stdout.write(event.choices?.[0]?.delta?.content ?? "");
}
// 3. End the session — triggers fact extraction + consolidation.
await sonzai.agents.sessions.end(AGENT_ID, {
userId: USER_ID,
sessionId: SESSION_ID,
totalMessages: 2,
});跳过显式会话
如果不调用 sessions.start,Sonzai 会在第一次 agents.chat 时自动开启会话,
并在空闲时关闭。会话 ID 仍会附加到提取的事实上。需要会话级工具、明确的边界
或回放语义时再使用显式生命周期即可。