状态、工具与用户知识
为智能体附加状态,定义 LLM 可调用的自定义工具,并在首次对话前为用户预加载知识。
自定义状态
灵活的键值存储,在聊天时注入到 LLM 上下文中。用于传递环境状态、任务进度、资源或任何应用数据,直接影响每次 AI 响应。
作用域模型
全局状态
按实例在实例中所有用户之间共享。用于环境状态、配置、智能体状态、全局事件。
用户级状态
按实例 + 用户限定于实例中的单个用户。用于分配任务、工作流进度、用户偏好、活跃工具。
实例
所有状态都限定于 instanceId — 智能体的一个部署上下文(如工作区或环境)。省略 instanceId 则使用默认实例。参见 实例 了解管理多个上下文。
创建状态
import { Sonzai } from "@sonzai-labs/agents";
const client = new Sonzai({ apiKey: "sk-..." });
// 全局状态(所有用户共享)
await client.agents.customStates.create("agent-id", {
key: "current_status",
value: "Processing requests",
scope: "global",
contentType: "text",
instanceId: "workspace-1", // 省略则使用默认实例
});
// 用户级状态
await client.agents.customStates.create("agent-id", {
key: "assigned_tasks",
value: { reports: 1, reviews: 3 },
scope: "user",
contentType: "json",
userId: "user-123",
instanceId: "workspace-1",
});Upsert(创建或更新)
upsert 在键不存在时创建状态,已存在时更新值。幂等操作 — 可安全在每次更新周期调用。
await client.agents.customStates.upsert("agent-id", {
key: "workflow_stage",
value: "review_started",
scope: "user",
userId: "user-123",
});按键获取
通过组合键检索特定状态。
const state = await client.agents.customStates.getByKey("agent-id", {
key: "assigned_tasks",
scope: "user",
userId: "user-123",
});
console.log(state.value); // { reports: 1, reviews: 3 }
console.log(state.updatedAt); // ISO 时间戳列出状态
// 实例的所有全局状态
const globals = await client.agents.customStates.list("agent-id", {
scope: "global",
instanceId: "workspace-1",
});
// 特定用户的所有用户级状态
const userStates = await client.agents.customStates.list("agent-id", {
scope: "user",
userId: "user-123",
});按键删除
await client.agents.customStates.deleteByKey("agent-id", {
key: "assigned_tasks",
scope: "user",
userId: "user-123",
});工具
工具让 LLM 在推理过程中调用函数。Sonzai 处理 sonzai_ 前缀的内置工具。自定义工具由您定义并由后端执行 — Sonzai 将调用作为副作用呈现。
内置工具(能力)
按智能体切换平台管理的能力。在创建智能体时启用,或通过能力 API 更新。
sonzai_memory_recall始终开启在推理时搜索已存储的记忆。自动注入上下文。
sonzai_remember_name可切换为后续对话保存用户姓名。默认开启。
sonzai_web_search可切换通过 Google 进行实时网络搜索。默认开启。
sonzai_inventory可切换读取用户资源项并与知识库数据关联。
// 创建智能体时设置能力
const agent = await client.agents.create({
agentId: "your-stable-uuid", // 推荐 — 使创建操作幂等
name: "Luna",
big5: { openness: 0.75, conscientiousness: 0.6, extraversion: 0.8,
agreeableness: 0.7, neuroticism: 0.3 },
toolCapabilities: {
webSearch: true,
rememberName: true,
imageGeneration: false,
inventory: true,
},
});
// 或更新现有智能体的能力
await client.agents.update("agent-id", {
toolCapabilities: {
webSearch: false,
inventory: true,
},
});保留前缀
sonzai_ 前缀是保留的。您的自定义工具不得使用此前缀 — API 会拒绝。
自定义工具(智能体级)
持久化存储在智能体上的工具,在每次聊天中可用,不受会话或实例限制。
// 创建自定义工具
await client.agents.createCustomTool("agent-id", {
name: "check_inventory",
description: "Check the user's current tasks and their statuses",
parameters: {
type: "object",
properties: {
item_type: {
type: "string",
description: "Filter by category: active, pending, completed",
},
},
},
});
// 列出所有自定义工具
const tools = await client.agents.listCustomTools("agent-id");
// 更新工具的描述或参数
await client.agents.updateCustomTool("agent-id", "check_inventory", {
description: "Check and summarize the user's tasks by category",
});
// 删除工具
await client.agents.deleteCustomTool("agent-id", "check_inventory");会话级工具(临时)
为特定会话动态注入工具。会话工具与智能体级工具合并 — 同名会话工具优先。会话结束后丢弃。
方式 1 — 为已有会话设置
await client.agents.sessions.setTools("agent-id", "session-id", [
{
name: "execute_action",
description: "Execute an action from the agent's capabilities",
parameters: {
type: "object",
properties: {
action_name: { type: "string" },
target: { type: "string" },
},
required: ["action_name"],
},
},
]);方式 2 — 在聊天调用中内联传入
for await (const event of client.agents.chatStream({
agent: "agent-id",
messages: [{ role: "user", content: "Check my tools" }],
userId: "user-123",
toolDefinitions: [
{
name: "check_inventory",
description: "List the agent's active tools",
parameters: { type: "object", properties: {} },
},
],
})) {
// 处理事件...
}处理工具调用
当 LLM 决定调用自定义工具时,它会作为 SSE 流中的副作用出现。您的后端执行工具并在下一条消息中返回结果。
1. 接收工具调用
const toolCalls: { name: string; arguments: Record<string, unknown> }[] = [];
for await (const event of client.agents.chatStream({
agent: "agent-id",
messages: [{ role: "user", content: "What tasks do I have?" }],
userId: "user-123",
})) {
// 将内容流式传给用户
const content = event.choices?.[0]?.delta?.content;
if (content) process.stdout.write(content);
// 从副作用中收集工具调用
const calls = event.sideEffects?.externalToolCalls ?? [];
toolCalls.push(...calls);
}2. 执行并返回结果
// 在后端执行工具调用
const toolResults: string[] = [];
for (const call of toolCalls) {
const result = await myBackend.executeTool(call.name, call.arguments);
toolResults.push(result);
}
// 在下一条聊天消息中返回结果
for await (const event of client.agents.chatStream({
agent: "agent-id",
userId: "user-123",
messages: [
{ role: "user", content: "What tasks do I have?" },
{ role: "tool", content: toolResults.join("\n") },
],
})) {
process.stdout.write(event.choices?.[0]?.delta?.content ?? "");
}工具作用域总结
| 类型 | 作用域 | 持久性 | 管理方式 |
|---|---|---|---|
内置 (sonzai_) | 所有实例 | 平台管理 | SDK 能力、仪表板 |
| 智能体级自定义 | 所有实例 | 持久 | SDK、仪表板 |
| 会话级 | 按会话 | 临时 | SDK(内联或 setTools) |
用户级知识(引导)
在首次对话前预加载智能体对用户的了解。适用于 CRM 数据、用户档案、购买历史或任何应从第一天起就可用的用户级知识。
引导用户
primeUser 异步为用户预设事实。返回任务 ID,可轮询检查提取是否完成。
const job = await client.agents.priming.primeUser(
"agent-id",
"user-123",
{
display_name: "Jane Smith",
metadata: {
company: "Acme Corp",
title: "Product Manager",
email: "[email protected]",
custom: { tier: "premium", region: "us-west" },
},
content: [
{
type: "text",
content: "Jane joined in 2024 and prefers concise answers. She focuses on mobile growth.",
},
],
source: "crm_import",
},
);
// 检查引导是否完成
const status = await client.agents.priming.getPrimeStatus(
"agent-id", "user-123", job.jobId
);
console.log(status.status); // "pending" | "processing" | "completed" | "failed"获取与更新用户元数据
// 获取用户的已存储元数据
const meta = await client.agents.priming.getMetadata("agent-id", "user-123");
console.log(meta.displayName, meta.company, meta.customFields);
// 更新元数据(部分更新 — 未指定字段保持不变)
await client.agents.priming.updateMetadata("agent-id", "user-123", {
custom: { tier: "enterprise", lastContact: "2026-03-28" },
});批量导入(多用户)
一次导入多个用户。返回任务 ID 以跟踪进度。
const job = await client.agents.priming.batchImport("agent-id", {
users: [
{
userId: "user-1",
displayName: "Alice",
metadata: { company: "Acme", custom: { tier: "pro" } },
content: [{ type: "text", content: "Alice is a power user." }],
},
{
userId: "user-2",
displayName: "Bob",
metadata: { company: "Globex" },
},
],
source: "bulk_crm_sync",
});
// 轮询导入状态
const status = await client.agents.priming.getImportStatus(
"agent-id", job.jobId
);
console.log(status.processed, status.total, status.failed);
// 列出最近的导入任务
const jobs = await client.agents.priming.listImportJobs("agent-id", 10);