AI 伴侣 — 快速入门
构建一个具有大五人格、四维情绪、关系追踪和主动外联能力的角色驱动智能体。本指南端到端地讲解完整的伴侣技术栈。
本快速入门适用于构建 AI 伴侣 — 拥有真实人格、丰富内心世界,并与用户建立随时间演变关系的角色。典型场景:AI 角色、VTuber、个人伴侣、故事 NPC。
**你将构建的内容:**Luna,一个温暖而好奇的伴侣,能记住你的对话、发展真实的关系,并在适当时机主动联系你。
**你将用到的能力:**大五人格、四维情绪、层级记忆、关系追踪、主动唤醒,以及(可选)语音。
1. 获取 API 密钥
前往 platform.sonz.ai,创建项目并生成 API 密钥。
Authorization: Bearer sk_your_api_key2. 从描述生成智能体
最快捷的方式:用自然语言描述角色,让平台自动推导人格、说话方式和种子记忆。
import { Sonzai } from "@sonzai-labs/agents";
const client = new Sonzai({ apiKey: process.env.SONZAI_API_KEY! });
const agent = await client.agents.generation.generateAndCreate({
name: "Luna",
description: "Luna is a warm, creative dreamer who speaks poetically. She loves stargazing, coffee shops at 2am, and asking the question beneath the question.",
language: "en",
});
console.log(agent.agent_id);
console.log(agent.personality); // full Big5 profile derived from the description你也可以显式定义角色 — 手动设置大五得分、说话方式和详细简介。参见智能体生成。
3. 为关系预热
在用户首次对话前告知智能体这位用户是谁。预热会创建初始记忆树 — 智能体会自然地引用这些信息。
await client.agents.priming.primeUser("agent-id", "user-123", {
displayName: "Sam",
interests: ["astronomy", "lo-fi music", "photography"],
context: "Sam is a night-owl grad student who tends to overthink. They came to Luna after a tough week.",
});4. 对话 — 伴侣的标准是流式输出
伴侣应该让人感觉鲜活。务必使用流式输出。
for await (const event of client.agents.chatStream({
agent: "agent-id",
userId: "user-123",
messages: [{ role: "user", content: "I can't sleep again." }],
})) {
const delta = event.choices?.[0]?.delta?.content;
if (delta) process.stdout.write(delta);
}每轮对话结束后,Sonzai 会自动:
- 将新的事实、事件和承诺提取到记忆中。
- 根据对话的情感内容更新情绪(快乐度、能量值、平静度、亲密度)。
- 如果交互揭示了角色方向上的稳定特征,则微调大五特质。
- 更新关系状态(亲密度得分、化学反应、连续互动天数)。
这些都无需你手动管理。
5. 读取情绪和关系状态
若要驱动 UI — 一个小情绪指示器、按关系等级设置的解锁门控,或根据化学反应变化的主题 — 请获取当前状态。
// 当前情绪(四维)——与人格档案分开读取
const mood = await client.agents.getMood("agent-id", { userId: "user-123" });
console.log(mood.happiness, mood.energy, mood.calmness, mood.affection);
// 当前人格档案(大五、维度、说话方式)
const personality = await client.agents.personality.get("agent-id");
console.log(personality.profile.big5);6. 让 Luna 主动联系
主动唤醒是伴侣区别于普通聊天机器人的关键。平台会根据关系上下文自动安排唤醒 — 你也可以显式触发。
// Poll periodically (or register a webhook).
const pending = await client.agents.notifications.list("agent-id", {
userId: "user-123",
status: "pending",
});
for (const n of pending.notifications) {
// Render n.content in your UI; mark consumed when shown.
await client.agents.notifications.consume("agent-id", n.notificationId);
}7. 为 Luna 添加语音(可选)
从全局语音目录中选择一个语音或克隆一个,然后流式播放 TTS 或双工音频。完整接口参见语音。
const voices = await client.voices.list({ language: "en" });
await client.agents.update("agent-id", { voiceId: voices[0].voiceId });下一步
人格
大五模型、特质、进化、说话方式。
情绪与心情
四维情绪模型、衰减、事件驱动变化。
记忆
层级记忆树:事实、事件、承诺、摘要。
对话
流式输出、会话、多轮流程。
语音
TTS、STT、双工流式传输、语音克隆。
主动唤醒
定时外联如何触发和送达。
当前 SDK 版本:TypeScript 1.1.3 · Python 1.1.4 · Go 1.2.0(截至 2026-04-17)