Skip to main content
Sonzai Docs

知识库

为您的 AI 智能体提供一个实时可搜索的大脑。上传文档或通过 API 推送数据 — 知识库自动构建知识图谱,供智能体在对话中查询。

概述

知识库是一个领域无关的系统,将您的数据转化为结构化的知识图谱。AI 智能体在对话中搜索此图谱,提供准确、有据可依的响应,而非凭空臆断。

上传文档 / API 推送
       |
       v
提取实体 + 关系
       |
       v
构建知识图谱(去重节点 + 边)
       |
       v
运行分析规则(推荐、趋势)
       |
       v
智能体在对话中查询图谱

两种数据摄取方式

1. 文档上传

上传 PDF、DOCX、Markdown 或纯文本文件。平台自动处理文档、提取实体和关系,并将其添加到知识图谱中。

import fs from "fs";

const doc = await client.knowledge.uploadDocument(projectId, {
  file: fs.createReadStream("product_catalog.pdf"),
  fileName: "product_catalog.pdf",
});

console.log(doc.documentId, doc.status); // "processing"

2. API 推送(结构化数据)

以编程方式推送结构化数据 — 适用于爬虫、库存数据源、价格追踪器或任何外部数据源。

await client.knowledge.insertFacts(projectId, {
  source: "inventory_sync",
  facts: [
    {
      entityType: "product",
      label: "Widget Pro X",
      properties: {
        price:    29.99,
        category: "electronics",
        inStock:  true,
        tags:     ["wireless", "bluetooth"],
      },
    },
  ],
  relationships: [
    { fromLabel: "Widget Pro X", toLabel: "Electronics", edgeType: "belongs_to" },
  ],
});

Upsert 语义

如果具有相同标签 + 类型的实体已存在,属性将被合并且版本号递增。每次变更都会记录在版本历史中,包含来源和时间戳。

SDK:插入与搜索

使用 SDK 从服务器推送数据和搜索:

import { Sonzai } from "@sonzai-labs/agents";

const client = new Sonzai({ apiKey: "sk-..." });

// 插入实体
await client.knowledge.insertFacts(projectId, {
  source: "price_sync",
  facts: [
    {
      entityType: "item",
      label: "Charizard Base Set",
      properties: { price: 450, trend: "+12%", condition: "PSA 10" },
    },
  ],
  relationships: [
    { fromLabel: "Charizard Base Set", toLabel: "Fire Pokemon", edgeType: "is_type" },
  ],
});

// 搜索
const results = await client.knowledge.search(projectId, {
  query: "fire pokemon under 500",
  type: "item",
  limit: 10,
});
for (const r of results.results) {
  console.log(r.label, r.properties);
}

SDK:批量更新

使用 bulkUpdate 批量同步外部数据(价格、库存、统计)。仅更新已变更的字段 — 适合频繁同步。

await client.knowledge.bulkUpdate(projectId, {
  source: "price_sync",
  updates: [
    { label: "Charizard Base Set", entityType: "item", properties: { price: 460 } },
    { label: "Blastoise Base Set", entityType: "item", properties: { price: 390 } },
  ],
});

实体模式

定义带有类型化字段的自定义实体类型。模式引导提取,使平台确切知道要查找哪些字段。支持的类型:stringnumberboolean dateenumarray

await client.knowledge.createSchema(projectId, {
  entityType: "pokemon_card",
  description: "Collectible trading cards",
  fields: [
    { name: "price",     type: "number", required: true },
    { name: "condition", type: "enum",   enumValues: ["PSA 10", "PSA 9", "Raw"] },
    { name: "set",       type: "string", required: true },
    { name: "rarity",    type: "enum",   enumValues: ["Common", "Uncommon", "Rare", "Ultra Rare"] },
    { name: "tags",      type: "array" },
  ],
  similarityConfig: {
    enabled: true,
    threshold: 0.7,
    fieldWeights: { price: 0.3, set: 0.4, rarity: 0.3 },
  },
});

知识图谱

实体通过类型化关系连接。图谱支持任意实体类型和关系类型 — 完全与领域无关。

节点具有类型、标签和灵活属性的实体。通过标准化标签 + 类型进行去重。
节点之间的类型化关系(belongs_to、similar_to、located_in 等)。支持双向遍历。
相似度在模式上启用后,系统基于属性相似度分数自动创建实体之间的 similar_to 边。
版本历史每次变更都带有来源、时间戳和先前值的版本记录。完整的审计追踪,满足合规需求。

搜索

跨所有实体标签和属性的全文搜索。支持类型过滤、属性过滤和图遍历以包含相关实体。

