WeKnora/docs/api/chat.md

193 lines
8.8 KiB
Markdown
Raw Normal View History

# 聊天功能 API
[返回目录](./README.md)
| 方法 | 路径 | 描述 |
| ---- | ----------------------------- | ------------------------ |
| POST | `/knowledge-chat/:session_id` | 基于知识库的问答 |
| POST | `/agent-chat/:session_id` | 基于 Agent 的智能问答 |
| POST | `/knowledge-search` | 基于知识库的搜索知识 |
| GET | `/sessions/:session_id/messages/:message_id/suggestions` | 获取已生成的回答后推荐 |
| POST | `/sessions/:session_id/messages/:message_id/suggestions` | 确保生成或换一批推荐 |
| POST | `/sessions/:session_id/suggestion-events` | 上报曝光、点击、关闭事件 |
## POST `/knowledge-chat/:session_id` - 基于知识库的问答
基于知识库的 RAG 问答,支持 SSE 流式响应。
**查询参数**:
| 参数 | 取值 | 说明 |
|------|------|------|
| `resource_urls` | `handle`(默认)/ `public` | `public` 让答案与引用里的图片直接返回可加载的 http(s) 链接,省去逐个调用 `/files` 代理。详见[文件与图片引用](./README.md#文件与图片引用resource-与直链) |
同样适用于下面的 `/agent-chat/:session_id`、`/knowledge-search`、`/knowledge-bases/:id/hybrid-search` 与 `/sessions/continue-stream/:session_id`。
**请求参数**:
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `query` | string | 是 | 查询文本 |
| `knowledge_base_ids` | string[] | 否 | 知识库 ID 列表 |
| `knowledge_ids` | string[] | 否 | 知识文件 ID 列表,指定具体文件进行检索 |
| `agent_id` | string | 否 | 自定义 Agent ID,指定使用的智能体 |
| `summary_model_id` | string | 否 | 覆盖默认的摘要模型 ID |
| `mentioned_items` | object[] | 否 | @提及的知识库和文件列表 |
| `disable_title` | bool | 否 | 是否禁用自动标题生成(默认 false) |
| `images` | object[] | 否 | 附带的图片(base64 格式),需要 Agent 启用图片上传 |
| `channel` | string | 否 | 来源渠道标识:`web`、`api`、`im`、`browser_extension` |
| `suggestion_attribution` | object | 否 | 用户从推荐问题发起本轮时传入 `{suggestion_set_id, question_id}`;服务端会校验归属 |
fix(agent): search bound knowledge bases before answering, and pass suggested-question origins (#3400) * fix(agent): search bound knowledge bases before answering, and pass suggested-question origins A user picked the suggested question "为什么在比较图形时需要谨慎处理?" and the agent answered in round 1 with no tool call, claiming it had searched the knowledge base and found nothing, then explained misleading statistical charts. The question had been generated from "Corners Don't Look Like That: Regarding Screenspace Ambient Occlusion" in a bound base, where "comparing graphs" means SSAO falloff curves. Two things let that happen: the grounding prompt said "Stable general explanations need no lookup", and nothing told the agent where the question came from - the base in question had no profile, only two recent titles in the directory, and the click sent the text alone. Prompt - With knowledge tools available, search bound bases before answering a question about a topic, even one that reads like general knowledge; directory profiles and recent titles cannot prove a base lacks it. - The general-explanation exemption applies only without bound bases. - Say you searched or found nothing only when a search tool ran. Question origin - Suggested questions from FAQ/document chunks also return knowledge_id. - Picking one on the home or chat page sends question_origin {knowledge_base_id, knowledge_id} with that question only. - The service keeps the origin only when its base is inside the turn's resolved scope and the document belongs to that base; it never changes the scope (unlike knowledge_base_ids, which narrows it). - The engine renders it in runtime_context as <question_origin> with the base and document handles and a note to search it before answering. * fix(agent): keep question origins across file/tag scopes and bind them to the send Review follow-up for the suggested-question origin. - Scope check: the origin was kept only when its base was in the resolved KB list, which is empty for file-only and tag-only scopes even though their bases are searched. It is now checked against SearchTargets after they are built; the document is kept only when a target for that base covers it (unfiltered base, or a document scope listing it). resolveQuestionOriginInfo re-checks SearchTargets, looks up the name of a base that is not in kbInfos, and the renderer omits an unknown name. - Frontend: the origin travelled through module-level "pending" state, so a send that returned early (agent not ready, upload in progress, steering) left it behind and a second pick overwrote it. It now rides with the one send: triggerSend(text, options) -> createSession -> send-msg -> sendMsg / changeFirstQuery. - RetrieveKBOnlyWhenMentioned: suggestions are still generated from the agent's bases, but picking one retrieved nothing. The origin now selects its base, as an @mention would, when the agent may read it. - API sync: question_origin in docs/api/chat.md and swagger; QuestionOrigin on the Go SDK's KnowledgeQARequest/AgentQARequest and knowledge_id on SuggestedQuestion.
2026-09-18 09:00:47 +00:00
| `question_origin` | object | 否 | 用户点选智能体推荐问题(`GET /api/v1/agents/{id}/suggested-questions`)时传入该问题的 `{knowledge_base_id, knowledge_id}`。Agent 会先检索这个来源再作答;它只是本轮检索范围内的提示,不会扩大范围。对仅在 @ 提及时检索知识库的智能体,若该知识库在智能体可用范围内,则本轮检索该知识库 |
**请求**:
```curl
curl --location 'http://localhost:8080/api/v1/knowledge-chat/ceb9babb-1e30-41d7-817d-fd584954304b' \
--header 'X-API-Key: sk-xxxxx' \
--header 'Content-Type: application/json' \
--data '{
"query": "彗尾的形状",
"knowledge_base_ids": ["kb-00000001"],
"agent_id": "builtin-quick-answer"
}'
```
**响应格式**:
服务器端事件流(Server-Sent Events,Content-Type: text/event-stream)
**响应**:
```
event: message
data: {"id":"3475c004-0ada-4306-9d30-d7f5efce50d2","response_type":"references","content":"","done":false,"knowledge_references":[{"id":"c8347bef-...","content":"彗星xxx。","knowledge_id":"a6790b93-...","chunk_index":0,"knowledge_title":"彗星.txt","score":4.04,"match_type":3,"chunk_type":"text","knowledge_filename":"彗星.txt"}]}
event: message
data: {"id":"3475c004-0ada-4306-9d30-d7f5efce50d2","response_type":"answer","content":"彗尾的形状主要表现为...","done":false,"knowledge_references":null}
event: message
data: {"id":"3475c004-0ada-4306-9d30-d7f5efce50d2","response_type":"answer","content":"","done":true,"knowledge_references":null}
```
## POST `/agent-chat/:session_id` - 基于 Agent 的智能问答
Agent 模式支持更智能的问答,包括工具调用、网络搜索、多知识库检索等能力。
**请求参数**:
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `query` | string | 是 | 查询文本 |
| `knowledge_base_ids` | string[] | 否 | 知识库 ID 列表,可动态指定本次查询使用的知识库 |
| `knowledge_ids` | string[] | 否 | 知识文件 ID 列表,可动态指定本次查询使用的具体文件 |
| `agent_enabled` | bool | 否 | 是否启用 Agent 模式(默认 false,优先使用 Agent 配置) |
| `agent_id` | string | 否 | 自定义 Agent ID,指定使用的智能体(支持共享 Agent) |
| `web_search_enabled` | bool | 否 | 是否启用网络搜索(默认 false) |
| `summary_model_id` | string | 否 | 覆盖默认的摘要模型 ID |
| `mentioned_items` | object[] | 否 | @提及的知识库和文件列表 |
| `disable_title` | bool | 否 | 是否禁用自动标题生成(默认 false) |
| `images` | object[] | 否 | 附带的图片(base64 格式),需要 Agent 启用图片上传 |
| `channel` | string | 否 | 来源渠道标识:`web`、`api`、`im`、`browser_extension` |
| `suggestion_attribution` | object | 否 | 用户从推荐问题发起本轮时传入 `{suggestion_set_id, question_id}`;服务端会校验归属 |
fix(agent): search bound knowledge bases before answering, and pass suggested-question origins (#3400) * fix(agent): search bound knowledge bases before answering, and pass suggested-question origins A user picked the suggested question "为什么在比较图形时需要谨慎处理?" and the agent answered in round 1 with no tool call, claiming it had searched the knowledge base and found nothing, then explained misleading statistical charts. The question had been generated from "Corners Don't Look Like That: Regarding Screenspace Ambient Occlusion" in a bound base, where "comparing graphs" means SSAO falloff curves. Two things let that happen: the grounding prompt said "Stable general explanations need no lookup", and nothing told the agent where the question came from - the base in question had no profile, only two recent titles in the directory, and the click sent the text alone. Prompt - With knowledge tools available, search bound bases before answering a question about a topic, even one that reads like general knowledge; directory profiles and recent titles cannot prove a base lacks it. - The general-explanation exemption applies only without bound bases. - Say you searched or found nothing only when a search tool ran. Question origin - Suggested questions from FAQ/document chunks also return knowledge_id. - Picking one on the home or chat page sends question_origin {knowledge_base_id, knowledge_id} with that question only. - The service keeps the origin only when its base is inside the turn's resolved scope and the document belongs to that base; it never changes the scope (unlike knowledge_base_ids, which narrows it). - The engine renders it in runtime_context as <question_origin> with the base and document handles and a note to search it before answering. * fix(agent): keep question origins across file/tag scopes and bind them to the send Review follow-up for the suggested-question origin. - Scope check: the origin was kept only when its base was in the resolved KB list, which is empty for file-only and tag-only scopes even though their bases are searched. It is now checked against SearchTargets after they are built; the document is kept only when a target for that base covers it (unfiltered base, or a document scope listing it). resolveQuestionOriginInfo re-checks SearchTargets, looks up the name of a base that is not in kbInfos, and the renderer omits an unknown name. - Frontend: the origin travelled through module-level "pending" state, so a send that returned early (agent not ready, upload in progress, steering) left it behind and a second pick overwrote it. It now rides with the one send: triggerSend(text, options) -> createSession -> send-msg -> sendMsg / changeFirstQuery. - RetrieveKBOnlyWhenMentioned: suggestions are still generated from the agent's bases, but picking one retrieved nothing. The origin now selects its base, as an @mention would, when the agent may read it. - API sync: question_origin in docs/api/chat.md and swagger; QuestionOrigin on the Go SDK's KnowledgeQARequest/AgentQARequest and knowledge_id on SuggestedQuestion.
2026-09-18 09:00:47 +00:00
| `question_origin` | object | 否 | 用户点选智能体推荐问题(`GET /api/v1/agents/{id}/suggested-questions`)时传入该问题的 `{knowledge_base_id, knowledge_id}`。Agent 会先检索这个来源再作答;它只是本轮检索范围内的提示,不会扩大范围。对仅在 @ 提及时检索知识库的智能体,若该知识库在智能体可用范围内,则本轮检索该知识库 |
## 回答后推荐问题
回答主消息完成后,服务端会异步生成推荐问题,不阻塞 SSE 的 `complete`/`done` 事件。生成结果按“空间、助手消息、位置、配置快照、语言”持久化并去重。
```http
POST /api/v1/sessions/{session_id}/messages/{message_id}/suggestions
Content-Type: application/json
{"regenerate": false}
```
状态包括 `generating`、`ready`、`suppressed`、`failed`。`ready` 时的每个问题都有稳定 `id`,点击后应先上报事件,并在下一次聊天请求中携带 `suggestion_attribution`。
```http
POST /api/v1/sessions/{session_id}/suggestion-events
Content-Type: application/json
{
"suggestion_set_id": "...",
"question_id": "...",
"event_type": "click"
}
```
网页嵌入提供同构接口:`/api/v1/embed/{channel_id}/sessions/{session_id}/...`,继续使用嵌入令牌和 `X-Embed-Session`。
**mentioned_items 结构**:
| 字段 | 类型 | 说明 |
|------|------|------|
| `id` | string | 知识库或文件 ID |
| `name` | string | 显示名称 |
| `type` | string | 类型:`kb`(知识库)或 `file`(文件) |
| `kb_type` | string | 知识库类型:`document` 或 `faq`(仅 `type=kb` 时) |
**images 结构**:
| 字段 | 类型 | 说明 |
|------|------|------|
| `data` | string | base64 编码的图片数据(`data:image/png;base64,...`) |
**请求**:
```curl
curl --location 'http://localhost:8080/api/v1/agent-chat/ceb9babb-1e30-41d7-817d-fd584954304b' \
--header 'X-API-Key: sk-xxxxx' \
--header 'Content-Type: application/json' \
--data '{
"query": "帮我查询今天的天气",
"agent_enabled": true,
"web_search_enabled": true,
"knowledge_base_ids": ["kb-00000001"],
"agent_id": "builtin-smart-reasoning",
"mentioned_items": [
{
"id": "kb-00000001",
"name": "天气知识库",
"type": "kb",
"kb_type": "document"
}
]
}'
```
**响应格式**:
服务器端事件流(Server-Sent Events,Content-Type: text/event-stream)
**响应类型说明**:
| response_type | 描述 |
|---------------|------|
| `agent_query` | Agent 开始处理查询 |
| `thinking` | Agent 思考过程 |
| `tool_call` | 工具调用信息 |
| `tool_result` | 工具调用结果 |
| `references` | 知识库检索引用 |
| `answer` | 最终回答内容 |
feat(agent): preview skill artifacts and verify installs without running them (#2823) * feat(agent): preview skill artifacts and verify installs without running them Generated files open in the chat drawer with overlay/Esc returning to the list, and install verification no longer executes guessed skill entry points. A failed install can be retried from the saved archive. * ui(chat): use a folder icon and corner count for skill artifacts The eye and document glyphs read as preview or copy, and TDesign's loading spinner sat beside the icon. A folder with a top-right count matches the generated-files drawer without covering the toolbar action. * feat(artifact): implement inline artifact references with previews Add support for inline artifact references in Markdown, allowing generated files to be displayed as clickable cards. Implemented a new rendering mechanism for artifacts, enabling previews directly from the chat interface. Updated localization files for new inline preview hints and missing file messages. Introduced tests for artifact reference normalization and rendering logic. * fix(client): document AgentResponseType constants for revive Touching the const block made golangci-lint require comments on every exported value. Match the rest of the SDK and describe artifacts_pending. * fix(agent): wrap artifact-reference prompt lines for lll Pre-push golangci-lint rejected the branch on three lines over 120 characters in the sandbox: reference guidance. * fix(agent): scope HTML scripts and tighten install verification Keep scripted HTML preview on skill artifacts only, recreate sandbox workspace dirs after they are deleted, and treat nested skill files as dependencies rather than first-party imports. * refactor(artifact): enhance artifact reference handling and metadata Updated artifact metadata to include a stable resource handle for better identification. Adjusted artifact reference resolution to support both handle and name forms, ensuring compatibility with existing references. Enhanced tests to validate the new handling logic and ensure proper rendering of artifacts in chat messages. Improved documentation for clarity on artifact reference formats and their usage in the system.
2026-08-27 02:30:32 +00:00
| `artifacts_pending` | Skill/沙箱产物正在上传;`data.count` 为待保存文件数。回答可能已经 `done`,文件按钮会在此期间显示加载态,直至 `complete` 带上 `artifacts` |
| `reflection` | Agent 反思内容 |
| `session_title` | 自动生成的会话标题 |
| `error` | 错误信息 |
**响应示例**:
```
event: message
data: {"id":"req-001","response_type":"thinking","content":"用户想查询天气,我需要使用网络搜索工具...","done":false}
event: message
data: {"id":"req-001","response_type":"tool_call","content":"","done":false,"data":{"tool_name":"web_search","arguments":{"query":"今天天气"}}}
event: message
data: {"id":"req-001","response_type":"tool_result","content":"搜索结果:今天晴,气温25°C...","done":false}
event: message
data: {"id":"req-001","response_type":"answer","content":"根据查询结果,今天天气晴朗,气温约25°C。","done":false}
event: message
data: {"id":"req-001","response_type":"answer","content":"","done":true}
```