集成指南
将您的应用连接到心智层。包含 REST API 和官方 SDK 的端到端指南及示例。
概述
您的后端管理业务逻辑和用户会话。调用心智层获取智能体的智能 — 它拥有记忆、人格、情绪、关系和上下文组装。
通过 REST API 使用 Go、TypeScript 和 Python 的官方 SDK 进行集成。
官方 SDK
Go、TypeScript 和 Python 的官方 SDK。每个 SDK 封装了完整的 REST API,提供类型化方法、SSE 流式传输、自动重试和错误处理。
REST API
基于 JSON 的接口。聊天响应通过 Server-Sent Events (SSE) 流式传输。
认证
所有 REST 请求使用项目 API 密钥进行 Bearer 认证:
# 所有 REST 请求使用项目 API 密钥进行 Bearer 认证
curl -H "Authorization: Bearer sk_your_api_key" \
https://api.sonz.ai/api/v1/agents/{agentId}/chat核心交互流程 (REST)
# 聊天 (SSE 流式响应)
POST /api/v1/agents/{agentId}/chat
{ "messages": [{"role":"user","content":"Hello!"}], "user_id": "user-123" }
# 响应: Server-Sent Events
# data: {"choices":[{"delta":{"content":"Hi"}}]}
# data: [DONE]SSE 解析
每行以 data: 开头。去除前缀后对剩余部分执行 JSON.parse。流以 data: [DONE] 结束。
可用 REST 接口
POST /api/v1/agents 创建智能体
GET /api/v1/agents 列出智能体
GET /api/v1/agents/{agentId} 获取智能体
POST /api/v1/agents/{agentId}/chat 聊天 (SSE 流式)
GET /api/v1/agents/{agentId}/notifications 待处理通知
POST /api/v1/agents/{agentId}/notifications/{id}/consume 消费通知
GET /api/v1/agents/{agentId}/notifications/history 通知历史TypeScript SDK(服务端)
适用于 Node.js 后端、Serverless 函数和服务端框架。支持 Node.js >= 18、Bun 和 Deno。 不可用于浏览器/客户端— API 密钥会被暴露。
import { Sonzai } from "@sonzai-labs/agents";
const client = new Sonzai({ apiKey: "sk_your_api_key" });
// 聊天(非流式)
const response = await client.agents.chat("agent-id", {
messages: [{ role: "user", content: "Hello!" }],
userId: "user-123",
});
console.log(response.content);
// 聊天(流式)
for await (const event of client.agents.chatStream("agent-id", {
messages: [{ role: "user", content: "Tell me a story" }],
userId: "user-123",
language: "en",
timezone: "America/New_York",
})) {
process.stdout.write(event.choices?.[0]?.delta?.content ?? "");
}
// 记忆、人格、上下文引擎数据
const memory = await client.agents.memory.list("agent-id", { userId: "user-123" });
const personality = await client.agents.personality.get("agent-id");
const mood = await client.agents.getMood("agent-id", { userId: "user-123" });Python SDK
适用于 Python 后端、数据管道和评估脚本。支持同步和异步客户端。
from sonzai import Sonzai
client = Sonzai(api_key="sk_your_api_key")
# 聊天(非流式)
response = client.agents.chat(
"agent-id",
messages=[{"role": "user", "content": "Hello!"}],
user_id="user-123",
)
print(response.content)
# 聊天(流式)
for event in client.agents.chat(
"agent-id",
messages=[{"role": "user", "content": "Tell me a story"}],
user_id="user-123",
language="en",
timezone="America/New_York",
stream=True,
):
print(event.content, end="", flush=True)
# 记忆、人格、上下文引擎数据
memory = client.agents.memory.list("agent-id", user_id="user-123")
personality = client.agents.personality.get("agent-id")
mood = client.agents.get_mood("agent-id", user_id="user-123")
client.close()浏览器 / 前端应用
需要服务端代理
Sonzai API 不接受浏览器(客户端)请求。API 密钥绝不能暴露在前端代码中。这与 OpenAI、Anthropic 及其他 AI API 提供商使用的模式相同。
对于 Web 应用(React、Next.js、Vue 等),创建一个后端 API 路由代理到 Sonzai。您的前端调用您的服务器;您的服务器使用 API 密钥调用 Sonzai。
Next.js API 路由
// app/api/chat/route.ts(在您的服务器上运行)
import { Sonzai } from "@sonzai-labs/agents";
const client = new Sonzai({ apiKey: process.env.SONZAI_API_KEY! });
export async function POST(req: Request) {
const { agentId, messages, userId } = await req.json();
const stream = client.agents.chatStream(agentId, { messages, userId });
return new Response(
new ReadableStream({
async start(controller) {
for await (const event of stream) {
controller.enqueue(new TextEncoder().encode(
`data: ${JSON.stringify(event)}\n\n`
));
}
controller.enqueue(new TextEncoder().encode("data: [DONE]\n\n"));
controller.close();
},
}),
{ headers: { "Content-Type": "text/event-stream" } }
);
}前端(任意框架)
// 调用您的服务器,而非直接调用 Sonzai
const res = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
agentId: "agent-uuid",
messages: [{ role: "user", content: "Hello!" }],
userId: "user-123",
}),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
// 解析来自代理的 SSE 数据块
console.log(decoder.decode(value));
}Express / Fastify
// server.ts
import express from "express";
import { Sonzai } from "@sonzai-labs/agents";
const app = express();
const client = new Sonzai({ apiKey: process.env.SONZAI_API_KEY! });
app.post("/api/chat", async (req, res) => {
const { agentId, messages, userId } = req.body;
res.setHeader("Content-Type", "text/event-stream");
for await (const event of client.agents.chatStream(agentId, { messages, userId })) {
res.write(`data: ${JSON.stringify(event)}\n\n`);
}
res.write("data: [DONE]\n\n");
res.end();
});Go SDK
适用于后端和对性能敏感的应用,Go SDK 提供对 REST API 的类型化访问。
连接设置
import sonzai "github.com/sonz-ai/sonzai-go"
// 默认连接 api.sonz.ai — 只需提供 API 密钥
client := sonzai.NewClient("sk_your_api_key")
// 为本地开发/自托管覆盖基础 URL
client := sonzai.NewClient("sk_your_api_key",
sonzai.WithBaseURL("http://localhost:8090"),
)智能体生命周期
创建智能体
当用户在您的应用中创建新智能体时,调用 CreateAgent 并传入人格配置:
resp, err := client.Agents.Create(ctx, sonzai.CreateAgentRequest{
Name: "Luna",
Gender: "female",
Big5: sonzai.Big5Scores{
Openness: 0.75,
Conscientiousness: 0.60,
Extraversion: 0.80,
Agreeableness: 0.70,
Neuroticism: 0.30,
},
Language: "en",
})
// resp.AgentID 是平台生成的 UUID
// 将其存储在您的用户记录中获取智能体
agent, err := client.Agents.Get(ctx, agentId)
// agent 包含: 名称、人格提示词、大五人格、情绪等聊天会话流程
这是核心集成循环。聊天接口在一次调用中处理上下文组装、AI 流式传输和状态更新:
流式聊天
聊天接口自动组装上下文、流式传输 AI 响应,并自动更新内部智能体状态:
stream, err := client.Agents.ChatStream(ctx, agentId, sonzai.ChatRequest{
UserID: userId,
Messages: []sonzai.Message{
{Role: "user", Content: "I had a great day hiking!"},
},
Language: "en",
})
// 读取流式事件
for event := range stream {
fmt.Print(event.Content)
}情绪标签
标签:Blissful (80-100)、Content (60-79)、Neutral (40-59)、Melancholy (20-39)、Troubled (0-19)。情绪会随时间自然向智能体的人格基线回归。
主动通知
智能体可以在对话之间主动联系用户。触发后,平台使用智能体的完整状态生成上下文消息,并将其存储为"待处理"状态。您的应用轮询并在交付后将通知标记为已消费。
REST 轮询
# 轮询待处理的主动消息
GET /api/v1/agents/{agentId}/notifications?status=pending&user_id=user-123
# 响应
{
"notifications": [{
"message_id": "msg-uuid",
"user_id": "user-123",
"check_type": "check_in",
"intent": "Ask about yesterday's hiking trip",
"generated_message": "Hey! How was the hike at Mount Rainier?",
"status": "pending",
"created_at": "2026-03-07T10:00:00Z"
}]
}
# 交付给用户后,标记为已消费
POST /api/v1/agents/{agentId}/notifications/{messageId}/consume交付最佳实践
每 30-60 秒轮询一次。交付后务必标记为已消费,以防重复交付。
Webhook 集成
注册 Webhook 以接收事件回调(唤醒、整合、突破):
// 注册 Webhook 端点
PUT /api/projects/{projectId}/webhooks/{eventType}
{
"webhook_url": "https://your-server.com/platform/webhooks/wakeup",
"auth_header": "Bearer YOUR_SERVER_KEY"
}
// 事件类型:
// - "wakeup" : 智能体想要主动触达
// - "consolidation" : 记忆整合完成
// - "breakthrough" : 重大人格演化唤醒 Webhook 载荷
包含生成的消息,可直接交付:
{
"event_type": "on_wakeup_ready",
"agent_id": "agent-uuid",
"user_id": "user-123",
"generated_message": "Hey! How was the hike?",
"wakeup_id": "wakeup-uuid",
"check_type": "check_in"
}轮询替代方案
偏好轮询?使用通知 API 代替 Webhook。
示例:后端集成流程
三层服务架构:
客户端应用 您的后端 心智层
| | |
|--- 认证 ----------->| |
| | |
|--- 创建智能体 ----->| |
| |--- REST: CreateAgent ------>|
| |<-- 智能体 ID + 档案 --------|
|<-- 智能体就绪 ------| |
| | |
|--- 发送消息 -------->| |
| |--- REST: Chat (SSE) ------->|
|<-- 流式响应 <-- AI 数据块 + 副作用 ----------------|您的后端将应用事件转换为心智层 API 调用。您可以在不改变智能体行为的情况下更换后端,或跨应用复用智能体。
知识库 (Go SDK)
上传文档或推送结构化数据,构建项目级别的知识图谱。智能体在对话中搜索此图谱。
推送结构化数据
// 插入实体和关系
resp, err := client.Knowledge.InsertFacts(ctx, projectID, sonzai.InsertFactsOptions{
Source: "product_catalog",
Facts: []sonzai.InsertFactEntry{
{
EntityType: "product",
Label: "Widget Pro",
Properties: map[string]any{"price": 29.99, "category": "tools"},
},
},
Relationships: []sonzai.InsertRelEntry{
{FromLabel: "Widget Pro", ToLabel: "Tools", EdgeType: "belongs_to"},
},
})
fmt.Printf("Created: %d, Updated: %d\n", resp.Created, resp.Updated)搜索知识图谱
results, err := client.Knowledge.Search(ctx, projectID, sonzai.KBSearchOptions{
Query: "widget price",
Limit: 10,
})
for _, r := range results.Results {
fmt.Printf("%s (%s): score=%.2f\n", r.Label, r.NodeType, r.Score)
}实体模式
// 定义模式,让 LLM 知道要提取哪些字段
schema, err := client.Knowledge.CreateSchema(ctx, projectID, sonzai.CreateSchemaOptions{
EntityType: "product",
Fields: []sonzai.KBSchemaField{
{Name: "price", Type: "number", Required: true},
{Name: "category", Type: "string"},
},
})分析规则
// 创建推荐规则
rule, err := client.Knowledge.CreateAnalyticsRule(ctx, projectID, sonzai.CreateAnalyticsRuleOptions{
RuleType: "recommendation",
Name: "Similar products",
Config: map[string]any{"match_fields": []string{"category"}, "limit": 5},
Enabled: true,
})
// 获取推荐
recs, err := client.Knowledge.GetRecommendations(ctx, projectID, rule.RuleID, sourceNodeID, 5)用户引导 (Go SDK)
预加载用户元数据和内容,使 AI 智能体从第一次对话开始就了解用户。元数据(姓名、公司、职位)会立即成为事实;内容块通过 LLM 异步提取。
引导单个用户
resp, err := client.Agents.Priming.PrimeUser(ctx, agentID, userID, sonzai.PrimeUserOptions{
DisplayName: "Jane Smith",
Metadata: &sonzai.PrimeUserMetadata{
Company: "Acme Corp",
Title: "VP Engineering",
Email: "[email protected]",
Custom: map[string]string{"region": "APAC", "tier": "enterprise"},
},
Content: []sonzai.PrimeContentBlock{
{Type: "text", Body: "Jane led the migration from AWS to GCP..."},
},
Source: "crm",
})
fmt.Printf("Job: %s, Facts created: %d\n", resp.JobID, resp.FactsCreated)批量导入
resp, err := client.Agents.Priming.BatchImport(ctx, agentID, sonzai.BatchImportOptions{
Users: []sonzai.BatchImportUser{
{UserID: "user-1", DisplayName: "Jane", Metadata: &sonzai.PrimeUserMetadata{Company: "Acme"}},
{UserID: "user-2", DisplayName: "Bob", Metadata: &sonzai.PrimeUserMetadata{Company: "Globex"}},
},
Source: "crm_sync",
})
fmt.Printf("Job: %s, Users: %d\n", resp.JobID, resp.TotalUsers)管理元数据
// 获取元数据
meta, err := client.Agents.Priming.GetMetadata(ctx, agentID, userID)
// 更新元数据(部分更新 — 与现有数据合并)
updated, err := client.Agents.Priming.UpdateMetadata(ctx, agentID, userID, sonzai.UpdateMetadataOptions{
Company: ptr("New Corp"),
Custom: map[string]string{"tier": "premium"},
})异步处理
元数据事实(姓名、公司、职位)同步创建。内容块(文本、聊天记录)通过 LLM 提取在后台异步处理。可轮询任务状态以跟踪进度。
最佳实践
- 使用
StreamChat— 一次调用即可处理上下文组装、AI 流式传输和状态更新。 - 始终通过
GameContext.custom_fields传递应用状态。平台不会缓存此数据。 - 注册 Webhook 以接收唤醒事件,使智能体能够主动发起联系。
- 不要重复实现人格、记忆或关系逻辑 — 让平台拥有智能体数据。
- 每 30-60 秒轮询通知。交付后标记为已消费,防止重复交付。
- 所有集成均使用 REST API。使用 Go、TypeScript 或 Python 的官方 SDK 获取最佳开发体验。
- 浏览器应用必须通过后端代理 — 切勿在客户端代码中暴露 API 密钥。参见上方的浏览器/前端应用章节。