const results = await client.knowledge.search(projectId, {
  query:   "bluetooth speaker",
  type:    "product",
  limit:   10,
  filters: { in_stock: true },
});

for (const r of results.results) {
  console.log(r.label, r.score, r.properties);
  // r.related[] 包含 1 跳遍历的关联节点
}

推荐引擎

定义基于字段匹配将源实体与目标实体关联的规则。引擎防止反馈循环,并通过转化反馈随时间改进推荐。

字段匹配通过精确值、范围容差、最小阈值、数组重叠或数值接近度进行匹配。每条规则有可配置的权重。
转化追踪记录推荐何时导致行动(购买、注册)。系统从中学习并持续改进。
过期过滤在可配置的时间窗口内未更新的实体会自动排除在推荐之外。
// 创建推荐规则
const rule = await client.knowledge.createAnalyticsRule(projectId, {
  ruleType: "recommendation",
  name: "Similar cards",
  config: { matchFields: ["set", "rarity"], limit: 5 },
  enabled: true,
});

// 获取推荐
const recs = await client.knowledge.getRecommendations(
  projectId, rule.ruleId, sourceNodeId, 5
);
for (const rec of recs.results) {
  console.log(rec.label, rec.score);
}

// 记录反馈(改进未来推荐)
await client.knowledge.recordFeedback(projectId, {
  ruleId:       rule.ruleId,
  sourceNodeId: sourceNodeId,
  targetNodeId: rec.nodeId,
  action:       "converted",  // "shown" | "converted"
});

趋势分析

追踪实体属性在时间窗口(7 天、30 天、90 天)内的变化。获取涨幅最大、跌幅最大、波动最大和最高均值的排名。

// 获取趋势排名
const trends = await client.knowledge.getTrendRankings(projectId, {
  ruleId: ruleId,
  type:   "top_gainers",   // "top_gainers" | "top_losers" | "most_volatile" | "highest_avg"
  window: "30d",           // "7d" | "30d" | "90d"
  limit:  10,
});

for (const item of trends.rankings) {
  console.log(item.label, item.currentValue, item.changePercent);
}

智能体如何使用知识

在对话中,AI 智能体可以使用 knowledge_search 工具查询知识库。智能体从图谱中获取准确数据(包括实体属性、关系和推荐),而非凭空臆断。

用户:"500 美元以下最好的卡牌是什么?"
       |
       v
智能体调用 knowledge_search("cards under 500")
       |
       v
知识库返回: Charizard ($450, +12%), Blastoise ($380, +8%)
       |
       v
智能体:"Charizard Base Set 售价 $450,本月上涨了 12%
        — 500 美元以内的绝佳投资选择。"

有据可依的响应

知识库支持的响应基于您的真实数据。智能体了解当前价格、库存水平、规格和关系,因为它实时查询图谱。

使用场景

价格追踪每小时抓取价格,通过 API 推送。智能体用真实数据回答'什么在上涨?'趋势规则追踪涨跌。
房地产从 MLS 数据源推送房产列表。推荐规则根据预算、卧室数和社区匹配买家与房产。
电子商务上传产品目录。相似度检测关联相关产品。智能体根据偏好和转化数据推荐。
内部知识上传员工手册、政策文档、产品手册。智能体用准确的引用信息回答问题。
产品目录通过 API 推送产品数据。智能体使用最新数据为用户提供选项、配置和推荐建议。

API 参考

所有接口使用 Authorization: Bearer {api_key} 请求头。

接口方法用途
/knowledge/documentsPOST上传文档(multipart)
/knowledge/documentsGET列出文档及状态
/knowledge/documents/{docId}DELETE删除文档
/knowledge/factsPOST创建/更新实体和关系
/knowledge/search?q=...GET带过滤的全文搜索
/knowledge/nodesGET列出节点(可选类型过滤)
/knowledge/nodes/{nodeId}GET获取节点及其边和历史
/knowledge/schemasPOST创建实体模式
/knowledge/schemasGET列出模式
/knowledge/schemas/{schemaId}PUT更新模式
/knowledge/statsGET获取知识库统计
/knowledge/analytics/rulesPOST创建分析规则
/knowledge/analytics/rulesGET列出规则
/knowledge/analytics/rules/{ruleId}/runPOST触发规则执行
/knowledge/recommendationsGET获取预计算的推荐
/knowledge/trendsGET获取趋势聚合
/knowledge/trends/rankingsGET获取趋势排名
/knowledge/conversionsGET获取转化统计
/knowledge/feedbackPOST记录推荐反馈

基础路径

以上所有路径相对于 /api/v1/projects/{projectId}。在仪表板的项目页面获取项目 ID。