mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-12-05 12:49:46 +08:00
merge: 同步主仓最新 OpenAPI 契约
This commit is contained in:
commit
7f11200546
102 files changed
+4826
-785
No files matched your search
@@ -207,10 +207,94 @@ paths:
|
||||
responses:
|
||||
'200': {description: 决定已保存,包含审核人及时间}
|
||||
'409': {description: 申请已经处理}
|
||||
/api/admin/v1/kb-concurrency:
|
||||
get:
|
||||
summary: 获取知识库并发配置
|
||||
description: 仅管理员;缺省学习并发为1,图片并发沿用已有视觉配置或默认为1。
|
||||
responses:
|
||||
'200':
|
||||
description: 当前并发配置
|
||||
content:
|
||||
application/json:
|
||||
schema: &kbConcurrency
|
||||
type: object
|
||||
required: [learning_concurrency, image_concurrency]
|
||||
properties:
|
||||
learning_concurrency: {type: integer, minimum: 1, maximum: 20, default: 1, description: 跨服务实例的学习任务并发上限}
|
||||
image_concurrency: {type: integer, minimum: 1, maximum: 20, default: 1, description: 每个服务实例的图片识别并发上限}
|
||||
put:
|
||||
summary: 保存知识库并发配置
|
||||
description: 仅管理员;两项必填,降低上限不中断在途任务,后续准入读取新值。无需配置模型即可保存。
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: *kbConcurrency
|
||||
responses:
|
||||
'200':
|
||||
description: 已保存
|
||||
content:
|
||||
application/json:
|
||||
schema: *kbConcurrency
|
||||
'400': {description: 并发数缺失或不是1至20的整数}
|
||||
/api/admin/v1/kb-models:
|
||||
get:
|
||||
summary: 获取知识库专用模型配置
|
||||
description: 仅管理员。最多一个vision和一个embedding;返回api_key_configured,不返回api_key。没有标签和授权范围。
|
||||
responses:
|
||||
'200':
|
||||
description: 配置列表
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
items:
|
||||
type: array
|
||||
maxItems: 2
|
||||
items:
|
||||
type: object
|
||||
properties:
|
||||
id: {type: string, format: uuid}
|
||||
kind: {type: string, enum: [vision, embedding]}
|
||||
model_id: {type: string}
|
||||
base_url: {type: string}
|
||||
protocol: {type: string}
|
||||
proxy_id: {type: string}
|
||||
api_key_configured: {type: boolean}
|
||||
enabled: {type: boolean}
|
||||
embedding_config: {type: object, properties: {dimension: {type: integer}}}
|
||||
advanced_config: {type: object, properties: {max_output_tokens: {type: integer}, concurrency: {type: integer, minimum: 1, maximum: 20, default: 1}}}
|
||||
/api/admin/v1/kb-models/{kind}:
|
||||
put:
|
||||
summary: 保存知识库模型配置
|
||||
description: 仅管理员;同类配置串行保存,以最后成功提交为准。密钥空白保留。向量维度保存时探测,向量配置读写 models 中最新的系统向量模型,视觉配置读写 knowledge_base_models。向量空间变化清理受影响知识库索引并重新学习。视觉调用不使用通用模型授权或计费配置。
|
||||
parameters:
|
||||
- {name: kind, in: path, required: true, schema: {type: string, enum: [vision, embedding]}}
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [model_id, base_url, enabled]
|
||||
properties:
|
||||
model_id: {type: string, minLength: 1}
|
||||
base_url: {type: string, format: uri}
|
||||
api_key: {type: string, writeOnly: true, description: 首次保存必填,更新空白保留}
|
||||
protocol: {type: string, enum: [openai_chat_completions, openai_responses, anthropic, openai_embeddings]}
|
||||
proxy_id: {type: string}
|
||||
max_output_tokens: {type: integer, minimum: 1, maximum: 65536, description: 视觉模型必填}
|
||||
concurrency: {type: integer, minimum: 1, maximum: 20, description: 视觉模型图片识别并发数,首次配置省略默认1,更新省略保留原值;每个服务进程共用上限}
|
||||
enabled: {type: boolean}
|
||||
responses:
|
||||
'200': {description: 保存后的脱敏配置}
|
||||
'400': {description: 参数、模型探测或网络配置无效}
|
||||
|
||||
/internal/kb/imports/images/upload:
|
||||
post:
|
||||
summary: anydoc 转换图片回调
|
||||
description: 仅用于后端生成的签名回调URL;不使用管理员会话,不向浏览器提供。验证专用令牌及发起者当前写权限。只接受 PNG/JPEG/GIF/WebP/BMP/TIFF,单图32 MiB、2500万像素;path 只校验导入目录,存储键按内容摘要生成。令牌不得写入日志。
|
||||
description: 仅用于后端生成的签名回调URL;不使用管理员会话,不向浏览器提供。验证专用令牌及发起者当前写权限。只接受 PNG/JPEG/GIF/WebP/BMP/TIFF,单图100 MiB、2500万像素;path 只校验导入目录,存储键按内容摘要生成。令牌不得写入日志。
|
||||
security: []
|
||||
parameters:
|
||||
- {name: token, in: query, required: true, schema: {type: string}}
|
||||
@@ -3311,7 +3395,7 @@ paths:
|
||||
/api/admin/v1/models/{modelID}/probe:
|
||||
post:
|
||||
summary: 使用已保存配置测试系统大语言模型或向量模型
|
||||
description: 按模型协议、Base URL、已保存密钥和网络代理向上游发送非流式请求,不缓存、不跟随重定向。大语言模型使用对应协议接口,返回提取的文本和响应有效性;向量模型将 message 作为 embedding 输入,返回维度、配置一致性、向量预览和 Token 用量。
|
||||
description: 按模型协议、Base URL、已保存密钥和网络代理向上游发送非流式请求,不缓存、不跟随重定向。大语言模型使用对应协议接口,返回提取的文本和响应有效性;向量模型的管理入口已调整至知识库模型配置,不接受此入口。
|
||||
parameters:
|
||||
- {name: modelID, in: path, required: true, schema: {type: string, format: uuid}}
|
||||
requestBody:
|
||||
@@ -3323,7 +3407,7 @@ paths:
|
||||
additionalProperties: false
|
||||
required: [message]
|
||||
properties:
|
||||
message: {type: string, minLength: 1, maxLength: 4000, description: 大语言模型的测试消息或向量模型的 embedding 输入。}
|
||||
message: {type: string, minLength: 1, maxLength: 4000, description: 大语言模型的测试消息。}
|
||||
responses:
|
||||
'200':
|
||||
description: 大语言模型或向量模型的 JSON 测试结果。
|
||||
@@ -6057,7 +6141,7 @@ paths:
|
||||
'401': {$ref: '#/components/responses/ResourceError401'}
|
||||
post:
|
||||
summary: 创建知识库
|
||||
description: 后端自动选择可用的系统 embedding 模型;存在可用模型时自动启用向量检索,否则仅使用全文检索。无需配置知识库向量模型。
|
||||
description: 后端使用 models 中的系统向量模型配置;存在启用且有有效维度的配置时自动启用向量检索,否则仅全文检索。通过知识库模型配置管理。
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
@@ -6091,7 +6175,7 @@ paths:
|
||||
parameters: [{$ref: '#/components/parameters/ResourceID'}]
|
||||
post:
|
||||
summary: 上传知识库正文图片
|
||||
description: 需要管理员会话,仅允许上传系统知识库图片;个人知识库在管理端只读。 使用 multipart/form-data 的 file 字段上传一张图片,最多 32 MiB、2500 万像素,支持 PNG、JPEG、GIF、WebP、BMP、TIFF;按真实内容完整解码校验,拒绝 SVG。图片按知识库和内容摘要存入对象存储,不新增关联表。返回的 url 及 markdown 可写入文档正文,读取时仍检查当前权限。此操作不创建或修改文档。
|
||||
description: 需要管理员会话,仅允许上传系统知识库图片;个人知识库在管理端只读。 使用 multipart/form-data 的 file 字段上传一张图片,最多 100 MiB、2500 万像素,支持 PNG、JPEG、GIF、WebP、BMP、TIFF;按真实内容完整解码校验,拒绝 SVG。图片按知识库和内容摘要存入对象存储,不新增关联表。返回的 url 及 markdown 可写入文档正文,读取时仍检查当前权限。此操作不创建或修改文档。
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
@@ -6113,7 +6197,7 @@ paths:
|
||||
name: {type: string, description: 内容摘要加真实图片扩展名}
|
||||
url: {type: string, description: 受权限保护的 /api/kb/<id>/assets/<name> 相对地址}
|
||||
mime_type: {type: string, enum: [image/png, image/jpeg, image/gif, image/webp, image/bmp, image/tiff]}
|
||||
size_bytes: {type: integer, minimum: 1, maximum: 33554432}
|
||||
size_bytes: {type: integer, minimum: 1, maximum: 104857600}
|
||||
markdown: {type: string, description: 可直接插入正文的 Markdown 图片语法}
|
||||
'400': {description: 无效图片、文件超限或 multipart 字段不合法}
|
||||
'401': {description: 未登录或凭证失效}
|
||||
@@ -6288,7 +6372,7 @@ paths:
|
||||
parameters: [{$ref: '#/components/parameters/ResourceID'}]
|
||||
post:
|
||||
summary: 上传待导入文件
|
||||
description: 上传并处理原件,最多32 MiB。文本直接保存,JPEG/PNG 同步视觉解析后保存,Office/PDF 返回 pending;以预分配 document_id 作为 AnyDoc task_id,提交信号量限制进程内并发。上下文及等待队列不落表,客户端退出后不后台查询或入库。响应不含正文;原件保存后的下游失败返回 failed/error/import_context,retryable 表示上游暂时不可用或提交结果不确定,须复用原上下文重试。需要当前知识库写权限,图片必须提供 model_id。
|
||||
description: 上传并处理原件,multipart 原件最多100 MiB,图片仍最多100 MiB、文本正文最多16 MiB。文本直接保存,JPEG/PNG/WebP 同步视觉解析后保存,Office/PDF 返回 pending;以预分配 document_id 作为 AnyDoc task_id,提交信号量限制进程内并发。上下文及等待队列不落表,客户端退出后不后台查询或入库。响应不含正文;原件保存后的下游失败返回 failed/error/import_context,retryable 表示上游暂时不可用或提交结果不确定,须复用原上下文重试。需要当前知识库写权限,图片自动读取 knowledge_base_models 中唯一的视觉模型,无需传模型 ID。
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
@@ -6301,7 +6385,6 @@ paths:
|
||||
upload_key: {type: string, pattern: "^[0-9a-fA-F]{32}$", description: 客户端生成的上传键,同一次上传重试复用。}
|
||||
title: {type: string}
|
||||
parent_id: {type: string, format: uuid}
|
||||
model_id: {type: string, format: uuid}
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
@@ -6310,7 +6393,6 @@ paths:
|
||||
import_context: {type: string}
|
||||
title: {type: string}
|
||||
parent_id: {type: [string, 'null'], format: uuid}
|
||||
model_id: {type: string, format: uuid}
|
||||
responses:
|
||||
'200':
|
||||
description: 上传待导入文件成功
|
||||
@@ -9517,11 +9599,11 @@ components:
|
||||
description: 模型最后更新时间。
|
||||
ModelProtocol:
|
||||
type: string
|
||||
enum: [openai_chat_completions, openai_responses, anthropic, image_generation, video_generation, openai_embeddings]
|
||||
enum: [openai_chat_completions, openai_responses, anthropic, image_generation, video_generation]
|
||||
description: MonkeyAI 与上游服务通信时使用的协议。
|
||||
ModelKind:
|
||||
type: string
|
||||
enum: [text, image, video, embedding]
|
||||
enum: [text, image, video]
|
||||
description: 模型对外提供的能力;省略时兼容为 text。
|
||||
ModelProvider:
|
||||
type: string
|
||||
@@ -10993,7 +11075,7 @@ components:
|
||||
|
||||
KbFileType:
|
||||
type: string
|
||||
enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png]
|
||||
enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png, webp]
|
||||
description: 后端校验的原始格式;直接创建文本为 md,转换后的 Office/PDF 仍保留原格式。客户端不能修改。
|
||||
KbImportContextInput:
|
||||
type: object
|
||||
@@ -11040,7 +11122,7 @@ components:
|
||||
children: {type: array, items: {$ref: '#/components/schemas/KbDocument'}}
|
||||
title: {type: string}
|
||||
source_type: {type: string, enum: [text, file, url]}
|
||||
file_type: {type: [string, 'null'], enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png, null], readOnly: true}
|
||||
file_type: {type: [string, 'null'], enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png, webp, null], readOnly: true}
|
||||
content_editable: {type: boolean, readOnly: true, description: 正文格式允许编辑;调用方仍须满足当前写权限。}
|
||||
has_original: {type: boolean, readOnly: true}
|
||||
content: {type: string}
|
||||
@@ -11077,7 +11159,7 @@ components:
|
||||
required: [query]
|
||||
properties:
|
||||
kb_ids: {type: array, maxItems: 50, items: {type: string, format: uuid}}
|
||||
file_types: {type: array, items: {type: string, enum: [jpg, png]}, description: 可选图片格式,在候选召回前过滤。}
|
||||
file_types: {type: array, items: {type: string, enum: [jpg, png, webp]}, description: 可选图片格式,在候选召回前过滤。}
|
||||
query: {type: string, minLength: 1}
|
||||
top_k: {type: integer, minimum: 1, maximum: 20, default: 8}
|
||||
filters: {type: object, additionalProperties: true, description: 当前版本保留字段,暂不参与过滤。}
|
||||
@@ -11100,7 +11182,7 @@ components:
|
||||
properties:
|
||||
kb_id: {type: string, format: uuid}
|
||||
document_id: {type: string, format: uuid}
|
||||
file_type: {type: string, enum: [jpg, png]}
|
||||
file_type: {type: string, enum: [jpg, png, webp]}
|
||||
mime_type: {type: string, enum: [image/jpeg, image/png]}
|
||||
file_name: {type: string}
|
||||
preview_url: {type: string}
|
||||
@@ -11136,7 +11218,7 @@ components:
|
||||
properties:
|
||||
pending: {type: integer}
|
||||
running: {type: integer}
|
||||
failed: {type: integer}
|
||||
failed: {type: integer, description: 当前学习失败且没有待执行或执行中重试任务的文档数;按文档去重,不包含历史失败任务。}
|
||||
by_operation:
|
||||
type: object
|
||||
additionalProperties:
|
||||
|
||||
@@ -4851,7 +4851,7 @@ paths:
|
||||
parameters: [{$ref: '#/components/parameters/ResourceID'}]
|
||||
post:
|
||||
summary: 上传知识库正文图片
|
||||
description: 需要 OAuth access token 及启用知识库的正文写权限,支持个人库所有者或拥有 read_write 授权的成员;只有阅读权限时返回 403,无访问权限时返回 404。 使用 multipart/form-data 的 file 字段上传一张图片,最多 32 MiB、2500 万像素,支持 PNG、JPEG、GIF、WebP、BMP、TIFF;按真实内容完整解码校验,拒绝 SVG。图片按知识库和内容摘要存入对象存储,不新增关联表。返回的 url 及 markdown 可写入文档正文,读取时仍检查当前权限。此操作不创建或修改文档。
|
||||
description: 需要 OAuth access token 及启用知识库的正文写权限,支持个人库所有者或拥有 read_write 授权的成员;只有阅读权限时返回 403,无访问权限时返回 404。 使用 multipart/form-data 的 file 字段上传一张图片,最多 100 MiB、2500 万像素,支持 PNG、JPEG、GIF、WebP、BMP、TIFF;按真实内容完整解码校验,拒绝 SVG。图片按知识库和内容摘要存入对象存储,不新增关联表。返回的 url 及 markdown 可写入文档正文,读取时仍检查当前权限。此操作不创建或修改文档。
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
@@ -4873,7 +4873,7 @@ paths:
|
||||
name: {type: string, description: 内容摘要加真实图片扩展名}
|
||||
url: {type: string, description: 受权限保护的 /api/kb/<id>/assets/<name> 相对地址}
|
||||
mime_type: {type: string, enum: [image/png, image/jpeg, image/gif, image/webp, image/bmp, image/tiff]}
|
||||
size_bytes: {type: integer, minimum: 1, maximum: 33554432}
|
||||
size_bytes: {type: integer, minimum: 1, maximum: 104857600}
|
||||
markdown: {type: string, description: 可直接插入正文的 Markdown 图片语法}
|
||||
'400': {description: 无效图片、文件超限或 multipart 字段不合法}
|
||||
'401': {description: 未登录或凭证失效}
|
||||
@@ -5055,7 +5055,7 @@ paths:
|
||||
parameters: [{$ref: '#/components/parameters/ResourceID'}]
|
||||
post:
|
||||
summary: 上传待导入文件
|
||||
description: 上传并处理原件,最多32 MiB。文本直接保存,JPEG/PNG 同步视觉解析后保存,Office/PDF 返回 pending;以预分配 document_id 作为 AnyDoc task_id,提交信号量限制进程内并发。上下文及等待队列不落表,客户端退出后不后台查询或入库。响应不含正文;原件保存后的下游失败返回 failed/error/import_context,retryable 表示上游暂时不可用或提交结果不确定,须复用原上下文重试。需要当前知识库写权限,图片必须提供 model_id。
|
||||
description: 上传并处理原件,multipart 原件最多100 MiB,图片仍最多100 MiB、文本正文最多16 MiB。文本直接保存,JPEG/PNG/WebP 同步视觉解析后保存,Office/PDF 返回 pending;以预分配 document_id 作为 AnyDoc task_id,提交信号量限制进程内并发。上下文及等待队列不落表,客户端退出后不后台查询或入库。响应不含正文;原件保存后的下游失败返回 failed/error/import_context,retryable 表示上游暂时不可用或提交结果不确定,须复用原上下文重试。需要当前知识库写权限,图片自动读取 knowledge_base_models 中唯一的视觉模型,无需传模型 ID。
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
@@ -5068,7 +5068,6 @@ paths:
|
||||
upload_key: {type: string, pattern: "^[0-9a-fA-F]{32}$", description: 客户端生成的上传键,同一次上传重试复用。}
|
||||
title: {type: string}
|
||||
parent_id: {type: string, format: uuid}
|
||||
model_id: {type: string, format: uuid}
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
@@ -5077,7 +5076,6 @@ paths:
|
||||
import_context: {type: string}
|
||||
title: {type: string}
|
||||
parent_id: {type: [string, 'null'], format: uuid}
|
||||
model_id: {type: string, format: uuid}
|
||||
responses:
|
||||
'200':
|
||||
description: 上传待导入文件成功
|
||||
@@ -5157,6 +5155,23 @@ paths:
|
||||
'404': {description: 知识库或文档不可访问}
|
||||
'413': {description: 请求超过大小限制}
|
||||
'503': {description: 导入签名、对象存储或 anydoc 未配置}
|
||||
/api/kb/{id}/assets/{name}:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/ResourceID'}
|
||||
- {name: name, in: path, required: true, schema: {type: string}}
|
||||
get:
|
||||
summary: 读取知识库图片资源或文档原件
|
||||
description: 文档 url 返回此资源地址的完整 URL。原件名称为 document_id.ext,正文图片仍为内容摘要加后缀。每次校验阅读权限;PDF、JPG、PNG 原件内联返回,HTML/SVG 等原件强制附件。支持客户端 Bearer Token 或网页会话,MCP Key 不适用于此 REST 路由。私有响应禁止缓存。
|
||||
responses:
|
||||
'200':
|
||||
description: 原始资源二进制
|
||||
content:
|
||||
application/octet-stream: {schema: {type: string, format: binary}}
|
||||
application/pdf: {schema: {type: string, format: binary}}
|
||||
image/png: {schema: {type: string, format: binary}}
|
||||
image/jpeg: {schema: {type: string, format: binary}}
|
||||
'401': {description: 未登录或凭证失效}
|
||||
'404': {description: 资源不存在或无阅读权限}
|
||||
/api/v1/kb/{id}/documents/{documentId}/file/detail:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/ResourceID'}
|
||||
@@ -5179,7 +5194,7 @@ paths:
|
||||
parameters: [{$ref: '#/components/parameters/ResourceID'}]
|
||||
get:
|
||||
summary: 查询当前用户可访问的知识库文档
|
||||
description: 返回当前用户有权限的系统或个人知识库文档。系统知识库需同时具备系统资源使用资格及知识库授权;个人知识库允许所有者或明确分享给当前用户的用户读取。支持分页,并可按标题或文件名、学习状态和来源类型筛选;列表不返回正文。
|
||||
description: 返回当前用户有权限的系统或个人知识库文档。系统知识库需同时具备系统资源使用资格及知识库授权;个人知识库允许所有者或明确分享给当前用户的用户读取。支持分页,并可按标题或文件名、学习状态和来源类型筛选;列表不返回 content 字段。
|
||||
parameters:
|
||||
- $ref: '#/components/parameters/AgentPage'
|
||||
- $ref: '#/components/parameters/AgentPageSize'
|
||||
@@ -5304,8 +5319,8 @@ paths:
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/ResourceID'}
|
||||
post:
|
||||
summary: 使用 MCP Key 上传知识库原文件
|
||||
description: 上传并处理原件,最多32 MiB。文本直接保存,JPEG/PNG 同步视觉解析后保存,Office/PDF 返回 pending;以预分配 document_id 作为 AnyDoc task_id,提交信号量限制进程内并发。上下文及等待队列不落表,客户端退出后不后台查询或入库。响应不含正文;原件保存后的下游失败返回 failed/error/import_context,retryable 表示上游暂时不可用或提交结果不确定,须复用原上下文重试。需要当前知识库写权限,图片必须提供 model_id。
|
||||
summary: 使用临时上传凭证或 MCP Key 上传知识库原文件
|
||||
description: 上传并处理原件,multipart 原件最多100 MiB,图片仍最多100 MiB、文本正文最多16 MiB。Authorization Bearer 接受 kb_upload_file 返回的 upload_token(5分钟有效,仅限返回路径中的知识库),也兼容原 mcp:invoke Key。临时凭证可在有效期内重试,同次上传须复用 upload_key;每次重新检查用户状态及写权限。文本直接保存,JPEG/PNG/WebP 同步视觉解析后保存,Office/PDF 返回 pending;以预分配 document_id 作为 AnyDoc task_id,提交信号量限制进程内并发。上下文及等待队列不落表,客户端退出后不后台查询或入库。响应不含正文;原件保存后的下游失败返回 failed/error/import_context,retryable 表示上游暂时不可用或提交结果不确定,须复用原上下文重试。需要当前知识库写权限,图片自动读取 knowledge_base_models 中唯一的视觉模型,无需传模型 ID。
|
||||
security: [{InvocationKey: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
@@ -5315,11 +5330,10 @@ paths:
|
||||
type: object
|
||||
required: [file]
|
||||
properties:
|
||||
file: {type: string, format: binary, description: 单个原始文件字节,最多32 MiB}
|
||||
file: {type: string, format: binary, description: 单个原始文件字节,最多100 MiB(图片100 MiB、文本正文16 MiB)}
|
||||
upload_key: {type: string, pattern: "^[0-9a-fA-F]{32}$", description: 客户端生成的上传键,同一次上传重试复用。}
|
||||
title: {type: string}
|
||||
parent_id: {type: string, format: uuid}
|
||||
model_id: {type: string, format: uuid}
|
||||
responses:
|
||||
'201':
|
||||
description: 原件已保存,签名上下文有效期24小时。响应中不返回正文。
|
||||
@@ -5327,14 +5341,14 @@ paths:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/KbImportUploadResult'}
|
||||
'400': {$ref: '#/components/responses/ResourceError400'}
|
||||
'401': {description: MCP Key缺失、无效或缺少mcp:invoke权限}
|
||||
'401': {description: 上传凭证缺失、无效、过期、目标库不匹配,或 MCP Key 缺少 mcp:invoke 权限}
|
||||
'403': {$ref: '#/components/responses/ResourceError403'}
|
||||
'404': {$ref: '#/components/responses/ResourceError404'}
|
||||
'503': {description: 文件签名或对象存储未配置}
|
||||
/mcp/kb:
|
||||
post:
|
||||
summary: 百智办公知识库 MCP
|
||||
description: 使用含 mcp:invoke 的全局 API Key。无状态 streamable HTTP JSON-RPC;支持 initialize、ping、tools/list、tools/call。工具为 kb_list、kb_list_documents、kb_get_document、kb_create_document、kb_update_document、kb_delete_document、kb_search。kb_list 支持 owner、q、标签和分页,不含客户端管理草稿,仅返回已生效的 knowledge_bases、user、total_count、page、page_size 和 version;kb_list_documents 支持分页、标题或文件名搜索、学习状态和来源类型筛选。文档读取工具支持当前用户有权限的系统或个人知识库;文档写入允许个人库所有者或目标库的读写成员,不能管理授权或删除整个库。MCP 协作更新/删除须传 expected_revision。多格式文件使用 kb_upload_file、kb_get_file_import_status;优先在客户端以同一 MCP Key 调用 POST /mcp/kb/{id}/files/upload 上传原始字节及处理参数,pending 时按 task_context 查询;import_context 仅用于复用原件继续提交。kb_upload_file 也兼容客户端程序化注入 file_name/data_base64,但禁止模型生成或复制Base64。原文件最多32 MiB;Base64 JSON允许44,804,780字节(编码膨胀加64 KiB),其他常规请求仍最多1 MiB。转换正文不回传模型,查询完成时服务端直接保存并返回document_id;completed表示入库成功,学习仍异步。
|
||||
description: 使用含 mcp:invoke 的全局 API Key。无状态 streamable HTTP JSON-RPC;支持 initialize、ping、tools/list、tools/call。工具为 kb_list、kb_list_documents、kb_get_document、kb_create_document、kb_update_document、kb_delete_document、kb_search。kb_list 支持 owner、q、标签和分页,不含客户端管理草稿,仅返回已生效的 knowledge_bases、user、total_count、page、page_size 和 version;kb_list_documents 支持分页、标题或文件名搜索、学习状态和来源类型筛选。文档读取工具支持当前用户有权限的系统或个人知识库;文档写入允许个人库所有者或目标库的读写成员,不能管理授权或删除整个库。MCP 协作更新/删除须传 expected_revision。多格式文件使用 kb_upload_file、kb_get_file_import_status;只传 kb_id 时返回完整 upload_url(基于配置的 PublicURL,缺失或无效时返回错误)、兼容的相对 upload_path、upload_token、expires_at(Unix秒)和 expires_in(秒);优先在客户端以临时 upload_token 作为 Bearer 凭证调用 POST /mcp/kb/{id}/files/upload 上传原始字节及处理参数,pending 时按 task_context 查询;import_context 仅用于复用原件继续提交。kb_upload_file 也兼容客户端程序化注入 file_name/data_base64,但禁止模型生成或复制Base64。multipart 原文件最多100 MiB(图片100 MiB、文本正文16 MiB),Base64 原文件仍最多100 MiB;Base64 JSON允许139,875,672字节(编码膨胀加64 KiB),其他常规请求仍最多1 MiB。转换正文不回传模型,查询完成时服务端直接保存并返回document_id;completed表示入库成功,学习仍异步。
|
||||
security: [{InvocationKey: []}]
|
||||
parameters:
|
||||
- {name: MCP-Protocol-Version, in: header, required: false, schema: {type: string, enum: ['2024-11-05', '2025-03-26', '2025-06-18', '2025-11-25']}}
|
||||
@@ -8891,7 +8905,7 @@ components:
|
||||
description: 仅知识库所有者可见的授权范围;被分享者不返回。
|
||||
KbFileType:
|
||||
type: string
|
||||
enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png]
|
||||
enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png, webp]
|
||||
description: 后端校验的原始格式;直接创建文本为 md,转换后的 Office/PDF 仍保留原格式。客户端不能修改。
|
||||
KbImportContextInput:
|
||||
type: object
|
||||
@@ -8926,7 +8940,7 @@ components:
|
||||
document_id: {type: string, format: uuid}
|
||||
KbDocument:
|
||||
type: object
|
||||
required: [id, kb_id, node_type, title, source_type, content, status, chunk_count, revision, created_at, updated_at]
|
||||
required: [id, kb_id, node_type, title, source_type, status, chunk_count, revision, created_at, updated_at]
|
||||
properties:
|
||||
updated_by_user_id: {type: [string, 'null'], format: uuid}
|
||||
content_updated_at: {type: [string, 'null'], format: date-time}
|
||||
@@ -8938,10 +8952,11 @@ components:
|
||||
children: {type: array, items: {$ref: '#/components/schemas/KbDocument'}}
|
||||
title: {type: string}
|
||||
source_type: {type: string, enum: [text, file, url]}
|
||||
file_type: {type: [string, 'null'], enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png, null], readOnly: true}
|
||||
file_type: {type: [string, 'null'], enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png, webp, null], readOnly: true}
|
||||
content_editable: {type: boolean, readOnly: true, description: 正文格式允许编辑;调用方仍须满足当前写权限。}
|
||||
has_original: {type: boolean, readOnly: true}
|
||||
content: {type: string}
|
||||
url: {type: string, readOnly: true, description: "原文件完整资源 URL,使用配置的 PublicURL 加 /api/kb/{kb_id}/assets/{document_id}.{ext};携带客户端 Bearer Token,无原件或文件夹为空字符串。"}
|
||||
content: {type: string, description: 可编辑格式及未知类型返回已保存正文;已知不可编辑格式固定返回空字符串,不暴露 AnyDoc 或 LLM 解析正文。}
|
||||
file_name: {type: [string, 'null']}
|
||||
mime_type: {type: [string, 'null']}
|
||||
size_bytes: {type: integer}
|
||||
@@ -8966,9 +8981,10 @@ components:
|
||||
children: {type: array, items: {$ref: '#/components/schemas/KbDocumentSummary'}}
|
||||
title: {type: string}
|
||||
source_type: {type: string, enum: [text, file, url]}
|
||||
file_type: {type: [string, 'null'], enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png, null], readOnly: true}
|
||||
file_type: {type: [string, 'null'], enum: [txt, md, html, svg, csv, docx, xls, xlsx, pptx, pdf, jpg, png, webp, null], readOnly: true}
|
||||
content_editable: {type: boolean, readOnly: true, description: 正文格式允许编辑;调用方仍须满足当前写权限。}
|
||||
has_original: {type: boolean, readOnly: true}
|
||||
url: {type: string, readOnly: true, description: "原文件完整资源 URL,使用配置的 PublicURL 加 /api/kb/{kb_id}/assets/{document_id}.{ext};携带客户端 Bearer Token,无原件或文件夹为空字符串。"}
|
||||
file_name: {type: [string, 'null']}
|
||||
mime_type: {type: [string, 'null']}
|
||||
size_bytes: {type: integer}
|
||||
@@ -9041,7 +9057,7 @@ components:
|
||||
required: [query]
|
||||
properties:
|
||||
kb_ids: {type: array, maxItems: 50, items: {type: string, format: uuid}}
|
||||
file_types: {type: array, items: {type: string, enum: [jpg, png]}, description: 可选图片格式,在候选召回前过滤。}
|
||||
file_types: {type: array, items: {type: string, enum: [jpg, png, webp]}, description: 可选图片格式,在候选召回前过滤。}
|
||||
query: {type: string, minLength: 1}
|
||||
top_k: {type: integer, minimum: 1, maximum: 20, default: 8}
|
||||
filters: {type: object, additionalProperties: true, description: 当前版本保留字段,暂不参与过滤。}
|
||||
@@ -9053,7 +9069,8 @@ components:
|
||||
document_id: {type: string, format: uuid}
|
||||
chunk_id: {type: string, format: uuid}
|
||||
chunk_index: {type: integer}
|
||||
content: {type: string}
|
||||
content: {type: string, description: 返回命中的正文分片,包括不可编辑格式的解析分片。}
|
||||
url: {type: string, description: 原文件完整资源 URL,需客户端 Bearer Token;无原件时为空字符串。}
|
||||
title: {type: string}
|
||||
score: {type: number}
|
||||
retrieval_source: {type: string, enum: [lexical, vector, both]}
|
||||
@@ -9064,7 +9081,7 @@ components:
|
||||
properties:
|
||||
kb_id: {type: string, format: uuid}
|
||||
document_id: {type: string, format: uuid}
|
||||
file_type: {type: string, enum: [jpg, png]}
|
||||
file_type: {type: string, enum: [jpg, png, webp]}
|
||||
mime_type: {type: string, enum: [image/jpeg, image/png]}
|
||||
file_name: {type: string}
|
||||
preview_url: {type: string}
|
||||
@@ -9100,7 +9117,7 @@ components:
|
||||
properties:
|
||||
pending: {type: integer}
|
||||
running: {type: integer}
|
||||
failed: {type: integer}
|
||||
failed: {type: integer, description: 当前学习失败且没有待执行或执行中重试任务的文档数;按文档去重,不包含历史失败任务。}
|
||||
by_operation:
|
||||
type: object
|
||||
additionalProperties:
|
||||
|
||||
@@ -263,7 +263,7 @@ func newApplicationHandlerWithMembers(ctx context.Context, logger *slog.Logger,
|
||||
return nil, fmt.Errorf("初始化知识库导入签名密钥: %w", err)
|
||||
}
|
||||
}
|
||||
knowledgeBases := kb.NewService(store, models).WithStorage(storage).WithAnyDoc(kb.AnyDocConfig{URL: cfg.AnyDocURL, CallbackBaseURL: cfg.AnyDocCallbackBaseURL, SigningKey: cfg.AnyDocSigningKey})
|
||||
knowledgeBases := kb.NewService(store, models).WithPublicURL(cfg.PublicURL).WithStorage(storage).WithAnyDoc(kb.AnyDocConfig{URL: cfg.AnyDocURL, CallbackBaseURL: cfg.AnyDocCallbackBaseURL, SigningKey: cfg.AnyDocSigningKey})
|
||||
execution := executionServices{pool: pool, settings: settings, sessions: sessions, identities: identities, executions: executions, keys: keys, charges: charges, modelRepo: modelRepo, models: models, storage: storage, connectors: connectors, knowledgeBases: knowledgeBases}
|
||||
knowledgeBases.WithImageDescriber(knowledgeVision{services: execution, logger: logger})
|
||||
if cfg.Role == config.RoleProxy {
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -28,35 +29,50 @@ type knowledgeVision struct {
|
||||
}
|
||||
|
||||
func (v knowledgeVision) ImageModels(ctx context.Context, actor string) ([]resource.Object, error) {
|
||||
items, err := v.services.models.AgentModels(ctx, actor)
|
||||
m, err := v.services.knowledgeBases.ConfiguredModel(ctx, "vision")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := []resource.Object{}
|
||||
for _, m := range items {
|
||||
if m.Kind == model.KindText && m.SupportsVision {
|
||||
out = append(out, resource.Object{"id": m.ID, "display_name": m.DisplayName, "protocol": m.Protocol})
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
return []resource.Object{{"id": m.ID, "display_name": m.ModelID, "protocol": m.Protocol}}, nil
|
||||
}
|
||||
|
||||
func (v knowledgeVision) DescribeImage(ctx context.Context, actor, id, kind string, data []byte) (string, error) {
|
||||
// Resolve as the authenticated importing user, never as a privileged service account.
|
||||
m, err := v.services.modelRepo.Resolve(ctx, actor, id)
|
||||
func (v knowledgeVision) DescribeImage(ctx context.Context, actor, kind string, data []byte) (result string, resultErr error) {
|
||||
var configured model.Model
|
||||
var response *visionResponse
|
||||
defer func() {
|
||||
if resultErr == nil {
|
||||
return
|
||||
}
|
||||
var status int
|
||||
var body []byte
|
||||
if response != nil {
|
||||
status = response.status
|
||||
body = response.body.Bytes()
|
||||
}
|
||||
model.LogModelRequestError(ctx, v.logger, "vision", configured, status, body, resultErr)
|
||||
if configured.ModelID == "" {
|
||||
resultErr = fmt.Errorf("视觉模型调用失败:%w", resultErr)
|
||||
} else {
|
||||
resultErr = fmt.Errorf("视觉模型(%s)调用失败:%w", configured.ModelID, resultErr)
|
||||
}
|
||||
}()
|
||||
// Knowledge-base access was checked by the importer; model configuration is global.
|
||||
m, err := v.services.knowledgeBases.ConfiguredModel(ctx, "vision")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if m.ID != id || m.Kind != model.KindText || !m.AdvancedConfig.SupportsVision {
|
||||
return "", resource.Invalid("请选择有权使用且支持图片输入的文本模型")
|
||||
configured = m
|
||||
id := m.ID
|
||||
if m.Kind != model.KindText || !m.AdvancedConfig.SupportsVision {
|
||||
return "", resource.Invalid("知识库视觉模型不支持图片解析,请检查视觉模型配置")
|
||||
}
|
||||
requestPath, body, err := visionRequest(m, kind, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
resolver := proxy.ResolverFunc(func(run context.Context, _, requested string) (proxy.Target, error) {
|
||||
// Re-resolve immediately before the gateway bills and sends the request.
|
||||
current, err := v.services.modelRepo.Resolve(run, actor, id)
|
||||
// Re-read before dispatch so a changed or disabled configuration cannot be used.
|
||||
current, err := v.services.knowledgeBases.ConfiguredModel(run, "vision")
|
||||
if err != nil {
|
||||
return proxy.Target{}, err
|
||||
}
|
||||
@@ -72,7 +88,8 @@ func (v knowledgeVision) DescribeImage(ctx context.Context, actor, id, kind stri
|
||||
}
|
||||
return proxy.Target{ModelID: current.ID, OwnershipType: current.OwnershipType, UpstreamModel: current.ModelID, Protocol: string(current.Protocol), UserID: actor, BaseURL: current.BaseURL, ProxyURL: proxyURL, APIKey: current.APIKey}, nil
|
||||
})
|
||||
gateway := proxy.NewProxy(resolver, v.logger).WithTransport(proxy.GatewayTransport(v.services.settings.ModelBlockedCIDRs)).WithBilling(modelBilling{service: v.services.charges}).WithUsageRecorder(modelUsageRecorder{models: v.services.modelRepo})
|
||||
// Knowledge-base vision is unmetered: do not attach billing or usage recorders.
|
||||
gateway := proxy.NewProxy(resolver, v.logger).WithTransport(proxy.GatewayTransport(v.services.settings.ModelBlockedCIDRs))
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, requestPath, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -82,15 +99,21 @@ func (v knowledgeVision) DescribeImage(ctx context.Context, actor, id, kind stri
|
||||
request.Header.Set("Authorization", "Bearer internal-kb-image")
|
||||
request.Header.Set("User-Agent", "ohmyagent-kb-image")
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := &visionResponse{header: make(http.Header)}
|
||||
response = &visionResponse{header: make(http.Header)}
|
||||
gateway.ServeKnowledgeImage(response, request)
|
||||
settle, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
|
||||
defer cancel()
|
||||
if err = gateway.Wait(settle); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if response.status != http.StatusOK || response.overflow {
|
||||
return "", resource.Invalid("图片模型调用失败或响应过大,请检查模型、额度及图片限制;重试可能再次计费")
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if response.overflow {
|
||||
return "", resource.Invalid("响应过大,请检查视觉模型配置及图片大小限制")
|
||||
}
|
||||
if response.status != http.StatusOK {
|
||||
return "", resource.Invalid(fmt.Sprintf("上游返回 HTTP %d,请检查视觉模型配置", response.status))
|
||||
}
|
||||
return visionDescription(m.Protocol, response.body.Bytes())
|
||||
}
|
||||
@@ -98,7 +121,7 @@ func (v knowledgeVision) DescribeImage(ctx context.Context, actor, id, kind stri
|
||||
func visionRequest(m model.Model, kind string, data []byte) (string, []byte, error) {
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
url := "data:" + kind + ";base64," + encoded
|
||||
tokens := min(m.AdvancedConfig.MaxOutputTokens, int64(8192))
|
||||
tokens := m.AdvancedConfig.MaxOutputTokens
|
||||
if tokens <= 0 {
|
||||
return "", nil, resource.Invalid("模型输出 Token 上限未配置")
|
||||
}
|
||||
@@ -151,7 +174,7 @@ func visionDescription(protocol model.Protocol, body []byte) (string, error) {
|
||||
switch protocol {
|
||||
case model.ProtocolOpenAIChat:
|
||||
if len(response.Choices) != 1 || response.Choices[0].Finish != "stop" || response.Choices[0].Message.Refusal != "" {
|
||||
return "", resource.Invalid("图片解析未完整完成或模型拒绝")
|
||||
return "", resource.Invalid("知识库视觉模型未完成图片解析或拒绝了请求")
|
||||
}
|
||||
text = response.Choices[0].Message.Content
|
||||
case model.ProtocolOpenAIResponses:
|
||||
|
||||
@@ -3,6 +3,7 @@ package app
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/kb"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/model"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/setting"
|
||||
@@ -63,7 +64,7 @@ func TestVisionProtocolsCarryImageAndRejectIncompleteResults(t *testing.T) {
|
||||
result := `{"description":"一只棕色的狗坐在草地上。","text":""}`
|
||||
for _, protocol := range []model.Protocol{model.ProtocolOpenAIChat, model.ProtocolOpenAIResponses, model.ProtocolAnthropic} {
|
||||
t.Run(string(protocol), func(t *testing.T) {
|
||||
m := model.Model{ID: "model", Protocol: protocol, AdvancedConfig: model.AdvancedConfig{MaxOutputTokens: 4096}}
|
||||
m := model.Model{ID: "model", Protocol: protocol, AdvancedConfig: model.AdvancedConfig{MaxOutputTokens: 16384}}
|
||||
path, body, err := visionRequest(m, "image/png", []byte("image-bytes"))
|
||||
if err != nil || path == "" || !strings.Contains(string(body), "aW1hZ2UtYnl0ZXM=") {
|
||||
t.Fatalf("request path=%s err=%v", path, err)
|
||||
@@ -73,6 +74,10 @@ func TestVisionProtocolsCarryImageAndRejectIncompleteResults(t *testing.T) {
|
||||
t.Fatal("invalid payload")
|
||||
}
|
||||
var response any
|
||||
tokenField := map[model.Protocol]string{model.ProtocolOpenAIChat: "max_completion_tokens", model.ProtocolOpenAIResponses: "max_output_tokens", model.ProtocolAnthropic: "max_tokens"}[protocol]
|
||||
if got := payload[tokenField]; got != float64(m.AdvancedConfig.MaxOutputTokens) {
|
||||
t.Fatalf("%s = %v, want %d", tokenField, got, m.AdvancedConfig.MaxOutputTokens)
|
||||
}
|
||||
switch protocol {
|
||||
case model.ProtocolOpenAIChat:
|
||||
response = map[string]any{"choices": []any{map[string]any{"finish_reason": "stop", "message": map[string]any{"content": result}}}}
|
||||
@@ -117,13 +122,22 @@ func TestKnowledgeVisionGatewayIntegration(t *testing.T) {
|
||||
repo := model.NewPostgres(pool)
|
||||
models := model.NewService(repo)
|
||||
settings := setting.NewService(setting.NewPostgres(pool))
|
||||
services := executionServices{pool: pool, modelRepo: repo, models: models, settings: settings}
|
||||
services := executionServices{pool: pool, modelRepo: repo, models: models, settings: settings, knowledgeBases: kb.NewService(resource.NewStore(pool), models)}
|
||||
v := knowledgeVision{services: services, logger: slog.New(slog.NewTextHandler(io.Discard, nil))}
|
||||
for _, protocol := range []model.Protocol{model.ProtocolOpenAIChat, model.ProtocolOpenAIResponses, model.ProtocolAnthropic} {
|
||||
t.Run(string(protocol), func(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
var reject atomic.Bool
|
||||
var logs bytes.Buffer
|
||||
vision := v
|
||||
vision.logger = slog.New(slog.NewJSONHandler(&logs, nil))
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
if reject.Load() {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":{"message":"unsupported image provider-secret"}}`))
|
||||
return
|
||||
}
|
||||
data, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
@@ -153,11 +167,11 @@ func TestKnowledgeVisionGatewayIntegration(t *testing.T) {
|
||||
}))
|
||||
defer upstream.Close()
|
||||
id := resource.ID()
|
||||
_, err := pool.Exec(ctx, `INSERT INTO models(id,ownership_type,owner_user_id,model_id,display_name,protocol,base_url,api_key,advanced_config) VALUES($1,'user',$2,'upstream-vision','Vision',$3,$4,'provider-secret','{"context_window_tokens":128000,"max_output_tokens":4096,"supports_vision":true}')`, id, actor, string(protocol), upstream.URL+"/v1")
|
||||
_, err := pool.Exec(ctx, `INSERT INTO knowledge_base_models(id,kind,model_id,protocol,base_url,api_key,advanced_config) VALUES($1,'vision','upstream-vision',$2,$3,'provider-secret','{"max_output_tokens":4096,"supports_vision":true}') ON CONFLICT(kind) DO UPDATE SET id=EXCLUDED.id,protocol=EXCLUDED.protocol,base_url=EXCLUDED.base_url,enabled=true`, id, string(protocol), upstream.URL+"/v1")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output, err := v.DescribeImage(ctx, actor, id, "image/png", []byte("image-bytes"))
|
||||
output, err := v.DescribeImage(ctx, actor, "image/png", []byte("image-bytes"))
|
||||
if err != nil || !strings.Contains(output, "狗") {
|
||||
t.Fatalf("%s %v", output, err)
|
||||
}
|
||||
@@ -165,19 +179,23 @@ func TestKnowledgeVisionGatewayIntegration(t *testing.T) {
|
||||
t.Fatal("unexpected upstream calls")
|
||||
}
|
||||
var recorded int
|
||||
if err = pool.QueryRow(ctx, `SELECT count(*) FROM model_calls WHERE user_id=$1 AND model_id=$2`, actor, id).Scan(&recorded); err != nil || recorded != 1 {
|
||||
if err = pool.QueryRow(ctx, `SELECT count(*) FROM model_calls WHERE user_id=$1 AND model_id=$2`, actor, id).Scan(&recorded); err != nil || recorded != 0 {
|
||||
t.Fatalf("usage %d %v", recorded, err)
|
||||
}
|
||||
if _, err = v.DescribeImage(ctx, other, id, "image/png", []byte("image-bytes")); err == nil {
|
||||
t.Fatal("unauthorized model accepted")
|
||||
reject.Store(true)
|
||||
if _, err = vision.DescribeImage(ctx, actor, "image/png", []byte("image-bytes")); err == nil || !strings.Contains(err.Error(), "视觉模型(upstream-vision)") || !strings.Contains(err.Error(), "HTTP 400") {
|
||||
t.Fatalf("vision error=%v", err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `UPDATE models SET advanced_config=jsonb_set(advanced_config,'{supports_vision}','false') WHERE id=$1`, id); err != nil {
|
||||
if !strings.Contains(logs.String(), `"model_kind":"vision"`) || !strings.Contains(logs.String(), "unsupported image") || strings.Contains(logs.String(), "provider-secret") || strings.Contains(logs.String(), "aW1hZ2UtYnl0ZXM=") {
|
||||
t.Fatalf("vision log=%s", logs.String())
|
||||
}
|
||||
if _, err = pool.Exec(ctx, `UPDATE knowledge_base_models SET enabled=false WHERE id=$1`, id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = v.DescribeImage(ctx, actor, id, "image/png", []byte("image-bytes")); err == nil {
|
||||
t.Fatal("non-vision model accepted")
|
||||
if _, err = v.DescribeImage(ctx, actor, "image/png", []byte("image-bytes")); err == nil {
|
||||
t.Fatal("disabled vision model accepted")
|
||||
}
|
||||
if calls.Load() != 1 {
|
||||
if calls.Load() != 2 {
|
||||
t.Fatal("rejected request reached provider")
|
||||
}
|
||||
})
|
||||
|
||||
@@ -15,6 +15,8 @@ import (
|
||||
)
|
||||
|
||||
func (s *Service) RegisterAdmin(r chi.Router) {
|
||||
s.registerModelConfig(r)
|
||||
s.registerConcurrencyConfig(r)
|
||||
s.CRUD.Register(r)
|
||||
r.Post("/kb", s.saveKb)
|
||||
r.Put("/kb/{id}", s.saveKb)
|
||||
|
||||
@@ -239,7 +239,7 @@ func (s *Service) RegisterAgent(r chi.Router) {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
resource.JSON(r.Context(), w, http.StatusAccepted, publicDocument(item))
|
||||
resource.JSON(r.Context(), w, http.StatusAccepted, s.agentDocument(item))
|
||||
})
|
||||
|
||||
r.Get("/kb/{id}/documents/{documentId}", func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -249,7 +249,7 @@ func (s *Service) RegisterAgent(r chi.Router) {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
resource.JSON(r.Context(), w, http.StatusOK, publicDocument(item))
|
||||
resource.JSON(r.Context(), w, http.StatusOK, s.agentDocument(item))
|
||||
})
|
||||
|
||||
r.Put("/kb/{id}/documents/{documentId}", func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -276,7 +276,7 @@ func (s *Service) RegisterAgent(r chi.Router) {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
resource.JSON(r.Context(), w, http.StatusAccepted, publicDocument(item))
|
||||
resource.JSON(r.Context(), w, http.StatusAccepted, s.agentDocument(item))
|
||||
})
|
||||
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
)
|
||||
|
||||
func TestAgentDocumentOriginalContract(t *testing.T) {
|
||||
s := (&Service{}).WithPublicURL("https://kb.example.test/")
|
||||
for _, kind := range []string{"txt", "md", "html", "svg", "csv", "pdf", "docx", "xls", "xlsx", "pptx", "jpg", "png", "", "legacy"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
item := resource.Object{"id": "doc", "kb_id": "kb", "node_type": "document", "file_type": kind, "content": "private parsed text", "storage_key": "private/key"}
|
||||
result := s.agentDocument(item)
|
||||
_, hasContent := result["content"]
|
||||
wantContent := ""
|
||||
switch kind {
|
||||
case "txt", "md", "html", "svg", "csv", "", "legacy":
|
||||
wantContent = "private parsed text"
|
||||
}
|
||||
if !hasContent || result["content"] != wantContent || result.Bool("content_editable") != textFileType(kind) {
|
||||
t.Fatalf("content visibility: %v", result)
|
||||
}
|
||||
if result.String("url") != "https://kb.example.test/api/kb/kb/assets/doc."+originalDocumentExtension(item) || !result.Bool("has_original") {
|
||||
t.Fatalf("original metadata: %v", result)
|
||||
}
|
||||
if _, ok := result["storage_key"]; ok {
|
||||
t.Fatal("private key leaked")
|
||||
}
|
||||
if publicDocument(item).String("content") != "private parsed text" {
|
||||
t.Fatal("admin content changed")
|
||||
}
|
||||
summary := s.agentDocumentSummary(item)
|
||||
if _, ok := summary["content"]; ok {
|
||||
t.Fatal("list content leaked")
|
||||
}
|
||||
if summary.String("url") != result.String("url") {
|
||||
t.Fatal("list original URL missing")
|
||||
}
|
||||
delete(item, "storage_key")
|
||||
if s.agentDocument(item).String("url") != "" {
|
||||
t.Fatal("missing original has URL")
|
||||
}
|
||||
})
|
||||
}
|
||||
folder := resource.Object{"id": "folder", "kb_id": "kb", "node_type": "folder", "children": []resource.Object{{"id": "nested", "kb_id": "kb", "node_type": "document", "file_type": "pdf", "content": "hidden", "storage_key": "key"}}}
|
||||
tree := s.agentDocumentTree([]resource.Object{folder})
|
||||
children := tree[0]["children"].([]resource.Object)
|
||||
if tree[0].String("url") != "" || children[0].String("url") == "" {
|
||||
t.Fatalf("tree URLs: %v", tree)
|
||||
}
|
||||
for _, node := range []resource.Object{tree[0], children[0]} {
|
||||
if _, ok := node["content"]; ok {
|
||||
t.Fatal("目录树节点不应包含 content 字段")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPReadDerivedDocumentReturnsOriginal(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
s := NewService(resource.NewStore(pool), nil).WithPublicURL("https://kb.example.test")
|
||||
book, err := s.CreateUserKB(t.Context(), actor, resource.Object{"name": "original contract"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
kbID := book.String("id")
|
||||
doc, err := s.CreateUserDocument(t.Context(), actor, DocumentInput{KbID: kbID, Title: "original", Content: "derived secret"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = pool.Exec(t.Context(), "UPDATE knowledge_base_documents SET file_type='pdf', storage_key='original.pdf' WHERE id=$1", doc.String("id"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result, err := s.readMCPDocument(t.Context(), actor, map[string]any{"kb_id": kbID, "document_id": doc.String("id")})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if content, ok := result["content"]; !ok || content != "" {
|
||||
t.Fatal("derived content must be an empty string")
|
||||
}
|
||||
if result.String("url") == "" {
|
||||
t.Fatal("original URL missing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestOriginalAssetBytes(t *testing.T) {
|
||||
for _, kind := range []string{"pdf", "png", "jpg", "html", "svg"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
data := []byte("%PDF-original bytes")
|
||||
if kind == "png" || kind == "jpg" {
|
||||
format := kind
|
||||
if format == "jpg" {
|
||||
format = "jpeg"
|
||||
}
|
||||
data = avatarImage(t, format)
|
||||
}
|
||||
storage := &originalTestStorage{&avatarStorage{files: map[string][]byte{"original": data}}}
|
||||
s := (&Service{}).WithStorage(storage).WithPublicURL("https://kb.example.test")
|
||||
doc := resource.Object{"id": resource.ID(), "kb_id": resource.ID(), "file_type": kind, "storage_key": "original"}
|
||||
url := s.originalDocumentURL(doc)
|
||||
name := url[strings.LastIndex(url, "/")+1:]
|
||||
if !originalAssetName.MatchString(name) {
|
||||
t.Fatalf("unroutable URL %s", url)
|
||||
}
|
||||
req := httptest.NewRequest("GET", url, nil)
|
||||
w := httptest.NewRecorder()
|
||||
s.writeOriginal(w, req, doc, true)
|
||||
if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), data) {
|
||||
t.Fatalf("original bytes: %d %q", w.Code, w.Body.String())
|
||||
}
|
||||
disposition := "inline"
|
||||
if kind == "html" || kind == "svg" {
|
||||
disposition = "attachment"
|
||||
}
|
||||
if !strings.HasPrefix(w.Header().Get("Content-Disposition"), disposition) || w.Header().Get("Cache-Control") != "private, no-store" {
|
||||
t.Fatalf("headers: %v", w.Header())
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, name := range []string{"../original.pdf", "original.pdf", resource.ID() + ".exe"} {
|
||||
if originalAssetName.MatchString(name) {
|
||||
t.Fatalf("invalid original name: %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
@@ -13,13 +12,14 @@ import (
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
)
|
||||
|
||||
const importFileLimit = 32 << 20
|
||||
const importFileLimit = 100 << 20
|
||||
const importContentLimit = 16 << 20
|
||||
|
||||
type ImportStorage interface {
|
||||
@@ -120,7 +120,16 @@ func (s *Service) anydocRequest(ctx context.Context, method, endpoint, contentTy
|
||||
if contentType != "" {
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
client := http.Client{Timeout: 2 * time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
timeout := 2 * time.Minute
|
||||
if file, ok := body.(*os.File); ok {
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.ContentLength = info.Size()
|
||||
timeout = 15 * time.Minute
|
||||
}
|
||||
client := http.Client{Timeout: timeout, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
resp, e := client.Do(req)
|
||||
if e != nil {
|
||||
return &resource.Error{Status: 503, Code: "anydoc_request_uncertain", Message: "anydoc 请求结果不确定,请使用相同上下文重试"}
|
||||
@@ -184,8 +193,12 @@ func (s *Service) submitAnyDoc(ctx context.Context, c importContext, uploader an
|
||||
return err
|
||||
}
|
||||
defer original.Close()
|
||||
var body bytes.Buffer
|
||||
writer := multipart.NewWriter(&body)
|
||||
body, err := os.CreateTemp("", "kb-anydoc-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { body.Close(); os.Remove(body.Name()) }()
|
||||
writer := multipart.NewWriter(body)
|
||||
if err = writer.WriteField("task_id", c.Task); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -211,7 +224,10 @@ func (s *Service) submitAnyDoc(ctx context.Context, c importContext, uploader an
|
||||
return err
|
||||
}
|
||||
|
||||
err = s.anydocRequest(ctx, http.MethodPost, "/api/slim/task/create", writer.FormDataContentType(), &body, &task)
|
||||
if _, err = body.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.anydocRequest(ctx, http.MethodPost, "/api/slim/task/create", writer.FormDataContentType(), body, &task)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -13,12 +14,16 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// Original document assets use document IDs; embedded images keep their content hashes.
|
||||
var originalAssetName = regexp.MustCompile(`^([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})\.(txt|md|html|svg|csv|docx|xls|xlsx|pptx|pdf|jpg|png|webp|bin)$`)
|
||||
|
||||
// ServeAsset requires an authenticated browser or agent identity supplied by the caller.
|
||||
func (s *Service) ServeAsset(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
user, ok := identity.UserFromContext(ctx)
|
||||
id, name := chi.URLParam(r, "id"), chi.URLParam(r, "name")
|
||||
if !ok || !assetName.MatchString(name) || s.storage == nil {
|
||||
original := originalAssetName.FindStringSubmatch(name)
|
||||
if !ok || (!assetName.MatchString(name) && original == nil) || s.storage == nil {
|
||||
resource.Fail(ctx, w, resource.NotFound)
|
||||
return
|
||||
}
|
||||
@@ -41,6 +46,19 @@ func (s *Service) ServeAsset(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if original != nil {
|
||||
doc, err := s.documentInKB(ctx, id, original[1])
|
||||
if err != nil {
|
||||
resource.Fail(ctx, w, err)
|
||||
return
|
||||
}
|
||||
if original[2] != originalDocumentExtension(doc) || doc.String("node_type") == "folder" {
|
||||
resource.Fail(ctx, w, resource.NotFound)
|
||||
return
|
||||
}
|
||||
s.writeOriginal(w, r, doc, true)
|
||||
return
|
||||
}
|
||||
data, mime, err := s.readAsset(ctx, id, name)
|
||||
if err != nil {
|
||||
resource.Fail(ctx, w, err)
|
||||
@@ -64,12 +82,12 @@ func (s *Service) readAsset(ctx context.Context, id, name string) ([]byte, strin
|
||||
return nil, "", resource.NotFound
|
||||
}
|
||||
defer body.Close()
|
||||
data, err := io.ReadAll(io.LimitReader(body, (32<<20)+1))
|
||||
data, err := io.ReadAll(io.LimitReader(body, imageUploadLimit+1))
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
mime := assetMIME(data)
|
||||
if len(data) > 32<<20 || mime == "" || !strings.HasPrefix(name, strings.TrimPrefix(imageHash(data), "sha256:")+".") {
|
||||
if len(data) > imageUploadLimit || mime == "" || !strings.HasPrefix(name, strings.TrimPrefix(imageHash(data), "sha256:")+".") {
|
||||
return nil, "", &resource.Error{Status: 502, Code: "storage_corrupted", Message: "知识库图片读取失败"}
|
||||
}
|
||||
return data, mime, nil
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/kb/sqlc"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type concurrencyConfig struct {
|
||||
Learning int `json:"learning_concurrency"`
|
||||
Image int `json:"image_concurrency"`
|
||||
}
|
||||
|
||||
func (c concurrencyConfig) validate() error {
|
||||
if c.Learning < 1 || c.Learning > 20 || c.Image < 1 || c.Image > 20 {
|
||||
return resource.Invalid("学习任务和图片识别并发数必须为1至20的整数")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readConcurrency(ctx context.Context, q *sqlc.Queries) (concurrencyConfig, error) {
|
||||
config := concurrencyConfig{Learning: 1, Image: 1}
|
||||
raw, err := q.GetKnowledgeConcurrency(ctx)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// Preserve the image limit configured before the dedicated settings tab.
|
||||
raw, err = q.GetKnowledgeModel(ctx, "vision")
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return config, nil
|
||||
}
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
_, object, err := knowledgeModel(raw)
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
config.Image = knowledgeVisionConcurrency(object)
|
||||
return config, nil
|
||||
}
|
||||
if err != nil {
|
||||
return config, err
|
||||
}
|
||||
if err = json.Unmarshal(raw, &config); err != nil {
|
||||
return config, err
|
||||
}
|
||||
return config, config.validate()
|
||||
}
|
||||
|
||||
func (s *Service) registerConcurrencyConfig(r chi.Router) {
|
||||
r.Get("/kb-concurrency", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
config, err := readConcurrency(r.Context(), sqlc.New(s.store.Pool))
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
resource.JSON(r.Context(), w, http.StatusOK, config)
|
||||
})
|
||||
r.Put("/kb-concurrency", func(w http.ResponseWriter, r *http.Request) {
|
||||
var config concurrencyConfig
|
||||
if err := resource.Decode(w, r, &config); err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
if err := config.validate(); err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
raw, err := json.Marshal(config)
|
||||
if err == nil {
|
||||
user, _ := identity.UserFromContext(r.Context())
|
||||
var actor *string
|
||||
if user.ID != "" {
|
||||
actor = &user.ID
|
||||
}
|
||||
err = sqlc.New(s.store.Pool).SaveKnowledgeConcurrency(r.Context(), sqlc.SaveKnowledgeConcurrencyParams{Value: raw, Actor: actor})
|
||||
}
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
resource.JSON(r.Context(), w, http.StatusOK, config)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/model"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/kb/sqlc"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func TestConcurrencyConfigBounds(t *testing.T) {
|
||||
for _, n := range []int{-1, 0, 1, 20, 21} {
|
||||
for _, config := range []concurrencyConfig{{n, 1}, {1, n}} {
|
||||
if (config.validate() == nil) != (n >= 1 && n <= 20) {
|
||||
t.Fatalf("invalid result: %+v", config)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrencyConfigRejectsInvalidRequests(t *testing.T) {
|
||||
r := chi.NewRouter()
|
||||
new(Service).registerConcurrencyConfig(r)
|
||||
for _, body := range []string{`{}`, `{"learning_concurrency":1}`, `{"learning_concurrency":1.5,"image_concurrency":1}`, `{"learning_concurrency":21,"image_concurrency":1}`, `{"learning_concurrency":1,"image_concurrency":21}`, `{"learning_concurrency":null,"image_concurrency":1}`} {
|
||||
w := httptest.NewRecorder()
|
||||
r.ServeHTTP(w, httptest.NewRequest("PUT", "/kb-concurrency", strings.NewReader(body)))
|
||||
if w.Code != 400 {
|
||||
t.Fatalf("%s: %d %s", body, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrencyConfigPersistenceAndAdmission(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
s, _, _ := seedLearningKB(t, pool, actor, OperationLearn, "pending")
|
||||
q := sqlc.New(pool)
|
||||
config, err := readConcurrency(t.Context(), q)
|
||||
if err != nil || config != (concurrencyConfig{1, 1}) {
|
||||
t.Fatalf("default %+v %v", config, err)
|
||||
}
|
||||
for _, config := range []concurrencyConfig{{20, 20}, {1, 1}} {
|
||||
raw, _ := json.Marshal(config)
|
||||
if err := q.SaveKnowledgeConcurrency(t.Context(), sqlc.SaveKnowledgeConcurrencyParams{Value: raw, Actor: &actor}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := readConcurrency(t.Context(), q)
|
||||
if err != nil || got != config {
|
||||
t.Fatalf("saved %+v %v", got, err)
|
||||
}
|
||||
image, err := s.visionConcurrency(t.Context())
|
||||
if err != nil || image != config.Image {
|
||||
t.Fatalf("image %d %v", image, err)
|
||||
}
|
||||
}
|
||||
worker := resource.ID()
|
||||
if _, err = q.ClaimKbLearningJob(t.Context(), &worker); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A second pending job must remain queued while the first lease is active.
|
||||
_, _, _ = seedLearningKB(t, pool, actor, OperationLearn, "pending")
|
||||
if worked, err := s.runLearningJob(t.Context()); err != nil || worked {
|
||||
t.Fatalf("limit ignored: %v %v", worked, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestudyRetainsConcurrencyUntilOldExecutionExits(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
s, _, docID := seedLearningKB(t, pool, actor, OperationLearn, "pending")
|
||||
// Use the document job path exercised by restudy.
|
||||
if _, err := pool.Exec(t.Context(), `UPDATE knowledge_base_learning_jobs SET document_id=$1`, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
started, release := make(chan struct{}), make(chan struct{})
|
||||
var unblock sync.Once
|
||||
defer unblock.Do(func() { close(release) })
|
||||
s.models = callbackEmbedder(func(ctx context.Context, _, _ string) (model.EmbeddingResult, error) {
|
||||
close(started)
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return model.EmbeddingResult{}, ctx.Err()
|
||||
}
|
||||
return model.EmbeddingResult{Vector: []float64{1, 2, 3}}, nil
|
||||
})
|
||||
done := make(chan error, 1)
|
||||
go func() { _, err := s.runLearningJob(t.Context()); done <- err }()
|
||||
select {
|
||||
case <-started:
|
||||
case err := <-done:
|
||||
t.Fatalf("job stopped before embedding: %v", err)
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("embedding did not start")
|
||||
}
|
||||
if _, err := s.RestudyDocument(t.Context(), docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A different service models another instance: local semaphores are insufficient.
|
||||
other := NewService(resource.NewStore(pool), nil)
|
||||
if worked, err := other.runLearningJob(t.Context()); err != nil || worked {
|
||||
t.Fatalf("canceled execution lost its slot: %v %v", worked, err)
|
||||
}
|
||||
unblock.Do(func() { close(release) })
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("old execution did not finish")
|
||||
}
|
||||
active, err := sqlc.New(pool).CountRunningKnowledgeJobs(t.Context())
|
||||
if err != nil || active != 0 {
|
||||
t.Fatalf("slot leaked: %d %v", active, err)
|
||||
}
|
||||
other.models = callbackEmbedder(func(context.Context, string, string) (model.EmbeddingResult, error) {
|
||||
return model.EmbeddingResult{Vector: []float64{1, 2, 3}}, nil
|
||||
})
|
||||
if worked, err := other.runLearningJob(t.Context()); err != nil || !worked {
|
||||
t.Fatalf("replacement did not run: %v %v", worked, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
)
|
||||
|
||||
func convertedFileType(kind string) bool {
|
||||
switch kind {
|
||||
case "pdf", "docx", "pptx", "xls", "xlsx":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Converted images must be references to this knowledge base's managed assets.
|
||||
// Read object storage directly; never issue HTTP requests for document links.
|
||||
func (s *Service) describeConvertedImages(ctx context.Context, document, book resource.Object) (string, error) {
|
||||
concurrency, err := s.visionConcurrency(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return describeStoredImages(ctx, document.String("content"), document.String("kb_id"), concurrency, func(attempt context.Context, name string) (string, error) {
|
||||
c := importContext{Actor: document.String("created_by_user_id"), KB: document.String("kb_id"), Admin: book.String("ownership_type") == "system"}
|
||||
if err := s.importAccess(attempt, c); err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, mime, err := s.readAsset(attempt, c.KB, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, _, err = readContentImage(data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s.describeVisionImage(attempt, c.Actor, mime, data)
|
||||
})
|
||||
}
|
||||
|
||||
func describeStoredImages(ctx context.Context, content, kbID string, concurrency int, describe func(context.Context, string) (string, error)) (string, error) {
|
||||
batch := newImageLearningBatch()
|
||||
invalid := map[string]string{}
|
||||
// Only actual image nodes are selected; ordinary links and code are not images.
|
||||
render := func(resolve func(string) (string, error)) (string, error) {
|
||||
return replaceAllMarkdownImages(content, func(string) bool { return true }, resolve)
|
||||
}
|
||||
prefix := "/api/kb/" + kbID + "/assets/"
|
||||
_, err := render(func(source string) (string, error) {
|
||||
name := strings.TrimPrefix(source, prefix)
|
||||
if !strings.HasPrefix(source, prefix) || !assetName.MatchString(name) {
|
||||
invalid[source] = "图片解析失败:图片引用不属于当前知识库或格式无效"
|
||||
} else {
|
||||
batch.add(source, func(attempt context.Context) (string, error) { return describe(attempt, name) })
|
||||
}
|
||||
return "图片待识别", nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = batch.run(ctx, concurrency); err != nil {
|
||||
return "", err
|
||||
}
|
||||
result, err := render(func(source string) (string, error) {
|
||||
if reason, ok := invalid[source]; ok {
|
||||
return reason, nil
|
||||
}
|
||||
return batch.results[source].result, nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(result) > importContentLimit {
|
||||
return "", resource.Invalid("转换后的学习文本超过 16 MiB")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestStoredImageLearningReferencesAndFailures(t *testing.T) {
|
||||
name := strings.Repeat("a", 64) + ".png"
|
||||
url := assetURL("book", name)
|
||||
source := "前文\n\n\n\n中间\n\n<img src=\"" + url + "\">\n\n![ref][pic]\n\n后文\n\n[pic]: " + url
|
||||
for _, fail := range []bool{false, true} {
|
||||
calls := 0
|
||||
got, err := describeStoredImages(t.Context(), source, "book", 3, func(_ context.Context, asset string) (string, error) {
|
||||
calls++
|
||||
if asset != name {
|
||||
t.Fatal(asset)
|
||||
}
|
||||
if fail {
|
||||
return "", errors.New("unavailable")
|
||||
}
|
||||
return "画面描述", nil
|
||||
})
|
||||
want, attempts := "画面描述", 1
|
||||
if fail {
|
||||
want, attempts = "图片识别失败", 3
|
||||
}
|
||||
if err != nil || calls != attempts || strings.Count(got, want) != 3 || !strings.Contains(got, "后文") {
|
||||
t.Fatalf("got=%s calls=%d err=%v", got, calls, err)
|
||||
}
|
||||
if strings.Index(got, want) < strings.Index(got, "前文") || strings.LastIndex(got, want) > strings.Index(got, "后文") {
|
||||
t.Fatal("wrong image position")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoredImagesRejectForeignReferencesAndIgnoreExamples(t *testing.T) {
|
||||
url := assetURL("book", strings.Repeat("a", 64)+".png")
|
||||
examples := "[link](" + url + ")\n\n```html\n<img src=\"" + url + "\">\n```\n\n``"
|
||||
got, err := describeStoredImages(t.Context(), examples, "book", 2, func(context.Context, string) (string, error) { t.Fatal("example fetched"); return "", nil })
|
||||
if err != nil || got != examples {
|
||||
t.Fatalf("got=%s err=%v", got, err)
|
||||
}
|
||||
for _, source := range []string{"https://127.0.0.1/a.png", assetURL("other", strings.Repeat("a", 64)+".png"), "/api/kb/book/assets/../a.png"} {
|
||||
got, err := describeStoredImages(t.Context(), "", "book", 2, func(context.Context, string) (string, error) { t.Fatal("unsafe reference fetched"); return "", nil })
|
||||
if err != nil || !strings.Contains(got, "图片解析失败") {
|
||||
t.Fatalf("got=%s err=%v", got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertedFormatsLearnStoredImages(t *testing.T) {
|
||||
for _, kind := range []string{"pdf", "docx", "pptx", "xls", "xlsx"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
s, kbID, docID := seedLearningKB(t, pool, actor, OperationRebuildParse, "pending")
|
||||
data := avatarImage(t, "png")
|
||||
name, _, err := readContentImage(data)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
storage := &avatarStorage{files: map[string][]byte{assetObjectKey(kbID, name): data}}
|
||||
vision := &visionStub{content: "棕色小狗"}
|
||||
s.WithStorage(storage).WithImageDescriber(vision)
|
||||
var embedded atomic.Int32
|
||||
s.models = callbackEmbedder(func(_ context.Context, _, content string) (model.EmbeddingResult, error) {
|
||||
embedded.Add(1)
|
||||
if !strings.Contains(content, "棕色小狗") || strings.Contains(content, "/assets/") {
|
||||
t.Errorf("bad embedding text: %s", content)
|
||||
}
|
||||
return model.EmbeddingResult{Vector: []float64{1, 2, 3}}, nil
|
||||
})
|
||||
source := "前文\n\n + ")\n\n后文"
|
||||
if _, err = pool.Exec(t.Context(), `UPDATE knowledge_base_documents SET file_type=$2,content=$3 WHERE id=$1`, docID, kind, source); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(t.Context(), `UPDATE knowledge_base_learning_jobs SET document_id=$2 WHERE kb_id=$1`, kbID, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if worked, err := s.runLearningJob(t.Context()); err != nil || !worked {
|
||||
t.Fatalf("worked=%v err=%v", worked, err)
|
||||
}
|
||||
doc, err := s.GetDocument(t.Context(), docID)
|
||||
if err != nil || doc.String("status") != "learned" || doc.String("content") != source || vision.calls != 1 || embedded.Load() == 0 {
|
||||
t.Fatalf("doc=%v calls=%d err=%v", doc, vision.calls, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -183,13 +183,13 @@ func (s *Service) ListAccessibleDocuments(ctx context.Context, userID, kbID stri
|
||||
return DocumentPage{}, err
|
||||
}
|
||||
if strings.TrimSpace(filter.Query) == "" && strings.TrimSpace(filter.Status) == "" && strings.TrimSpace(filter.SourceType) == "" && filter.Page == 0 && filter.PageSize == 0 {
|
||||
tree := publicDocumentTree(buildDocumentTree(items))
|
||||
tree := s.agentDocumentTree(buildDocumentTree(items))
|
||||
return DocumentPage{Items: tree, TotalCount: len(tree), Page: 1, PageSize: len(tree)}, nil
|
||||
}
|
||||
return filterDocumentPage(items, filter)
|
||||
return s.filterDocumentPage(items, filter)
|
||||
}
|
||||
|
||||
func filterDocumentPage(items []resource.Object, filter DocumentListFilter) (DocumentPage, error) {
|
||||
func (s *Service) filterDocumentPage(items []resource.Object, filter DocumentListFilter) (DocumentPage, error) {
|
||||
normalized, err := normalizeDocumentListFilter(filter)
|
||||
if err != nil {
|
||||
return DocumentPage{}, err
|
||||
@@ -211,7 +211,7 @@ func filterDocumentPage(items []resource.Object, filter DocumentListFilter) (Doc
|
||||
selected := resource.PageSlice(filtered, normalized.Page, normalized.PageSize)
|
||||
out := make([]resource.Object, 0, len(selected))
|
||||
for _, item := range selected {
|
||||
out = append(out, publicDocumentSummary(item))
|
||||
out = append(out, s.agentDocumentSummary(item))
|
||||
}
|
||||
return DocumentPage{
|
||||
Items: out,
|
||||
@@ -698,28 +698,17 @@ func (s *Service) restudyDocument(ctx context.Context, id, actor string) (resour
|
||||
return nil, err
|
||||
}
|
||||
modelID, dimension := embeddingBindingTarget(binding.EmbeddingModelID, binding.EmbeddingDimension)
|
||||
if documentHasChunks(document) {
|
||||
if modelID == "" || dimension <= 0 {
|
||||
if err = queries.SetKbDocumentLexicallyLearned(ctx, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
revision, err := queries.SetKbDocumentVectorLearning(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = createKbDocumentJob(ctx, queries, document.String("kb_id"), id, OperationRebuildVector, revision, modelID, dimension); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
revision, err := queries.SetKbDocumentPending(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = createKbDocumentJob(ctx, queries, document.String("kb_id"), id, OperationRelearn, revision, modelID, dimension); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Explicit restudy rebuilds from source, including image descriptions and
|
||||
// chunk boundaries. Model lifecycle jobs still reuse existing chunks.
|
||||
if err = queries.DeleteKbChunksByDocument(ctx, id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
revision, err := queries.SetKbDocumentPending(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = createKbDocumentJob(ctx, queries, document.String("kb_id"), id, OperationRelearn, revision, modelID, dimension); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
@@ -762,7 +751,7 @@ func (s *Service) SearchLearnedWithResponse(ctx context.Context, userID string,
|
||||
} else {
|
||||
normalized.KbIDs = ids
|
||||
}
|
||||
return s.searchWithPermissionRecheck(ctx, userID, accessible, normalized)
|
||||
return s.searchWithPermissionRecheck(ctx, userID, accessible, normalized, true)
|
||||
}
|
||||
|
||||
func (s *Service) SearchWithResponse(ctx context.Context, userID string, input SearchInput) (SearchResponse, error) {
|
||||
@@ -770,7 +759,7 @@ func (s *Service) SearchWithResponse(ctx context.Context, userID string, input S
|
||||
if err != nil {
|
||||
return SearchResponse{}, err
|
||||
}
|
||||
return s.searchWithPermissionRecheck(ctx, userID, accessible, input)
|
||||
return s.searchWithPermissionRecheck(ctx, userID, accessible, input, false)
|
||||
}
|
||||
|
||||
func normalizeSearchInput(input SearchInput) (SearchInput, error) {
|
||||
@@ -790,7 +779,7 @@ func normalizeSearchInput(input SearchInput) (SearchInput, error) {
|
||||
}
|
||||
for _, typ := range input.FileTypes {
|
||||
if !imageFileType(typ) {
|
||||
return SearchInput{}, resource.Invalid("file_types 仅支持 jpg、png")
|
||||
return SearchInput{}, resource.Invalid("file_types 仅支持 jpg、png、webp")
|
||||
}
|
||||
}
|
||||
input.FileTypes = uniqueStrings(input.FileTypes)
|
||||
@@ -803,7 +792,7 @@ func learnedKBIDs(items []resource.Object) []string {
|
||||
ids := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
id := item.String("id")
|
||||
if id == "" || objectInt64(item["learned_count"]) <= 0 {
|
||||
if id == "" || objectInt64(item["indexed_count"]) <= 0 {
|
||||
continue
|
||||
}
|
||||
ids = append(ids, id)
|
||||
|
||||
@@ -10,13 +10,14 @@ import (
|
||||
|
||||
func TestLearnedKBIDs(t *testing.T) {
|
||||
items := []resource.Object{
|
||||
{"id": "learned-int64", "learned_count": int64(2)},
|
||||
{"id": "learned-float64", "learned_count": float64(1)},
|
||||
{"id": "empty", "learned_count": int64(0)},
|
||||
{"id": "learned-int64", "indexed_count": int64(2)},
|
||||
{"id": "learned-float64", "indexed_count": float64(1)},
|
||||
{"id": "empty", "indexed_count": int64(0), "learned_count": int64(1)},
|
||||
{"id": "relearning", "indexed_count": int64(1), "learned_count": int64(0)},
|
||||
{"id": "missing"},
|
||||
{"learned_count": int64(1)},
|
||||
{"indexed_count": int64(1)},
|
||||
}
|
||||
if got, want := learnedKBIDs(items), []string{"learned-int64", "learned-float64"}; !reflect.DeepEqual(got, want) {
|
||||
if got, want := learnedKBIDs(items), []string{"learned-int64", "learned-float64", "relearning"}; !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("learnedKBIDs() = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
@@ -55,10 +56,10 @@ func TestFilterDocumentPage(t *testing.T) {
|
||||
{"id": "1", "title": "差旅制度", "file_name": "travel.pdf", "source_type": "file", "status": "learned", "content": "正文 1"},
|
||||
{"id": "2", "title": "差旅报销", "file_name": "reimburse.pdf", "source_type": "file", "status": "learning", "content": "正文 2"},
|
||||
{"id": "3", "title": "员工手册", "file_name": "handbook.pdf", "source_type": "file", "status": "learned", "content": "正文 3"},
|
||||
{"id": "4", "title": "差旅说明", "file_name": "travel.txt", "source_type": "text", "status": "learned", "content": "正文 4"},
|
||||
{"id": "4", "title": "差旅说明", "file_name": "travel.txt", "file_type": "txt", "source_type": "text", "status": "learned", "content": "正文 4"},
|
||||
}
|
||||
|
||||
page, err := filterDocumentPage(items, DocumentListFilter{Query: "TRAVEL", Status: "learned", SourceType: "file", Page: 1, PageSize: 1})
|
||||
page, err := (&Service{}).filterDocumentPage(items, DocumentListFilter{Query: "TRAVEL", Status: "learned", SourceType: "file", Page: 1, PageSize: 1})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -66,10 +67,10 @@ func TestFilterDocumentPage(t *testing.T) {
|
||||
t.Fatalf("筛选和分页结果不正确: %+v", page)
|
||||
}
|
||||
if _, ok := page.Items[0]["content"]; ok {
|
||||
t.Fatal("文档列表不应返回正文")
|
||||
t.Fatal("不可编辑文档列表不应包含 content 字段")
|
||||
}
|
||||
|
||||
page, err = filterDocumentPage(items, DocumentListFilter{Query: "差旅", Page: 2, PageSize: 2})
|
||||
page, err = (&Service{}).filterDocumentPage(items, DocumentListFilter{Query: "差旅", Page: 2, PageSize: 2})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -77,7 +78,10 @@ func TestFilterDocumentPage(t *testing.T) {
|
||||
t.Fatalf("第二页结果不正确: %+v", page)
|
||||
}
|
||||
|
||||
page, err = filterDocumentPage(items, DocumentListFilter{})
|
||||
if _, ok := page.Items[0]["content"]; ok {
|
||||
t.Fatal("可编辑文档列表不应包含 content 字段")
|
||||
}
|
||||
page, err = (&Service{}).filterDocumentPage(items, DocumentListFilter{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -91,7 +95,7 @@ func TestFilterDocumentPage(t *testing.T) {
|
||||
{Page: -1},
|
||||
{PageSize: documentMaxPageSize + 1},
|
||||
} {
|
||||
if _, err := filterDocumentPage(items, filter); err == nil {
|
||||
if _, err := (&Service{}).filterDocumentPage(items, filter); err == nil {
|
||||
t.Fatalf("非法筛选参数应返回错误: %+v", filter)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,3 +93,53 @@ func project(item resource.Object, fields []string) resource.Object {
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func hasReadableDocumentContent(item resource.Object) bool {
|
||||
kind := item.String("file_type")
|
||||
return item.String("node_type") != "folder" && (textFileType(kind) || !knownFileType(kind))
|
||||
}
|
||||
|
||||
// agentDocument keeps derived parsing text internal while exposing authenticated originals.
|
||||
func (s *Service) agentDocument(item resource.Object) resource.Object {
|
||||
out := publicDocument(item)
|
||||
if !hasReadableDocumentContent(item) {
|
||||
out["content"] = ""
|
||||
}
|
||||
out["url"] = s.originalDocumentURL(item)
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Service) originalDocumentURL(item resource.Object) string {
|
||||
return s.originalAssetURL(item, item.String("id"), item.String("node_type") != "folder" && item.String("storage_key") != "")
|
||||
}
|
||||
|
||||
func (s *Service) originalAssetURL(item resource.Object, documentID string, hasOriginal bool) string {
|
||||
if !hasOriginal || s.publicURL == "" {
|
||||
return ""
|
||||
}
|
||||
return s.publicURL + assetURL(item.String("kb_id"), documentID+"."+originalDocumentExtension(item))
|
||||
}
|
||||
|
||||
func (s *Service) agentDocumentSummary(item resource.Object) resource.Object {
|
||||
out := s.agentDocument(item)
|
||||
delete(out, "content")
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *Service) agentDocumentTree(items []resource.Object) []resource.Object {
|
||||
out := make([]resource.Object, 0, len(items))
|
||||
for _, item := range items {
|
||||
node := s.agentDocumentSummary(item)
|
||||
children, _ := item["children"].([]resource.Object)
|
||||
node["children"] = s.agentDocumentTree(children)
|
||||
out = append(out, node)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func originalDocumentExtension(item resource.Object) string {
|
||||
if knownFileType(item.String("file_type")) {
|
||||
return item.String("file_type")
|
||||
}
|
||||
return "bin"
|
||||
}
|
||||
@@ -214,13 +214,17 @@ func TestVectorFailureKeepsLexicalAndRetryOnlyFillsMissingChunks(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.runLearningJob(ctx); err != nil {
|
||||
if _, err := s.runLearningJob(ctx); !errors.Is(err, errVectorLearningFailed) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
document, err = s.GetDocument(ctx, document.String("id"))
|
||||
if err != nil || document.String("status") != "failed" || objectInt64(document["chunk_count"]) != 2 || document.String("error_message") == "" {
|
||||
t.Fatalf("向量失败后状态异常: %v, %v", document, err)
|
||||
}
|
||||
var jobStatus, jobError string
|
||||
if err := pool.QueryRow(ctx, `SELECT status,error_message FROM knowledge_base_learning_jobs WHERE document_id=$1 ORDER BY created_at DESC LIMIT 1`, document.String("id")).Scan(&jobStatus, &jobError); err != nil || jobStatus != "pending" || !strings.Contains(jobError, "upstream vector failure") {
|
||||
t.Fatalf("job status=%q error=%q query error=%v", jobStatus, jobError, err)
|
||||
}
|
||||
chunks, err := s.ListChunks(ctx, document.String("id"))
|
||||
if err != nil || len(chunks) != 2 || !chunks[0].Bool("has_vector") || chunks[1].Bool("has_vector") {
|
||||
t.Fatalf("向量失败分片结果异常: %v, %v", chunks, err)
|
||||
@@ -239,7 +243,7 @@ func TestVectorFailureKeepsLexicalAndRetryOnlyFillsMissingChunks(t *testing.T) {
|
||||
return model.EmbeddingResult{Vector: []float64{1, 2, 3}}, nil
|
||||
})
|
||||
document, err = s.RestudyDocument(ctx, document.String("id"))
|
||||
if err != nil || document.String("status") != "learning" {
|
||||
if err != nil || document.String("status") != "pending" {
|
||||
t.Fatalf("重试未进入学习中: %v, %v", document, err)
|
||||
}
|
||||
if _, err := s.runLearningJob(ctx); err != nil {
|
||||
@@ -247,10 +251,10 @@ func TestVectorFailureKeepsLexicalAndRetryOnlyFillsMissingChunks(t *testing.T) {
|
||||
}
|
||||
document, err = s.GetDocument(ctx, document.String("id"))
|
||||
if err != nil || document.String("status") != "learned" {
|
||||
t.Fatalf("补齐向量后未恢复已学习: %v, %v", document, err)
|
||||
t.Fatalf("重新切片和向量化后未恢复已学习: %v, %v", document, err)
|
||||
}
|
||||
if retryCalls != 1 {
|
||||
t.Fatalf("重试应只补齐缺失分片,实际调用 %d 次", retryCalls)
|
||||
if retryCalls != 2 {
|
||||
t.Fatalf("重新学习应重建全部分片向量,实际调用 %d 次", retryCalls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,7 +277,7 @@ func TestDisablingEmbeddingPreservesVectorFailedDocumentState(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.runLearningJob(ctx); err != nil {
|
||||
if _, err := s.runLearningJob(ctx); !errors.Is(err, errVectorLearningFailed) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -30,7 +30,6 @@ type fileImportInput struct {
|
||||
TaskContext string `json:"task_context"`
|
||||
Title string `json:"title"`
|
||||
ParentID *string `json:"parent_id"`
|
||||
ModelID string `json:"model_id"`
|
||||
}
|
||||
|
||||
func validateImportText(b []byte) (string, error) {
|
||||
@@ -51,8 +50,11 @@ func importType(name string, data []byte) (string, string, error) {
|
||||
if t == "jpeg" {
|
||||
t = "jpg"
|
||||
}
|
||||
if t == "xls" || t == "ppt" || t == "doc" {
|
||||
return "", "", resource.Invalid("不支持旧版 Office 格式,请在客户端转换为 .xlsx、.pptx 或 .docx 后上传")
|
||||
}
|
||||
if !knownFileType(t) {
|
||||
return "", "", resource.Invalid("不支持此文件格式(不支持 DOC、PPT)")
|
||||
return "", "", resource.Invalid("不支持此文件格式")
|
||||
}
|
||||
if imageFileType(t) {
|
||||
name, kind, err := readContentImage(data)
|
||||
@@ -64,12 +66,12 @@ func importType(name string, data []byte) (string, string, error) {
|
||||
}
|
||||
return t, kind, nil
|
||||
}
|
||||
m := map[string]string{"csv": "text/csv", "txt": "text/plain", "md": "text/markdown", "html": "text/html", "svg": "image/svg+xml", "pdf": "application/pdf", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", "xls": "application/vnd.ms-excel"}[t]
|
||||
m := map[string]string{"csv": "text/csv", "txt": "text/plain", "md": "text/markdown", "html": "text/html", "svg": "image/svg+xml", "pdf": "application/pdf", "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"}[t]
|
||||
if textFileType(t) {
|
||||
_, e := validateImportText(data)
|
||||
return t, m, e
|
||||
}
|
||||
if (t == "pdf" && !bytes.HasPrefix(data, []byte("%PDF-"))) || (t == "xls" && !bytes.HasPrefix(data, []byte{0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1})) || ((t == "docx" || t == "xlsx" || t == "pptx") && !bytes.HasPrefix(data, []byte("PK\x03\x04"))) {
|
||||
if (t == "pdf" && !bytes.HasPrefix(data, []byte("%PDF-"))) || ((t == "docx" || t == "xlsx" || t == "pptx") && !bytes.HasPrefix(data, []byte("PK\x03\x04"))) {
|
||||
return "", "", resource.Invalid("文件内容与格式不匹配")
|
||||
}
|
||||
return t, m, nil
|
||||
@@ -111,28 +113,41 @@ func (s *Service) importAccessTx(ctx context.Context, tx pgx.Tx, c importContext
|
||||
return resource.RequireEditable(ctx, tx, "kb", c.KB)
|
||||
}
|
||||
func readImportMultipart(w http.ResponseWriter, r *http.Request) (string, []byte, error) {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, importFileLimit+(64<<10))
|
||||
return readImportMultipartLimit(w, r, importFileLimit)
|
||||
}
|
||||
|
||||
func readImportMultipartLimit(w http.ResponseWriter, r *http.Request, limit int64) (string, []byte, error) {
|
||||
if r.ContentLength > limit+(64<<10) {
|
||||
return "", nil, resource.Invalid("文件上传请求超过大小限制")
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit+(64<<10))
|
||||
e := r.ParseMultipartForm(1 << 20)
|
||||
if r.MultipartForm != nil {
|
||||
defer r.MultipartForm.RemoveAll()
|
||||
}
|
||||
if e != nil || r.MultipartForm == nil {
|
||||
return "", nil, resource.Invalid("请上传不超过 32 MiB 的文件")
|
||||
return "", nil, resource.Invalid("请上传不超过 100 MiB 的文件")
|
||||
}
|
||||
files := r.MultipartForm.File["file"]
|
||||
if len(files) != 1 || len(r.MultipartForm.File) != 1 {
|
||||
return "", nil, resource.Invalid("请上传一个 file 文件")
|
||||
}
|
||||
if files[0].Size <= 0 || files[0].Size > limit {
|
||||
return "", nil, resource.Invalid("文件大小无效")
|
||||
}
|
||||
f, e := files[0].Open()
|
||||
if e != nil {
|
||||
return "", nil, e
|
||||
}
|
||||
defer f.Close()
|
||||
b, e := io.ReadAll(io.LimitReader(f, importFileLimit+1))
|
||||
// Multipart parsing measured the actual bytes and spilled large files to disk.
|
||||
// Allocate exactly once instead of growing a 100 MiB ReadAll buffer.
|
||||
b := make([]byte, int(files[0].Size))
|
||||
_, e = io.ReadFull(f, b)
|
||||
if e != nil {
|
||||
return "", nil, e
|
||||
}
|
||||
if len(b) == 0 || len(b) > importFileLimit {
|
||||
if len(b) == 0 || int64(len(b)) > limit {
|
||||
return "", nil, resource.Invalid("文件大小无效")
|
||||
}
|
||||
return path.Base(strings.ReplaceAll(files[0].Filename, "\\", "/")), b, nil
|
||||
@@ -164,22 +179,7 @@ func (s *Service) handleFileImport(w http.ResponseWriter, r *http.Request, admin
|
||||
return
|
||||
}
|
||||
if op == "upload" && !strings.HasPrefix(r.Header.Get("Content-Type"), "application/json") {
|
||||
var name string
|
||||
var data []byte
|
||||
name, data, e = readImportMultipart(w, r)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
var uploaded resource.Object
|
||||
c.DocumentID, e = multipartDocumentID(c, r.PostFormValue("upload_key"), name, data)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
uploaded, e = s.uploadFileImport(ctx, c, name, data, false)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
c, e = s.verifyImport(uploaded.String("import_context"), "import")
|
||||
c, e = s.storeMultipartOriginal(w, r, c)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
@@ -215,6 +215,29 @@ func (s *Service) handleFileImport(w http.ResponseWriter, r *http.Request, admin
|
||||
}
|
||||
}
|
||||
|
||||
// Release the shared byte-buffer slot before any synchronous conversion or model call.
|
||||
func (s *Service) storeMultipartOriginal(w http.ResponseWriter, r *http.Request, c importContext) (importContext, error) {
|
||||
ctx := r.Context()
|
||||
release, err := acquireImportSlot(ctx, fileUploads)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
defer release()
|
||||
name, data, err := readImportMultipart(w, r)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
c.DocumentID, err = multipartDocumentID(c, r.PostFormValue("upload_key"), name, data)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
uploaded, err := s.uploadFileImport(ctx, c, name, data, false)
|
||||
if err != nil {
|
||||
return c, err
|
||||
}
|
||||
return s.verifyImport(uploaded.String("import_context"), "import")
|
||||
}
|
||||
|
||||
// Bind browser retries to the same original without allowing callers to choose a document ID.
|
||||
func multipartDocumentID(c importContext, key, name string, data []byte) (string, error) {
|
||||
if key == "" {
|
||||
@@ -441,6 +464,11 @@ func (s *Service) serveOriginal(w http.ResponseWriter, r *http.Request, admin bo
|
||||
resource.Fail(ctx, w, e)
|
||||
return
|
||||
}
|
||||
s.writeOriginal(w, r, doc, r.URL.Query().Get("preview") == "true")
|
||||
}
|
||||
|
||||
func (s *Service) writeOriginal(w http.ResponseWriter, r *http.Request, doc resource.Object, preview bool) {
|
||||
ctx := r.Context()
|
||||
storage, ok := s.storage.(ImportStorage)
|
||||
if !ok || doc.String("storage_key") == "" {
|
||||
resource.Fail(ctx, w, resource.NotFound)
|
||||
@@ -458,9 +486,9 @@ func (s *Service) serveOriginal(w http.ResponseWriter, r *http.Request, admin bo
|
||||
kind = "application/octet-stream"
|
||||
}
|
||||
disposition := "attachment"
|
||||
if r.URL.Query().Get("preview") == "true" && (doc.String("file_type") == "pdf" || imageFileType(doc.String("file_type"))) {
|
||||
if preview && (doc.String("file_type") == "pdf" || imageFileType(doc.String("file_type"))) {
|
||||
disposition = "inline"
|
||||
kind = map[string]string{"pdf": "application/pdf", "jpg": "image/jpeg", "png": "image/png"}[doc.String("file_type")]
|
||||
kind = map[string]string{"pdf": "application/pdf", "jpg": "image/jpeg", "png": "image/png", "webp": "image/webp"}[doc.String("file_type")]
|
||||
}
|
||||
f, e := storage.Get(ctx, doc.String("storage_key"))
|
||||
if e != nil {
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -151,3 +153,69 @@ func TestCSVImportIsDirectAndEditable(t *testing.T) {
|
||||
t.Fatal("CSV sent to conversion")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportMultipartSizeBoundary(t *testing.T) {
|
||||
for _, size := range []int{0, 1024, 1025} {
|
||||
body, kind := mcpFileBody(t, "source.pdf", bytes.Repeat([]byte("x"), size))
|
||||
request := httptest.NewRequest("POST", "/", body)
|
||||
request.Header.Set("Content-Type", kind)
|
||||
_, data, err := readImportMultipartLimit(httptest.NewRecorder(), request, 1024)
|
||||
if size == 1024 {
|
||||
if err != nil || len(data) != size {
|
||||
t.Fatalf("boundary rejected: %v", err)
|
||||
}
|
||||
} else if err == nil {
|
||||
t.Fatalf("invalid size %d accepted", size)
|
||||
}
|
||||
}
|
||||
// An over-limit chunked request must be bounded by actual bytes, not its header.
|
||||
body, kind := mcpFileBody(t, "source.pdf", bytes.Repeat([]byte("x"), (64<<10)+1025))
|
||||
request := httptest.NewRequest("POST", "/", body)
|
||||
request.ContentLength = -1
|
||||
request.Header.Set("Content-Type", kind)
|
||||
if _, _, err := readImportMultipartLimit(httptest.NewRecorder(), request, 1024); err == nil {
|
||||
t.Fatal("oversized chunked upload accepted")
|
||||
}
|
||||
request = httptest.NewRequest("POST", "/", nil)
|
||||
request.ContentLength = importFileLimit + (64 << 10) + 1
|
||||
if _, _, err := readImportMultipart(httptest.NewRecorder(), request); err == nil {
|
||||
t.Fatal("over-limit Content-Length accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportMultipartAbovePreviousLimit(t *testing.T) {
|
||||
// Exercise the real spill-to-disk path above the previous 32 MiB ceiling.
|
||||
original := bytes.Repeat([]byte("x"), 33<<20)
|
||||
body, kind := mcpFileBody(t, "large.pdf", original)
|
||||
request := httptest.NewRequest("POST", "/", body)
|
||||
request.Header.Set("Content-Type", kind)
|
||||
_, got, err := readImportMultipart(httptest.NewRecorder(), request)
|
||||
if err != nil || !bytes.Equal(got, original) {
|
||||
t.Fatalf("large upload changed or rejected: %v", err)
|
||||
}
|
||||
if importFileLimit != 100<<20 {
|
||||
t.Fatal("unexpected original size limit")
|
||||
}
|
||||
// Parsing temp files must have been removed even after the bytes were returned.
|
||||
if f, err := request.MultipartForm.File["file"][0].Open(); err == nil {
|
||||
f.Close()
|
||||
t.Fatal("multipart temporary file was not removed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLargeImageUploadAndReadback(t *testing.T) {
|
||||
data := make([]byte, imageUploadLimit+1)
|
||||
copy(data, avatarImage(t, "png"))
|
||||
name, _, err := readContentImage(data[:imageUploadLimit])
|
||||
if err != nil {
|
||||
t.Fatalf("100 MiB image rejected: %v", err)
|
||||
}
|
||||
service := NewService(nil, nil).WithStorage(&avatarStorage{files: map[string][]byte{assetObjectKey("book", name): data[:imageUploadLimit]}})
|
||||
got, _, err := service.readAsset(t.Context(), "book", name)
|
||||
if err != nil || !bytes.Equal(got, data[:imageUploadLimit]) {
|
||||
t.Fatalf("image readback: %v", err)
|
||||
}
|
||||
if _, _, err := readContentImage(data); err == nil {
|
||||
t.Fatal("oversized image accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
// Preserve source bytes outside image tags, including the position of each image.
|
||||
func replaceHTMLImages(content string, describe func(string) (string, error)) (string, error) {
|
||||
return replaceHTMLImagesMatching(content, embeddedImage, describe)
|
||||
}
|
||||
|
||||
func replaceHTMLImagesMatching(content string, matches func(string) bool, describe func(string) (string, error)) (string, error) {
|
||||
z := html.NewTokenizer(strings.NewReader(content))
|
||||
var out strings.Builder
|
||||
for {
|
||||
kind := z.Next()
|
||||
if kind == html.ErrorToken {
|
||||
if z.Err() != io.EOF {
|
||||
return "", z.Err()
|
||||
}
|
||||
break
|
||||
}
|
||||
raw := string(z.Raw())
|
||||
replacement := raw
|
||||
if kind == html.StartTagToken || kind == html.SelfClosingTagToken {
|
||||
token := z.Token()
|
||||
if token.Data == "img" {
|
||||
for _, attr := range token.Attr {
|
||||
source := strings.TrimSpace(attr.Val)
|
||||
if attr.Key != "src" || !matches(source) {
|
||||
continue
|
||||
}
|
||||
value, err := describe(source)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
replacement = "<span>" + html.EscapeString("[图片描述:"+value+"]") + "</span>"
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
out.WriteString(replacement)
|
||||
if out.Len() > importContentLimit {
|
||||
return "", resource.Invalid("转换后的正文超过 16 MiB")
|
||||
}
|
||||
}
|
||||
result := out.String()
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) describeLearningImages(ctx context.Context, document, book resource.Object) (string, error) {
|
||||
concurrency, err := s.visionConcurrency(ctx)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return describeDocumentImagesParallel(ctx, document.String("content"), document.String("file_type"), concurrency, func(ctx context.Context, data []byte, mime string) (string, error) {
|
||||
if s.vision == nil {
|
||||
return "", resource.Invalid("知识库图片解析服务不可用")
|
||||
}
|
||||
actor := document.String("created_by_user_id")
|
||||
if _, err := s.storeContentImage(ctx, actor, document.String("kb_id"), book.String("ownership_type") == "system", func() ([]byte, error) { return data, nil }); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s.describeVisionImage(ctx, actor, mime, data)
|
||||
})
|
||||
}
|
||||
|
||||
// Markdown code and comments must not turn example tags into vision requests.
|
||||
func replaceMarkdownHTMLImages(content string, matches func(string) bool, describe func(string) (string, error)) (string, error) {
|
||||
spans := importHTMLImage.FindAllStringIndex(importLinkSource(content), -1)
|
||||
for i := len(spans) - 1; i >= 0; i-- {
|
||||
span := spans[i]
|
||||
if importEscaped(content, span[0]) {
|
||||
continue
|
||||
}
|
||||
replacement, err := replaceHTMLImagesMatching(content[span[0]:span[1]], matches, describe)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
content = content[:span[0]] + replacement + content[span[1]:]
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestHTMLImageDescriptionsPreservePosition(t *testing.T) {
|
||||
data := avatarImage(t, "png")
|
||||
source := "data:image/png;base64," + base64.StdEncoding.EncodeToString(data)
|
||||
input := `<p>前文</p><IMG SRC="` + source + `" alt="old"><p>中间</p><img src='` + source + `'/><p>后文</p>`
|
||||
calls := 0
|
||||
got, err := describeDocumentImages(input, "html", func(b []byte, mime string) (string, error) {
|
||||
calls++
|
||||
if !bytes.Equal(b, data) || mime != "image/png" {
|
||||
t.Fatal("incorrect image bytes")
|
||||
}
|
||||
return "狗 & <草地>", nil
|
||||
})
|
||||
expected := `<p>前文</p><span>[图片描述:狗 & <草地>]</span><p>中间</p><span>[图片描述:狗 & <草地>]</span><p>后文</p>`
|
||||
if err != nil || got != expected || calls != 1 {
|
||||
t.Fatalf("got=%q calls=%d err=%v", got, calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTMLImageDescriptionFailures(t *testing.T) {
|
||||
source := "data:image/png;base64," + base64.StdEncoding.EncodeToString(avatarImage(t, "png"))
|
||||
for _, input := range []string{`<img src="data:image/png;base64,???">`, `<img src="data:image/png;base64,aGVsbG8=">`, `<img srcset="` + source + ` 1x">`, `<img src="` + source + `">`} {
|
||||
got, err := describeDocumentImages(input, "html", func([]byte, string) (string, error) { return "", errors.New("vision unavailable") })
|
||||
if err == nil || got != "" {
|
||||
t.Fatalf("accepted failed conversion: %q %v", got, err)
|
||||
}
|
||||
}
|
||||
input := `<p>正文</p><img src="https://example.test/a.png">`
|
||||
got, err := describeDocumentImages(input, "html", func([]byte, string) (string, error) { t.Fatal("unexpected image download"); return "", nil })
|
||||
if err != nil || got != input {
|
||||
t.Fatalf("changed ordinary HTML: %q %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLearningImagesPreservesOriginal(t *testing.T) {
|
||||
for _, kind := range []string{"html", "svg", "md"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
s, kbID, docID := seedLearningKB(t, pool, actor, OperationRebuildParse, "pending")
|
||||
storage := &avatarStorage{files: map[string][]byte{}}
|
||||
vision := &visionStub{content: "一只棕色的狗坐在草地上"}
|
||||
s.WithStorage(storage).WithImageDescriber(vision)
|
||||
s.models = callbackEmbedder(func(_ context.Context, _, content string) (model.EmbeddingResult, error) {
|
||||
if strings.Contains(content, "base64") || !strings.Contains(content, "棕色") {
|
||||
t.Fatal("embedding received raw image")
|
||||
}
|
||||
if kind == "html" && (strings.Contains(content, "<p>") || strings.Contains(content, "<span>")) {
|
||||
t.Fatal("HTML markup reached embedding")
|
||||
}
|
||||
return model.EmbeddingResult{Vector: []float64{1, 2, 3}}, nil
|
||||
})
|
||||
source := "data:image/png;base64," + base64.StdEncoding.EncodeToString(avatarImage(t, "png"))
|
||||
input := imageDocument(kind, source)
|
||||
if _, err := pool.Exec(t.Context(), `UPDATE knowledge_base_documents SET file_type=$3,content=$2 WHERE id=$1`, docID, input, kind); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Start with stale chunks to exercise the explicit restudy entry.
|
||||
if _, err := pool.Exec(t.Context(), `INSERT INTO knowledge_base_chunks(kb_id,document_id,chunk_index,content) VALUES($1,$2,0,'stale image chunk')`, kbID, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(t.Context(), `UPDATE knowledge_base_documents SET chunk_count=1 WHERE id=$1`, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(t.Context(), `UPDATE knowledge_base_learning_jobs SET document_id=$2 WHERE kb_id=$1`, kbID, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := s.RestudyDocument(t.Context(), docID)
|
||||
if err != nil || pending.String("status") != "pending" || pending.String("content") != input {
|
||||
t.Fatalf("pending=%v err=%v", pending, err)
|
||||
}
|
||||
oldChunks, err := s.ListChunks(t.Context(), docID)
|
||||
if err != nil || len(oldChunks) != 0 {
|
||||
t.Fatalf("old chunks=%v err=%v", oldChunks, err)
|
||||
}
|
||||
if worked, err := s.runLearningJob(t.Context()); err != nil || !worked {
|
||||
t.Fatalf("worked=%v err=%v", worked, err)
|
||||
}
|
||||
doc, err := s.GetDocument(t.Context(), docID)
|
||||
if err != nil || doc.String("status") != "learned" || doc.String("content") != input {
|
||||
t.Fatalf("doc=%v err=%v", doc, err)
|
||||
}
|
||||
if vision.calls != 1 || len(storage.files) != 1 {
|
||||
t.Fatalf("calls=%d assets=%d kb=%s", vision.calls, len(storage.files), kbID)
|
||||
}
|
||||
chunks, err := s.ListChunks(t.Context(), docID)
|
||||
if err != nil || len(chunks) == 0 {
|
||||
t.Fatalf("chunks=%v err=%v", chunks, err)
|
||||
}
|
||||
for _, chunk := range chunks {
|
||||
if kind == "html" && strings.Contains(chunk.String("content"), "<span>") {
|
||||
t.Fatal("HTML markup in chunks")
|
||||
}
|
||||
if strings.Contains(chunk.String("content"), "base64") {
|
||||
t.Fatal("raw image in chunks")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func imageDocument(kind, source string) string {
|
||||
switch kind {
|
||||
case "svg":
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><text>前文</text><image xlink:href="` + source + `"></image><text>后文</text></svg>`
|
||||
case "md":
|
||||
return "前文\n\n\n\n后文"
|
||||
default:
|
||||
return `<p>前文</p><img src="` + source + `"><p>后文</p>`
|
||||
}
|
||||
}
|
||||
|
||||
func TestLearningImageFormats(t *testing.T) {
|
||||
source := "data:image/png;base64," + base64.StdEncoding.EncodeToString(avatarImage(t, "png"))
|
||||
for _, tc := range []struct{ kind, input string }{
|
||||
{"html", imageDocument("html", source)},
|
||||
{"svg", imageDocument("svg", source)},
|
||||
{"svg", `<svg><image href="` + source + `"/></svg>`},
|
||||
{"md", imageDocument("md", source)},
|
||||
{"md", "前文\n\n![照片][pic]\n\n后文\n\n[pic]: " + source},
|
||||
{"md", imageDocument("html", source)},
|
||||
} {
|
||||
t.Run(tc.kind, func(t *testing.T) {
|
||||
calls := 0
|
||||
got, err := describeDocumentImages(tc.input, tc.kind, func([]byte, string) (string, error) { calls++; return "棕色小狗", nil })
|
||||
if err != nil || calls != 1 || !strings.Contains(got, "棕色小狗") || strings.Contains(got, "base64") {
|
||||
t.Fatalf("got=%s calls=%d err=%v", got, calls, err)
|
||||
}
|
||||
if strings.Contains(tc.input, "前文") && !(strings.Index(got, "前文") < strings.Index(got, "棕色小狗") && strings.Index(got, "棕色小狗") < strings.Index(got, "后文")) {
|
||||
t.Fatal("image position changed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageFailureStillCompletesLearning(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
s, kbID, docID := seedLearningKB(t, pool, actor, OperationRebuildParse, "pending")
|
||||
vision := &visionStub{content: ""}
|
||||
s.WithStorage(&avatarStorage{files: map[string][]byte{}}).WithImageDescriber(vision)
|
||||
s.models = callbackEmbedder(func(_ context.Context, _, content string) (model.EmbeddingResult, error) {
|
||||
if !strings.Contains(content, "图片识别失败") || strings.Contains(content, "base64") {
|
||||
t.Errorf("unexpected embedding input: %q", content)
|
||||
}
|
||||
return model.EmbeddingResult{Vector: []float64{1, 2, 3}}, nil
|
||||
})
|
||||
input := imageDocument("html", "data:image/png;base64,"+base64.StdEncoding.EncodeToString(avatarImage(t, "png")))
|
||||
if _, err := pool.Exec(t.Context(), `UPDATE knowledge_base_documents SET file_type='html',content=$2 WHERE id=$1`, docID, input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(t.Context(), `UPDATE knowledge_base_learning_jobs SET document_id=$2 WHERE kb_id=$1`, kbID, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if worked, err := s.runLearningJob(t.Context()); err != nil || !worked {
|
||||
t.Fatalf("worked=%v err=%v", worked, err)
|
||||
}
|
||||
doc, err := s.GetDocument(t.Context(), docID)
|
||||
if err != nil || doc.String("status") != "learned" || doc.String("content") != input || objectInt64(doc["chunk_count"]) == 0 || vision.calls != 3 {
|
||||
t.Fatalf("doc=%v calls=%d err=%v", doc, vision.calls, err)
|
||||
}
|
||||
var attempts int
|
||||
var status string
|
||||
if err := pool.QueryRow(t.Context(), `SELECT attempts,status FROM knowledge_base_learning_jobs WHERE document_id=$1`, docID).Scan(&attempts, &status); err != nil || attempts != 1 || status != "succeeded" {
|
||||
t.Fatalf("attempts=%d status=%s err=%v", attempts, status, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarkdownAndHTMLShareEmbeddedImage(t *testing.T) {
|
||||
source := "data:image/png;base64," + base64.StdEncoding.EncodeToString(avatarImage(t, "png"))
|
||||
calls := 0
|
||||
got, err := describeDocumentImagesParallel(t.Context(), "\n\n<img src=\""+source+"\">", "md", 2, func(context.Context, []byte, string) (string, error) { calls++; return "共同描述", nil })
|
||||
if err != nil || calls != 1 || strings.Count(got, "共同描述") != 2 || strings.Contains(got, "base64") {
|
||||
t.Fatalf("got=%s calls=%d err=%v", got, calls, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
// htmlLearningText extracts body text without executing HTML or fetching assets.
|
||||
// This is structural extraction, not browser CSS/layout evaluation.
|
||||
func htmlLearningText(source string) (string, error) {
|
||||
root, err := html.Parse(strings.NewReader(source))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var out strings.Builder
|
||||
var walk func(*html.Node)
|
||||
walk = func(n *html.Node) {
|
||||
block := false
|
||||
if n.Type == html.ElementNode {
|
||||
switch n.Data {
|
||||
case "head", "script", "style", "template", "noscript", "iframe", "object", "embed":
|
||||
return
|
||||
}
|
||||
for _, attr := range n.Attr {
|
||||
if attr.Key == "hidden" || (attr.Key == "aria-hidden" && strings.EqualFold(strings.TrimSpace(attr.Val), "true")) {
|
||||
return
|
||||
}
|
||||
}
|
||||
switch n.Data {
|
||||
case "p", "div", "section", "article", "header", "footer", "main", "nav", "aside", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li", "dl", "dt", "dd", "blockquote", "pre", "table", "tr", "br", "hr":
|
||||
block = true
|
||||
out.WriteByte('\n')
|
||||
case "td", "th":
|
||||
out.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
if n.Type == html.TextNode {
|
||||
out.WriteString(n.Data)
|
||||
}
|
||||
for child := n.FirstChild; child != nil; child = child.NextSibling {
|
||||
walk(child)
|
||||
}
|
||||
if block {
|
||||
out.WriteByte('\n')
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
var lines []string
|
||||
for _, line := range strings.Split(out.String(), "\n") {
|
||||
if line = strings.Join(strings.Fields(line), " "); line != "" {
|
||||
lines = append(lines, line)
|
||||
}
|
||||
}
|
||||
return strings.Join(lines, "\n"), nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHTMLLearningText(t *testing.T) {
|
||||
input := `<!doctype html><html><head><title>metadata</title><style>.secret { color:red }</style></head><body><!--comment--><h1>部署文档</h1><p class="classsecret" style="background: red">前文<strong>强调</strong>&后文</p><script>javascriptsecret()</script><template>templatesecret</template><div hidden>hiddensecret</div><div aria-hidden="true">ariasecret</div><p>下一段<br>换行</p><table><tr><td>甲</td><td>乙</td></tr></table><p><示例></p></body></html>`
|
||||
got, err := htmlLearningText(input)
|
||||
want := "部署文档\n前文强调&后文\n下一段\n换行\n甲 乙\n<示例>"
|
||||
if err != nil || got != want {
|
||||
t.Fatalf("got=%q err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTMLLearningImageDescriptionBecomesBodyText(t *testing.T) {
|
||||
source := "data:image/png;base64," + base64.StdEncoding.EncodeToString(avatarImage(t, "png"))
|
||||
converted, err := describeDocumentImages(`<p>前文</p><img src="`+source+`"><p>后文</p>`, "html", func([]byte, string) (string, error) { return "图片包含 <标签> & 文字", nil })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := htmlLearningText(converted)
|
||||
if err != nil || got != "前文\n[图片描述:图片包含 <标签> & 文字]\n后文" {
|
||||
t.Fatalf("got=%q err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHTMLLearningCSSDoesNotCreateChunks(t *testing.T) {
|
||||
got, err := htmlLearningText("<style>" + strings.Repeat(".css {color: red}", 10000) + "</style><p>正文</p>")
|
||||
if err != nil || got != "正文" || len(splitContent(got)) != 1 {
|
||||
t.Fatalf("got=%q err=%v", got, err)
|
||||
}
|
||||
got, err = htmlLearningText("<style>body{color:red}</style><script>alert(1)</script>")
|
||||
if err != nil || len(splitContent(got)) != 0 {
|
||||
t.Fatalf("non-body content created chunks: %q %v", got, err)
|
||||
}
|
||||
}
|
||||
@@ -20,11 +20,11 @@ import (
|
||||
_ "golang.org/x/image/webp"
|
||||
)
|
||||
|
||||
const imageUploadLimit = 32 << 20
|
||||
const imageUploadLimit = importFileLimit
|
||||
|
||||
func readContentImage(data []byte) (string, string, error) {
|
||||
if len(data) == 0 || len(data) > imageUploadLimit {
|
||||
return "", "", resource.Invalid("图片不能为空且不能超过 32 MiB")
|
||||
return "", "", resource.Invalid("图片不能为空且不能超过 100 MiB")
|
||||
}
|
||||
config, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
ext := map[string]string{"png": "png", "jpeg": "jpg", "gif": "gif", "webp": "webp", "bmp": "bmp", "tiff": "tiff"}[format]
|
||||
@@ -54,14 +54,14 @@ func (s *Service) uploadContentImage(w http.ResponseWriter, r *http.Request, adm
|
||||
defer r.MultipartForm.RemoveAll()
|
||||
}
|
||||
if parseErr != nil || r.MultipartForm == nil {
|
||||
return nil, resource.Invalid("请通过 multipart/form-data 上传不超过 32 MiB 的图片")
|
||||
return nil, resource.Invalid("请通过 multipart/form-data 上传不超过 100 MiB 的图片")
|
||||
}
|
||||
files := r.MultipartForm.File["file"]
|
||||
if len(files) != 1 || len(r.MultipartForm.File) != 1 {
|
||||
return nil, resource.Invalid("请使用 file 字段上传一张图片")
|
||||
}
|
||||
if files[0].Size > imageUploadLimit {
|
||||
return nil, resource.Invalid("图片不能超过 32 MiB")
|
||||
return nil, resource.Invalid("图片不能超过 100 MiB")
|
||||
}
|
||||
file, err := files[0].Open()
|
||||
if err != nil {
|
||||
|
||||
@@ -13,8 +13,11 @@ import (
|
||||
|
||||
// These limits are shared by all knowledge-base services in this process.
|
||||
// AnyDoc's own parser limit governs asynchronous work after create returns.
|
||||
// Bound the full original buffer across both REST and MCP multipart uploads.
|
||||
var fileUploads = make(chan struct{}, 1)
|
||||
|
||||
var anydocSubmissions = make(chan struct{}, 2)
|
||||
var imageSubmissions = make(chan struct{}, 2)
|
||||
var imageSubmissions = make(chan struct{}, 10)
|
||||
|
||||
func acquireImportSlot(ctx context.Context, slots chan struct{}) (func(), error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
@@ -33,7 +36,7 @@ func acquireImportSlot(ctx context.Context, slots chan struct{}) (func(), error)
|
||||
}
|
||||
|
||||
func multipartImportInput(formValue func(string) string) fileImportInput {
|
||||
in := fileImportInput{Title: formValue("title"), ModelID: formValue("model_id")}
|
||||
in := fileImportInput{Title: formValue("title")}
|
||||
if parent := formValue("parent_id"); parent != "" {
|
||||
in.ParentID = &parent
|
||||
}
|
||||
@@ -49,7 +52,7 @@ func (s *Service) startFileImport(ctx context.Context, c importContext, in fileI
|
||||
if existing, err := s.mcpImportExisting(ctx, c); err != nil || existing != nil {
|
||||
return existing, err
|
||||
}
|
||||
// Once an attempt has started, its title, destination, model and callback
|
||||
// Once an attempt has started, its title, destination and callback
|
||||
// deadline stay stable across retries, including a lost create response.
|
||||
if c.Task == "" {
|
||||
c.ImportTitle = strings.TrimSpace(in.Title)
|
||||
@@ -61,13 +64,9 @@ func (s *Service) startFileImport(ctx context.Context, c importContext, in fileI
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.ModelID = strings.TrimSpace(in.ModelID)
|
||||
c.Task = c.DocumentID
|
||||
c.TaskExpires = min(c.Expires, time.Now().Add(30*time.Minute).Unix())
|
||||
}
|
||||
if imageFileType(c.Type) && strings.TrimSpace(in.ModelID) != "" {
|
||||
c.ModelID = strings.TrimSpace(in.ModelID)
|
||||
}
|
||||
if c.TargetParent != nil {
|
||||
parent, err := s.documentInKB(ctx, c.KB, *c.TargetParent)
|
||||
if err != nil {
|
||||
@@ -100,7 +99,7 @@ func (s *Service) startFileImport(ctx context.Context, c importContext, in fileI
|
||||
return base, nil
|
||||
}
|
||||
if imageFileType(c.Type) {
|
||||
saved, err := s.processImageImport(ctx, c, c.ModelID, true)
|
||||
saved, err := s.processImageImport(ctx, c, true)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIndexJobSummaryCountsCurrentFailedDocuments(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
s, kbID, docID := seedLearningKB(t, pool, actor, OperationLearn, "failed")
|
||||
ctx := t.Context()
|
||||
if _, err := pool.Exec(ctx, `UPDATE knowledge_base_learning_jobs SET status='canceled' WHERE kb_id=$1`, kbID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Three historical attempts for one document must not appear as three failures.
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO knowledge_base_learning_jobs(kb_id,document_id,operation,status)
|
||||
SELECT $1::uuid,$2::uuid,'learn','failed' FROM generate_series(1,3)`, kbID, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertSummary := func(failed, pending, running int64) {
|
||||
t.Helper()
|
||||
item, err := s.Get(ctx, kbID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
summary := item["index_job_summary"].(resource.Object)
|
||||
if objectInt64(summary["failed"]) != failed || objectInt64(summary["pending"]) != pending || objectInt64(summary["running"]) != running {
|
||||
t.Fatalf("summary=%v, want failed=%d pending=%d running=%d", summary, failed, pending, running)
|
||||
}
|
||||
var operationFailures int64
|
||||
for _, counts := range summary["by_operation"].(map[string]any) {
|
||||
operationFailures += objectInt64(counts.(map[string]any)["failed"])
|
||||
}
|
||||
if operationFailures != failed {
|
||||
t.Fatalf("operation failures=%d, total=%d", operationFailures, failed)
|
||||
}
|
||||
}
|
||||
assertSummary(1, 0, 0)
|
||||
var retryID string
|
||||
if err := pool.QueryRow(ctx, `INSERT INTO knowledge_base_learning_jobs(kb_id,document_id,operation,status)
|
||||
VALUES($1,$2,'relearn','pending') RETURNING id::text`, kbID, docID).Scan(&retryID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertSummary(0, 1, 0)
|
||||
if _, err := pool.Exec(ctx, `UPDATE knowledge_base_learning_jobs SET status='running' WHERE id=$1`, retryID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertSummary(0, 0, 1)
|
||||
// Vector failure can leave a failed document with a succeeded job.
|
||||
if _, err := pool.Exec(ctx, `UPDATE knowledge_base_learning_jobs SET status='succeeded' WHERE id=$1`, retryID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertSummary(1, 0, 0)
|
||||
if _, err := pool.Exec(ctx, `UPDATE knowledge_base_documents SET status='learned' WHERE id=$1`, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertSummary(0, 0, 0)
|
||||
var history int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM knowledge_base_learning_jobs WHERE kb_id=$1 AND status='failed'`, kbID).Scan(&history); err != nil || history != 3 {
|
||||
t.Fatalf("history=%d err=%v", history, err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM knowledge_base_documents WHERE id=$1`, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertSummary(0, 0, 0)
|
||||
}
|
||||
@@ -74,6 +74,8 @@ type learnedChunk struct {
|
||||
|
||||
var errLearningJobCanceled = errors.New("学习任务已取消")
|
||||
|
||||
var errVectorLearningFailed = errors.New("向量生成失败")
|
||||
|
||||
var errDocumentChanged = errors.New("文档已更新或删除")
|
||||
|
||||
func (s *Service) checkLearningJob(ctx context.Context, queries *sqlc.Queries, job sqlc.ClaimKbLearningJobRow) error {
|
||||
@@ -153,7 +155,7 @@ func (s *Service) learnDocument(ctx context.Context, id string, job sqlc.ClaimKb
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
if resultErr != nil && !errors.Is(resultErr, errDocumentChanged) && !errors.Is(resultErr, errLearningJobCanceled) {
|
||||
if resultErr != nil && !errors.Is(resultErr, errVectorLearningFailed) && !errors.Is(resultErr, errDocumentChanged) && !errors.Is(resultErr, errLearningJobCanceled) {
|
||||
resultErr = errors.Join(resultErr, s.failLearningDocument(ctx, document, job, resultErr))
|
||||
}
|
||||
}()
|
||||
@@ -164,9 +166,28 @@ func (s *Service) learnDocument(ctx context.Context, id string, job sqlc.ClaimKb
|
||||
if len(document.String("content")) > importContentLimit {
|
||||
return resource.Invalid("正文超过 16 MiB")
|
||||
}
|
||||
chunks := splitContent(document.String("content"))
|
||||
content := document.String("content")
|
||||
if kind := document.String("file_type"); kind == "html" || kind == "svg" || kind == "md" {
|
||||
content, err = s.describeLearningImages(ctx, document, knowledgeBase)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if convertedFileType(document.String("file_type")) {
|
||||
content, err = s.describeConvertedImages(ctx, document, knowledgeBase)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if document.String("file_type") == "html" {
|
||||
content, err = htmlLearningText(content)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
chunks := splitContent(content)
|
||||
if document.String("file_type") == "md" || !textFileType(document.String("file_type")) {
|
||||
chunks = splitMarkdown(document.String("content"))
|
||||
chunks = splitMarkdown(content)
|
||||
}
|
||||
vectorEnabled := modelID != "" && dimension > 0
|
||||
|
||||
@@ -276,7 +297,15 @@ func (s *Service) learnDocument(ctx context.Context, id string, job sqlc.ClaimKb
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
if err = queries.AdvanceKbLearningJobRevision(ctx, sqlc.AdvanceKbLearningJobRevisionParams{
|
||||
ID: job.ID, Attempts: job.Attempts, WorkerID: optionalString(s.workerID()),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w: %s", errVectorLearningFailed, message)
|
||||
}
|
||||
if err = queries.FinishKbDocumentLearning(ctx, sqlc.FinishKbDocumentLearningParams{
|
||||
ID: id,
|
||||
@@ -401,7 +430,15 @@ func (s *Service) rebuildDocumentVector(ctx context.Context, id string, job sqlc
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
if err = queries.AdvanceKbLearningJobRevision(ctx, sqlc.AdvanceKbLearningJobRevisionParams{
|
||||
ID: job.ID, Attempts: job.Attempts, WorkerID: optionalString(s.workerID()),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%w: %s", errVectorLearningFailed, message)
|
||||
}
|
||||
if err = queries.FinishKbDocumentVectorLearning(ctx, id); err != nil {
|
||||
return err
|
||||
|
||||
@@ -2,6 +2,8 @@ package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/model"
|
||||
"strings"
|
||||
@@ -109,3 +111,75 @@ func TestLearningSkipsUnsearchableChunksBeforeEmbedding(t *testing.T) {
|
||||
t.Fatalf("document=%v err=%v calls=%d index=%d vector=%v", document, err, calls, index, hasVector)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVectorFailureRetriesWholeJob(t *testing.T) {
|
||||
for _, operation := range []string{OperationLearn, OperationRebuildVector} {
|
||||
for _, recover := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("%s/recover=%v", operation, recover), func(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
ctx := t.Context()
|
||||
s, kbID, docID := seedLearningKB(t, pool, actor, operation, "learned")
|
||||
if _, err := pool.Exec(ctx, `UPDATE knowledge_base_learning_jobs SET document_id=$2 WHERE kb_id=$1`, kbID, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO knowledge_base_chunks(kb_id,document_id,chunk_index,content,search_tokens) VALUES($1,$2,0,'old content','old content')`, kbID, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
calls := 0
|
||||
s.models = callbackEmbedder(func(context.Context, string, string) (model.EmbeddingResult, error) {
|
||||
calls++
|
||||
if recover && calls == 3 {
|
||||
return model.EmbeddingResult{Vector: []float64{1, 2, 3}}, nil
|
||||
}
|
||||
return model.EmbeddingResult{}, errors.New("upstream vector failure")
|
||||
})
|
||||
for attempt := 1; attempt <= 3; attempt++ {
|
||||
worked, err := s.runLearningJob(ctx)
|
||||
success := recover && attempt == 3
|
||||
if !worked || (success && err != nil) || (!success && !errors.Is(err, errVectorLearningFailed)) {
|
||||
t.Fatalf("attempt=%d worked=%v err=%v", attempt, worked, err)
|
||||
}
|
||||
var status, message string
|
||||
var attempts int
|
||||
var finished, unlocked, delayed, revisionMatches bool
|
||||
if err := pool.QueryRow(ctx, `SELECT j.status,COALESCE(j.error_message,''),j.attempts,j.finished_at IS NOT NULL,j.locked_at IS NULL AND j.locked_by IS NULL,j.available_at > now(),j.document_revision=d.revision FROM knowledge_base_learning_jobs j JOIN knowledge_base_documents d ON j.document_id=d.id WHERE j.kb_id=$1`, kbID).Scan(&status, &message, &attempts, &finished, &unlocked, &delayed, &revisionMatches); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := "pending"
|
||||
if attempt == 3 {
|
||||
expected = "failed"
|
||||
}
|
||||
if success {
|
||||
expected = "succeeded"
|
||||
}
|
||||
if status != expected || attempts != attempt || !unlocked || finished != (attempt == 3) || (!success && (message == "" || !revisionMatches)) || (success && message != "") || (attempt < 3 && !delayed) {
|
||||
t.Fatalf("attempt=%d status=%s error=%s attempts=%d finished=%v unlocked=%v delayed=%v revision=%v", attempt, status, message, attempts, finished, unlocked, delayed, revisionMatches)
|
||||
}
|
||||
document, err := s.GetDocument(ctx, docID)
|
||||
expectedDocument := "failed"
|
||||
if success {
|
||||
expectedDocument = "learned"
|
||||
}
|
||||
if err != nil || document.String("status") != expectedDocument || objectInt64(document["chunk_count"]) != 1 {
|
||||
t.Fatalf("document=%v err=%v", document, err)
|
||||
}
|
||||
chunks, err := s.ListChunks(ctx, docID)
|
||||
if err != nil || len(chunks) != 1 {
|
||||
t.Fatalf("chunks=%v err=%v", chunks, err)
|
||||
}
|
||||
if worked, err := s.runLearningJob(ctx); worked || err != nil {
|
||||
t.Fatalf("job ran before delay or after completion: worked=%v err=%v", worked, err)
|
||||
}
|
||||
if attempt < 3 {
|
||||
if _, err := pool.Exec(ctx, `UPDATE knowledge_base_learning_jobs SET available_at=now()-interval '1 second' WHERE kb_id=$1`, kbID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if calls != 3 {
|
||||
t.Fatalf("vector calls=%d, want 3", calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/kb/sqlc"
|
||||
@@ -15,8 +16,7 @@ const learningWorkerPollInterval = time.Second
|
||||
const embeddingSyncInterval = 5 * time.Second
|
||||
|
||||
// Run consumes durable learning jobs until the application context is canceled.
|
||||
// A single worker keeps embedding pressure bounded; the claim query still uses
|
||||
// SKIP LOCKED so additional workers can be added without changing job semantics.
|
||||
// Admission is serialized in PostgreSQL so the configured limit spans instances.
|
||||
func (s *Service) Run(ctx context.Context) {
|
||||
// Reconcile independently so a long embedding task cannot delay discovering
|
||||
// newly available models. Stop the reconciler before Run returns.
|
||||
@@ -31,6 +31,15 @@ func (s *Service) Run(ctx context.Context) {
|
||||
}()
|
||||
defer func() { cancelSync(); <-syncDone }()
|
||||
|
||||
var workers sync.WaitGroup
|
||||
for range 20 {
|
||||
workers.Add(1)
|
||||
go func() { defer workers.Done(); s.runLearningWorker(ctx) }()
|
||||
}
|
||||
workers.Wait()
|
||||
}
|
||||
|
||||
func (s *Service) runLearningWorker(ctx context.Context) {
|
||||
ticker := time.NewTicker(learningWorkerPollInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
@@ -52,18 +61,61 @@ func (s *Service) Run(ctx context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) runLearningJob(ctx context.Context) (bool, error) {
|
||||
queries := sqlc.New(s.store.Pool)
|
||||
func (s *Service) runLearningJob(ctx context.Context) (worked bool, resultErr error) {
|
||||
tx, err := s.store.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
admission := sqlc.New(tx)
|
||||
if err = admission.LockKnowledgeLearningAdmission(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
config, err := readConcurrency(ctx, admission)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
active, err := admission.CountRunningKnowledgeJobs(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if active >= int64(config.Learning) {
|
||||
return false, nil
|
||||
}
|
||||
worker := s.workerID()
|
||||
job, err := queries.ClaimKbLearningJob(ctx, &worker)
|
||||
job, err := admission.ClaimKbLearningJob(ctx, &worker)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return false, err
|
||||
}
|
||||
queries := sqlc.New(s.store.Pool)
|
||||
// Cancellation changes business state before the execution goroutine exits.
|
||||
// Retain its lease as a concurrency slot until all work and heartbeat stop.
|
||||
defer func() {
|
||||
release, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
|
||||
defer cancel()
|
||||
resultErr = errors.Join(resultErr, queries.ReleaseCanceledKnowledgeJob(release, sqlc.ReleaseCanceledKnowledgeJobParams{
|
||||
ID: job.ID, Attempts: job.Attempts, WorkerID: &worker,
|
||||
}))
|
||||
}()
|
||||
|
||||
err = s.executeLearningJob(ctx, job)
|
||||
err = withLearningLease(ctx, 30*time.Second, func(run context.Context) error {
|
||||
return s.executeLearningJob(run, job)
|
||||
}, func(renew context.Context) error {
|
||||
count, err := queries.RenewKbLearningJob(renew, sqlc.RenewKbLearningJobParams{ID: job.ID, Attempts: job.Attempts, WorkerID: &worker})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count != 1 {
|
||||
return errLearningJobCanceled
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, errLearningJobCanceled) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/yuin/goldmark"
|
||||
"github.com/yuin/goldmark/ast"
|
||||
"github.com/yuin/goldmark/parser"
|
||||
"github.com/yuin/goldmark/text"
|
||||
"github.com/yuin/goldmark/util"
|
||||
"golang.org/x/net/html"
|
||||
)
|
||||
|
||||
// Only the returned learning copy is transformed; document content stays intact.
|
||||
func describeDocumentImages(content, kind string, describe func([]byte, string) (string, error)) (string, error) {
|
||||
return transformDocumentImages(content, kind, describe, false)
|
||||
}
|
||||
|
||||
func transformDocumentImages(content, kind string, describe func([]byte, string) (string, error), tolerateInvalid bool) (string, error) {
|
||||
cache := map[string]string{}
|
||||
resolve := func(source string) (value string, resultErr error) {
|
||||
defer func() {
|
||||
if tolerateInvalid && resultErr != nil {
|
||||
value = "图片解析失败:图片数据无效,未生成描述"
|
||||
resultErr = nil
|
||||
cache[source] = value
|
||||
}
|
||||
}()
|
||||
source = strings.TrimSpace(source)
|
||||
if value, ok := cache[source]; ok {
|
||||
return value, nil
|
||||
}
|
||||
header, encoded, ok := strings.Cut(source, ",")
|
||||
if !ok || !strings.HasSuffix(strings.ToLower(header), ";base64") {
|
||||
return "", resource.Invalid("内嵌图片必须使用 Base64 编码")
|
||||
}
|
||||
if len(encoded) > (imageUploadLimit+2)/3*4 {
|
||||
return "", resource.Invalid("内嵌图片过大")
|
||||
}
|
||||
data, err := base64.StdEncoding.Strict().DecodeString(encoded)
|
||||
if err != nil {
|
||||
return "", resource.Invalid("内嵌图片 Base64 无效")
|
||||
}
|
||||
_, mime, err := readContentImage(data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
value, err = describe(data, mime)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("第 %d 张内嵌图片识别失败: %w", len(cache)+1, err)
|
||||
}
|
||||
value, err = validateImportText([]byte(value))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if strings.Contains(strings.ToLower(value), "data:image/") {
|
||||
return "", resource.Invalid("图片描述不能包含内嵌图片数据")
|
||||
}
|
||||
cache[source] = value
|
||||
return value, nil
|
||||
}
|
||||
var result string
|
||||
var err error
|
||||
switch kind {
|
||||
case "svg":
|
||||
result, err = replaceSVGImages(content, resolve)
|
||||
case "md":
|
||||
result, err = replaceAllMarkdownImages(content, embeddedImage, resolve)
|
||||
default:
|
||||
result, err = replaceHTMLImages(content, resolve)
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if len(result) > importContentLimit {
|
||||
return "", resource.Invalid("转换后的学习文本超过 16 MiB")
|
||||
}
|
||||
// Clean reference definitions only after both Markdown and HTML image use
|
||||
// sites were replaced; a shared source must not erase a later HTML image.
|
||||
if kind == "md" {
|
||||
return cleanMarkdownImageReferences(result, cache)
|
||||
}
|
||||
if strings.Contains(strings.ToLower(result), "data:image/") {
|
||||
return "", resource.Invalid("文档存在不支持的内嵌图片位置")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func embeddedImage(source string) bool {
|
||||
return strings.HasPrefix(strings.ToLower(strings.TrimSpace(source)), "data:image/")
|
||||
}
|
||||
|
||||
var markdownImageDefinition = regexp.MustCompile(`(?m)^(?: {0,3}>[ \t]?)* {0,3}\[[^\]\n]+\]:[ \t]*(?:\r?\n[ \t]*(?:>[ \t]*)*)?(?:<([^<>\r\n]*)>|([^\s<>]+))`)
|
||||
var embeddedImagePayload = regexp.MustCompile(`(?i)data:image/[a-z0-9.+-]+(?:;[^,\s<>"']*)?,`)
|
||||
|
||||
func cleanMarkdownImageReferences(content string, cache map[string]string) (string, error) {
|
||||
if !strings.Contains(strings.ToLower(content), "data:image/") {
|
||||
return content, nil
|
||||
}
|
||||
source := importLinkSource(content)
|
||||
var out strings.Builder
|
||||
last := 0
|
||||
for _, m := range markdownImageDefinition.FindAllStringSubmatchIndex(source, -1) {
|
||||
start, end := m[2], m[3]
|
||||
if start < 0 {
|
||||
start, end = m[4], m[5]
|
||||
}
|
||||
target := content[start:end]
|
||||
if !embeddedImage(target) {
|
||||
continue
|
||||
}
|
||||
if embeddedImagePayload.MatchString(source[last:start]) {
|
||||
return "", resource.Invalid("文档存在不支持的内嵌图片位置")
|
||||
}
|
||||
if _, ok := cache[target]; !ok {
|
||||
return "", resource.Invalid("文档存在不支持的内嵌图片位置")
|
||||
}
|
||||
out.WriteString(content[last:start])
|
||||
out.WriteString("#embedded-image")
|
||||
last = end
|
||||
}
|
||||
if embeddedImagePayload.MatchString(source[last:]) {
|
||||
return "", resource.Invalid("文档存在不支持的内嵌图片位置")
|
||||
}
|
||||
if last == 0 {
|
||||
return content, nil
|
||||
}
|
||||
out.WriteString(content[last:])
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
func replaceSVGImages(content string, describe func(string) (string, error)) (string, error) {
|
||||
decoder := xml.NewDecoder(strings.NewReader(content))
|
||||
var out strings.Builder
|
||||
last := 0
|
||||
for {
|
||||
start := int(decoder.InputOffset())
|
||||
token, err := decoder.Token()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return "", resource.Invalid("SVG 文档格式无效")
|
||||
}
|
||||
element, ok := token.(xml.StartElement)
|
||||
if !ok || element.Name.Local != "image" {
|
||||
continue
|
||||
}
|
||||
for _, attr := range element.Attr {
|
||||
if attr.Name.Local != "href" || !embeddedImage(attr.Value) {
|
||||
continue
|
||||
}
|
||||
value, err := describe(attr.Value)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = decoder.Skip(); err != nil {
|
||||
return "", resource.Invalid("SVG 图片元素格式无效")
|
||||
}
|
||||
out.WriteString(content[last:start])
|
||||
out.WriteString("<text>" + html.EscapeString("[图片描述:"+value+"]") + "</text>")
|
||||
last = int(decoder.InputOffset())
|
||||
break
|
||||
}
|
||||
}
|
||||
out.WriteString(content[last:])
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
func replaceMarkdownImages(content string, describe func(string) (string, error)) (string, error) {
|
||||
return replaceMarkdownImagesMatching(content, embeddedImage, describe)
|
||||
}
|
||||
|
||||
func replaceMarkdownImagesMatching(content string, matches func(string) bool, describe func(string) (string, error)) (string, error) {
|
||||
return replaceMarkdownImageNodes(content, matches, describe, false)
|
||||
}
|
||||
|
||||
// Locate both syntaxes in the original source. Generated descriptions must never
|
||||
// influence code/comment detection or become input to another image scan.
|
||||
func replaceAllMarkdownImages(content string, matches func(string) bool, describe func(string) (string, error)) (string, error) {
|
||||
return replaceMarkdownImageNodes(content, matches, describe, true)
|
||||
}
|
||||
|
||||
func replaceMarkdownImageNodes(content string, matches func(string) bool, describe func(string) (string, error), includeHTML bool) (string, error) {
|
||||
tracker := &importImageParser{InlineParser: parser.NewLinkParser(), labels: map[ast.Node]int{}, images: map[*ast.Image]imageSpan{}}
|
||||
inline := parser.DefaultInlineParsers()
|
||||
for i, entry := range inline {
|
||||
if entry.Value == parser.NewLinkParser() {
|
||||
inline[i].Value = tracker
|
||||
}
|
||||
}
|
||||
md := goldmark.New(goldmark.WithParser(parser.NewParser(parser.WithBlockParsers(parser.DefaultBlockParsers()...), parser.WithInlineParsers(inline...), parser.WithParagraphTransformers(parser.DefaultParagraphTransformers()...))))
|
||||
root := md.Parser().Parse(text.NewReader([]byte(content)))
|
||||
type edit struct {
|
||||
start, end int
|
||||
value string
|
||||
}
|
||||
var edits []edit
|
||||
err := ast.Walk(root, func(n ast.Node, entering bool) (ast.WalkStatus, error) {
|
||||
image, ok := n.(*ast.Image)
|
||||
if !entering || !ok {
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
source := string(util.UnescapePunctuations(image.Destination))
|
||||
if !matches(source) {
|
||||
return ast.WalkContinue, nil
|
||||
}
|
||||
value, err := describe(source)
|
||||
if err != nil {
|
||||
return ast.WalkStop, err
|
||||
}
|
||||
span, ok := tracker.images[image]
|
||||
if !ok {
|
||||
return ast.WalkStop, resource.Invalid("无法定位 Markdown 图片")
|
||||
}
|
||||
// Preserve model output as escaped text in the replacement.
|
||||
edits = append(edits, edit{span.start, span.end, "<span>" + html.EscapeString("[图片描述:"+value+"]") + "</span>"})
|
||||
return ast.WalkSkipChildren, nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if includeHTML {
|
||||
for _, span := range importHTMLImage.FindAllStringIndex(importLinkSource(content), -1) {
|
||||
if importEscaped(content, span[0]) {
|
||||
continue
|
||||
}
|
||||
// An image's alt text or title can contain an img tag; the outer
|
||||
// Markdown replacement already owns that source range.
|
||||
overlaps := false
|
||||
for _, e := range edits {
|
||||
if span[0] < e.end && span[1] > e.start {
|
||||
overlaps = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if overlaps {
|
||||
continue
|
||||
}
|
||||
replacement, err := replaceHTMLImagesMatching(content[span[0]:span[1]], matches, describe)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
edits = append(edits, edit{span[0], span[1], replacement})
|
||||
}
|
||||
}
|
||||
if len(edits) == 0 {
|
||||
return content, nil
|
||||
}
|
||||
slices.SortFunc(edits, func(a, b edit) int { return a.start - b.start })
|
||||
var out strings.Builder
|
||||
last := 0
|
||||
for _, e := range edits {
|
||||
out.WriteString(content[last:e.start])
|
||||
out.WriteString(e.value)
|
||||
last = e.end
|
||||
}
|
||||
out.WriteString(content[last:])
|
||||
return out.String(), nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Cancel work when its lease cannot be renewed. Join the heartbeat before job
|
||||
// completion so it cannot race with a succeeded/failed status transition.
|
||||
func withLearningLease(ctx context.Context, interval time.Duration, run func(context.Context) error, renew func(context.Context) error) error {
|
||||
work, cancel := context.WithCancelCause(ctx)
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-work.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
refresh, stop := context.WithTimeout(work, 10*time.Second)
|
||||
err := renew(refresh)
|
||||
stop()
|
||||
if err != nil {
|
||||
cancel(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
err := run(work)
|
||||
cancel(nil)
|
||||
<-done
|
||||
if cause := context.Cause(work); cause != nil && cause != context.Canceled {
|
||||
return cause
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLearningLeaseRenewalAndLoss(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
|
||||
defer cancel()
|
||||
var calls atomic.Int32
|
||||
lost := errors.New("lease lost")
|
||||
err := withLearningLease(ctx, time.Millisecond, func(ctx context.Context) error { <-ctx.Done(); return ctx.Err() }, func(context.Context) error {
|
||||
if calls.Add(1) == 2 {
|
||||
return lost
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if !errors.Is(err, lost) || calls.Load() != 2 {
|
||||
t.Fatalf("err=%v calls=%d", err, calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLearningLeaseStopsAfterWork(t *testing.T) {
|
||||
expected := errors.New("processing failed")
|
||||
err := withLearningLease(t.Context(), time.Hour, func(context.Context) error { return expected }, func(context.Context) error { t.Error("unexpected heartbeat"); return nil })
|
||||
if !errors.Is(err, expected) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -164,7 +164,7 @@ func (s *Service) callMCPTool(ctx context.Context, userID string, params json.Ra
|
||||
if _, batch := call.Arguments["ids"]; batch {
|
||||
payload = item
|
||||
} else {
|
||||
payload = publicDocument(item)
|
||||
payload = s.agentDocument(item)
|
||||
}
|
||||
case "kb_upload_file", "kb_get_file_import_status":
|
||||
item, err := s.callMCPFileImport(ctx, userID, call.Name, call.Arguments)
|
||||
@@ -232,8 +232,8 @@ func (s *Service) callMCPTool(ctx context.Context, userID string, params json.Ra
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := publicDocument(item)
|
||||
if !includeContent {
|
||||
out := s.agentDocument(item)
|
||||
if !includeContent && hasReadableDocumentContent(item) {
|
||||
delete(out, "content")
|
||||
}
|
||||
payload = out
|
||||
@@ -246,7 +246,7 @@ func (s *Service) callMCPTool(ctx context.Context, userID string, params json.Ra
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload = publicDocument(item)
|
||||
payload = s.agentDocument(item)
|
||||
case "kb_create_document":
|
||||
input, err := mcpDocumentInput(call.Arguments)
|
||||
if err != nil {
|
||||
@@ -256,7 +256,7 @@ func (s *Service) callMCPTool(ctx context.Context, userID string, params json.Ra
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload = publicDocument(item)
|
||||
payload = s.agentDocument(item)
|
||||
case "kb_update_document":
|
||||
kbID, err := mcpRequiredString(call.Arguments, "kb_id")
|
||||
if err != nil {
|
||||
@@ -280,7 +280,7 @@ func (s *Service) callMCPTool(ctx context.Context, userID string, params json.Ra
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload = publicDocument(item)
|
||||
payload = s.agentDocument(item)
|
||||
case "kb_delete_document":
|
||||
if _, ok := call.Arguments["ids"]; ok {
|
||||
result, err := s.writeMCPDocuments(ctx, userID, call.Name, call.Arguments)
|
||||
|
||||
@@ -100,5 +100,5 @@ func (s *Service) editMCPDocument(ctx context.Context, actor string, arguments m
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return publicDocumentSummary(item), nil
|
||||
return s.agentDocumentSummary(item), nil
|
||||
}
|
||||
@@ -74,8 +74,15 @@ func TestTextPage(t *testing.T) {
|
||||
if err != nil || p["next_offset"] != nil || p["has_more"] != false {
|
||||
t.Fatalf("%v %v", p, err)
|
||||
}
|
||||
for _, pair := range [][2]int{{-1, 1}, {6, 1}, {0, 0}, {0, mcpTextPageMax + 1}} {
|
||||
if _, err := textPage("a中文🙂z", pair[0], pair[1]); err == nil {
|
||||
if _, err := textPage("a中文🙂z", 6, 1); err == nil {
|
||||
t.Fatal("应拒绝超出正文长度的偏移")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPReadRejectsInvalidPaginationBeforeLookup(t *testing.T) {
|
||||
for _, pair := range [][2]int{{-1, 1}, {0, 0}, {0, mcpTextPageMax + 1}} {
|
||||
_, err := (&Service{}).readMCPDocument(t.Context(), "actor", map[string]any{"kb_id": "kb", "document_id": "doc", "offset": pair[0], "limit": pair[1]})
|
||||
if err == nil {
|
||||
t.Fatal(pair)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -17,13 +19,13 @@ func (s *Service) registerMCPFileUpload(router chi.Router, keys MCPKeyAuthentica
|
||||
scheme, token, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") || strings.TrimSpace(token) == "" {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="mcp"`)
|
||||
resource.Fail(r.Context(), w, &resource.Error{Status: 401, Code: "invalid_key", Message: "缺少 MCP 调用密钥"})
|
||||
resource.Fail(r.Context(), w, &resource.Error{Status: 401, Code: "invalid_key", Message: "缺少上传临时密钥或 MCP 调用密钥"})
|
||||
return
|
||||
}
|
||||
actor, err := keys.Authenticate(r.Context(), strings.TrimSpace(token), "mcp:invoke")
|
||||
actor, err := s.authenticateFileUpload(r.Context(), keys, strings.TrimSpace(token), chi.URLParam(r, "id"))
|
||||
if err != nil {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="mcp", error="invalid_token"`)
|
||||
resource.Fail(r.Context(), w, &resource.Error{Status: 401, Code: "invalid_key", Message: "MCP 调用密钥无效或权限不足"})
|
||||
resource.Fail(r.Context(), w, &resource.Error{Status: 401, Code: "invalid_key", Message: "上传凭证无效、已过期或权限不足"})
|
||||
return
|
||||
}
|
||||
c := importContext{Actor: actor, KB: chi.URLParam(r, "id")}
|
||||
@@ -32,27 +34,12 @@ func (s *Service) registerMCPFileUpload(router chi.Router, keys MCPKeyAuthentica
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
name, data, err := readImportMultipart(w, r)
|
||||
c, err = s.storeMultipartOriginal(w, r, c)
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
c.DocumentID, err = multipartDocumentID(c, r.PostFormValue("upload_key"), name, data)
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
out, err := s.uploadFileImport(r.Context(), c, name, data, false)
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
c, err = s.verifyImport(out.String("import_context"), "import")
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
out, err = s.startFileImport(r.Context(), c, multipartImportInput(r.FormValue))
|
||||
out, err := s.startFileImport(r.Context(), c, multipartImportInput(r.FormValue))
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
@@ -70,7 +57,6 @@ type mcpFileInput struct {
|
||||
Task string `json:"task_context"`
|
||||
Title string `json:"title"`
|
||||
Parent *string `json:"parent_id"`
|
||||
ModelID string `json:"model_id"`
|
||||
}
|
||||
|
||||
func (s *Service) callMCPFileImport(ctx context.Context, actor, tool string, args map[string]any) (resource.Object, error) {
|
||||
@@ -106,7 +92,15 @@ func (s *Service) callMCPFileImport(ctx context.Context, actor, tool string, arg
|
||||
return nil, err
|
||||
}
|
||||
if in.Import == "" && in.Data == "" && in.Name == "" {
|
||||
return resource.Object{"status": "upload_required", "upload_path": "/mcp/kb/" + in.KB + "/files/upload", "method": "POST", "encoding": "multipart/form-data", "file_field": "file", "idempotency_field": "upload_key", "idempotency_format": "32 hexadecimal characters; reuse for retries of the same upload", "authentication": "Authorization: Bearer <same MCP Key>", "max_file_bytes": importFileLimit, "supported_formats": []string{"txt", "md", "markdown", "html", "htm", "svg", "csv", "docx", "xls", "xlsx", "pptx", "pdf", "jpg", "jpeg", "png"}, "next": "客户端在模型上下文之外上传文件及 title/parent_id,图片另传 model_id;上传即开始处理,pending 时用 task_context 查询;不要让模型生成或搬运文件 Base64"}, nil
|
||||
uploadURL, err := s.fileUploadURL(in.KB)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
uploadKey, expires, err := s.issueFileUploadKey(actor, in.KB)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resource.Object{"upload_url": uploadURL, "upload_token": uploadKey, "expires_at": expires, "expires_in": int(fileUploadKeyTTL.Seconds()), "status": "upload_required", "upload_path": "/mcp/kb/" + in.KB + "/files/upload", "method": "POST", "encoding": "multipart/form-data", "file_field": "file", "idempotency_field": "upload_key", "idempotency_format": "32 hexadecimal characters; reuse for retries of the same upload", "authentication": "Authorization: Bearer <upload_token>", "max_file_bytes": importFileLimit, "max_image_bytes": imageUploadLimit, "max_text_bytes": importContentLimit, "supported_formats": []string{"txt", "md", "markdown", "html", "htm", "svg", "csv", "docx", "xlsx", "pptx", "pdf", "jpg", "jpeg", "png", "webp"}, "next": "向返回的完整 upload_url 使用 upload_token 在 Authorization 请求头中上传文件及 title/parent_id,文件字节在模型上下文之外传输,图片默认使用全局知识库视觉模型;上传即开始处理,pending 时用 task_context 查询;不要让模型生成或搬运文件 Base64"}, nil
|
||||
}
|
||||
if in.Import != "" && (in.Data != "" || in.Name != "") {
|
||||
return nil, resource.Invalid("import_context 与文件字节不能同时提供")
|
||||
@@ -114,7 +108,7 @@ func (s *Service) callMCPFileImport(ctx context.Context, actor, tool string, arg
|
||||
token := in.Import
|
||||
if token == "" {
|
||||
if in.Name == "" || len(in.Data) == 0 || len(in.Data) > mcpImageBase64Limit {
|
||||
return nil, resource.Invalid("需要 file_name 和不超过 32 MiB 的文件 Base64")
|
||||
return nil, resource.Invalid("需要 file_name 和不超过 100 MiB 的文件 Base64")
|
||||
}
|
||||
original, err := base64.StdEncoding.Strict().DecodeString(in.Data)
|
||||
if err != nil {
|
||||
@@ -138,7 +132,7 @@ func (s *Service) callMCPFileImport(ctx context.Context, actor, tool string, arg
|
||||
if c.Actor != actor || c.KB != in.KB || c.Admin {
|
||||
return nil, resource.NotFound
|
||||
}
|
||||
return s.startFileImport(ctx, c, fileImportInput{Title: in.Title, ParentID: in.Parent, ModelID: in.ModelID})
|
||||
return s.startFileImport(ctx, c, fileImportInput{Title: in.Title, ParentID: in.Parent})
|
||||
}
|
||||
|
||||
// Query before conversion or saving so a lost reply never duplicates a document.
|
||||
@@ -163,10 +157,11 @@ func (s *Service) saveMCPImport(ctx context.Context, c importContext, content, p
|
||||
|
||||
func mcpFileTools() []resource.Object {
|
||||
return []resource.Object{
|
||||
{"name": "kb_upload_file", "description": "导入 TXT/Markdown/HTML/SVG/CSV/DOCX/XLS/XLSX/PPTX/PDF/JPEG/JPG/PNG,不支持 DOC/PPT。只传 kb_id 获取 multipart 上传地址;客户端使用同一 mcp:invoke Key 在模型上下文之外上传文件及 title/parent_id,图片必须提供 model_id。上传即开始处理,文本及图片成功返回 completed/document_id,Office/PDF 返回 pending/task_context,按 poll_after_seconds 调 kb_get_file_import_status。也可由客户端程序化提供 file_name/data_base64,最多32 MiB;禁止模型生成、复制或搬运 Base64。不接受本地路径或任意URL。import_context 可复用原件继续提交,与文件字节互斥。图片同步付费解析,失败不静默自动重试。页面或客户端退出后不后台查询或入库;同一 document_id 直接作为 anydoc task_id 并去重保存。", "inputSchema": mcpObjectSchema(resource.Object{
|
||||
"upload_key": resource.Object{"type": "string", "pattern": "^[0-9a-fA-F]{32}$", "description": "客户端生成的上传幂等键,同一次上传重试必须复用;与 file_name/data_base64 一起提供"},
|
||||
"kb_id": mcpIDSchema(),
|
||||
"model_id": mcpIDSchema(),
|
||||
{"name": "kb_upload_file", "description": "导入 TXT/Markdown/HTML/SVG/CSV/DOCX/XLS/XLSX/PPTX/PDF/JPEG/JPG/PNG/WebP/WebP,不支持 DOC/PPT。只传 kb_id 获取完整 multipart 上传地址 upload_url 和5分钟有效的 upload_token;上传请求设置 Authorization: Bearer <upload_token>,无需读取长期 MCP Key。临时凭证仅用于目标库上传,可在有效期内重试,同次上传复用 upload_key;客户端在模型上下文之外上传文件及 title/parent_id,multipart 原件最多100 MiB,图片最多100 MiB、文本正文最多16 MiB,图片自动读取 knowledge_base_models 中唯一的视觉模型,无需传模型 ID。上传即开始处理,文本及图片成功返回 completed/document_id,Office/PDF 返回 pending/task_context,按 poll_after_seconds 调 kb_get_file_import_status。也可由客户端程序化提供 file_name/data_base64,最多100 MiB;禁止模型生成、复制或搬运 Base64。不接受本地路径或任意URL。import_context 可复用原件继续提交,与文件字节互斥。图片同步调用知识库视觉模型解析,失败不静默自动重试。页面或客户端退出后不后台查询或入库;同一 document_id 直接作为 anydoc task_id 并去重保存。", "inputSchema": mcpObjectSchema(resource.Object{
|
||||
"upload_key": resource.Object{"type": "string", "pattern": "^[0-9a-fA-F]{32}$", "description": "客户端生成的上传幂等键,同一次上传重试必须复用;与 file_name/data_base64 一起提供"},
|
||||
"kb_id": mcpIDSchema(),
|
||||
"model_id": resource.Object{"type": "string", "deprecated": true, "description": "仅兼容旧客户端;此字段被忽略,不会覆盖知识库视觉模型"},
|
||||
|
||||
"file_name": resource.Object{"type": "string", "minLength": 1, "maxLength": 1024},
|
||||
"data_base64": resource.Object{"type": "string", "minLength": 1, "maxLength": mcpImageBase64Limit, "description": "仅由客户端在模型上下文之外程序化读取、编码、注入。优先使用 multipart 上传后传 import_context;禁止模型复制或生成 Base64"},
|
||||
"import_context": resource.Object{"type": "string", "maxLength": 32768, "description": "二进制上传返回的签名上下文,与 file_name/data_base64 互斥;同一上下文重试不重复保存文档"},
|
||||
@@ -178,3 +173,38 @@ func mcpFileTools() []resource.Object {
|
||||
}, "kb_id", "task_context")},
|
||||
}
|
||||
}
|
||||
|
||||
// A separate prefix and purpose prevent import/callback contexts from becoming credentials.
|
||||
const fileUploadKeyPrefix = "kbup_"
|
||||
const fileUploadKeyTTL = 5 * time.Minute
|
||||
|
||||
func (s *Service) issueFileUploadKey(actor, kb string) (string, int64, error) {
|
||||
expires := time.Now().Add(fileUploadKeyTTL).Unix()
|
||||
token, err := s.signImport(importContext{Purpose: "mcp_file_upload", Actor: actor, KB: kb, ID: resource.ID(), DocumentID: resource.ID(), Expires: expires})
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
return fileUploadKeyPrefix + token, expires, nil
|
||||
}
|
||||
|
||||
func (s *Service) authenticateFileUpload(ctx context.Context, keys MCPKeyAuthenticator, token, kb string) (string, error) {
|
||||
if !strings.HasPrefix(token, fileUploadKeyPrefix) {
|
||||
return keys.Authenticate(ctx, token, "mcp:invoke")
|
||||
}
|
||||
claims, err := s.verifyImport(strings.TrimPrefix(token, fileUploadKeyPrefix), "mcp_file_upload")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if claims.KB != kb || claims.Admin {
|
||||
return "", resource.NotFound
|
||||
}
|
||||
return claims.Actor, nil
|
||||
}
|
||||
|
||||
func (s *Service) fileUploadURL(kb string) (string, error) {
|
||||
base, err := url.Parse(s.publicURL)
|
||||
if err != nil || base.Host == "" || (base.Scheme != "http" && base.Scheme != "https") || base.User != nil || base.RawQuery != "" || base.Fragment != "" {
|
||||
return "", &resource.Error{Status: 503, Code: "import_unavailable", Message: "文件上传外部地址 PublicURL 未配置或无效"}
|
||||
}
|
||||
return strings.TrimRight(base.String(), "/") + "/mcp/kb/" + url.PathEscape(kb) + "/files/upload", nil
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package kb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -94,10 +95,29 @@ func TestMCPFileClientTextAndPermissions(t *testing.T) {
|
||||
mcpFileUpload(t, client, server.URL, "wrong", kb, "a.txt", []byte("source"), 401)
|
||||
mcpFileUpload(t, client, server.URL, "key", kb, "legacy.doc", []byte("doc"), 400)
|
||||
mcpFileUpload(t, client, server.URL, "key", kb, "fake.pdf", []byte("not PDF"), 400)
|
||||
s.WithPublicURL(server.URL)
|
||||
info, failed := mcpFileCall(t, client, server.URL, "key", "kb_upload_file", resource.Object{"kb_id": kb})
|
||||
if failed || info.String("status") != "upload_required" || info.String("upload_path") != "/mcp/kb/"+kb+"/files/upload" {
|
||||
t.Fatalf("guide %v", info)
|
||||
}
|
||||
temporary := info.String("upload_token")
|
||||
if info.String("upload_url") != server.URL+"/mcp/kb/"+kb+"/files/upload" {
|
||||
t.Fatalf("upload URL: %v", info)
|
||||
}
|
||||
if temporary == "" {
|
||||
t.Fatal("missing temporary upload key")
|
||||
}
|
||||
uploadedTemporary := mcpFileUpload(t, client, server.URL, temporary, kb, "temporary.txt", []byte("temporary upload"), 201)
|
||||
if uploadedTemporary.String("status") != "completed" {
|
||||
t.Fatalf("temporary upload: %v", uploadedTemporary)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, "UPDATE users SET status='disabled' WHERE id=$1", owner); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mcpFileUpload(t, client, server.URL, temporary, kb, "denied.txt", []byte("denied"), 404)
|
||||
if _, err := pool.Exec(ctx, "UPDATE users SET status='active' WHERE id=$1", owner); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, ext := range []string{"txt", "md", "html", "svg", "csv"} {
|
||||
original := []byte("<div>original source " + ext + "</div>")
|
||||
uploaded := mcpFileUpload(t, client, server.URL, "key", kb, "source."+ext, original, 201)
|
||||
@@ -388,7 +408,19 @@ func TestMCPFileArgumentsAndRequestLimits(t *testing.T) {
|
||||
func TestMCPUploadKeyReplaysSavedTextAndImage(t *testing.T) {
|
||||
pool, owner := kbTestPool(t)
|
||||
storage := &originalTestStorage{&avatarStorage{files: map[string][]byte{}}}
|
||||
vision := &visionStub{content: "image description"}
|
||||
calls := 0
|
||||
vision := &poolCheckingVision{check: func(ctx context.Context) error {
|
||||
// A second multipart request must be admitted while recognition is in flight.
|
||||
probe, cancel := context.WithTimeout(ctx, time.Second)
|
||||
defer cancel()
|
||||
release, err := acquireImportSlot(probe, fileUploads)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
release()
|
||||
calls++
|
||||
return nil
|
||||
}}
|
||||
s := NewService(resource.NewStore(pool), nil).WithStorage(storage).WithAnyDoc(AnyDocConfig{SigningKey: strings.Repeat("k", 32)}).WithImageDescriber(vision)
|
||||
book, err := s.CreateUserKB(t.Context(), owner, resource.Object{"name": "idempotent uploads"})
|
||||
if err != nil {
|
||||
@@ -398,17 +430,16 @@ func TestMCPUploadKeyReplaysSavedTextAndImage(t *testing.T) {
|
||||
s.RegisterMCP(router, testMCPKeys{token: "key", scope: "mcp:invoke", user: owner})
|
||||
server := httptest.NewServer(router)
|
||||
defer server.Close()
|
||||
for _, format := range []string{"txt", "png"} {
|
||||
for _, format := range []string{"txt", "png", "webp"} {
|
||||
data := []byte("text")
|
||||
if format == "png" {
|
||||
data = imageBytes(t, "png")
|
||||
if imageFileType(format) {
|
||||
data = imageBytes(t, format)
|
||||
}
|
||||
var id string
|
||||
for attempt := 0; attempt < 2; attempt++ {
|
||||
body := new(bytes.Buffer)
|
||||
writer := multipart.NewWriter(body)
|
||||
writer.WriteField("upload_key", strings.Repeat("a", 32))
|
||||
writer.WriteField("model_id", "vision")
|
||||
file, _ := writer.CreateFormFile("file", "source."+format)
|
||||
file.Write(data)
|
||||
writer.Close()
|
||||
@@ -432,13 +463,13 @@ func TestMCPUploadKeyReplaysSavedTextAndImage(t *testing.T) {
|
||||
}
|
||||
}
|
||||
// The programmatic Base64 path shares the same identity with multipart.
|
||||
result, failed := mcpFileCall(t, server.Client(), server.URL, "key", "kb_upload_file", resource.Object{"kb_id": book.String("id"), "file_name": "source." + format, "data_base64": base64.StdEncoding.EncodeToString(data), "upload_key": strings.Repeat("a", 32), "model_id": "vision"})
|
||||
result, failed := mcpFileCall(t, server.Client(), server.URL, "key", "kb_upload_file", resource.Object{"kb_id": book.String("id"), "model_id": "legacy-vision", "file_name": "source." + format, "data_base64": base64.StdEncoding.EncodeToString(data), "upload_key": strings.Repeat("a", 32)})
|
||||
if failed || result.String("document_id") != id {
|
||||
t.Fatal("Base64 replay", result)
|
||||
}
|
||||
}
|
||||
if vision.calls != 1 {
|
||||
t.Fatalf("paid parser invoked %d times", vision.calls)
|
||||
if calls != 2 {
|
||||
t.Fatalf("paid parser invoked %d times", calls)
|
||||
}
|
||||
var documents, jobs int
|
||||
if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM knowledge_base_documents WHERE kb_id=$1", book.String("id")).Scan(&documents); err != nil {
|
||||
@@ -447,7 +478,71 @@ func TestMCPUploadKeyReplaysSavedTextAndImage(t *testing.T) {
|
||||
if err := pool.QueryRow(t.Context(), "SELECT count(*) FROM knowledge_base_learning_jobs WHERE kb_id=$1", book.String("id")).Scan(&jobs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if documents != 2 || jobs != 2 {
|
||||
if documents != 3 || jobs != 3 {
|
||||
t.Fatalf("documents=%d jobs=%d", documents, jobs)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTemporaryFileUploadKey(t *testing.T) {
|
||||
s := NewService(nil, nil).WithAnyDoc(AnyDocConfig{SigningKey: strings.Repeat("k", 32)})
|
||||
keys := testMCPKeys{token: "long-term", scope: "mcp:invoke", user: "owner"}
|
||||
token, expires, err := s.issueFileUploadKey("owner", "book")
|
||||
if err != nil || expires <= time.Now().Unix() || expires > time.Now().Add(fileUploadKeyTTL).Unix() {
|
||||
t.Fatalf("issue: %v", err)
|
||||
}
|
||||
actor, err := s.authenticateFileUpload(t.Context(), keys, token, "book")
|
||||
if err != nil || actor != "owner" {
|
||||
t.Fatalf("authenticate: %q %v", actor, err)
|
||||
}
|
||||
if _, err := keys.Authenticate(t.Context(), token, "mcp:invoke"); err == nil {
|
||||
t.Fatal("temporary key accepted as MCP key")
|
||||
}
|
||||
for _, tc := range []struct{ name, token, kb string }{
|
||||
{"cross-library", token, "other"}, {"tampered", token + "x", "book"},
|
||||
{"missing", "", "book"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if _, err := s.authenticateFileUpload(t.Context(), keys, tc.token, tc.kb); err == nil {
|
||||
t.Fatal("invalid key accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, c := range []importContext{
|
||||
{Purpose: "mcp_file_upload", Actor: "owner", KB: "book", ID: "id", DocumentID: "doc", Expires: time.Now().Unix()},
|
||||
{Purpose: "import", Actor: "owner", KB: "book", ID: "id", DocumentID: "doc", Expires: expires},
|
||||
{Purpose: "upload", Actor: "owner", KB: "book", ID: "id", DocumentID: "doc", Expires: expires},
|
||||
{Purpose: "mcp_file_upload", Actor: "owner", KB: "book", ID: "id", DocumentID: "doc", Expires: expires, Admin: true},
|
||||
} {
|
||||
signed, err := s.signImport(c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.authenticateFileUpload(t.Context(), keys, fileUploadKeyPrefix+signed, "book"); err == nil {
|
||||
t.Fatalf("invalid claims accepted: %+v", c)
|
||||
}
|
||||
}
|
||||
if actor, err := s.authenticateFileUpload(t.Context(), keys, "long-term", "book"); err != nil || actor != "owner" {
|
||||
t.Fatal("legacy key rejected")
|
||||
}
|
||||
s.anydoc.SigningKey = ""
|
||||
if _, _, err := s.issueFileUploadKey("owner", "book"); err == nil {
|
||||
t.Fatal("issued without signing key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileUploadURL(t *testing.T) {
|
||||
s := NewService(nil, nil)
|
||||
for _, base := range []string{"", "/relative", "ftp://example.com", "https://user:pass@example.com", "https://example.com?token=x", "https://example.com#fragment"} {
|
||||
s.WithPublicURL(base)
|
||||
if _, err := s.fileUploadURL("book"); err == nil {
|
||||
t.Fatalf("accepted invalid PublicURL %q", base)
|
||||
}
|
||||
}
|
||||
for _, base := range []string{"https://example.com", "https://example.com/", "https://example.com/prefix/"} {
|
||||
s.WithPublicURL(base)
|
||||
got, err := s.fileUploadURL("book")
|
||||
if err != nil || got != strings.TrimRight(base, "/")+"/mcp/kb/book/files/upload" {
|
||||
t.Fatalf("URL %q: %q %v", base, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,14 +12,14 @@ const mcpImageRequestLimit = mcpImageBase64Limit + (64 << 10)
|
||||
|
||||
func decodeMCPImage(encoded string) ([]byte, error) {
|
||||
if len(encoded) == 0 || len(encoded) > mcpImageBase64Limit {
|
||||
return nil, resource.Invalid("图片不能为空且不能超过 32 MiB")
|
||||
return nil, resource.Invalid("图片不能为空且不能超过 100 MiB")
|
||||
}
|
||||
data, err := base64.StdEncoding.Strict().DecodeString(encoded)
|
||||
if err != nil {
|
||||
return nil, resource.Invalid("图片必须使用标准 Base64 编码,不包含 data URL 前缀")
|
||||
}
|
||||
if len(data) == 0 || len(data) > imageUploadLimit {
|
||||
return nil, resource.Invalid("图片不能为空且不能超过 32 MiB")
|
||||
return nil, resource.Invalid("图片不能为空且不能超过 100 MiB")
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
@@ -10,9 +10,6 @@ const mcpTextPageDefault = 4000
|
||||
const mcpTextPageMax = 16000
|
||||
|
||||
func textPage(content string, offset, limit int) (resource.Object, error) {
|
||||
if offset < 0 || limit < 1 || limit > mcpTextPageMax {
|
||||
return nil, resource.Invalid("offset 必须非负,limit 必须为 1 到 16000")
|
||||
}
|
||||
chars := []rune(content)
|
||||
if offset > len(chars) {
|
||||
return nil, resource.Invalid("offset 超出正文长度")
|
||||
@@ -39,6 +36,9 @@ func (s *Service) readMCPDocument(ctx context.Context, actor string, arguments m
|
||||
if strings.TrimSpace(input.KbID) == "" || strings.TrimSpace(input.DocumentID) == "" || input.ExpectedRevision < 0 {
|
||||
return nil, resource.Invalid("kb_id、document_id 必填,版本不能为负数")
|
||||
}
|
||||
if input.Offset < 0 || input.Limit < 1 || input.Limit > mcpTextPageMax {
|
||||
return nil, resource.Invalid("offset 必须非负,limit 必须为 1 到 16000")
|
||||
}
|
||||
if input.Offset > 0 && input.ExpectedRevision == 0 {
|
||||
return nil, &resource.Error{Status: 428, Code: "precondition_required", Message: "继续读取须提供首页返回的 revision,避免拼接不同版本"}
|
||||
}
|
||||
@@ -52,10 +52,13 @@ func (s *Service) readMCPDocument(ctx context.Context, actor string, arguments m
|
||||
if err := checkDocumentVersion(item, input.ExpectedRevision); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !hasReadableDocumentContent(item) {
|
||||
return resource.Object{"content": "", "document": s.agentDocumentSummary(item), "url": s.originalDocumentURL(item)}, nil
|
||||
}
|
||||
page, err := textPage(item.String("content"), input.Offset, input.Limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
page["document"] = publicDocumentSummary(item)
|
||||
page["document"] = s.agentDocumentSummary(item)
|
||||
return page, nil
|
||||
}
|
||||
@@ -11,7 +11,7 @@ func MCPTools() []resource.Object {
|
||||
editMCPTool(), readMCPDocumentTool(),
|
||||
{
|
||||
"name": "kb_upload_image",
|
||||
"description": "图片上传需求优先使用 REST POST /api/v1/kb/{id}/images/upload,以 multipart/form-data 的 file 字段由客户端直接上传文件。不要让大模型通过 tool calling 生成、复制或传递图片 Base64 来调用本工具。REST 需要 Agent 登录凭证,MCP Key 不能替代;缺少上传能力或登录凭证时,应提示使用客户端上传入口,不要回退为模型生成 Base64。本工具仅保留给可在模型上下文之外读取文件并程序化注入 Base64 的客户端。要求知识库启用且调用者有正文读写权限。data_base64 为标准 Base64(无 data URL 前缀),原图最多 32 MiB、2500 万像素,支持 PNG/JPEG/GIF/WebP。返回 name、url、mime_type、size_bytes、markdown;将 markdown 写入文档正文后通过文档工具保存,上传本身不修改文档。",
|
||||
"description": "图片上传需求优先使用 REST POST /api/v1/kb/{id}/images/upload,以 multipart/form-data 的 file 字段由客户端直接上传文件。不要让大模型通过 tool calling 生成、复制或传递图片 Base64 来调用本工具。REST 需要 Agent 登录凭证,MCP Key 不能替代;缺少上传能力或登录凭证时,应提示使用客户端上传入口,不要回退为模型生成 Base64。本工具仅保留给可在模型上下文之外读取文件并程序化注入 Base64 的客户端。要求知识库启用且调用者有正文读写权限。data_base64 为标准 Base64(无 data URL 前缀),原图最多 100 MiB、2500 万像素,支持 PNG/JPEG/GIF/WebP。返回 name、url、mime_type、size_bytes、markdown;将 markdown 写入文档正文后通过文档工具保存,上传本身不修改文档。",
|
||||
"inputSchema": resource.Object{
|
||||
"type": "object",
|
||||
"properties": resource.Object{
|
||||
@@ -68,7 +68,7 @@ func MCPTools() []resource.Object {
|
||||
},
|
||||
{
|
||||
"name": "kb_get_document",
|
||||
"description": "读取文档元数据和 revision;include_content=true 返回完整正文(兼容接口),长文档优先使用 kb_read_document 分段读取;无权文档返回 kb_not_found",
|
||||
"description": "读取文档元数据和 revision;include_content=true 对可编辑格式和未知类型返回已保存正文;已知不可编辑格式 content 固定为空字符串,通过 url 读取原件,长文档优先使用 kb_read_document 分段读取;无权文档返回 kb_not_found",
|
||||
"inputSchema": resource.Object{
|
||||
"type": "object",
|
||||
"properties": resource.Object{
|
||||
@@ -119,11 +119,11 @@ func MCPTools() []resource.Object {
|
||||
},
|
||||
{
|
||||
"name": "kb_search",
|
||||
"description": "在可访问知识库中检索;绑定可用向量模型的知识库自动执行 lexical+vector 混合检索,否则仅执行 lexical。查找图片时传 file_types=[jpg,png],query 使用具体画面对象或场景,如狗、草地;按画面描述判断匹配,不能把图片内文字提到狗等同于画面有狗。图片命中返回 image 元数据,用 kb_get_document_image 获取原图并在客户端展示,不能生成新图替代。top_k 仅为相关候选,不是全库完整清单。",
|
||||
"description": "在可访问知识库中检索;绑定可用向量模型的知识库自动执行 lexical+vector 混合检索,否则仅执行 lexical。查找图片时传 file_types=[jpg,png,webp],query 使用具体画面对象或场景,如狗、草地;检索 content 返回命中的正文分片(包括不可编辑格式),并返回原件 url;结合画面描述和原图判断匹配,不能把图片内文字提到狗等同于画面有狗。图片命中返回 image 元数据,用 kb_get_document_image 获取原图并在客户端展示,不能生成新图替代。top_k 仅为相关候选,不是全库完整清单。",
|
||||
"inputSchema": resource.Object{
|
||||
"type": "object",
|
||||
"properties": resource.Object{
|
||||
"file_types": resource.Object{"type": "array", "items": resource.Object{"type": "string", "enum": []string{"jpg", "png"}}, "description": "可选,仅检索指定图片格式;在召回前过滤"},
|
||||
"file_types": resource.Object{"type": "array", "items": resource.Object{"type": "string", "enum": []string{"jpg", "png", "webp"}}, "description": "可选,仅检索指定图片格式;在召回前过滤"},
|
||||
"query": resource.Object{"type": "string", "description": "检索问题"},
|
||||
"kb_ids": resource.Object{"type": "array", "items": resource.Object{"type": "string", "format": "uuid"}},
|
||||
"top_k": resource.Object{"type": "integer", "minimum": 1, "maximum": 20, "default": 8},
|
||||
@@ -264,7 +264,7 @@ func editMCPTool() resource.Object {
|
||||
}
|
||||
|
||||
func readMCPDocumentTool() resource.Object {
|
||||
return resource.Object{"name": "kb_read_document", "description": "按 Unicode 字符偏移分段读取原始正文,适合长文档编辑。返回 content、document(含 revision)、next_offset、has_more 和 total_characters。首次从 offset=0 读取;后续使用 next_offset 并提供首页 revision 作为 expected_revision,冲突时从头重新读取。索引分块不是原始正文,不应拿来整体覆盖文档。文件夹没有正文,不能读取。",
|
||||
return resource.Object{"name": "kb_read_document", "description": "已知不可编辑格式返回空字符串 content、document 元数据和原件 url。可编辑格式和未知类型按 Unicode 字符偏移分段读取原始正文,适合长文档编辑。返回 content、document(含 revision)、next_offset、has_more 和 total_characters。首次从 offset=0 读取;后续使用 next_offset 并提供首页 revision 作为 expected_revision,冲突时从头重新读取。索引分块不是原始正文,不应拿来整体覆盖文档。文件夹没有正文,不能读取。",
|
||||
"inputSchema": mcpObjectSchema(resource.Object{
|
||||
"kb_id": mcpIDSchema(), "document_id": mcpIDSchema(),
|
||||
"offset": resource.Object{"type": "integer", "minimum": 0, "default": 0},
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMarkdownDataImageExamples(t *testing.T) {
|
||||
source := "data:image/png;base64," + base64.StdEncoding.EncodeToString(avatarImage(t, "png"))
|
||||
example := "~~~html\n<img src=\"" + source + "\">\n~~~"
|
||||
for _, input := range []string{"图片前缀是 data:image/", example} {
|
||||
got, err := describeDocumentImagesParallel(t.Context(), input, "md", 1, func(context.Context, []byte, string) (string, error) {
|
||||
t.Fatal("example invoked vision")
|
||||
return "", nil
|
||||
})
|
||||
if err != nil || got != input {
|
||||
t.Fatalf("example changed: %q, %v", got, err)
|
||||
}
|
||||
}
|
||||
input := "![pic][ref]\n\n[ref]: " + source + "\n\n" + example
|
||||
got, err := describeDocumentImagesParallel(t.Context(), input, "md", 1, func(context.Context, []byte, string) (string, error) { return "小狗", nil })
|
||||
if err != nil || !strings.Contains(got, "[ref]: #embedded-image") || !strings.HasSuffix(got, example) {
|
||||
t.Fatalf("mixed example changed: %s, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMixedImagesWithFencedVisionDescription(t *testing.T) {
|
||||
// Match the Markdown shape returned by app.visionDescription, including its
|
||||
// final fence with no trailing newline.
|
||||
description := "## 画面描述\n\n```text\n小狗\n```\n\n## 图片内文字\n\n```text\n未见可辨识文字\n```"
|
||||
for _, embedded := range []bool{false, true} {
|
||||
name := "stored"
|
||||
source := assetURL("book", strings.Repeat("a", 64)+".png")
|
||||
if embedded {
|
||||
name = "embedded"
|
||||
source = "data:image/png;base64," + base64.StdEncoding.EncodeToString(avatarImage(t, "png"))
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
for _, htmlFirst := range []bool{false, true} {
|
||||
markdown := ""
|
||||
tag := "<img src=\"" + source + "\">"
|
||||
first, second := markdown, tag
|
||||
if htmlFirst {
|
||||
first, second = second, first
|
||||
}
|
||||
example := "\n\n```html\n<img src=\"example.png\">\n```"
|
||||
input := "前文\n\n" + first + "\n\n中间\n\n" + second + "\n\n后文" + example
|
||||
calls := 0
|
||||
var got string
|
||||
var err error
|
||||
if embedded {
|
||||
got, err = describeDocumentImagesParallel(t.Context(), input, "md", 2, func(context.Context, []byte, string) (string, error) {
|
||||
calls++
|
||||
return description, nil
|
||||
})
|
||||
} else {
|
||||
got, err = describeStoredImages(t.Context(), input, "book", 2, func(context.Context, string) (string, error) {
|
||||
calls++
|
||||
return description, nil
|
||||
})
|
||||
}
|
||||
if err != nil || calls != 1 || strings.Count(got, description) != 2 || strings.Contains(got, source) || !strings.HasSuffix(got, example) {
|
||||
t.Fatalf("htmlFirst=%v calls=%d err=%v output=%s", htmlFirst, calls, err, got)
|
||||
}
|
||||
if strings.Index(got, description) > strings.Index(got, "中间") || strings.LastIndex(got, description) < strings.Index(got, "中间") {
|
||||
t.Fatalf("image positions changed: %s", got)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/kb/sqlc"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/model"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type knowledgeModelInput struct {
|
||||
ActorID string `json:"-"`
|
||||
Kind string `json:"kind"`
|
||||
ModelID string `json:"model_id"`
|
||||
BaseURL string `json:"base_url"`
|
||||
APIKey string `json:"api_key"`
|
||||
Protocol string `json:"protocol"`
|
||||
ProxyID string `json:"proxy_id"`
|
||||
MaxOutputTokens int64 `json:"max_output_tokens"`
|
||||
Concurrency *int `json:"concurrency,omitempty"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
func knowledgeModel(raw []byte) (model.Model, resource.Object, error) {
|
||||
var m model.Model
|
||||
var object resource.Object
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
return m, nil, err
|
||||
}
|
||||
if err := json.Unmarshal(raw, &object); err != nil {
|
||||
return m, nil, err
|
||||
}
|
||||
m.APIKey = object.String("api_key")
|
||||
m.DisplayName = m.ModelID
|
||||
m.OwnershipType = "system"
|
||||
m.Provider = model.ProviderPassthrough
|
||||
if object.String("kind") == "vision" {
|
||||
m.Kind = model.KindText
|
||||
m.AdvancedConfig.SupportsVision = true
|
||||
}
|
||||
return m, object, nil
|
||||
}
|
||||
|
||||
func publicKnowledgeModel(object resource.Object) resource.Object {
|
||||
if object.String("kind") == "vision" {
|
||||
config, _ := object["advanced_config"].(map[string]any)
|
||||
if config == nil {
|
||||
config = map[string]any{}
|
||||
object["advanced_config"] = config
|
||||
}
|
||||
if _, ok := config["concurrency"]; !ok {
|
||||
config["concurrency"] = 1
|
||||
}
|
||||
}
|
||||
object["api_key_configured"] = object.String("api_key") != ""
|
||||
delete(object, "api_key")
|
||||
return object
|
||||
}
|
||||
|
||||
// ConfiguredModel is server-internal: its secret must never be serialized to a client.
|
||||
func (s *Service) ConfiguredModel(ctx context.Context, kind string) (model.Model, error) {
|
||||
raw, err := sqlc.New(s.store.Pool).GetKnowledgeModel(ctx, kind)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
if kind == "vision" {
|
||||
return model.Model{}, resource.Invalid("知识库视觉模型未配置")
|
||||
}
|
||||
return model.Model{}, resource.Invalid("知识库向量模型未配置")
|
||||
}
|
||||
if err != nil {
|
||||
return model.Model{}, err
|
||||
}
|
||||
m, _, err := knowledgeModel(raw)
|
||||
if err != nil {
|
||||
return m, err
|
||||
}
|
||||
if !m.Enabled {
|
||||
if kind == "vision" {
|
||||
return m, resource.Invalid("知识库视觉模型已停用")
|
||||
}
|
||||
return m, resource.Invalid("知识库向量模型已停用")
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *Service) registerModelConfig(r chi.Router) {
|
||||
r.Get("/kb-models", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
rows, err := sqlc.New(s.store.Pool).ListKnowledgeModels(r.Context())
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
items := []resource.Object{}
|
||||
for _, raw := range rows {
|
||||
_, obj, err := knowledgeModel(raw)
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
items = append(items, publicKnowledgeModel(obj))
|
||||
}
|
||||
resource.JSON(r.Context(), w, 200, resource.Object{"items": items})
|
||||
})
|
||||
r.Put("/kb-models/{kind}", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
var input knowledgeModelInput
|
||||
if err := resource.Decode(w, r, &input); err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
input.Kind = chi.URLParam(r, "kind")
|
||||
user, _ := identity.UserFromContext(r.Context())
|
||||
input.ActorID = user.ID
|
||||
out, err := s.saveKnowledgeModel(r.Context(), input)
|
||||
if err != nil {
|
||||
resource.Fail(r.Context(), w, err)
|
||||
return
|
||||
}
|
||||
resource.JSON(r.Context(), w, 200, out)
|
||||
})
|
||||
}
|
||||
|
||||
func validateKnowledgeModel(in *knowledgeModelInput) error {
|
||||
if in.Enabled == nil {
|
||||
return resource.Invalid("enabled 必须为布尔值")
|
||||
}
|
||||
in.ModelID = strings.TrimSpace(in.ModelID)
|
||||
in.BaseURL = strings.TrimRight(strings.TrimSpace(in.BaseURL), "/")
|
||||
if in.Kind != "embedding" && in.Kind != "vision" {
|
||||
return resource.Invalid("模型类型必须为 embedding 或 vision")
|
||||
}
|
||||
base, err := url.Parse(in.BaseURL)
|
||||
if err != nil || base.Hostname() == "" || base.User != nil || base.RawQuery != "" || base.Fragment != "" || (base.Scheme != "https" && base.Scheme != "http") {
|
||||
return resource.Invalid("模型地址无效")
|
||||
}
|
||||
if in.ModelID == "" || len(in.BaseURL) > 4096 || len(in.ProxyID) > 256 || len(in.ModelID) > 1024 || len(in.APIKey) > 16384 || strings.ContainsAny(in.APIKey, "\r\n") {
|
||||
return resource.Invalid("模型名称或密钥无效")
|
||||
}
|
||||
if in.Kind == "embedding" {
|
||||
in.Protocol = string(model.ProtocolEmbedding)
|
||||
in.MaxOutputTokens = 0
|
||||
} else {
|
||||
switch model.Protocol(in.Protocol) {
|
||||
case model.ProtocolOpenAIChat, model.ProtocolOpenAIResponses, model.ProtocolAnthropic:
|
||||
default:
|
||||
return resource.Invalid("视觉模型协议无效")
|
||||
}
|
||||
if in.Concurrency != nil && (*in.Concurrency < 1 || *in.Concurrency > 20) {
|
||||
return resource.Invalid("视觉模型并发数必须为1至20的整数")
|
||||
}
|
||||
if in.MaxOutputTokens < 1 || in.MaxOutputTokens > 65536 {
|
||||
return resource.Invalid("视觉模型输出上限必须为1至65536")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) saveKnowledgeModel(ctx context.Context, in knowledgeModelInput) (resource.Object, error) {
|
||||
if err := validateKnowledgeModel(&in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enabled := *in.Enabled
|
||||
tx, err := s.store.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
tq := sqlc.New(tx)
|
||||
if err = tq.LockKnowledgeModel(ctx, in.Kind); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, err := tq.GetKnowledgeModel(ctx, in.Kind)
|
||||
exists := err == nil
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, err
|
||||
}
|
||||
var previous model.Model
|
||||
concurrency := 1
|
||||
if exists {
|
||||
var previousObject resource.Object
|
||||
previous, previousObject, err = knowledgeModel(raw)
|
||||
concurrency = knowledgeVisionConcurrency(previousObject)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if in.APIKey == "" {
|
||||
in.APIKey = previous.APIKey
|
||||
}
|
||||
if in.APIKey == "" {
|
||||
return nil, resource.Invalid("模型密钥不能为空")
|
||||
}
|
||||
m := model.Model{ID: previous.ID, ModelID: in.ModelID, BaseURL: in.BaseURL, APIKey: in.APIKey, ProxyID: in.ProxyID, Protocol: model.Protocol(in.Protocol), Kind: model.KindEmbedding, Enabled: true}
|
||||
if s.modelClient != nil {
|
||||
if err := s.modelClient.ValidateConfiguredProxy(ctx, in.ProxyID); err != nil {
|
||||
return nil, resource.Invalid(err.Error())
|
||||
}
|
||||
}
|
||||
dimension := 0
|
||||
if in.Kind == "embedding" {
|
||||
if s.modelClient == nil {
|
||||
return nil, resource.Invalid("向量模型探测不可用")
|
||||
}
|
||||
if !enabled && exists && previous.ModelID == in.ModelID && previous.BaseURL == in.BaseURL && previous.EmbeddingConfig != nil {
|
||||
dimension = previous.EmbeddingConfig.Dimension
|
||||
} else {
|
||||
dimension, err = s.modelClient.ProbeConfiguredEmbedding(ctx, m)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, resource.Invalid("向量维度探测失败: " + err.Error())
|
||||
}
|
||||
}
|
||||
oldDimension := 0
|
||||
if previous.EmbeddingConfig != nil {
|
||||
oldDimension = previous.EmbeddingConfig.Dimension
|
||||
}
|
||||
changed := !exists || previous.ModelID != in.ModelID || previous.BaseURL != in.BaseURL || previous.Protocol != m.Protocol || oldDimension != dimension
|
||||
id := previous.ID
|
||||
if !exists || (changed && in.Kind == "vision") {
|
||||
id = resource.ID()
|
||||
}
|
||||
object := resource.Object{"id": id, "kind": in.Kind, "model_id": in.ModelID, "base_url": in.BaseURL, "api_key": in.APIKey, "protocol": in.Protocol, "proxy_id": in.ProxyID, "enabled": enabled, "embedding_config": resource.Object{}, "advanced_config": resource.Object{}}
|
||||
if in.Kind == "embedding" {
|
||||
// Used on insert only; the conflict update preserves the existing owner.
|
||||
object["owner_user_id"] = in.ActorID
|
||||
object["embedding_config"] = resource.Object{"dimension": dimension}
|
||||
} else {
|
||||
if in.Concurrency != nil {
|
||||
concurrency = *in.Concurrency
|
||||
}
|
||||
object["advanced_config"] = resource.Object{"supports_vision": true, "max_output_tokens": in.MaxOutputTokens, "concurrency": concurrency}
|
||||
}
|
||||
payload, err := json.Marshal(object)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var saved []byte
|
||||
if in.Kind == "embedding" {
|
||||
saved, err = tq.SaveKnowledgeEmbeddingModel(ctx, payload)
|
||||
} else {
|
||||
saved, err = tq.SaveKnowledgeModel(ctx, payload)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if in.Kind == "embedding" && (changed || previous.Enabled != enabled) {
|
||||
ids, err := tq.ListKnowledgeModelAffectedBases(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, kbID := range ids {
|
||||
if _, err = tq.LockKbResource(ctx, kbID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tq.CancelKbLearningJobs(ctx, kbID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tq.ClearKbVectors(ctx, kbID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var dim *int32
|
||||
target := ""
|
||||
if enabled {
|
||||
d := int32(dimension)
|
||||
dim = &d
|
||||
target = id
|
||||
}
|
||||
if err = tq.SetKbEmbeddingModel(ctx, sqlc.SetKbEmbeddingModelParams{ID: kbID, EmbeddingModelID: id, EmbeddingDimension: dim}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = scheduleKbDocumentJobs(ctx, tq, kbID, target, knowledgeDimension(dim), enabled); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, out, err := knowledgeModel(saved)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return publicKnowledgeModel(out), nil
|
||||
}
|
||||
func knowledgeDimension(value *int32) int {
|
||||
if value == nil {
|
||||
return 0
|
||||
}
|
||||
return int(*value)
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/model"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func TestKnowledgeModelValidationAndSecrets(t *testing.T) {
|
||||
for _, kind := range []string{"embedding", "vision"} {
|
||||
in := knowledgeModelInput{Kind: kind, ModelID: " model ", BaseURL: "https://example.test/v1/", Protocol: "openai_chat_completions", MaxOutputTokens: 8192, Enabled: new(true)}
|
||||
if err := validateKnowledgeModel(&in); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if in.ModelID != "model" || in.BaseURL != "https://example.test/v1" {
|
||||
t.Fatal("not normalized")
|
||||
}
|
||||
}
|
||||
for _, in := range []knowledgeModelInput{
|
||||
{Kind: "other", ModelID: "m", BaseURL: "https://example.test"},
|
||||
{Kind: "embedding", ModelID: "m", BaseURL: "https://user:pass@example.test"},
|
||||
{Kind: "embedding", ModelID: "m", BaseURL: "https://example.test", APIKey: "key\nheader"},
|
||||
{Kind: "vision", ModelID: "m", BaseURL: "https://example.test", Protocol: "openai_embeddings", MaxOutputTokens: 8192},
|
||||
} {
|
||||
in.Enabled = new(true)
|
||||
if err := validateKnowledgeModel(&in); err == nil {
|
||||
t.Fatalf("invalid input accepted: %+v", in)
|
||||
}
|
||||
}
|
||||
m, obj, err := knowledgeModel([]byte(`{"kind":"vision","model_id":"v","api_key":"secret","enabled":true,"advanced_config":{"max_output_tokens":8192}}`))
|
||||
if err != nil || m.Kind != model.KindText || !m.AdvancedConfig.SupportsVision || m.APIKey != "secret" {
|
||||
t.Fatalf("decode: %+v %v", m, err)
|
||||
}
|
||||
out, _ := json.Marshal(publicKnowledgeModel(obj))
|
||||
if strings.Contains(string(out), "secret") || !strings.Contains(string(out), `"api_key_configured":true`) {
|
||||
t.Fatalf("secret leaked: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeModelRequiresEnabled(t *testing.T) {
|
||||
router := chi.NewRouter()
|
||||
new(Service).registerModelConfig(router)
|
||||
for _, kind := range []string{"embedding", "vision"} {
|
||||
for _, field := range []string{"", `,"enabled":null`} {
|
||||
body := `{"model_id":"m","base_url":"https://example.test","protocol":"openai_chat_completions","max_output_tokens":8192` + field + "}"
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, httptest.NewRequest("PUT", "/kb-models/"+kind, strings.NewReader(body)))
|
||||
if w.Code != 400 || !strings.Contains(w.Body.String(), "enabled") {
|
||||
t.Fatalf("%s %q: %d %s", kind, field, w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeModelConfigurationLifecycle(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
client := model.NewService(nil).WithEmbeddingDimensionProbe(func(_ context.Context, m model.Model) (int, error) { return 3, nil })
|
||||
s := NewService(resource.NewStore(pool), client)
|
||||
book, err := s.CreateUserKB(t.Context(), actor, resource.Object{"name": "config"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
in := knowledgeModelInput{ActorID: actor, Kind: "embedding", ModelID: "embed", BaseURL: "https://example.test/v1", APIKey: "secret", Enabled: new(true)}
|
||||
first, err := s.saveKnowledgeModel(t.Context(), in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, ok := first["revision"]; ok {
|
||||
t.Fatal("unexpected revision")
|
||||
}
|
||||
if _, ok := first["api_key"]; ok {
|
||||
t.Fatal("secret returned")
|
||||
}
|
||||
assertEmbeddingBinding(t, s, book.String("id"), first.String("id"), 3)
|
||||
in.ActorID = resource.ID()
|
||||
if _, err = pool.Exec(t.Context(), `INSERT INTO users(id,name,email,role) VALUES($1,'Admin B','admin-b@example.test','admin')`, in.ActorID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
in.APIKey = "rotated"
|
||||
if _, err = s.saveKnowledgeModel(t.Context(), in); err != nil {
|
||||
t.Fatalf("repeated save: %v", err)
|
||||
}
|
||||
in.APIKey = ""
|
||||
var owner, key string
|
||||
if err = pool.QueryRow(t.Context(), "SELECT owner_user_id::text, api_key FROM models WHERE id=$1", first.String("id")).Scan(&owner, &key); err != nil || owner != actor || key != "rotated" {
|
||||
t.Fatalf("key rotation failed to preserve ownership or persist key: %v", err)
|
||||
}
|
||||
in.ModelID = "replacement"
|
||||
next, err := s.saveKnowledgeModel(t.Context(), in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if next.String("id") != first.String("id") {
|
||||
t.Fatal("models record ID changed")
|
||||
}
|
||||
assertEmbeddingBinding(t, s, book.String("id"), next.String("id"), 3)
|
||||
var modelCount int
|
||||
if err = pool.QueryRow(t.Context(), "SELECT count(*) FROM models WHERE id=$1 AND kind='embedding'", first.String("id")).Scan(&modelCount); err != nil || modelCount != 1 {
|
||||
t.Fatalf("embedding not retained in models: %d %v", modelCount, err)
|
||||
}
|
||||
in.Enabled = new(false)
|
||||
if _, err = s.saveKnowledgeModel(t.Context(), in); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertEmbeddingBinding(t, s, book.String("id"), next.String("id"), 0)
|
||||
v := knowledgeModelInput{Kind: "vision", ModelID: "vision", BaseURL: "https://example.test/v1", APIKey: "vision-secret", Protocol: "openai_chat_completions", MaxOutputTokens: 8192, Enabled: new(true)}
|
||||
if _, err = s.saveKnowledgeModel(t.Context(), v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int
|
||||
if err = pool.QueryRow(t.Context(), "SELECT count(*) FROM knowledge_base_models").Scan(&count); err != nil || count != 1 {
|
||||
t.Fatalf("count %d %v", count, err)
|
||||
}
|
||||
if _, err = pool.Exec(t.Context(), `INSERT INTO knowledge_base_models(kind,model_id,base_url,api_key,protocol) VALUES('vision','duplicate','https://example.test','x','openai_chat_completions')`); err == nil {
|
||||
t.Fatal("third configuration allowed")
|
||||
}
|
||||
router := chi.NewRouter()
|
||||
s.registerModelConfig(router)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest("GET", "/kb-models", nil))
|
||||
if response.Code != 200 || strings.Contains(response.Body.String(), "secret") {
|
||||
t.Fatalf("list leaked secret: %s", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgeModelMigrationPreservesEmbedding(t *testing.T) {
|
||||
pool, actor := kbTestPool(t)
|
||||
ctx := t.Context()
|
||||
older, newer := resource.ID(), resource.ID()
|
||||
for i, id := range []string{older, newer} {
|
||||
_, err := pool.Exec(ctx, `INSERT INTO models(id,ownership_type,owner_user_id,model_id,display_name,protocol,base_url,api_key,advanced_config,kind,provider,embedding_config,created_at)
|
||||
VALUES($1,'system',$2,$3,'Embedding','openai_embeddings','https://example.test/v1','secret','{}','embedding','passthrough','{"dimension":3}',now()+$4*interval '1 second')`, id, actor, id, i)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s := NewService(resource.NewStore(pool), nil)
|
||||
book, err := s.CreateUserKB(ctx, actor, resource.Object{"name": "migration"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, "UPDATE knowledge_bases SET embedding_model_id=$2,embedding_dimension=3 WHERE id=$1", book.String("id"), older); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, "DROP TABLE knowledge_base_models"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
migration, err := os.ReadFile("../../migrations/000066_kb_models.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = pool.Exec(ctx, string(migration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var visionCount int
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM knowledge_base_models").Scan(&visionCount); err != nil || visionCount != 0 {
|
||||
t.Fatalf("migration copied embedding into vision table: %d %v", visionCount, err)
|
||||
}
|
||||
configured, err := s.ConfiguredModel(ctx, "embedding")
|
||||
if err != nil || configured.ID != newer || configured.APIKey != "secret" {
|
||||
t.Fatalf("migration chose wrong model: %s %v", configured.ID, err)
|
||||
}
|
||||
assertEmbeddingBinding(t, s, book.String("id"), older, 3)
|
||||
if err = s.SyncEmbeddingModels(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertEmbeddingBinding(t, s, book.String("id"), older, 3)
|
||||
var count int
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM models WHERE id IN ($1,$2)", older, newer).Scan(&count); err != nil || count != 2 {
|
||||
t.Fatalf("legacy models lost: %d %v", count, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLegacyOfficeUploadRejected(t *testing.T) {
|
||||
ole := []byte{0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1}
|
||||
for _, ext := range []string{"xls", "ppt", "doc", "XLS", "PPT", "DOC"} {
|
||||
for _, data := range [][]byte{ole, []byte("PK\x03\x04")} {
|
||||
_, _, err := importType("document."+ext, data)
|
||||
if err == nil || !strings.Contains(err.Error(), "客户端转换") {
|
||||
t.Fatalf("%s: expected conversion guidance, got %v", ext, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, ext := range []string{"xlsx", "pptx", "docx"} {
|
||||
if _, _, err := importType("renamed."+ext, ole); err == nil {
|
||||
t.Fatalf("accepted renamed OLE file as %s", ext)
|
||||
}
|
||||
// This checks the existing signature contract, not full Office parsing.
|
||||
if kind, _, err := importType("document."+strings.ToUpper(ext), []byte("PK\x03\x04")); err != nil || kind != ext {
|
||||
t.Fatalf("%s: %s %v", ext, kind, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Extract and validate before any model calls. The final pass uses only cached
|
||||
// results, so completion order cannot change image positions in the document.
|
||||
func describeDocumentImagesParallel(ctx context.Context, content, kind string, concurrency int, describe func(context.Context, []byte, string) (string, error)) (string, error) {
|
||||
batch := newImageLearningBatch()
|
||||
_, err := transformDocumentImages(content, kind, func(data []byte, mime string) (string, error) {
|
||||
batch.add(imageHash(data), func(attempt context.Context) (string, error) { return describe(attempt, data, mime) })
|
||||
return "图片待识别", nil
|
||||
}, true)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err = batch.run(ctx, concurrency); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return transformDocumentImages(content, kind, func(data []byte, _ string) (string, error) { return batch.results[imageHash(data)].result, nil }, true)
|
||||
}
|
||||
|
||||
type imageLearningTask struct {
|
||||
describe func(context.Context) (string, error)
|
||||
result string
|
||||
}
|
||||
|
||||
// One batch owns de-duplication, bounded workers and per-image failure handling.
|
||||
// Adapters collect references first and render results only after run returns.
|
||||
type imageLearningBatch struct {
|
||||
tasks []*imageLearningTask
|
||||
results map[string]*imageLearningTask
|
||||
}
|
||||
|
||||
func newImageLearningBatch() *imageLearningBatch {
|
||||
return &imageLearningBatch{results: map[string]*imageLearningTask{}}
|
||||
}
|
||||
func (b *imageLearningBatch) add(key string, describe func(context.Context) (string, error)) {
|
||||
if b.results[key] != nil {
|
||||
return
|
||||
}
|
||||
task := &imageLearningTask{describe: describe}
|
||||
b.results[key] = task
|
||||
b.tasks = append(b.tasks, task)
|
||||
}
|
||||
func (b *imageLearningBatch) run(ctx context.Context, concurrency int) error {
|
||||
jobs := make(chan int, len(b.tasks))
|
||||
for i := range b.tasks {
|
||||
jobs <- i
|
||||
}
|
||||
close(jobs)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < min(max(concurrency, 1), 20, len(b.tasks)); i++ {
|
||||
wg.Go(func() {
|
||||
for index := range jobs {
|
||||
task := b.tasks[index]
|
||||
result, err := describeImageWithRetries(ctx, index+1, task.describe)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
task.result = result
|
||||
}
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// A failed image contributes a visible placeholder, never aborts its siblings.
|
||||
func describeImageWithRetries(ctx context.Context, index int, describe func(context.Context) (string, error)) (string, error) {
|
||||
for attempt := 1; attempt <= 3; attempt++ {
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
imageCtx, stop := context.WithTimeout(ctx, 60*time.Second)
|
||||
result, err := describe(imageCtx)
|
||||
if imageCtx.Err() != nil {
|
||||
err = imageCtx.Err()
|
||||
}
|
||||
stop()
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
if err == nil {
|
||||
result, err = validateImportText([]byte(result))
|
||||
}
|
||||
if err == nil && strings.Contains(strings.ToLower(result), "data:image/") {
|
||||
err = resource.Invalid("图片描述不能包含内嵌图片数据")
|
||||
}
|
||||
if err == nil {
|
||||
return result, nil
|
||||
}
|
||||
slog.WarnContext(ctx, "文档图片识别失败", "image_index", index, "attempt", attempt, "error", err)
|
||||
}
|
||||
return "图片识别失败:已尝试 3 次,未生成描述", nil
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
)
|
||||
|
||||
func TestParallelImageDescriptions(t *testing.T) {
|
||||
for _, limit := range []int{1, 3, 10, 20} {
|
||||
t.Run(fmt.Sprint(limit), func(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
var source strings.Builder
|
||||
labels := map[string]string{}
|
||||
for i := 0; i < 40; i++ {
|
||||
img := image.NewRGBA(image.Rect(0, 0, 1, 1))
|
||||
img.Set(0, 0, color.RGBA{R: uint8(i), A: 255})
|
||||
var b bytes.Buffer
|
||||
if err := png.Encode(&b, img); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
labels[imageHash(b.Bytes())] = fmt.Sprintf("description-%02d", i)
|
||||
fmt.Fprintf(&source, `<img src="data:image/png;base64,%s">`, base64.StdEncoding.EncodeToString(b.Bytes()))
|
||||
}
|
||||
// Repeated image positions must reuse the same result.
|
||||
source.WriteString(source.String())
|
||||
started := make(chan struct{}, 40)
|
||||
release := make(chan struct{})
|
||||
var active, peak, calls atomic.Int32
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
got, err := describeDocumentImagesParallel(ctx, source.String(), "html", limit, func(ctx context.Context, data []byte, _ string) (string, error) {
|
||||
n := active.Add(1)
|
||||
defer active.Add(-1)
|
||||
calls.Add(1)
|
||||
for old := peak.Load(); n > old; old = peak.Load() {
|
||||
if peak.CompareAndSwap(old, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
started <- struct{}{}
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
}
|
||||
return labels[imageHash(data)], nil
|
||||
})
|
||||
if err == nil {
|
||||
previous := -1
|
||||
for i := 0; i < 40; i++ {
|
||||
pos := strings.Index(got, fmt.Sprintf("description-%02d", i))
|
||||
if pos <= previous {
|
||||
err = errors.New("image order changed")
|
||||
break
|
||||
}
|
||||
previous = pos
|
||||
}
|
||||
if strings.Contains(got, "base64") {
|
||||
err = errors.New("base64 remains")
|
||||
}
|
||||
}
|
||||
done <- err
|
||||
}()
|
||||
for i := 0; i < limit; i++ {
|
||||
select {
|
||||
case <-started:
|
||||
case <-ctx.Done():
|
||||
t.Fatal("workers did not run concurrently")
|
||||
}
|
||||
}
|
||||
close(release)
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if peak.Load() != int32(limit) || calls.Load() != 40 {
|
||||
t.Fatalf("peak=%d calls=%d", peak.Load(), calls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisionGateSharedLimitAndCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
||||
defer cancel()
|
||||
var gate visionGate
|
||||
limit := func(context.Context) (int, error) { return 1, nil }
|
||||
release, err := gate.acquire(ctx, limit)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
canceled, stop := context.WithCancel(ctx)
|
||||
stop()
|
||||
if _, err = gate.acquire(canceled, limit); !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
release()
|
||||
release() // Idempotent release must not create extra capacity.
|
||||
var wg sync.WaitGroup
|
||||
var active, peak atomic.Int32
|
||||
for i := 0; i < 20; i++ {
|
||||
wg.Go(func() {
|
||||
release, err := gate.acquire(ctx, limit)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
n := active.Add(1)
|
||||
for old := peak.Load(); n > old; old = peak.Load() {
|
||||
if peak.CompareAndSwap(old, n) {
|
||||
break
|
||||
}
|
||||
}
|
||||
active.Add(-1)
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
if peak.Load() != 1 {
|
||||
t.Fatalf("peak=%d", peak.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisionConcurrencyConfiguration(t *testing.T) {
|
||||
for _, n := range []int{-1, 0, 1, 10, 20, 21} {
|
||||
in := knowledgeModelInput{Kind: "vision", ModelID: "v", BaseURL: "https://example.test", Protocol: "openai_chat_completions", MaxOutputTokens: 8192, Enabled: new(true), Concurrency: &n}
|
||||
err := validateKnowledgeModel(&in)
|
||||
if (err == nil) != (n >= 1 && n <= 20) {
|
||||
t.Fatalf("n=%d err=%v", n, err)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{`{"kind":"vision","advanced_config":{}}`, `{"kind":"vision","advanced_config":{"concurrency":10}}`} {
|
||||
_, obj, err := knowledgeModel([]byte(raw))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := 1
|
||||
if strings.Contains(raw, "10") {
|
||||
expected = 10
|
||||
}
|
||||
if n := knowledgeVisionConcurrency(publicKnowledgeModel(obj)); n != expected {
|
||||
t.Fatalf("n=%d", n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVisionConcurrencyPersists(t *testing.T) {
|
||||
pool, _ := kbTestPool(t)
|
||||
s := NewService(resource.NewStore(pool), nil)
|
||||
in := knowledgeModelInput{Kind: "vision", ModelID: "v", BaseURL: "https://example.test", APIKey: "key", Protocol: "openai_chat_completions", MaxOutputTokens: 8192, Enabled: new(true)}
|
||||
for _, n := range []*int{nil, new(10), nil, new(1)} {
|
||||
in.Concurrency = n
|
||||
out, err := s.saveKnowledgeModel(t.Context(), in)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual, err := s.visionConcurrency(t.Context())
|
||||
if err != nil || actual != knowledgeVisionConcurrency(out) {
|
||||
t.Fatalf("actual=%d out=%v err=%v", actual, out, err)
|
||||
}
|
||||
if n != nil && actual != *n {
|
||||
t.Fatalf("actual=%d want=%d", actual, *n)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParallelImageFailuresDoNotInterruptLearning(t *testing.T) {
|
||||
for _, failures := range []int{2, 3} {
|
||||
t.Run(fmt.Sprint(failures), func(t *testing.T) {
|
||||
source := `<p>前文</p><img src="data:image/png;base64,` + base64.StdEncoding.EncodeToString(avatarImage(t, "png")) + `"><img src="data:image/webp;base64,` + base64.StdEncoding.EncodeToString(avatarImage(t, "webp")) + `"><p>后文</p>`
|
||||
var pngCalls, webpCalls atomic.Int32
|
||||
got, err := describeDocumentImagesParallel(t.Context(), source, "html", 2, func(ctx context.Context, _ []byte, mime string) (string, error) {
|
||||
if mime == "image/png" {
|
||||
if pngCalls.Add(1) <= int32(failures) {
|
||||
return "", errors.New("model failed")
|
||||
}
|
||||
return "恢复成功", nil
|
||||
}
|
||||
webpCalls.Add(1)
|
||||
return "另一张图片描述", nil
|
||||
})
|
||||
expected := "恢复成功"
|
||||
if failures == 3 {
|
||||
expected = "图片识别失败"
|
||||
}
|
||||
if err != nil || pngCalls.Load() != 3 || webpCalls.Load() != 1 || !strings.Contains(got, expected) || !strings.Contains(got, "另一张图片描述") || !strings.Contains(got, "后文") || strings.Contains(got, "base64") {
|
||||
t.Fatalf("got=%s err=%v png=%d webp=%d", got, err, pngCalls.Load(), webpCalls.Load())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidEmbeddedImageDoesNotInterruptLearning(t *testing.T) {
|
||||
got, err := describeDocumentImagesParallel(t.Context(), `<p>正文</p><img src="data:image/png;base64,???"><p>后文</p>`, "html", 1, func(context.Context, []byte, string) (string, error) {
|
||||
t.Fatal("invalid image reached model")
|
||||
return "", nil
|
||||
})
|
||||
if err != nil || !strings.Contains(got, "图片解析失败") || !strings.Contains(got, "后文") || strings.Contains(got, "base64") {
|
||||
t.Fatalf("got=%q err=%v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImageParentCancellationStopsRetries(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
calls := 0
|
||||
source := `<img src="data:image/png;base64,` + base64.StdEncoding.EncodeToString(avatarImage(t, "png")) + `">`
|
||||
_, err := describeDocumentImagesParallel(ctx, source, "html", 1, func(context.Context, []byte, string) (string, error) { calls++; cancel(); return "", context.Canceled })
|
||||
if !errors.Is(err, context.Canceled) || calls != 1 {
|
||||
t.Fatalf("calls=%d err=%v", calls, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestImagesHaveIndependentDeadlines(t *testing.T) {
|
||||
source := `<img src="data:image/png;base64,` + base64.StdEncoding.EncodeToString(avatarImage(t, "png")) + `"><img src="data:image/webp;base64,` + base64.StdEncoding.EncodeToString(avatarImage(t, "webp")) + `">`
|
||||
var deadlines []time.Time
|
||||
_, err := describeDocumentImagesParallel(t.Context(), source, "html", 1, func(ctx context.Context, _ []byte, _ string) (string, error) {
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok || time.Until(deadline) < 59*time.Second || time.Until(deadline) > 60*time.Second {
|
||||
t.Error("image did not receive its own 60-second budget")
|
||||
}
|
||||
deadlines = append(deadlines, deadline)
|
||||
return "image description", nil
|
||||
})
|
||||
if err != nil || len(deadlines) != 2 || !deadlines[1].After(deadlines[0]) {
|
||||
t.Fatalf("deadlines=%v err=%v", deadlines, err)
|
||||
}
|
||||
}
|
||||
@@ -161,7 +161,7 @@ func bumpDocumentVersion(ctx context.Context, tx pgx.Tx, current resource.Object
|
||||
}
|
||||
|
||||
// Embedding requests may outlive a grant. Recheck before returning retrieved text.
|
||||
func (s *Service) searchWithPermissionRecheck(ctx context.Context, actor string, accessible []resource.Object, input SearchInput) (SearchResponse, error) {
|
||||
func (s *Service) searchWithPermissionRecheck(ctx context.Context, actor string, accessible []resource.Object, input SearchInput, includeOriginalURL bool) (SearchResponse, error) {
|
||||
response, err := s.searchAccessible(ctx, accessible, input)
|
||||
if err != nil {
|
||||
return SearchResponse{}, err
|
||||
@@ -169,13 +169,16 @@ func (s *Service) searchWithPermissionRecheck(ctx context.Context, actor string,
|
||||
checked := map[string]bool{}
|
||||
for _, result := range response.Items {
|
||||
id := result.String("kb_id")
|
||||
if checked[id] {
|
||||
continue
|
||||
if !checked[id] {
|
||||
if _, err = s.accessibleKB(ctx, actor, id); err != nil {
|
||||
return SearchResponse{}, err
|
||||
}
|
||||
checked[id] = true
|
||||
}
|
||||
if _, err = s.accessibleKB(ctx, actor, id); err != nil {
|
||||
return SearchResponse{}, err
|
||||
if includeOriginalURL {
|
||||
result["url"] = s.originalAssetURL(result, result.String("document_id"), result.Bool("has_original"))
|
||||
}
|
||||
checked[id] = true
|
||||
delete(result, "has_original")
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
@@ -89,14 +89,38 @@ WHERE knowledge_bases.id = sqlc.arg(id);
|
||||
|
||||
-- name: CountKbDocuments :one
|
||||
SELECT count(*) FILTER (WHERE node_type = 'document')::bigint AS total,
|
||||
count(*) FILTER (WHERE node_type = 'document' AND chunk_count > 0)::bigint AS learned
|
||||
count(*) FILTER (WHERE node_type = 'document' AND status = 'learned')::bigint AS learned,
|
||||
count(*) FILTER (WHERE node_type = 'document' AND chunk_count > 0)::bigint AS indexed
|
||||
FROM knowledge_base_documents
|
||||
WHERE kb_id = $1;
|
||||
|
||||
-- name: CountKbLearningJobs :many
|
||||
WITH current_summary AS (
|
||||
SELECT history.operation, history.status
|
||||
FROM knowledge_base_learning_jobs history
|
||||
WHERE history.kb_id = $1 AND history.status <> 'failed'
|
||||
UNION ALL
|
||||
-- Failed documents are counted once. Historical job failures never
|
||||
-- contribute to this count.
|
||||
SELECT COALESCE(latest.operation, 'learn') AS operation, 'failed'::text AS status
|
||||
FROM knowledge_base_documents d
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT j.operation
|
||||
FROM knowledge_base_learning_jobs j
|
||||
WHERE j.kb_id = d.kb_id AND (j.document_id = d.id OR j.document_id IS NULL)
|
||||
ORDER BY j.created_at DESC, j.id DESC
|
||||
LIMIT 1
|
||||
) latest ON true
|
||||
WHERE d.kb_id = $1 AND d.node_type = 'document' AND d.status = 'failed'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM knowledge_base_learning_jobs active
|
||||
WHERE active.kb_id = d.kb_id
|
||||
AND (active.document_id = d.id OR active.document_id IS NULL)
|
||||
AND active.status IN ('pending', 'running')
|
||||
)
|
||||
)
|
||||
SELECT operation, status, count(*)::bigint AS total
|
||||
FROM knowledge_base_learning_jobs
|
||||
WHERE kb_id = $1
|
||||
FROM current_summary
|
||||
GROUP BY operation, status;
|
||||
|
||||
-- name: ClaimKbLearningJob :one
|
||||
@@ -141,6 +165,20 @@ WHERE id = sqlc.arg(id)
|
||||
AND attempts = sqlc.arg(attempts)
|
||||
AND locked_by = sqlc.arg(worker_id);
|
||||
|
||||
-- name: AdvanceKbLearningJobRevision :exec
|
||||
-- Preserve the revision guard across this attempt's own vector-failure write.
|
||||
-- External edits still invalidate/cancel the job through the normal write path.
|
||||
UPDATE knowledge_base_learning_jobs j
|
||||
SET document_revision = d.revision,
|
||||
updated_at = now()
|
||||
FROM knowledge_base_documents d
|
||||
WHERE j.id = sqlc.arg(id)
|
||||
AND j.document_id = d.id
|
||||
AND j.document_revision IS NOT NULL
|
||||
AND j.status = 'running'
|
||||
AND j.attempts = sqlc.arg(attempts)
|
||||
AND j.locked_by = sqlc.arg(worker_id);
|
||||
|
||||
-- name: FailKbLearningJob :exec
|
||||
UPDATE knowledge_base_learning_jobs
|
||||
SET status = CASE WHEN attempts >= max_attempts THEN 'failed' ELSE 'pending' END,
|
||||
@@ -628,3 +666,66 @@ SELECT EXISTS(SELECT 1 FROM knowledge_base_documents WHERE storage_key=sqlc.arg(
|
||||
|
||||
-- name: KbLockImageImport :one
|
||||
SELECT pg_try_advisory_xact_lock(hashtextextended(sqlc.arg(import_lock)::text, 0))::boolean;
|
||||
|
||||
-- name: ListKnowledgeModels :many
|
||||
SELECT to_jsonb(m) FROM knowledge_base_models m
|
||||
UNION ALL
|
||||
SELECT to_jsonb(e) FROM (SELECT * FROM models WHERE kind='embedding' AND ownership_type='system' AND deleted_at IS NULL ORDER BY created_at DESC,id DESC LIMIT 1) e;
|
||||
|
||||
-- name: GetKnowledgeModel :one
|
||||
SELECT to_jsonb(m) FROM knowledge_base_models m WHERE m.kind=$1
|
||||
UNION ALL
|
||||
SELECT to_jsonb(e) FROM (SELECT source.* FROM models source WHERE $1::text='embedding' AND source.kind='embedding' AND source.ownership_type='system' AND source.deleted_at IS NULL ORDER BY source.created_at DESC,source.id DESC LIMIT 1) e;
|
||||
|
||||
-- name: LockKnowledgeModel :exec
|
||||
SELECT pg_advisory_xact_lock(hashtextextended('knowledge-model:' || $1::text, 0));
|
||||
|
||||
-- name: SaveKnowledgeModel :one
|
||||
INSERT INTO knowledge_base_models(id,kind,model_id,base_url,api_key,protocol,proxy_id,advanced_config,enabled)
|
||||
VALUES (($1::jsonb->>'id')::uuid,$1::jsonb->>'kind',$1::jsonb->>'model_id',$1::jsonb->>'base_url',
|
||||
$1::jsonb->>'api_key',$1::jsonb->>'protocol',$1::jsonb->>'proxy_id',
|
||||
$1::jsonb->'advanced_config',($1::jsonb->>'enabled')::boolean)
|
||||
ON CONFLICT(kind) DO UPDATE SET id=EXCLUDED.id,model_id=EXCLUDED.model_id,base_url=EXCLUDED.base_url,
|
||||
api_key=EXCLUDED.api_key,protocol=EXCLUDED.protocol,proxy_id=EXCLUDED.proxy_id,
|
||||
advanced_config=EXCLUDED.advanced_config,enabled=EXCLUDED.enabled,
|
||||
updated_at=now()
|
||||
RETURNING to_jsonb(knowledge_base_models.*);
|
||||
|
||||
-- name: ListKnowledgeModelAffectedBases :many
|
||||
SELECT id::text FROM knowledge_bases WHERE embedding_model_id=$1::uuid OR embedding_model_id IS NULL ORDER BY id;
|
||||
|
||||
-- name: SaveKnowledgeEmbeddingModel :one
|
||||
INSERT INTO models(id,kind,ownership_type,owner_user_id,model_id,display_name,base_url,api_key,protocol,proxy_id,embedding_config,advanced_config,enabled)
|
||||
VALUES (($1::jsonb->>'id')::uuid,'embedding','system',($1::jsonb->>'owner_user_id')::uuid,
|
||||
$1::jsonb->>'model_id',$1::jsonb->>'model_id',$1::jsonb->>'base_url',$1::jsonb->>'api_key',
|
||||
'openai_embeddings',$1::jsonb->>'proxy_id',$1::jsonb->'embedding_config','{}',($1::jsonb->>'enabled')::boolean)
|
||||
ON CONFLICT(id) DO UPDATE SET model_id=EXCLUDED.model_id,display_name=EXCLUDED.display_name,
|
||||
base_url=EXCLUDED.base_url,api_key=EXCLUDED.api_key,proxy_id=EXCLUDED.proxy_id,
|
||||
embedding_config=EXCLUDED.embedding_config,enabled=EXCLUDED.enabled,updated_at=now()
|
||||
RETURNING to_jsonb(models.*);
|
||||
|
||||
-- name: RenewKbLearningJob :execrows
|
||||
UPDATE knowledge_base_learning_jobs
|
||||
SET locked_at = now(), updated_at = now()
|
||||
WHERE id = sqlc.arg(id) AND status = 'running'
|
||||
AND attempts = sqlc.arg(attempts) AND locked_by = sqlc.arg(worker_id);
|
||||
|
||||
-- name: GetKnowledgeConcurrency :one
|
||||
SELECT value FROM settings WHERE key='kb_concurrency';
|
||||
|
||||
-- name: SaveKnowledgeConcurrency :exec
|
||||
INSERT INTO settings(key,value,schema_version,updated_by_user_id)
|
||||
VALUES('kb_concurrency',sqlc.arg(value)::jsonb,1,sqlc.narg(actor)::uuid)
|
||||
ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value, updated_by_user_id=EXCLUDED.updated_by_user_id, updated_at=now();
|
||||
|
||||
-- name: LockKnowledgeLearningAdmission :exec
|
||||
SELECT pg_advisory_xact_lock(731246801);
|
||||
|
||||
-- name: CountRunningKnowledgeJobs :one
|
||||
SELECT count(*) FROM knowledge_base_learning_jobs WHERE status IN ('running', 'canceled') AND locked_at >= now() - interval '5 minutes';
|
||||
|
||||
-- name: ReleaseCanceledKnowledgeJob :exec
|
||||
UPDATE knowledge_base_learning_jobs
|
||||
SET locked_at=NULL, locked_by=NULL, updated_at=now()
|
||||
WHERE id=sqlc.arg(id) AND attempts=sqlc.arg(attempts)
|
||||
AND locked_by=sqlc.arg(worker_id) AND status='canceled';
|
||||
@@ -35,6 +35,12 @@ func testBatchRestudyRoute(t *testing.T, ownership string) {
|
||||
return doc.String("id")
|
||||
}
|
||||
docID := create(kbID, "document")
|
||||
if _, err := pool.Exec(ctx, `INSERT INTO knowledge_base_chunks(kb_id,document_id,chunk_index,content) VALUES($1,$2,0,'old chunk')`, kbID, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pool.Exec(ctx, `UPDATE knowledge_base_documents SET chunk_count=1,status='learned' WHERE id=$1`, docID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
folderID := create(kbID, "folder")
|
||||
foreignID := create(createKB(), "document")
|
||||
missingID := resource.ID()
|
||||
@@ -71,6 +77,18 @@ func testBatchRestudyRoute(t *testing.T, ownership string) {
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM knowledge_base_learning_jobs WHERE document_id=$1 AND status IN ('pending','running')`, docID).Scan(&jobs); err != nil || jobs != 1 {
|
||||
t.Fatalf("expected one active job: %d %v", jobs, err)
|
||||
}
|
||||
var operation string
|
||||
if err := pool.QueryRow(ctx, `SELECT operation FROM knowledge_base_learning_jobs WHERE document_id=$1 AND status='pending'`, docID).Scan(&operation); err != nil || operation != OperationRelearn {
|
||||
t.Fatalf("operation=%s err=%v", operation, err)
|
||||
}
|
||||
document, err := s.GetDocument(ctx, docID)
|
||||
if err != nil || document.String("status") != "pending" || objectInt64(document["chunk_count"]) != 0 {
|
||||
t.Fatalf("document=%v err=%v", document, err)
|
||||
}
|
||||
chunks, err := s.ListChunks(ctx, docID)
|
||||
if err != nil || len(chunks) != 0 {
|
||||
t.Fatalf("stale chunks=%v err=%v", chunks, err)
|
||||
}
|
||||
foreign, err := s.GetDocument(ctx, foreignID)
|
||||
if err != nil || fmt.Sprint(foreign["revision"]) != "1" {
|
||||
t.Fatalf("foreign document changed: %v %v", foreign, err)
|
||||
|
||||
@@ -178,7 +178,6 @@ func (s *Service) searchAccessible(ctx context.Context, accessible []resource.Ob
|
||||
}
|
||||
}
|
||||
}
|
||||
delete(result, "has_original")
|
||||
}
|
||||
if len(normalized.Filters) > 0 {
|
||||
warnings = append(warnings, "filters_not_applied")
|
||||
|
||||
@@ -18,6 +18,8 @@ import (
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
modelClient *model.Service
|
||||
publicURL string
|
||||
anydoc AnyDocConfig
|
||||
CRUD *resource.CRUD
|
||||
store *resource.Store
|
||||
@@ -34,7 +36,10 @@ type Embedder interface {
|
||||
}
|
||||
|
||||
func NewService(store *resource.Store, models *model.Service) *Service {
|
||||
s := &Service{store: store, models: models, worker: resource.ID()}
|
||||
s := &Service{store: store, modelClient: models, worker: resource.ID()}
|
||||
if models != nil {
|
||||
s.models = models
|
||||
}
|
||||
s.CRUD = resource.NewCRUD(store, resource.Definition{
|
||||
Kind: "kb",
|
||||
Path: "/kb",
|
||||
@@ -105,6 +110,8 @@ func (s *Service) decorate(ctx context.Context, q resource.Queryer, item resourc
|
||||
}
|
||||
item["document_count"] = count.Total
|
||||
item["learned_count"] = count.Learned
|
||||
// Existing chunks remain searchable during vector learning or after vector failure.
|
||||
item["indexed_count"] = count.Indexed
|
||||
decorateRetrievalCapabilities(item)
|
||||
summary := resource.Object{
|
||||
"pending": int64(0),
|
||||
@@ -404,3 +411,9 @@ func (s *Service) persistAvatar(ctx context.Context, tx pgx.Tx, in resource.Obje
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithPublicURL configures the externally reachable origin for document assets.
|
||||
func (s *Service) WithPublicURL(publicURL string) *Service {
|
||||
s.publicURL = strings.TrimRight(publicURL, "/")
|
||||
return s
|
||||
}
|
||||
@@ -9,6 +9,32 @@ import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const advanceKbLearningJobRevision = `-- name: AdvanceKbLearningJobRevision :exec
|
||||
UPDATE knowledge_base_learning_jobs j
|
||||
SET document_revision = d.revision,
|
||||
updated_at = now()
|
||||
FROM knowledge_base_documents d
|
||||
WHERE j.id = $1
|
||||
AND j.document_id = d.id
|
||||
AND j.document_revision IS NOT NULL
|
||||
AND j.status = 'running'
|
||||
AND j.attempts = $2
|
||||
AND j.locked_by = $3
|
||||
`
|
||||
|
||||
type AdvanceKbLearningJobRevisionParams struct {
|
||||
ID string
|
||||
Attempts int32
|
||||
WorkerID *string
|
||||
}
|
||||
|
||||
// Preserve the revision guard across this attempt's own vector-failure write.
|
||||
// External edits still invalidate/cancel the job through the normal write path.
|
||||
func (q *Queries) AdvanceKbLearningJobRevision(ctx context.Context, arg AdvanceKbLearningJobRevisionParams) error {
|
||||
_, err := q.db.Exec(ctx, advanceKbLearningJobRevision, arg.ID, arg.Attempts, arg.WorkerID)
|
||||
return err
|
||||
}
|
||||
|
||||
const avatarReferenced = `-- name: AvatarReferenced :one
|
||||
SELECT EXISTS (SELECT 1 FROM knowledge_bases WHERE avatar_s3_key = $1)
|
||||
`
|
||||
@@ -152,7 +178,8 @@ func (q *Queries) CountKbDocumentChildren(ctx context.Context, parentID *string)
|
||||
|
||||
const countKbDocuments = `-- name: CountKbDocuments :one
|
||||
SELECT count(*) FILTER (WHERE node_type = 'document')::bigint AS total,
|
||||
count(*) FILTER (WHERE node_type = 'document' AND chunk_count > 0)::bigint AS learned
|
||||
count(*) FILTER (WHERE node_type = 'document' AND status = 'learned')::bigint AS learned,
|
||||
count(*) FILTER (WHERE node_type = 'document' AND chunk_count > 0)::bigint AS indexed
|
||||
FROM knowledge_base_documents
|
||||
WHERE kb_id = $1
|
||||
`
|
||||
@@ -160,19 +187,43 @@ WHERE kb_id = $1
|
||||
type CountKbDocumentsRow struct {
|
||||
Total int64
|
||||
Learned int64
|
||||
Indexed int64
|
||||
}
|
||||
|
||||
func (q *Queries) CountKbDocuments(ctx context.Context, kbID string) (CountKbDocumentsRow, error) {
|
||||
row := q.db.QueryRow(ctx, countKbDocuments, kbID)
|
||||
var i CountKbDocumentsRow
|
||||
err := row.Scan(&i.Total, &i.Learned)
|
||||
err := row.Scan(&i.Total, &i.Learned, &i.Indexed)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const countKbLearningJobs = `-- name: CountKbLearningJobs :many
|
||||
WITH current_summary AS (
|
||||
SELECT history.operation, history.status
|
||||
FROM knowledge_base_learning_jobs history
|
||||
WHERE history.kb_id = $1 AND history.status <> 'failed'
|
||||
UNION ALL
|
||||
-- Failed documents are counted once. Historical job failures never
|
||||
-- contribute to this count.
|
||||
SELECT COALESCE(latest.operation, 'learn') AS operation, 'failed'::text AS status
|
||||
FROM knowledge_base_documents d
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT j.operation
|
||||
FROM knowledge_base_learning_jobs j
|
||||
WHERE j.kb_id = d.kb_id AND (j.document_id = d.id OR j.document_id IS NULL)
|
||||
ORDER BY j.created_at DESC, j.id DESC
|
||||
LIMIT 1
|
||||
) latest ON true
|
||||
WHERE d.kb_id = $1 AND d.node_type = 'document' AND d.status = 'failed'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM knowledge_base_learning_jobs active
|
||||
WHERE active.kb_id = d.kb_id
|
||||
AND (active.document_id = d.id OR active.document_id IS NULL)
|
||||
AND active.status IN ('pending', 'running')
|
||||
)
|
||||
)
|
||||
SELECT operation, status, count(*)::bigint AS total
|
||||
FROM knowledge_base_learning_jobs
|
||||
WHERE kb_id = $1
|
||||
FROM current_summary
|
||||
GROUP BY operation, status
|
||||
`
|
||||
|
||||
@@ -202,6 +253,17 @@ func (q *Queries) CountKbLearningJobs(ctx context.Context, kbID string) ([]Count
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const countRunningKnowledgeJobs = `-- name: CountRunningKnowledgeJobs :one
|
||||
SELECT count(*) FROM knowledge_base_learning_jobs WHERE status IN ('running', 'canceled') AND locked_at >= now() - interval '5 minutes'
|
||||
`
|
||||
|
||||
func (q *Queries) CountRunningKnowledgeJobs(ctx context.Context) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, countRunningKnowledgeJobs)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const createKbDocument = `-- name: CreateKbDocument :exec
|
||||
INSERT INTO knowledge_base_documents (
|
||||
id, kb_id, title, source_type, content, file_name, mime_type, size_bytes,
|
||||
@@ -585,6 +647,30 @@ func (q *Queries) GetKbResource(ctx context.Context, id string) ([]byte, error)
|
||||
return to_jsonb, err
|
||||
}
|
||||
|
||||
const getKnowledgeConcurrency = `-- name: GetKnowledgeConcurrency :one
|
||||
SELECT value FROM settings WHERE key='kb_concurrency'
|
||||
`
|
||||
|
||||
func (q *Queries) GetKnowledgeConcurrency(ctx context.Context) ([]byte, error) {
|
||||
row := q.db.QueryRow(ctx, getKnowledgeConcurrency)
|
||||
var value []byte
|
||||
err := row.Scan(&value)
|
||||
return value, err
|
||||
}
|
||||
|
||||
const getKnowledgeModel = `-- name: GetKnowledgeModel :one
|
||||
SELECT to_jsonb(m) FROM knowledge_base_models m WHERE m.kind=$1
|
||||
UNION ALL
|
||||
SELECT to_jsonb(e) FROM (SELECT source.id, source.ownership_type, source.owner_user_id, source.model_id, source.display_name, source.protocol, source.base_url, source.api_key, source.advanced_config, source.credit_multiplier, source.enabled, source.created_at, source.updated_at, source.deleted_at, source.kind, source.provider, source.provider_options, source.image_config, source.image_pricing, source.video_config, source.video_pricing, source.proxy_id, source.embedding_config FROM models source WHERE $1::text='embedding' AND source.kind='embedding' AND source.ownership_type='system' AND source.deleted_at IS NULL ORDER BY source.created_at DESC,source.id DESC LIMIT 1) e
|
||||
`
|
||||
|
||||
func (q *Queries) GetKnowledgeModel(ctx context.Context, kind string) ([]byte, error) {
|
||||
row := q.db.QueryRow(ctx, getKnowledgeModel, kind)
|
||||
var to_jsonb []byte
|
||||
err := row.Scan(&to_jsonb)
|
||||
return to_jsonb, err
|
||||
}
|
||||
|
||||
const insertKbChunk = `-- name: InsertKbChunk :exec
|
||||
INSERT INTO knowledge_base_chunks (
|
||||
kb_id, document_id, chunk_index, content, token_count, search_tokens,
|
||||
@@ -956,6 +1042,56 @@ func (q *Queries) ListKbResources(ctx context.Context) ([][]byte, error) {
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listKnowledgeModelAffectedBases = `-- name: ListKnowledgeModelAffectedBases :many
|
||||
SELECT id::text FROM knowledge_bases WHERE embedding_model_id=$1::uuid OR embedding_model_id IS NULL ORDER BY id
|
||||
`
|
||||
|
||||
func (q *Queries) ListKnowledgeModelAffectedBases(ctx context.Context, dollar_1 string) ([]string, error) {
|
||||
rows, err := q.db.Query(ctx, listKnowledgeModelAffectedBases, dollar_1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listKnowledgeModels = `-- name: ListKnowledgeModels :many
|
||||
SELECT to_jsonb(m) FROM knowledge_base_models m
|
||||
UNION ALL
|
||||
SELECT to_jsonb(e) FROM (SELECT id, ownership_type, owner_user_id, model_id, display_name, protocol, base_url, api_key, advanced_config, credit_multiplier, enabled, created_at, updated_at, deleted_at, kind, provider, provider_options, image_config, image_pricing, video_config, video_pricing, proxy_id, embedding_config FROM models WHERE kind='embedding' AND ownership_type='system' AND deleted_at IS NULL ORDER BY created_at DESC,id DESC LIMIT 1) e
|
||||
`
|
||||
|
||||
func (q *Queries) ListKnowledgeModels(ctx context.Context) ([][]byte, error) {
|
||||
rows, err := q.db.Query(ctx, listKnowledgeModels)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := [][]byte{}
|
||||
for rows.Next() {
|
||||
var to_jsonb []byte
|
||||
if err := rows.Scan(&to_jsonb); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, to_jsonb)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockKbDocument = `-- name: LockKbDocument :one
|
||||
SELECT to_jsonb(d)
|
||||
FROM knowledge_base_documents d
|
||||
@@ -984,6 +1120,24 @@ func (q *Queries) LockKbResource(ctx context.Context, id string) ([]byte, error)
|
||||
return to_jsonb, err
|
||||
}
|
||||
|
||||
const lockKnowledgeLearningAdmission = `-- name: LockKnowledgeLearningAdmission :exec
|
||||
SELECT pg_advisory_xact_lock(731246801)
|
||||
`
|
||||
|
||||
func (q *Queries) LockKnowledgeLearningAdmission(ctx context.Context) error {
|
||||
_, err := q.db.Exec(ctx, lockKnowledgeLearningAdmission)
|
||||
return err
|
||||
}
|
||||
|
||||
const lockKnowledgeModel = `-- name: LockKnowledgeModel :exec
|
||||
SELECT pg_advisory_xact_lock(hashtextextended('knowledge-model:' || $1::text, 0))
|
||||
`
|
||||
|
||||
func (q *Queries) LockKnowledgeModel(ctx context.Context, dollar_1 string) error {
|
||||
_, err := q.db.Exec(ctx, lockKnowledgeModel, dollar_1)
|
||||
return err
|
||||
}
|
||||
|
||||
const markKbDocumentFailed = `-- name: MarkKbDocumentFailed :exec
|
||||
UPDATE knowledge_base_documents
|
||||
SET status = 'failed',
|
||||
@@ -1098,6 +1252,45 @@ func (q *Queries) PageKbResources(ctx context.Context, dollar_1 []byte) ([][]byt
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const releaseCanceledKnowledgeJob = `-- name: ReleaseCanceledKnowledgeJob :exec
|
||||
UPDATE knowledge_base_learning_jobs
|
||||
SET locked_at=NULL, locked_by=NULL, updated_at=now()
|
||||
WHERE id=$1 AND attempts=$2
|
||||
AND locked_by=$3 AND status='canceled'
|
||||
`
|
||||
|
||||
type ReleaseCanceledKnowledgeJobParams struct {
|
||||
ID string
|
||||
Attempts int32
|
||||
WorkerID *string
|
||||
}
|
||||
|
||||
func (q *Queries) ReleaseCanceledKnowledgeJob(ctx context.Context, arg ReleaseCanceledKnowledgeJobParams) error {
|
||||
_, err := q.db.Exec(ctx, releaseCanceledKnowledgeJob, arg.ID, arg.Attempts, arg.WorkerID)
|
||||
return err
|
||||
}
|
||||
|
||||
const renewKbLearningJob = `-- name: RenewKbLearningJob :execrows
|
||||
UPDATE knowledge_base_learning_jobs
|
||||
SET locked_at = now(), updated_at = now()
|
||||
WHERE id = $1 AND status = 'running'
|
||||
AND attempts = $2 AND locked_by = $3
|
||||
`
|
||||
|
||||
type RenewKbLearningJobParams struct {
|
||||
ID string
|
||||
Attempts int32
|
||||
WorkerID *string
|
||||
}
|
||||
|
||||
func (q *Queries) RenewKbLearningJob(ctx context.Context, arg RenewKbLearningJobParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, renewKbLearningJob, arg.ID, arg.Attempts, arg.WorkerID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const resolveKbImportTag = `-- name: ResolveKbImportTag :one
|
||||
INSERT INTO tags(name,created_by_user_id) VALUES($1,$2)
|
||||
ON CONFLICT (lower(name)) WHERE deleted_at IS NULL
|
||||
@@ -1116,6 +1309,59 @@ func (q *Queries) ResolveKbImportTag(ctx context.Context, arg ResolveKbImportTag
|
||||
return id, err
|
||||
}
|
||||
|
||||
const saveKnowledgeConcurrency = `-- name: SaveKnowledgeConcurrency :exec
|
||||
INSERT INTO settings(key,value,schema_version,updated_by_user_id)
|
||||
VALUES('kb_concurrency',$1::jsonb,1,$2::uuid)
|
||||
ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value, updated_by_user_id=EXCLUDED.updated_by_user_id, updated_at=now()
|
||||
`
|
||||
|
||||
type SaveKnowledgeConcurrencyParams struct {
|
||||
Value []byte
|
||||
Actor *string
|
||||
}
|
||||
|
||||
func (q *Queries) SaveKnowledgeConcurrency(ctx context.Context, arg SaveKnowledgeConcurrencyParams) error {
|
||||
_, err := q.db.Exec(ctx, saveKnowledgeConcurrency, arg.Value, arg.Actor)
|
||||
return err
|
||||
}
|
||||
|
||||
const saveKnowledgeEmbeddingModel = `-- name: SaveKnowledgeEmbeddingModel :one
|
||||
INSERT INTO models(id,kind,ownership_type,owner_user_id,model_id,display_name,base_url,api_key,protocol,proxy_id,embedding_config,advanced_config,enabled)
|
||||
VALUES (($1::jsonb->>'id')::uuid,'embedding','system',($1::jsonb->>'owner_user_id')::uuid,
|
||||
$1::jsonb->>'model_id',$1::jsonb->>'model_id',$1::jsonb->>'base_url',$1::jsonb->>'api_key',
|
||||
'openai_embeddings',$1::jsonb->>'proxy_id',$1::jsonb->'embedding_config','{}',($1::jsonb->>'enabled')::boolean)
|
||||
ON CONFLICT(id) DO UPDATE SET model_id=EXCLUDED.model_id,display_name=EXCLUDED.display_name,
|
||||
base_url=EXCLUDED.base_url,api_key=EXCLUDED.api_key,proxy_id=EXCLUDED.proxy_id,
|
||||
embedding_config=EXCLUDED.embedding_config,enabled=EXCLUDED.enabled,updated_at=now()
|
||||
RETURNING to_jsonb(models.*)
|
||||
`
|
||||
|
||||
func (q *Queries) SaveKnowledgeEmbeddingModel(ctx context.Context, dollar_1 []byte) ([]byte, error) {
|
||||
row := q.db.QueryRow(ctx, saveKnowledgeEmbeddingModel, dollar_1)
|
||||
var to_jsonb []byte
|
||||
err := row.Scan(&to_jsonb)
|
||||
return to_jsonb, err
|
||||
}
|
||||
|
||||
const saveKnowledgeModel = `-- name: SaveKnowledgeModel :one
|
||||
INSERT INTO knowledge_base_models(id,kind,model_id,base_url,api_key,protocol,proxy_id,advanced_config,enabled)
|
||||
VALUES (($1::jsonb->>'id')::uuid,$1::jsonb->>'kind',$1::jsonb->>'model_id',$1::jsonb->>'base_url',
|
||||
$1::jsonb->>'api_key',$1::jsonb->>'protocol',$1::jsonb->>'proxy_id',
|
||||
$1::jsonb->'advanced_config',($1::jsonb->>'enabled')::boolean)
|
||||
ON CONFLICT(kind) DO UPDATE SET id=EXCLUDED.id,model_id=EXCLUDED.model_id,base_url=EXCLUDED.base_url,
|
||||
api_key=EXCLUDED.api_key,protocol=EXCLUDED.protocol,proxy_id=EXCLUDED.proxy_id,
|
||||
advanced_config=EXCLUDED.advanced_config,enabled=EXCLUDED.enabled,
|
||||
updated_at=now()
|
||||
RETURNING to_jsonb(knowledge_base_models.*)
|
||||
`
|
||||
|
||||
func (q *Queries) SaveKnowledgeModel(ctx context.Context, dollar_1 []byte) ([]byte, error) {
|
||||
row := q.db.QueryRow(ctx, saveKnowledgeModel, dollar_1)
|
||||
var to_jsonb []byte
|
||||
err := row.Scan(&to_jsonb)
|
||||
return to_jsonb, err
|
||||
}
|
||||
|
||||
const searchKbChunksLexical = `-- name: SearchKbChunksLexical :many
|
||||
SELECT jsonb_build_object(
|
||||
'kb_id', c.kb_id,
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
@@ -18,11 +17,11 @@ import (
|
||||
|
||||
type ImageDescriber interface {
|
||||
ImageModels(context.Context, string) ([]resource.Object, error)
|
||||
DescribeImage(context.Context, string, string, string, []byte) (string, error)
|
||||
DescribeImage(context.Context, string, string, []byte) (string, error)
|
||||
}
|
||||
|
||||
func (s *Service) WithImageDescriber(v ImageDescriber) *Service { s.vision = v; return s }
|
||||
func imageFileType(t string) bool { return t == "jpg" || t == "png" }
|
||||
func imageFileType(t string) bool { return t == "jpg" || t == "png" || t == "webp" }
|
||||
|
||||
func (s *Service) serveImageModels(w http.ResponseWriter, r *http.Request, admin bool) {
|
||||
actor, ok := identity.UserFromContext(r.Context())
|
||||
@@ -35,7 +34,7 @@ func (s *Service) serveImageModels(w http.ResponseWriter, r *http.Request, admin
|
||||
return
|
||||
}
|
||||
if s.vision == nil {
|
||||
resource.Fail(r.Context(), w, resource.Invalid("图片解析模型未配置"))
|
||||
resource.Fail(r.Context(), w, resource.Invalid("知识库图片解析服务不可用"))
|
||||
return
|
||||
}
|
||||
items, err := s.vision.ImageModels(r.Context(), actor.ID)
|
||||
@@ -46,17 +45,17 @@ func (s *Service) serveImageModels(w http.ResponseWriter, r *http.Request, admin
|
||||
resource.JSON(r.Context(), w, 200, resource.Object{"items": items})
|
||||
}
|
||||
|
||||
func (s *Service) parseImageImport(ctx context.Context, c importContext, modelID string) (resource.Object, error) {
|
||||
return s.processImageImport(ctx, c, modelID, false)
|
||||
func (s *Service) parseImageImport(ctx context.Context, c importContext) (resource.Object, error) {
|
||||
return s.processImageImport(ctx, c, false)
|
||||
}
|
||||
|
||||
// Keep the import lock through persistence for the unified import flow.
|
||||
func (s *Service) processImageImport(ctx context.Context, c importContext, modelID string, save bool) (resource.Object, error) {
|
||||
if !imageFileType(c.Type) || strings.TrimSpace(modelID) == "" {
|
||||
return nil, resource.Invalid("图片解析需要 JPG/PNG 原件和 model_id")
|
||||
func (s *Service) processImageImport(ctx context.Context, c importContext, save bool) (resource.Object, error) {
|
||||
if !imageFileType(c.Type) {
|
||||
return nil, resource.Invalid("图片解析需要 JPG/PNG/WebP 原件")
|
||||
}
|
||||
if s.vision == nil {
|
||||
return nil, resource.Invalid("图片解析模型未配置")
|
||||
return nil, resource.Invalid("知识库图片解析服务不可用")
|
||||
}
|
||||
// Bound the entire operation, including lock acquisition and permission checks.
|
||||
ctx, cancel := context.WithTimeout(ctx, 100*time.Second)
|
||||
@@ -125,7 +124,7 @@ func (s *Service) processImageImport(ctx context.Context, c importContext, model
|
||||
if typ != c.Type || kind != c.MIME {
|
||||
return nil, resource.Invalid("图片原件与导入凭证不匹配")
|
||||
}
|
||||
content, err := s.vision.DescribeImage(ctx, c.Actor, modelID, kind, data)
|
||||
content, err := s.describeVisionImage(ctx, c.Actor, kind, data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -139,7 +138,7 @@ func (s *Service) processImageImport(ctx context.Context, c importContext, model
|
||||
if err = s.importAccess(ctx, c); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.Purpose, c.ModelID, c.Hash = "result", modelID, convertedHash(content)
|
||||
c.Purpose, c.Hash = "result", convertedHash(content)
|
||||
token, err := s.signImport(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -158,7 +157,7 @@ func originalImageMetadata(doc resource.Object, admin bool) resource.Object {
|
||||
prefix = "/api/admin/v1/kb/"
|
||||
}
|
||||
path := prefix + doc.String("kb_id") + "/documents/" + doc.String("id") + "/file/detail"
|
||||
return resource.Object{"kb_id": doc.String("kb_id"), "document_id": doc.String("id"), "file_type": doc.String("file_type"), "mime_type": map[string]string{"jpg": "image/jpeg", "png": "image/png"}[doc.String("file_type")], "preview_url": path + "?preview=true", "download_url": path, "read_tool": "kb_get_document_image"}
|
||||
return resource.Object{"kb_id": doc.String("kb_id"), "document_id": doc.String("id"), "file_type": doc.String("file_type"), "mime_type": map[string]string{"jpg": "image/jpeg", "png": "image/png", "webp": "image/webp"}[doc.String("file_type")], "preview_url": path + "?preview=true", "download_url": path, "read_tool": "kb_get_document_image"}
|
||||
}
|
||||
|
||||
func (s *Service) readMCPDocumentImage(ctx context.Context, actor string, args map[string]any) (resource.Object, error) {
|
||||
@@ -195,7 +194,7 @@ func (s *Service) readMCPDocumentImage(ctx context.Context, actor string, args m
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if kind != map[string]string{"jpg": "image/jpeg", "png": "image/png"}[doc.String("file_type")] {
|
||||
if kind != map[string]string{"jpg": "image/jpeg", "png": "image/png", "webp": "image/webp"}[doc.String("file_type")] {
|
||||
return nil, resource.Invalid("原图格式无效")
|
||||
}
|
||||
if _, err = s.GetAccessible(ctx, in.KB, actor); err != nil {
|
||||
|
||||
@@ -29,7 +29,7 @@ type poolCheckingVision struct {
|
||||
check func(context.Context) error
|
||||
}
|
||||
|
||||
func (v *poolCheckingVision) DescribeImage(ctx context.Context, _, _, _ string, _ []byte) (string, error) {
|
||||
func (v *poolCheckingVision) DescribeImage(ctx context.Context, _, _ string, _ []byte) (string, error) {
|
||||
if err := v.check(ctx); err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -73,19 +73,19 @@ func TestImageParseWithSingleBusinessConnection(t *testing.T) {
|
||||
return err
|
||||
}
|
||||
// A separate service has no shared in-memory guard, like another process.
|
||||
if _, err := other.parseImageImport(ctx, c, "vision"); err == nil || !strings.Contains(err.Error(), "图片正在解析") {
|
||||
if _, err := other.parseImageImport(ctx, c); err == nil || !strings.Contains(err.Error(), "图片正在解析") {
|
||||
t.Errorf("concurrent parse was not rejected: %v", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if _, err := s.parseImageImport(ctx, c, "vision"); err != nil {
|
||||
if _, err := s.parseImageImport(ctx, c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if otherVision.calls != 0 {
|
||||
t.Fatal("duplicate paid model call")
|
||||
}
|
||||
// The advisory lock must be released when the first request finishes.
|
||||
if _, err := other.parseImageImport(ctx, c, "vision"); err != nil || otherVision.calls != 1 {
|
||||
if _, err := other.parseImageImport(ctx, c); err != nil || otherVision.calls != 1 {
|
||||
t.Fatalf("lock not released: calls=%d err=%v", otherVision.calls, err)
|
||||
}
|
||||
}
|
||||
@@ -98,15 +98,18 @@ type visionStub struct {
|
||||
func (v *visionStub) ImageModels(context.Context, string) ([]resource.Object, error) {
|
||||
return []resource.Object{{"id": "vision", "display_name": "vision"}}, nil
|
||||
}
|
||||
func (v *visionStub) DescribeImage(_ context.Context, _, model, kind string, data []byte) (string, error) {
|
||||
func (v *visionStub) DescribeImage(_ context.Context, _, kind string, data []byte) (string, error) {
|
||||
v.calls++
|
||||
if model != "vision" || kind != "image/png" {
|
||||
if kind != "image/png" && kind != "image/webp" {
|
||||
return "", resource.Invalid("invalid model")
|
||||
}
|
||||
return v.content, nil
|
||||
}
|
||||
func imageBytes(t *testing.T, kind string) []byte {
|
||||
t.Helper()
|
||||
if kind == "webp" {
|
||||
return avatarImage(t, "webp")
|
||||
}
|
||||
im := image.NewRGBA(image.Rect(0, 0, 20, 20))
|
||||
im.Set(2, 2, color.RGBA{R: 255, A: 255})
|
||||
var b bytes.Buffer
|
||||
@@ -122,11 +125,14 @@ func imageBytes(t *testing.T, kind string) []byte {
|
||||
return b.Bytes()
|
||||
}
|
||||
func TestImportImagesValidateRealFormat(t *testing.T) {
|
||||
for _, name := range []string{"photo.jpeg", "photo.JPG", "photo.PNG"} {
|
||||
for _, name := range []string{"photo.jpeg", "photo.JPG", "photo.PNG", "photo.webp"} {
|
||||
kind := "jpg"
|
||||
if strings.HasSuffix(name, "PNG") {
|
||||
kind = "png"
|
||||
}
|
||||
if strings.HasSuffix(name, "webp") {
|
||||
kind = "webp"
|
||||
}
|
||||
typ, _, err := importType(name, imageBytes(t, kind))
|
||||
if err != nil || typ != kind {
|
||||
t.Fatalf("%s %s %v", name, typ, err)
|
||||
@@ -168,7 +174,7 @@ func TestImageImportSearchOriginalIntegration(t *testing.T) {
|
||||
if _, _, err = s.fileImportOperation(ctx, c, "list", fileImportInput{}); err == nil {
|
||||
t.Fatal("image reached anydoc")
|
||||
}
|
||||
parsed, err := s.parseImageImport(ctx, c, "vision")
|
||||
parsed, err := s.parseImageImport(ctx, c)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -191,7 +197,7 @@ func TestImageImportSearchOriginalIntegration(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out, err := s.callMCPFileImport(ctx, actor, "kb_upload_file", map[string]any{"kb_id": kbID, "import_context": uploaded.String("import_context"), "model_id": "vision"})
|
||||
out, err := s.callMCPFileImport(ctx, actor, "kb_upload_file", map[string]any{"kb_id": kbID, "import_context": uploaded.String("import_context")})
|
||||
if err != nil || out.String("status") != "completed" {
|
||||
t.Fatalf("MCP %v %v", out, err)
|
||||
}
|
||||
@@ -282,7 +288,7 @@ func TestImageImportSearchOriginalIntegration(t *testing.T) {
|
||||
}
|
||||
// Existing import returns the same document without another paid parse.
|
||||
before := vision.calls
|
||||
repeated, err := s.parseImageImport(ctx, c, "vision")
|
||||
repeated, err := s.parseImageImport(ctx, c)
|
||||
if err != nil || !repeated.Bool("exists") || vision.calls != before {
|
||||
t.Fatalf("repeat %v %v", repeated, err)
|
||||
}
|
||||
@@ -309,3 +315,16 @@ func TestImageImportSearchOriginalIntegration(t *testing.T) {
|
||||
t.Fatal("disabled actor read image")
|
||||
}
|
||||
}
|
||||
|
||||
func TestImportWebPRejectsMismatchedContent(t *testing.T) {
|
||||
if _, _, err := importType("photo.webp", imageBytes(t, "png")); err == nil {
|
||||
t.Fatal("PNG disguised as WebP accepted")
|
||||
}
|
||||
if _, _, err := importType("photo.png", imageBytes(t, "webp")); err == nil {
|
||||
t.Fatal("WebP disguised as PNG accepted")
|
||||
}
|
||||
typ, mime, err := importType("photo.WEBP", imageBytes(t, "webp"))
|
||||
if err != nil || typ != "webp" || mime != "image/webp" {
|
||||
t.Fatalf("%s %s %v", typ, mime, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package kb
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/kb/sqlc"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
)
|
||||
|
||||
func knowledgeVisionConcurrency(object resource.Object) int {
|
||||
config, _ := object["advanced_config"].(map[string]any)
|
||||
n := objectInt64(config["concurrency"])
|
||||
if n < 1 || n > 20 {
|
||||
return 1
|
||||
}
|
||||
return int(n)
|
||||
}
|
||||
|
||||
func (s *Service) visionConcurrency(ctx context.Context) (int, error) {
|
||||
config, err := readConcurrency(ctx, sqlc.New(s.store.Pool))
|
||||
return config.Image, err
|
||||
}
|
||||
|
||||
// All knowledge vision callers in one process share this gate. A lower limit
|
||||
// drains existing requests; it never interrupts a request already in flight.
|
||||
type visionGate struct {
|
||||
mu sync.Mutex
|
||||
active int
|
||||
changed chan struct{}
|
||||
}
|
||||
|
||||
var knowledgeVisionGate visionGate
|
||||
|
||||
func (g *visionGate) acquire(ctx context.Context, limit func(context.Context) (int, error)) (func(), error) {
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n, err := limit(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
g.mu.Lock()
|
||||
if g.changed == nil {
|
||||
g.changed = make(chan struct{})
|
||||
}
|
||||
if g.active < n {
|
||||
g.active++
|
||||
g.mu.Unlock()
|
||||
var once sync.Once
|
||||
return func() {
|
||||
once.Do(func() { g.mu.Lock(); g.active--; close(g.changed); g.changed = make(chan struct{}); g.mu.Unlock() })
|
||||
}, nil
|
||||
}
|
||||
changed := g.changed
|
||||
g.mu.Unlock()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case <-changed:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) describeVisionImage(ctx context.Context, actor, mime string, data []byte) (string, error) {
|
||||
if s.vision == nil {
|
||||
return "", resource.Invalid("知识库图片解析服务不可用")
|
||||
}
|
||||
release, err := knowledgeVisionGate.acquire(ctx, s.visionConcurrency)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer release()
|
||||
if err := ctx.Err(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return s.vision.DescribeImage(ctx, actor, mime, data)
|
||||
}
|
||||
@@ -16,6 +16,18 @@ import (
|
||||
)
|
||||
|
||||
func (s *Service) RegisterAdmin(router chi.Router) {
|
||||
router = router.With(func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if id := chi.URLParam(r, "modelID"); id != "" {
|
||||
item, err := s.repository.Get(r.Context(), id)
|
||||
if err == nil && item.Kind == KindEmbedding {
|
||||
modelError(r.Context(), w, http.StatusBadRequest, "向量模型请在知识库模型配置中管理")
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
})
|
||||
router.Get("/models", s.listModels)
|
||||
router.Get("/models/authorization-subjects", func(w http.ResponseWriter, r *http.Request) {
|
||||
subjects, err := s.Subjects(r.Context())
|
||||
@@ -62,6 +74,10 @@ func (s *Service) createModel(w http.ResponseWriter, r *http.Request) {
|
||||
modelError(r.Context(), w, http.StatusBadRequest, "请求格式无效")
|
||||
return
|
||||
}
|
||||
if input.Kind == KindEmbedding {
|
||||
modelError(r.Context(), w, http.StatusBadRequest, "向量模型请在知识库模型配置中管理")
|
||||
return
|
||||
}
|
||||
user, _ := identity.UserFromContext(r.Context())
|
||||
item, err := s.Create(r.Context(), user.ID, input)
|
||||
if err != nil {
|
||||
@@ -78,6 +94,10 @@ func (s *Service) updateModel(w http.ResponseWriter, r *http.Request) {
|
||||
modelError(r.Context(), w, http.StatusBadRequest, "请求格式无效")
|
||||
return
|
||||
}
|
||||
if input.Kind == KindEmbedding {
|
||||
modelError(r.Context(), w, http.StatusBadRequest, "向量模型请在知识库模型配置中管理")
|
||||
return
|
||||
}
|
||||
user, _ := identity.UserFromContext(r.Context())
|
||||
item, err := s.Update(r.Context(), chi.URLParam(r, "modelID"), user.ID, input)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,6 +3,7 @@ package model
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -18,6 +19,16 @@ func (s *Service) EmbedText(ctx context.Context, modelID, input string) (Embeddi
|
||||
if err != nil {
|
||||
return EmbeddingResult{}, err
|
||||
}
|
||||
return s.EmbedConfiguredText(ctx, item, input)
|
||||
}
|
||||
|
||||
// EmbedConfiguredText reuses the configured network policy without resolving a general model.
|
||||
func (s *Service) EmbedConfiguredText(ctx context.Context, item Model, input string) (result EmbeddingResult, resultErr error) {
|
||||
defer func() {
|
||||
if resultErr != nil {
|
||||
resultErr = fmt.Errorf("向量模型(%s)调用失败:%w", item.ModelID, resultErr)
|
||||
}
|
||||
}()
|
||||
if !item.Enabled {
|
||||
return EmbeddingResult{}, errors.New("向量模型已禁用")
|
||||
}
|
||||
@@ -32,21 +43,22 @@ func (s *Service) EmbedText(ctx context.Context, modelID, input string) (Embeddi
|
||||
if err != nil {
|
||||
return EmbeddingResult{}, err
|
||||
}
|
||||
if len(payload.Data) == 0 || len(payload.Data[0].Embedding) == 0 {
|
||||
return EmbeddingResult{}, errors.New("上游响应缺少有效的 embedding 向量")
|
||||
}
|
||||
dimension := len(payload.Data[0].Embedding)
|
||||
for _, item := range payload.Data {
|
||||
if len(item.Embedding) != dimension {
|
||||
return EmbeddingResult{}, errors.New("上游返回了维度不一致的 embedding 向量")
|
||||
}
|
||||
}
|
||||
if err := validateEmbeddingDimension(dimension); err != nil {
|
||||
return EmbeddingResult{}, err
|
||||
}
|
||||
return EmbeddingResult{
|
||||
Vector: append([]float64(nil), payload.Data[0].Embedding...),
|
||||
PromptTokens: payload.Usage.PromptTokens,
|
||||
TotalTokens: payload.Usage.TotalTokens,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ProbeConfiguredEmbedding detects the actual vector dimension before saving KB configuration.
|
||||
func (s *Service) ProbeConfiguredEmbedding(ctx context.Context, item Model) (int, error) {
|
||||
if err := s.validateProxy(ctx, item.ProxyID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return s.resolveEmbeddingDimension(ctx, item)
|
||||
}
|
||||
|
||||
// ValidateConfiguredProxy validates a server-managed configuration's network proxy.
|
||||
func (s *Service) ValidateConfiguredProxy(ctx context.Context, id string) error {
|
||||
return s.validateProxy(ctx, id)
|
||||
}
|
||||
@@ -111,7 +111,18 @@ func embeddingDimension(payload embeddingProbeResponse) (int, error) {
|
||||
return dimension, nil
|
||||
}
|
||||
|
||||
func (s *Service) requestEmbedding(ctx context.Context, item Model, input string, timeout time.Duration) (embeddingProbeResponse, error) {
|
||||
func (s *Service) requestEmbedding(ctx context.Context, item Model, input string, timeout time.Duration) (result embeddingProbeResponse, resultErr error) {
|
||||
var status int
|
||||
var diagnostic []byte
|
||||
var rawErr error
|
||||
defer func() {
|
||||
if resultErr != nil {
|
||||
if rawErr == nil {
|
||||
rawErr = resultErr
|
||||
}
|
||||
LogModelRequestError(ctx, nil, "embedding", item, status, diagnostic, rawErr)
|
||||
}
|
||||
}()
|
||||
if item.APIKey == "" || strings.ContainsAny(item.APIKey, "\r\n") {
|
||||
return embeddingProbeResponse{}, errors.New("模型密钥无效")
|
||||
}
|
||||
@@ -170,6 +181,7 @@ func (s *Service) requestEmbedding(ctx context.Context, item Model, input string
|
||||
},
|
||||
}).Do(req)
|
||||
if err != nil {
|
||||
rawErr = err
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
||||
return embeddingProbeResponse{}, errEmbeddingProbeTimeout
|
||||
}
|
||||
@@ -182,11 +194,15 @@ func (s *Service) requestEmbedding(ctx context.Context, item Model, input string
|
||||
return embeddingProbeResponse{}, errors.New("连接上游失败,请检查地址、密钥和网络代理")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
status = response.StatusCode
|
||||
if response.StatusCode != http.StatusOK {
|
||||
diagnostic, rawErr = io.ReadAll(io.LimitReader(response.Body, int64(ModelErrorLogLimit+len(item.APIKey)+1)))
|
||||
return embeddingProbeResponse{}, fmt.Errorf("上游返回 HTTP %d,请检查模型、地址和密钥", response.StatusCode)
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, embeddingProbeResponseLimit+1))
|
||||
diagnostic = data
|
||||
if err != nil {
|
||||
rawErr = err
|
||||
return embeddingProbeResponse{}, errors.New("读取上游响应失败")
|
||||
}
|
||||
if len(data) > embeddingProbeResponseLimit {
|
||||
@@ -194,7 +210,11 @@ func (s *Service) requestEmbedding(ctx context.Context, item Model, input string
|
||||
}
|
||||
var payload embeddingProbeResponse
|
||||
if err := json.Unmarshal(data, &payload); err != nil {
|
||||
rawErr = err
|
||||
return embeddingProbeResponse{}, errors.New("上游响应缺少有效的 embedding 向量")
|
||||
}
|
||||
if _, err := embeddingDimension(payload); err != nil {
|
||||
return embeddingProbeResponse{}, err
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
type knowledgeLegacyRepository struct{ Repository }
|
||||
|
||||
func (knowledgeLegacyRepository) Get(context.Context, string) (Model, error) {
|
||||
return Model{ID: "legacy", Kind: KindEmbedding}, nil
|
||||
}
|
||||
|
||||
func TestAdminRejectsLegacyEmbeddingConfiguration(t *testing.T) {
|
||||
router := chi.NewRouter()
|
||||
NewService(knowledgeLegacyRepository{}).RegisterAdmin(router)
|
||||
for _, test := range []struct{ method, path, body string }{
|
||||
{"POST", "/models", `{"kind":"embedding"}`},
|
||||
{"PUT", "/models/legacy", `{}`},
|
||||
{"DELETE", "/models/legacy", ``},
|
||||
{"PATCH", "/models/legacy/enabled", `{"enabled":true}`},
|
||||
{"POST", "/models/legacy/probe", `{"message":"test"}`},
|
||||
} {
|
||||
request := httptest.NewRequest(test.method, test.path, strings.NewReader(test.body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != 400 {
|
||||
t.Fatalf("%s %s: %d", test.method, test.path, response.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ SELECT
|
||||
FROM
|
||||
models
|
||||
WHERE
|
||||
deleted_at IS NULL
|
||||
deleted_at IS NULL AND kind <> 'embedding'
|
||||
AND ($1::text = ''
|
||||
OR ownership_type = $1::text)
|
||||
ORDER BY
|
||||
@@ -13,7 +13,7 @@ ORDER BY
|
||||
-- name: PageModels :many
|
||||
SELECT *
|
||||
FROM models
|
||||
WHERE deleted_at IS NULL
|
||||
WHERE deleted_at IS NULL AND kind <> 'embedding'
|
||||
AND (sqlc.arg(filter)::jsonb ->> 'ownership' = ''
|
||||
OR ownership_type = sqlc.arg(filter)::jsonb ->> 'ownership')
|
||||
AND (strpos(lower(display_name), lower(sqlc.arg(filter)::jsonb ->> 'search')) > 0
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const ModelErrorLogLimit = 4096
|
||||
|
||||
// LogModelRequestError records bounded upstream diagnostics, never request bodies
|
||||
// or authentication headers. Redact the configured key before truncating echoes.
|
||||
func LogModelRequestError(ctx context.Context, logger *slog.Logger, kind string, item Model, status int, body []byte, cause error) {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
summary := func(value string) (string, bool) {
|
||||
oversized := len(value) > ModelErrorLogLimit
|
||||
if item.APIKey != "" {
|
||||
value = strings.ReplaceAll(value, item.APIKey, "[REDACTED]")
|
||||
}
|
||||
truncated := len(value) > ModelErrorLogLimit
|
||||
if truncated {
|
||||
value = value[:ModelErrorLogLimit]
|
||||
for !utf8.ValidString(value) && len(value) > 0 {
|
||||
value = value[:len(value)-1]
|
||||
}
|
||||
}
|
||||
return value, truncated || oversized
|
||||
}
|
||||
upstream, truncated := summary(string(body))
|
||||
message := ""
|
||||
if cause != nil {
|
||||
message, _ = summary(cause.Error())
|
||||
}
|
||||
logger.ErrorContext(ctx, "模型请求失败", "module", "model", "model_kind", kind,
|
||||
"model_id", item.ID, "model_name", item.ModelID, "protocol", item.Protocol,
|
||||
"upstream_status", status, "upstream_body", upstream, "upstream_body_truncated", truncated, "error", message)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func TestModelRequestErrorLogIsBoundedAndRedactsKey(t *testing.T) {
|
||||
for _, kind := range []string{"embedding", "vision"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
logger := slog.New(slog.NewJSONHandler(&logs, nil))
|
||||
LogModelRequestError(t.Context(), logger, kind, Model{ModelID: "example", APIKey: "provider-secret"}, 400,
|
||||
[]byte("provider-secret "+strings.Repeat("错", 2000)), errors.New("rejected provider-secret"))
|
||||
var record map[string]any
|
||||
if err := json.Unmarshal(logs.Bytes(), &record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := record["upstream_body"].(string)
|
||||
if strings.Contains(logs.String(), "provider-secret") || !strings.Contains(body, "[REDACTED]") || len(body) > ModelErrorLogLimit || !utf8.ValidString(body) || record["upstream_body_truncated"] != true || record["model_kind"] != kind {
|
||||
t.Fatalf("invalid log: %s", logs.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddingHTTPErrorIncludesModelAndLogsUpstreamBody(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
previous := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil)))
|
||||
t.Cleanup(func() { slog.SetDefault(previous) })
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":{"message":"unsupported dimension provider-secret"}}`))
|
||||
}))
|
||||
defer upstream.Close()
|
||||
item := Model{ID: "configured-id", ModelID: "embedding-example", Kind: KindEmbedding, Protocol: ProtocolEmbedding, Enabled: true, BaseURL: upstream.URL, APIKey: "provider-secret"}
|
||||
_, err := NewService(&repositoryStub{}).EmbedConfiguredText(t.Context(), item, "private-document-input")
|
||||
if err == nil || !strings.Contains(err.Error(), "向量模型(embedding-example)") || !strings.Contains(err.Error(), "HTTP 400") {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
var record map[string]any
|
||||
if err := json.Unmarshal(logs.Bytes(), &record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if record["model_kind"] != "embedding" || record["upstream_status"] != float64(400) || !strings.Contains(record["upstream_body"].(string), "unsupported dimension") || strings.Contains(logs.String(), "provider-secret") || strings.Contains(logs.String(), "private-document-input") {
|
||||
t.Fatalf("log=%s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddingResponseValidationLogsOriginalBody(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, body string
|
||||
valid bool
|
||||
}{
|
||||
{name: "error JSON", body: `{"error":{"message":"invalid model provider-secret"}}`},
|
||||
{name: "empty vector", body: `{"data":[{"embedding":[]}]}`},
|
||||
{name: "inconsistent dimensions", body: `{"data":[{"embedding":[1,2]},{"embedding":[1]}]}`},
|
||||
{name: "oversized dimensions", body: `{"data":[{"embedding":[` + strings.Repeat("0,", maxEmbeddingDimensions) + `0]}]}`},
|
||||
{name: "invalid JSON", body: `upstream invalid response`},
|
||||
{name: "valid vector", body: `{"data":[{"embedding":[1,2,3]}]}`, valid: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
previous := slog.Default()
|
||||
slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil)))
|
||||
t.Cleanup(func() { slog.SetDefault(previous) })
|
||||
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte(tc.body)) }))
|
||||
defer upstream.Close()
|
||||
item := Model{ID: "configured-id", ModelID: "embedding-example", Kind: KindEmbedding, Protocol: ProtocolEmbedding, Enabled: true, BaseURL: upstream.URL, APIKey: "provider-secret"}
|
||||
result, err := NewService(&repositoryStub{}).EmbedConfiguredText(t.Context(), item, "private-document-input")
|
||||
if tc.valid {
|
||||
if err != nil || len(result.Vector) != 3 || logs.Len() != 0 {
|
||||
t.Fatalf("result=%v error=%v log=%s", result, err, logs.String())
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), "向量模型(embedding-example)") {
|
||||
t.Fatalf("error=%v", err)
|
||||
}
|
||||
var record map[string]any
|
||||
// A single JSON record also ensures validation does not log the failure twice.
|
||||
if err := json.Unmarshal(logs.Bytes(), &record); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := strings.ReplaceAll(tc.body, item.APIKey, "[REDACTED]")
|
||||
truncated := len(expected) > ModelErrorLogLimit
|
||||
if truncated {
|
||||
expected = expected[:ModelErrorLogLimit]
|
||||
}
|
||||
if record["upstream_body"] != expected || record["upstream_status"] != float64(200) || record["model_kind"] != "embedding" || record["upstream_body_truncated"] != truncated || strings.Contains(logs.String(), item.APIKey) || strings.Contains(logs.String(), "private-document-input") {
|
||||
t.Fatalf("log=%s", logs.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -417,7 +417,7 @@ SELECT
|
||||
FROM
|
||||
models
|
||||
WHERE
|
||||
deleted_at IS NULL
|
||||
deleted_at IS NULL AND kind <> 'embedding'
|
||||
AND ($1::text = ''
|
||||
OR ownership_type = $1::text)
|
||||
ORDER BY
|
||||
@@ -619,7 +619,7 @@ func (q *Queries) LockOwned(ctx context.Context, arg LockOwnedParams) (string, e
|
||||
const pageModels = `-- name: PageModels :many
|
||||
SELECT id, ownership_type, owner_user_id, model_id, display_name, protocol, base_url, api_key, advanced_config, credit_multiplier, enabled, created_at, updated_at, deleted_at, kind, provider, provider_options, image_config, image_pricing, video_config, video_pricing, proxy_id, embedding_config
|
||||
FROM models
|
||||
WHERE deleted_at IS NULL
|
||||
WHERE deleted_at IS NULL AND kind <> 'embedding'
|
||||
AND ($1::jsonb ->> 'ownership' = ''
|
||||
OR ownership_type = $1::jsonb ->> 'ownership')
|
||||
AND (strpos(lower(display_name), lower($1::jsonb ->> 'search')) > 0
|
||||
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
|
||||
func TestKnowledgeImageBodyLimitIsPrivate(t *testing.T) {
|
||||
p := NewProxy(nil, nil)
|
||||
// Encoded length of a 32 MiB original, plus the surrounding model JSON.
|
||||
body := `{"model":"vision","image":"` + strings.Repeat("A", 44739244) + `"}`
|
||||
// Encoded length of a 100 MiB original, plus the surrounding model JSON.
|
||||
body := `{"model":"vision","image":"` + strings.Repeat("A", 139810136) + `"}`
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
serve http.HandlerFunc
|
||||
|
||||
@@ -164,7 +164,7 @@ func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
// ServeKnowledgeImage is used only for server-built vision requests, never registered as a route.
|
||||
func (p *Proxy) ServeKnowledgeImage(w http.ResponseWriter, r *http.Request) {
|
||||
const encodedImageLimit = ((32<<20 + 2) / 3) * 4
|
||||
const encodedImageLimit = ((100<<20 + 2) / 3) * 4
|
||||
p.serveHTTP(w, r, encodedImageLimit+(64<<10))
|
||||
}
|
||||
|
||||
|
||||
@@ -752,3 +752,11 @@ user 搜索条件过长 The user search query is too long.
|
||||
解析生图配置: %w Could not parse image settings: %w
|
||||
解析视频积分: %w Could not parse video pricing: %w
|
||||
解析视频配置: %w Could not parse video settings: %w
|
||||
知识库视觉模型未配置 The knowledge base vision model is not configured.
|
||||
知识库向量模型未配置 The knowledge base embedding model is not configured.
|
||||
知识库视觉模型已停用 The knowledge base vision model is disabled.
|
||||
知识库向量模型已停用 The knowledge base embedding model is disabled.
|
||||
知识库图片解析服务不可用 The knowledge base image parsing service is unavailable.
|
||||
知识库视觉模型不支持图片解析,请检查视觉模型配置 The knowledge base vision model does not support image parsing. Check its configuration.
|
||||
知识库视觉模型调用失败或响应过大,请检查视觉模型配置及图片大小限制 The knowledge base vision model request failed or its response was too large. Check the vision model configuration and image size limits.
|
||||
知识库视觉模型未完成图片解析或拒绝了请求 The knowledge base vision model did not finish parsing the image or refused the request.
|
||||
|
@@ -0,0 +1,3 @@
|
||||
DELETE FROM settings WHERE key='kb_concurrency';
|
||||
ALTER TABLE settings DROP CONSTRAINT settings_key_check;
|
||||
ALTER TABLE settings ADD CONSTRAINT settings_key_check CHECK (key IN ('branding','authentication','email','billing','session_reporting','proxies','mcp','model_network','member_resource_policy'));
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE settings DROP CONSTRAINT settings_key_check;
|
||||
ALTER TABLE settings ADD CONSTRAINT settings_key_check CHECK (key IN ('branding','authentication','email','billing','session_reporting','proxies','mcp','model_network','member_resource_policy','kb_concurrency'));
|
||||
@@ -0,0 +1,7 @@
|
||||
BEGIN;
|
||||
-- Refuse rollback while WebP documents exist; export/remove them first.
|
||||
ALTER TABLE knowledge_base_documents DROP CONSTRAINT knowledge_base_documents_file_type_check;
|
||||
ALTER TABLE knowledge_base_documents ADD CONSTRAINT knowledge_base_documents_file_type_check
|
||||
CHECK (file_type IS NULL OR file_type IN ('txt','md','html','svg','csv','docx','xls','xlsx','pptx','pdf','jpg','png'));
|
||||
DROP TABLE knowledge_base_models;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,23 @@
|
||||
BEGIN;
|
||||
CREATE TABLE IF NOT EXISTS knowledge_base_models (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
kind text NOT NULL UNIQUE CHECK (kind = 'vision'),
|
||||
model_id text NOT NULL,
|
||||
base_url text NOT NULL,
|
||||
api_key text NOT NULL,
|
||||
protocol text NOT NULL,
|
||||
proxy_id text NOT NULL DEFAULT '',
|
||||
advanced_config jsonb NOT NULL DEFAULT '{}',
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CHECK (jsonb_typeof(advanced_config) = 'object'),
|
||||
CHECK (protocol IN ('openai_chat_completions','openai_responses','anthropic'))
|
||||
);
|
||||
COMMIT;
|
||||
|
||||
BEGIN;
|
||||
ALTER TABLE knowledge_base_documents DROP CONSTRAINT knowledge_base_documents_file_type_check;
|
||||
ALTER TABLE knowledge_base_documents ADD CONSTRAINT knowledge_base_documents_file_type_check
|
||||
CHECK (file_type IS NULL OR file_type IN ('txt','md','html','svg','csv','docx','xls','xlsx','pptx','pdf','jpg','png','webp'));
|
||||
COMMIT;
|
||||
@@ -1,5 +1,7 @@
|
||||
# 数据库迁移
|
||||
|
||||
迁移 66 为 admin_api_tokens,67 为 kb_concurrency_settings,68 为 kb_models。68 仅负责知识库视觉模型表和 WebP 文件类型约束。升级和回退见 `../../design/knowledge-base-models.md`。
|
||||
|
||||
版本 `64` 为已启用推理且未显式配置思考深度的文本模型补齐六档,默认中等。未开启推理、其他类型、已有配置均不修改。回退保留 JSON 属性,旧版本可忽略它。
|
||||
|
||||
版本 `63` 新增资源审核申请、草稿与分享明细,不回填已有资源或授权。先迁移再切换后端,旧实例退出后再启用严格策略。有审核记录或已保存策略时拒绝降级。
|
||||
@@ -20,7 +22,7 @@ migrate -path migrations -database "$MONKEYAI_DATABASE_URL" up
|
||||
migrate -path migrations -database "$MONKEYAI_DATABASE_URL" version
|
||||
```
|
||||
|
||||
成功后 `schema_migrations` 应为 `version=64, dirty=false`,再次 `up` 返回 `no change`。可丢弃测试库执行 `down -all` 后再 `up`,应能完整重建。
|
||||
成功后 `schema_migrations` 应为 `version=68, dirty=false`,再次 `up` 返回 `no change`。可丢弃测试库执行 `down -all` 后再 `up`,应能完整重建。
|
||||
|
||||
版本 61 新增专家与知识库的绑定。先迁移再启动新后端。回退会删除绑定并取消由专家继承的只读访问,不删除知识库、内容或已有直接授权。
|
||||
|
||||
|
||||
@@ -2303,3 +2303,28 @@ CREATE TABLE admin_api_tokens (
|
||||
disabled boolean NOT NULL DEFAULT false,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE settings DROP CONSTRAINT settings_key_check;
|
||||
|
||||
ALTER TABLE settings ADD CONSTRAINT settings_key_check CHECK (key IN ('branding','authentication','email','billing','session_reporting','proxies','mcp','model_network','member_resource_policy','kb_concurrency'));
|
||||
|
||||
CREATE TABLE IF NOT EXISTS knowledge_base_models (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
kind text NOT NULL UNIQUE CHECK (kind = 'vision'),
|
||||
model_id text NOT NULL,
|
||||
base_url text NOT NULL,
|
||||
api_key text NOT NULL,
|
||||
protocol text NOT NULL,
|
||||
proxy_id text NOT NULL DEFAULT '',
|
||||
advanced_config jsonb NOT NULL DEFAULT '{}',
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
CHECK (jsonb_typeof(advanced_config) = 'object'),
|
||||
CHECK (protocol IN ('openai_chat_completions','openai_responses','anthropic'))
|
||||
);
|
||||
|
||||
ALTER TABLE knowledge_base_documents DROP CONSTRAINT knowledge_base_documents_file_type_check;
|
||||
|
||||
ALTER TABLE knowledge_base_documents ADD CONSTRAINT knowledge_base_documents_file_type_check
|
||||
CHECK (file_type IS NULL OR file_type IN ('txt','md','html','svg','csv','docx','xls','xlsx','pptx','pdf','jpg','png','webp'));
|
||||
@@ -0,0 +1,31 @@
|
||||
# 知识库文档导航
|
||||
|
||||
整理日期:2026-12-02。按当前工作区组织文档;设计、源码接入、测试通过和生产发布是不同状态。本次整理只核对相关源码和文档结构,未重新运行功能或端到端测试。
|
||||
|
||||
## 按任务阅读
|
||||
|
||||
| 你要做什么 | 首选文档 | 该文档维护的契约 |
|
||||
| --- | --- | --- |
|
||||
| 理解架构、学习与检索 | [技术设计](knowledge-base-technical-design.md) | 模块职责、学习队列、索引、召回与降级 |
|
||||
| 导入文件、上传插图或读取原件 | [文件解析](knowledge-base-file-parsing.md) | 支持格式、大小限制、导入恢复、资源安全及格式迁移 |
|
||||
| 配置视觉或向量模型 | [模型配置](knowledge-base-models.md) | 配置来源、调用并发、图片重试及模型变更影响 |
|
||||
| 授权、协作或处理撤权 | [权限方案](knowledge-base-permissions-design.md) | 有效权限、内容与库管理边界、协作版本及权限迁移 |
|
||||
| 开发 MCP 客户端 | [MCP 设计](knowledge-base-mcp-design.md) | 协议、工具集合、请求体和文件传输限制 |
|
||||
| 开发 REST/Agent 集成 | [Agent 接入](knowledge-base-agent-integration.md) | 认证、读取/检索/导入步骤及示例 |
|
||||
| 整库迁入 Markdown 资源包 | [资源包导入](knowledge-base-resource-import-design.md) | ZIP v1 格式、分区事务、确认幂等与资源包迁移 |
|
||||
|
||||
单文件导入、正文插图和 ZIP 资源包是不同入口,不能互套格式及容量限制。
|
||||
|
||||
## 维护规则
|
||||
|
||||
- 同一契约只在上表指定专题完整维护,其他文档链接引用;Agent 文档保留操作示例,不复制格式白名单。
|
||||
- 功能调整直接更新所属章节,不在文末追加补丁;相关示例及链接同步修改。每篇二级标题不超过 10 个。
|
||||
- 数据库变更、Breaking Changes、升级回滚和部署影响留在所属专题,保留必要字段表及数据影响,不按讨论轮次堆叠。
|
||||
- 验证按范围记录已执行检查、未验证项和已知问题。旧版本、模拟接口及单元测试不能代替当前真实客户端端到端验证。
|
||||
- 接口字段以 [管理端 OpenAPI](../backend/api/admin.yaml)、[Agent OpenAPI](../backend/api/agent.yaml)、[MCP 工具定义](../backend/internal/kb/mcptools.go) 及其辅助定义交叉核对。发现描述与实际校验不一致时显式记录,不以“以代码为准”掩盖冲突。
|
||||
|
||||
## 发布前检查入口
|
||||
|
||||
文件导入验收见 [解析验收](knowledge-base-file-parsing.md#9-实现状态与验收),模型与图片学习见 [模型验证](knowledge-base-models.md#验证),MCP 客户端见 [MCP 验证](knowledge-base-mcp-design.md#5-验证与兼容性)。权限和资源包按各自验收章节执行。
|
||||
|
||||
发布前核对所有相关迁移及当前数据,再确定升级、回滚顺序;本导航不替代各专题迁移约束。当前已有记录包含数据库测试跳过、真实供应商/客户端待验收及全量测试既有失败,不能将文档整理完成视为发布验收完成。
|
||||
@@ -0,0 +1,151 @@
|
||||
# Agent 多格式知识库接入说明
|
||||
|
||||
本文面向通过 REST 或 MCP 接入 MonkeyAI 知识库的 Agent 客户端,描述当前代码契约。目标流程是:选择知识库 → 列出文档或检索 → 读取可编辑正文或下载原件。接口定义以 [Agent OpenAPI](../backend/api/agent.yaml) 和 [MCP 工具定义](../backend/internal/kb/mcptools.go) 为准。
|
||||
|
||||
## 1. 身份与入口
|
||||
|
||||
| 通道 | 入口 | 凭证 |
|
||||
| --- | --- | --- |
|
||||
| Agent REST | `{服务端地址}/api/v1/kb` | 有效客户端 Access Token,放在 `Authorization: Bearer <access_token>` |
|
||||
| MCP | 从资源目录获取 `mcp_gateway.url`,知识库入口为 `POST /mcp/kb` | 平台 API Key,需 `mcp:invoke`,放在 Bearer 请求头 |
|
||||
| 原件资源 | 文档返回的完整 `url` | REST 客户端 Access Token;网页会话也可读取 |
|
||||
|
||||
每次请求校验身份与知识库读取权限;写入还需内容写权限。**MCP Key 不能替代 REST Access Token 下载 `url`**。只有 MCP 凭证时,可检索正文分片;独立图片原图可用 `kb_get_document_image`,PDF/Office 原件下载需客户端另外具备 REST 身份。
|
||||
|
||||
MCP 使用标准初始化与 `tools/list` 发现工具,再通过 JSON-RPC `tools/call` 调用。普通工具结果优先读取 `result.structuredContent`,兼容客户端可解析 `result.content` 中的 text JSON;检查 `isError`。MCP 外层 `content` 是协议内容块,不是文档对象里的正文 `content`。
|
||||
|
||||
## 2. 格式与字段契约
|
||||
|
||||
支持格式、可编辑性、历史 XLS 兼容及格式归一化统一见 [格式范围](knowledge-base-file-parsing.md#1-目标与格式范围)。原件 URL、正文响应投影及兼容升级统一见 [Agent 原件读取契约](knowledge-base-file-parsing.md#agent-原件读取契约)。调用方按返回的 `content_editable` 和当前写权限决定编辑入口,不维护另一套扩展名白名单。
|
||||
|
||||
关键字段:
|
||||
|
||||
- `node_type`:`document` 或 `folder`;文件夹不作为文档下载。
|
||||
- `content_editable`:格式是否支持编辑,不代表当前用户有写权限。
|
||||
- `content`:列表不返回此字段。读取详情时,已知不可编辑格式返回空字符串是**响应投影**,数据库仍保存 AnyDoc/LLM 解析正文,用于学习和检索。不要将空字符串解释为“解析失败”或“文档无内容”。
|
||||
- `url`:`{PublicURL}/api/kb/{kb_id}/assets/{document_id}.{ext}`。无原件、文件夹或未配置 PublicURL 时为空字符串。
|
||||
- `has_original`:是否有关联原件;与 `url` 结合判断。若为 true 而 url 为空,检查部署的 PublicURL。
|
||||
- `status`:`pending / learning / learned / failed`,表示学习状态。读取已保存正文或原件不要求学习完成。
|
||||
|
||||
**检索是例外**:REST `/kb/search` 与 MCP `kb_search` 的结果 `content` 返回命中的解析正文分片,包括 PDF、Office 和图片。它不是完整文档,不要用检索分片覆盖原文。
|
||||
|
||||
MCP `kb_get_document` 默认不返回可编辑格式或未知类型的正文,需 `include_content: true`;已知不可编辑格式始终返回 `content: ""`。`kb_read_document` 对可编辑格式和未知类型分页读取正文,对已知不可编辑格式返回空 `content`、文档元数据和原件 `url`,不能用它绕过完整解析正文限制。
|
||||
|
||||
## 3. 推荐读取流程
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[获取可访问知识库] --> B{目标}
|
||||
B -->|浏览文件| C[分页列出文档]
|
||||
B -->|回答问题| D[检索命中分片]
|
||||
C --> E{是否可编辑}
|
||||
E -->|是| F[按文档 ID 读取正文]
|
||||
E -->|否| G[读取 url 原件]
|
||||
D --> H[使用命中 content 回答并保留引用]
|
||||
H -->|需要核对原件| G
|
||||
G --> I[客户端携带 REST Token 下载二进制]
|
||||
```
|
||||
|
||||
列表显式传 `page` 和 `page_size`,根据 `total_count` 遍历;列表只返回元数据。若使用树形响应,递归处理 `children`,跳过文件夹。不要把一次返回或检索的 `top_k` 当作完整文档清单。
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant C as Agent 客户端
|
||||
participant B as REST 或 MCP 服务
|
||||
participant D as 知识库数据库与索引
|
||||
participant O as 私有原件存储
|
||||
C->>B: 列表或检索(各通道对应凭证)
|
||||
B->>D: 检查权限并读取正文或命中分片
|
||||
B-->>C: content 按场景返回,附完整 url
|
||||
C->>B: GET url + REST Access Token
|
||||
B->>D: 再次校验库权限和文档归属
|
||||
B->>O: 读取既有原件
|
||||
B-->>C: 原始二进制
|
||||
```
|
||||
|
||||
## 4. REST 调用示例
|
||||
|
||||
以下是路径及请求体示例,替换真实 ID 和服务端地址。所有请求带 REST Bearer Token。
|
||||
|
||||
```http
|
||||
GET /api/v1/kb?page=1&page_size=20
|
||||
GET /api/v1/kb/{kb_id}/documents?page=1&page_size=20
|
||||
GET /api/v1/kb/{kb_id}/documents/{document_id}
|
||||
```
|
||||
|
||||
列表中的 PDF 文档示例(仅展示相关字段):
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "<document_id>",
|
||||
"kb_id": "<kb_id>",
|
||||
"node_type": "document",
|
||||
"file_type": "pdf",
|
||||
"content_editable": false,
|
||||
"has_original": true,
|
||||
"url": "https://your-server.example/api/kb/<kb_id>/assets/<document_id>.pdf"
|
||||
}
|
||||
```
|
||||
|
||||
检索:
|
||||
|
||||
```http
|
||||
POST /api/v1/kb/search
|
||||
Content-Type: application/json
|
||||
|
||||
{"kb_ids":["<kb_id>"],"query":"报销需要哪些材料","top_k":8}
|
||||
```
|
||||
|
||||
从响应 `items` 读取 `content`、`kb_id`、`document_id`、`chunk_id`、`citation` 和 `url`。图片检索可传 `file_types: ["jpg", "png", "webp"]`;这个过滤字段当前不支持任意文档格式。不要从 Markdown 猜测 PDF 页码、单元格或图片坐标。
|
||||
|
||||
直接 GET 文档 `url` 获取二进制,不再自行拼接 `/file/detail`。客户端将字节保存为文件或交给支持对应格式的阅读器。PDF/JPG/PNG/WebP 原件内联返回;HTML/SVG 等强制附件。
|
||||
|
||||
## 5. MCP 调用示例
|
||||
|
||||
发送至发现的知识库 MCP 地址,并携带 MCP Key。列出文档:
|
||||
|
||||
```json
|
||||
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"kb_list_documents","arguments":{"kb_id":"<kb_id>","page":1,"page_size":20}}}
|
||||
```
|
||||
|
||||
常用工具与参数:
|
||||
|
||||
| 操作 | 工具 | 参数示例 |
|
||||
| --- | --- | --- |
|
||||
| 选择知识库 | `kb_list` | `{"page":1,"page_size":20}` |
|
||||
| 读取详情 | `kb_get_document` | `{"kb_id":"…","document_id":"…","include_content":true}` |
|
||||
| 分页读取可编辑正文 | `kb_read_document` | `{"kb_id":"…","document_id":"…","offset":0,"limit":4000}` |
|
||||
| 检索 | `kb_search` | `{"kb_ids":["…"],"query":"报销材料","top_k":8}` |
|
||||
| 读取独立图片原图 | `kb_get_document_image` | `{"kb_id":"…","document_id":"…"}` |
|
||||
|
||||
正文分页按 Unicode 字符偏移,后续使用 `next_offset` 并携带首页 revision 作为 `expected_revision`,避免拼接不同版本;限制每页最多 16000 字符。发生版本冲突后重新读取。
|
||||
|
||||
独立图片工具返回 MCP image 内容块,原图内联上限为 8 MiB;超限需 REST 下载或网页预览。不要让模型生成或搬运图片 Base64。客户端需支持 image 内容块才能实际展示原图。
|
||||
|
||||
## 6. 导入与编辑
|
||||
|
||||
只读 Agent 可不实现此节。需要写入时使用已有权限体系:
|
||||
|
||||
1. REST 使用 `POST /api/v1/kb/{kb_id}/imports/upload`,multipart 上传 `file`,可带 `title`、`parent_id`;同一次上传重试复用客户端生成的 32 位十六进制 `upload_key`。原件最大100 MiB(图片100 MiB,文本正文16 MiB)。
|
||||
2. 文本直接保存;独立图片同步调用知识库唯一视觉模型,不传 `model_id`;PDF/Office 可能返回 `pending`。
|
||||
3. 遇到 `pending`,按 `poll_after_seconds` 调用 `POST /api/v1/kb/{kb_id}/imports/query`,传 `task_context`,直到 `completed/document_id` 或失败。`completed` 表示文档已保存,不表示索引已学习完成。
|
||||
4. MCP 使用 `kb_upload_file` 和 `kb_get_file_import_status`。先仅传 `kb_id` 获取完整 `upload_url` 和短期 `upload_token`,由客户端在模型上下文之外读取字节并以 Bearer 临时凭证上传;同次重试复用 `upload_key`。凭证边界见 [MCP 与文件传输](knowledge-base-file-parsing.md#mcp-与文件传输)。
|
||||
|
||||
转换上下文有效期、失败重试及结果确认遵循 [文件解析方案](knowledge-base-file-parsing.md)。页面或客户端退出后不依赖后台轮询继续入库;`retryable` 时复用原上下文有界重试,图片付费请求结果不确定时不要盲目重发。
|
||||
|
||||
直接创建文本使用 `POST /api/v1/kb/{kb_id}/documents` 或 `kb_create_document`。仅可编辑格式允许更新正文;MCP 长文档优先使用分段读取和 `kb_edit_document`,携带 `expected_revision`。大正文与文件字节由客户端程序处理,不要求模型复制整份文件作为工具参数。
|
||||
|
||||
## 7. 失败处理与升级验收
|
||||
|
||||
| 情况 | 客户端处理 |
|
||||
| --- | --- |
|
||||
| REST 401 | 刷新或重新获取登录凭证;不要拿 MCP Key 代替 |
|
||||
| 403 或 404 | 检查身份和资源授权;404 也可能是资源不可见、原件缺失或已删除 |
|
||||
| 不可编辑格式 `content` 为空 | 正常契约;需要全文时读原件,需要问答时检索 |
|
||||
| `url` 为空 | 不发起空地址请求;结合 has_original 检查缺失原件或部署配置 |
|
||||
| 学习失败或无检索命中 | 检查 status/error_message;不据此认定原件丢失 |
|
||||
| 文档数量较多 | 减小 page_size,逐页处理,仅将任务相关内容送入模型 |
|
||||
|
||||
升级与回滚遵循 [Agent 正文响应变更](knowledge-base-file-parsing.md#agent-原件读取契约) 和 [模型配置变更](knowledge-base-models.md#breaking-changes升级与回滚)。确认 PublicURL 是客户端实际可访问的外部地址,不能重复拼接域名。
|
||||
|
||||
接入验收至少覆盖:MD(直接创建/上传)、PDF、PNG、WebP;REST 与 MCP 列表/详情字段;PDF/PNG 检索分片;下载字节与上传原件一致;未授权、跨库、撤权和删除后的拒绝;MCP Key 单独不能下载 REST 原件。单元/接口契约检查不替代这些真实客户端验收;已有验证记录及缺口见 [文件解析验收](knowledge-base-file-parsing.md#9-实现状态与验收)。
|
||||
@@ -1,6 +1,6 @@
|
||||
# 知识库多格式兼容及文件解析方案
|
||||
|
||||
更新日期:2026-11-25。统一导入接口、document_id 复用及提交信号量已完成源码接入;无任务表或后台解析 worker。实际验证及待验收项见第 9 节。
|
||||
整理日期:2026-12-02。本文维护文件导入、正文插图、原件读取及格式迁移契约。阅读入口见 [知识库文档导航](knowledge-base-README.md)。验证记录为历史摘要,本次整理未重新运行功能测试。
|
||||
|
||||
## 1. 目标与格式范围
|
||||
|
||||
@@ -11,13 +11,15 @@
|
||||
| TXT、Markdown | 直接保存 UTF-8 文本 | 允许 |
|
||||
| HTML、SVG | 保存源码,提供安全预览 | 允许 |
|
||||
| CSV | 保存 UTF-8 文本,支持源码编辑与导出 | 允许 |
|
||||
| DOCX、XLS、XLSX、PPTX、PDF | AnyDoc slim 转为 Markdown | 只读 |
|
||||
| JPEG/JPG、PNG | 视觉 LLM 生成画面描述和图中文字 | 只读 |
|
||||
| DOC、PPT 及其他未支持格式 | 上传时拒绝,提示转为支持格式 | 不适用 |
|
||||
| DOCX、XLSX、PPTX、PDF | AnyDoc slim 转为 Markdown | 只读 |
|
||||
| JPEG/JPG、PNG、WebP | 视觉 LLM 生成画面描述和图中文字 | 只读 |
|
||||
| XLS、DOC、PPT 及其他未支持格式 | 上传时拒绝,提示转为支持格式 | 不适用 |
|
||||
|
||||
**Breaking Changes(2026-12-02)**:新上传的 Office 文件仅支持 `.xlsx`、`.pptx`、`.docx`;`.xls`、`.ppt`、`.doc` 由客户端自行转换,服务端明确拒绝,不提供旧格式转换。网页选择器和 MCP 支持列表同步收紧。后缀对应的内容签名仍须匹配,旧 OLE 文件改名为新格式也会被拒绝。历史 XLS 文档保留原有读取和学习行为,数据库及存量数据无需迁移。升级前客户端须完成格式转换适配;回滚本次上传校验及支持列表即可恢复原 XLS 上传行为。
|
||||
|
||||
`file_type` 表示**原始格式**,由后端依据后缀及内容校验确定:`markdown → md`、`htm → html`、`jpeg → jpg`。直接创建文本正文统一为 `md`。转换后的正文 MIME 为 `text/markdown`,原始 `file_type` 不变;历史未知格式不默认可编辑。
|
||||
|
||||
AnyDoc 只承担 Office/PDF 转换,视觉 LLM 只承担独立图片解析。文本导入不依赖这两者;重新学习和索引重建均读取已保存正文,不再次转换或识图。复杂排版、扫描件、公式和加密文件的质量须以真实样本验收为准。
|
||||
AnyDoc 承担 Office/PDF 转换;视觉 LLM 用于独立图片导入及文档内图片学习。文本保存不依赖这两者。重新学习读取已保存正文,不重新转换原件;独立图片复用已保存描述,含内嵌图片的文档会重新识图,见 [学习流程](knowledge-base-technical-design.md#62-学习步骤)。复杂排版、扫描件、公式和加密文件的质量须以真实样本验收为准。
|
||||
|
||||
## 2. 用户流程与模块职责
|
||||
|
||||
@@ -81,11 +83,9 @@ sequenceDiagram
|
||||
|
||||
| 接口 | 用途与主要契约 |
|
||||
| --- | --- |
|
||||
| `POST /imports/upload` | multipart 文件、标题、父目录,图片另传 model_id。保存原件并开始处理;文本和图片成功后返回 completed/document_id,Office/PDF 返回 pending 及签名上下文。不返回转换正文。原件保存后的可恢复错误须附原件上下文。 |
|
||||
| `POST /imports/upload` | multipart 文件、标题、父目录,图片由服务端读取 knowledge_base_models 中唯一视觉配置,不传 model_id。保存原件并开始处理;文本和图片成功后返回 completed/document_id,Office/PDF 返回 pending 及签名上下文。不返回转换正文。原件保存后的可恢复错误须附原件上下文。 |
|
||||
| `POST /imports/query` | 接收签名任务上下文,查询 AnyDoc;转换完成则校验并直接保存文档及学习任务,返回 completed/document_id。属于写操作。 |
|
||||
| `POST /imports/result` | 通过原件上下文查询目标文档是否存在,用于保存响应丢失后的恢复。 |
|
||||
| `GET /imports/models` | 列出当前用户可用的视觉文本模型。 |
|
||||
| `GET /documents/{documentId}/file/detail` | 鉴权下载原件;preview=true 对受支持的 PDF、JPEG、PNG 提供内联预览。 |
|
||||
|
||||
网页与 MCP multipart、MCP Base64 上传均支持客户端生成的 32 位十六进制 `upload_key`。同一用户、知识库、文件名、文件内容及键确定同一文档 ID;客户端重传必须复用键,主动新建副本使用新键。脚本上传前输出键,响应丢失后通过 `--upload-key` 重试单个文件。未传键的旧客户端继续按新上传处理。
|
||||
|
||||
@@ -93,16 +93,21 @@ sequenceDiagram
|
||||
|
||||
仅收到 `restart_required=true` 时清理原件上下文并分配新键,该标志用于转换任务失败、过期或不存在。普通处理失败、保存结果不确定及本地等待超时保留原键与原件上下文,用户重试先查 `result`。`retryable` 只控制有限自动退避,不能据其缺省值判断是否需要新建文档;图片失败仍要求显式重试。
|
||||
|
||||
不落表时仍需由签名上下文绑定原件键、document_id、用户、知识库、标题、目录及有效期,后端不能信任客户端传入的裸 ID 或任意对象路径。`import_context` 用于原件引用及保存结果查询,`task_context` 用于 Office/PDF 轮询;不向客户端返回派生正文,不再使用 result_context 或显式 commit。原件上下文最长 24 小时,转换及图片回调上下文最长 30 分钟。
|
||||
不落表时仍需由签名上下文绑定原件键、document_id、用户、知识库、标题、目录及有效期,后端不能信任客户端传入的裸 ID 或任意对象路径。`import_context` 用于原件引用及保存结果查询,`task_context` 用于 Office/PDF 轮询;不向客户端返回派生正文,原件上下文最长 24 小时,转换及图片回调上下文最长 30 分钟。
|
||||
|
||||
slim 归档内嵌图片、转换器资源及公网外链图片。外链下载校验全部 DNS 地址并固定拨号到已验证公网 IP,拒绝内网、保留地址、重定向及带凭据的 URL,按实际字节验证图片格式、像素和大小。MonkeyCode 图片回调及正文图片上传接受 BMP、TIFF,按原格式保存并返回对应 MIME;anydoc 的 BMP 原样上传和 TIFF 转 PNG 行为沿用原实现,下载或上传失败会返回任务失败。TIFF 浏览器内联显示能力取决于浏览器,接收支持不代表所有浏览器均可预览。MonkeyAI 校验最终图片资源地址和对象存在后入库。图片替换按语法节点定位,保留普通正文、链接及代码示例。
|
||||
|
||||
### MCP 与文件传输
|
||||
|
||||
- 同 Key 的 `POST /mcp/kb/{id}/files/upload` 上传真实文件并开始处理,返回 completed 或 pending;图片显式传 model_id,同步解析保存。
|
||||
- `kb_upload_file` 返回上传说明,或用已取得的原件上下文继续处理;`kb_get_file_import_status` 通过任务上下文查询并在完成时保存,属于写操作。
|
||||
- 本地脚本 `monkeyai/scripts/kb-file-import.py` 负责文件读取、上传及轮询,使用环境变量 MONKEYAI_MCP_KEY,图片使用 --model-id。客户端退出后不保证完成入库。
|
||||
- 程序化 file_name/data_base64 与原件上下文互斥;32 MiB 文件编码上限 44,739,244 字节,完整请求上限 44,804,780 字节,普通工具仍为 1 MiB。文件字节由客户端程序传输,禁止 Agent 生成或搬运大段 Base64。
|
||||
- 使用临时上传凭证(兼容原 MCP Key)的 `POST /mcp/kb/{id}/files/upload` 上传真实文件并开始处理,返回 completed 或 pending;图片默认使用全局知识库视觉模型,同步解析保存。
|
||||
- `kb_upload_file` 返回完整 `upload_url` 及 `upload_token`、`expires_at`(Unix 秒)、`expires_in`(300 秒),或用已取得的原件上下文继续处理;`kb_get_file_import_status` 通过任务上下文查询并在完成时保存,属于写操作。
|
||||
- 本地脚本 `monkeyai/scripts/kb-file-import.py` 负责文件读取、上传及轮询,使用环境变量 MONKEYAI_MCP_KEY,图片不接受 --model-id,由服务端使用唯一的知识库视觉模型。客户端退出后不保证完成入库。
|
||||
- 程序化 file_name/data_base64 与原件上下文互斥;100 MiB 文件编码上限 139,810,136 字节,完整请求上限 139,875,672 字节,普通工具仍为 1 MiB。文件字节由客户端程序传输,禁止 Agent 生成或搬运大段 Base64。
|
||||
- `upload_url` 使用配置的 `PublicURL` 拼接,保留部署路径前缀,不使用请求 Host 或本地代理地址;配置缺失或无效时明确失败,避免返回无法直传的相对地址。调用方直接向该 URL 发送 multipart。
|
||||
- 临时凭证以 `Authorization: Bearer <upload_token>` 发送,只允许目标库的文件上传路由,不允许普通 MCP 调用、下载或查询。复用现有签名密钥,使用独立前缀及签名用途,绑定用户、知识库和5分钟有效期;上传前及入库时检查用户状态和当前写权限。不得在 URL 查询参数或日志中记录凭证。签名配置缺失时明确失败。
|
||||
- 凭证是短期可重用授权,并非一次性票据:有效期内允许多次上传,每次仍受100 MiB原件限制(图片100 MiB、正文16 MiB);同一文件重试必须复用 `upload_key`。不新增持久化消费记录或承诺单次使用。原 MCP Key 撤销不会立即撤销已签发凭证,其最多剩余5分钟;用户停用或知识库撤权会阻止上传。凭证过期后重新调用 MCP 获取,重试仍保留原上传幂等键。
|
||||
- 原文件上限提高到100 MiB(104,857,600字节),multipart请求另预留64 KiB;图片和Base64原件同步提高到100 MiB;正文16 MiB及其他既有请求预算保持不变。网页和脚本按格式校验;网页原件上传及AnyDoc文件提交超时15分钟。multipart大文件落临时盘后一次分配原件缓冲,单进程同时处理一个multipart上传;AnyDoc转发使用临时文件并清理。部署须预留缓冲内存和临时盘,网关须允许100 MiB加64 KiB;本次不修改Docker配置。验证范围见第 9 节。
|
||||
- 本次变更兼容原 Key 上传,不修改数据库、Docker 或部署配置;沿用现有导入签名密钥。回滚后临时凭证不再被接受,客户端改用旧 Key 上传;已入库文档不受影响。
|
||||
- 每次 MCP 请求重新验证 Key 和权限;纯 MCP 客户端没有文件读取/上传能力时,不能只凭本地路径导入。图片读取工具沿用 kb_get_document_image。
|
||||
|
||||
## 4. Office/PDF 转换与图片回调
|
||||
@@ -121,17 +126,59 @@ slim 归档内嵌图片、转换器资源及公网外链图片。外链下载校
|
||||
|
||||
图片回调使用专用精简凭证,仅签入 purpose、import_id、document_id、actor、kb、admin、expires。标题、目标目录、模型及原件元数据保留在导入和轮询上下文中,避免长中文标题使 AnyDoc 的 uploader JSON 超过 8192 字节。同一导入重试保持回调凭证稳定,旧完整回调凭证仍沿用原校验规则有效至过期,新凭证也兼容原校验器。
|
||||
|
||||
图片按内容摘要保存为知识库 assets;成功协议必须为 HTTP 200 和 `{"code":0,"err":"","data":"/api/kb/<id>/assets/<name>"}`。正文保存稳定的鉴权资源路径,保存正文前检查图片属于当前知识库且真实存在;拒绝外部或缺失图片,避免缺图结果入库。正文插图与独立图片导入的区别见 [知识库正文图片上传](knowledge-base-image-upload.md)。
|
||||
图片按内容摘要保存为知识库 assets;成功协议必须为 HTTP 200 和 `{"code":0,"err":"","data":"/api/kb/<id>/assets/<name>"}`。正文保存稳定的鉴权资源路径,保存正文前检查图片属于当前知识库且真实存在;拒绝外部或缺失图片,避免缺图结果入库。手动插入正文图片的入口见下文“正文插图上传”;插图上传本身不创建文档。
|
||||
|
||||
### 正文插图上传
|
||||
|
||||
管理端:`POST /api/admin/v1/kb/{id}/images/upload`,使用管理员登录 Cookie,仅支持系统知识库。个人知识库在管理端保持只读。
|
||||
|
||||
客户端:`POST /api/v1/kb/{id}/images/upload`,使用 OAuth Bearer access token。知识库必须启用,调用者为个人库所有者或拥有正文 `read_write` 授权的成员。只读成员返回 403,无访问权限返回 404。上传时锁定知识库并检查权限,与权限撤销、删除操作串行。
|
||||
|
||||
请求使用 `multipart/form-data`,通过 `file` 字段上传一张图片。服务端支持 PNG、JPEG、GIF、WebP、BMP、TIFF,最多 100 MiB、2500 万像素。服务端根据真实内容识别格式并完整解码,不信任文件名或客户端 MIME,拒绝 SVG、损坏图片、空文件和多文件。超限请求返回 400。
|
||||
|
||||
```sh
|
||||
# 管理端:使用已登录的 Cookie 文件,并遵守现有管理 API 的来源校验。
|
||||
curl 'https://example.com/api/admin/v1/kb/KB_ID/images/upload' \
|
||||
-b cookies.txt -H 'Origin: https://example.com' -F 'file=@./picture.png'
|
||||
|
||||
# 客户端
|
||||
curl 'https://example.com/api/v1/kb/KB_ID/images/upload' \
|
||||
-H "Authorization: Bearer $ACCESS_TOKEN" -F 'file=@./picture.png'
|
||||
```
|
||||
|
||||
成功返回 HTTP 201:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "<sha256>.png",
|
||||
"url": "/api/kb/<kb-id>/assets/<sha256>.png",
|
||||
"mime_type": "image/png",
|
||||
"size_bytes": 1024,
|
||||
"markdown": ""
|
||||
}
|
||||
```
|
||||
|
||||
调用者将 `markdown` 插入文档正文,再调用原有文档保存接口。上传本身不修改正文或触发知识库学习。编辑器可以通过返回的 `url` 预览图片。
|
||||
|
||||
MCP 正文插图上传、参数和传输预算统一见 [MCP 文件传输](knowledge-base-mcp-design.md#3-请求体与文件传输)。
|
||||
|
||||
管理端知识库正文编辑器支持粘贴剪贴板图片,自动调用管理端上传接口并在粘贴位置插入 Markdown 图片。一次粘贴多张图片时依次上传;普通文本粘贴保持原有行为。上传期间可以继续输入,插入位置随文档编辑移动,不覆盖后续输入;页面显示上传状态并暂停手动和自动保存。上传失败提示错误并保留草稿;离开页面时取消未完成上传。只读文档不发起上传。浏览器另有格式选择限制;服务端接受格式不保证浏览器能内联预览(尤其 TIFF)。真实图片解码和像素限制由后端执行。
|
||||
|
||||
图片使用对象存储路径 `knowledge/<kb-id>/assets/<sha256>.<ext>` 和读取接口 `GET /api/kb/{id}/assets/{name}`,不新增数据库表。同库同图复用地址,不同知识库分别存储。读取接口支持浏览器 Cookie 和客户端 Bearer token,逐次检查阅读权限,响应禁止缓存,不公开对象存储 URL。
|
||||
|
||||
删除知识库后按 assets 前缀清理对象存储。上传后未引用的图片保留到知识库删除;对象存储写入成功但审计或数据库提交失败时可能留下未引用对象,当前没有自动回收任务。未配置对象存储返回 503,上传失败时不会返回成功地址。
|
||||
|
||||
完整请求和响应契约见 `backend/api/admin.yaml` 与 `backend/api/agent.yaml`。后端沿用项目现有 chi 路由、identity 鉴权和 kb 业务层。
|
||||
|
||||
## 5. 独立图片解析与检索
|
||||
|
||||
JPEG/PNG 不调用 AnyDoc。用户显式选择有权使用、已启用、`kind=text` 且 `supports_vision=true` 的模型,复用 OpenAI Chat Completions、OpenAI Responses 或 Anthropic Messages 协议。后端验证模型能力、权限与额度,不自动切换模型。
|
||||
JPEG/PNG/WebP 不调用 AnyDoc,不转码。服务端读取唯一且启用的知识库视觉配置,上传不传 `model_id`;配置来源、协议、并发与计费边界统一见 [模型配置](knowledge-base-models.md#保存和调用)。
|
||||
|
||||
固定提示词要求返回 `description`、`text` 两个 JSON 字段:描述画面对象、动作和场景,并提取图中文字;无文字不算失败。后端将两部分按字面文本放入独立 Markdown 代码块,保留换行并安全处理代码围栏。空描述、拒绝、截断或超限均失败;图片内的指令不触发工具执行。
|
||||
|
||||
图片由上传请求同步调用模型,不经过 AnyDoc。等待图片信号量和解析共用 100 秒预算,网关读超时为 150 秒,为计费收尾预留时间;网页图片上传与脚本请求预算为 180 秒。并发解析按预分配文档 ID 使用 PostgreSQL advisory lock 互斥,锁由独立短生命周期连接持有,避免占满业务连接池;部署容量须计入每个解析请求额外的一条数据库连接。结果未持久化时,断网或重启后的重试可能再次调用模型并计费,不做静默付费重试。
|
||||
|
||||
原图由后端从对象存储读取,程序化编码为供应商图片输入;Base64 不经过编排 Agent,但解析 LLM 会接收图片。内部识图入口允许 32 MiB 原图的 Base64 编码长度,另预留 64 KiB 给提示词和 JSON;公网模型代理仍限制完整请求为 32 MiB。供应商自身的图片限制仍然适用,不静默压缩、裁剪或改用公开图片 URL。
|
||||
视觉配置来源与调用计费边界见 [知识库专用模型](knowledge-base-models.md)。原图由后端从对象存储读取,程序化编码为供应商图片输入;Base64 不经过编排 Agent,但解析 LLM 会接收图片。内部识图入口允许 100 MiB 原图的 Base64 编码长度,另预留 64 KiB 给提示词和 JSON;公网模型代理仍限制完整请求为 32 MiB。供应商自身的图片限制仍然适用,不静默压缩、裁剪或改用公开图片 URL。
|
||||
|
||||
图片正文只读,原图与描述对照展示:桌面左右等宽,小屏上下排列。检索索引画面描述及图中文字,图片描述补充中文单字索引;不引入图像 embedding 或以图搜图,重学不重复识图。
|
||||
|
||||
@@ -143,7 +190,7 @@ MCP 搜索默认不内联图片,客户端按需调用 `kb_get_document_image`
|
||||
|
||||
### 正文与资源限制
|
||||
|
||||
- 原件最多 32 MiB;正文及索引文本各最多 16 MiB,须为非空 UTF-8、无 NUL;图片最多 2500 万像素,并校验真实格式及后缀匹配。
|
||||
- multipart 原件最多100 MiB,图片最多100 MiB;正文及索引文本各最多 16 MiB,须为非空 UTF-8、无 NUL;图片最多 2500 万像素,并校验真实格式及后缀匹配。
|
||||
- AnyDoc JSON 响应读取预算为正文上限的六倍加 64 KiB,再校验解码后的正文;上传、提交和模型调用还须满足客户端、网关及供应商限制。
|
||||
- 编辑能力由持久化 `file_type` 和当前权限共同决定。派生正文禁止替换、局部修改或清空,标题及目录可按权限修改;重新生成须显式重新导入。
|
||||
- 原件为不可变快照。文本编辑修改已保存正文;学习和重学读取正文。Markdown 按标题、段落、列表和表格分块,其他源码按纯文本索引;每片最多 1200 rune、重叠最多 200 rune。
|
||||
@@ -166,24 +213,38 @@ MCP 搜索默认不内联图片,客户端按需调用 `kb_get_document_image`
|
||||
|
||||
上下文及等待队列仅存客户端内存,不恢复关闭或刷新的页面,不承诺后端/AnyDoc 重启恢复或跨上传去重。原件凭证过期、任务丢失或转换明确失败后提示重新导入;终态失败任务不能以相同 ID 直接重新执行,再次导入分配新的 document_id。无删除回执时,有效旧上下文可能重建已删除文档;前端删除后丢弃对应上下文,不承诺跨删除幂等。
|
||||
|
||||
### Agent 原件读取契约
|
||||
|
||||
客户端调用步骤与示例见 [Agent 接入说明](knowledge-base-agent-integration.md)。
|
||||
|
||||
Agent REST 与 MCP 的文档列表、详情及写入回包增加 `url`:有原件时为 `{PublicURL}/api/kb/{kb_id}/assets/{document_id}.{ext}`,无原件、文件夹或未配置 PublicURL 时为空字符串。使用部署配置的外部域名生成绝对地址,不信任请求 Host;读取须携带有账户资源权限的客户端 Bearer Token,并在每次请求校验知识库阅读权限;不公开私有存储键或免鉴权对象地址。MCP Key 不可直接用于 REST,MCP 调用方下载须另具有效 REST 身份;图片仍可通过原有 MCP 原图工具读取。
|
||||
|
||||
原件资源名使用文档 UUID 与原始格式后缀(未知格式为 `bin`),正文内嵌图片继续使用摘要文件名;两者共享资源路由并按知识库隔离。直接读取既有原件,不复制对象、不新增表字段。PDF/JPG/PNG/WebP 内联返回,HTML/SVG 等作为附件。
|
||||
|
||||
已知不可编辑格式(Office、PDF、图片)的详情和写入回包向 Agent 返回 `content: ""`;MCP `include_content=true` 和 `kb_read_document` 同样不返回完整解析正文。REST 和 MCP 检索结果保留命中分片的 `content`,包括不可编辑格式,并同时返回原件 `url`。分页正文工具对这些格式返回空字符串 `content`、文档元数据及 `url`。可编辑文本格式仍按原契约读取;类型为空或未知的文档也返回已保存正文,但不允许编辑。文档列表仅返回元数据,不含 `content` 字段。管理端正文、内部学习与检索计算不变。
|
||||
|
||||
**Breaking Changes(Agent 正文返回)**:依赖详情接口完整派生 Markdown/图片描述的调用方须改为读取 `url` 原件,并处理无原件的空地址;检索结果继续返回命中分片。升级时先让客户端兼容空正文和原件地址,再发布后端;回滚恢复旧响应实现即可,保留原件与正文,无数据库迁移或容器配置变更。
|
||||
|
||||
## 7. 数据结构与兼容迁移
|
||||
|
||||
**不新增解析任务表、状态表、字段或索引**,删除原定 knowledge_base_file_parse_job 建表方案;该表尚未实现,无需执行 DROP TABLE 或新增删除迁移。等待队列留在客户端内存,转换状态由 AnyDoc 临时保存。只复用现有文档和学习队列,document_id 在正文入库时持久化。
|
||||
**不新增解析任务表或解析状态字段**;等待与恢复复用签名上下文,不建立 knowledge_base_file_parse_job。等待队列留在客户端内存,转换状态由 AnyDoc 临时保存。只复用现有文档和学习队列,document_id 在正文入库时持久化。
|
||||
|
||||
既有格式字段迁移保持如下:
|
||||
|
||||
| 字段名 | 变更类型(新增/删除) | 是否必须变更(必须/非必须) | 字段用途 |
|
||||
| --- | --- | --- | --- |
|
||||
| `knowledge_base_documents.file_type text` | 新增 | 必须 | 在本方案保留既有字段语义的前提下,必须单独记录原始格式,以决定转换、编辑和展示能力。正文 MIME 无法区分原生 Markdown 与派生 Markdown,source_type 只表示来源;从对象元数据推断会增加读取依赖且无法覆盖无原件正文,故选择新增字段。 |
|
||||
| `knowledge_base_documents.file_type` CHECK | 无新增/删除,仅扩展约束 | 必须 | 必须允许 csv、jpg、png 等已开放格式,否则入库被约束拒绝;复用同一字段,不增加格式专用列。 |
|
||||
| `knowledge_base_documents.file_type` CHECK | 删除旧约束并新增约束 | 必须 | 必须允许 csv、jpg、png、webp 等已开放格式,否则入库被约束拒绝;复用同一字段,不增加格式专用列。 |
|
||||
|
||||
执行 `000062_kb_file_type.up.sql` 新增可空的 `file_type`(无默认值),允许 NULL 或 `txt/md/html/svg/csv/docx/xls/xlsx/pptx/pdf/jpg/png`,并为非空原件键创建部分索引 `knowledge_base_documents_storage_key_idx`。仅将 `source_type=text`、无原件键且无文件名的历史正文回填为 md;其他未知记录保留 NULL,默认只读,核实来源后回填或重新导入。
|
||||
|
||||
迁移 `000067` 扩展同一 `file_type` CHECK 以允许 WebP,不新增表或字段。须先迁移再部署;down 恢复原约束,仍有 WebP 文档时事务失败,需先导出并移除这些文档或保留新约束,不自动删除数据。复用现有解码器,无新增依赖或 Docker 配置。
|
||||
|
||||
旧试验环境应对照该 Up 文件核实列、CHECK、回填结果和索引,不能仅凭已有同名列判定迁移完成。第 61 号迁移用于专家绑定知识库,与文件类型无关。
|
||||
|
||||
**Breaking Changes(统一导入流程)**:upload 改为上传并开始处理,文本和图片可能直接创建文档及产生模型费用;query 完成后由后端保存。移除旧转换准备 list/export、图片 parse 及显式 commit,AnyDoc task_id 改用 document_id。网页、REST、MCP、OpenAPI 和脚本须协同升级;切换前完成旧导入,旧任务上下文须重新导入。回滚时同时恢复调用方和后端契约,保留原件、正文及学习任务。此调整不新增数据库迁移、镜像、端口或挂载。
|
||||
**Breaking Changes(统一导入流程)**:upload 改为上传并开始处理,文本和图片可能直接创建文档及产生模型费用;query 完成后由后端保存。AnyDoc task_id 使用 document_id。网页、REST、MCP、OpenAPI 和脚本须协同升级;切换前完成旧导入,旧任务上下文须重新导入。回滚时同时恢复调用方和后端契约,保留原件、正文及学习任务。此调整不新增数据库迁移、镜像、端口或挂载。
|
||||
|
||||
**Breaking Changes(既有格式方案)**:旧正文创建接口仅接受 `source_type=text`(省略默认 text),显式 file/url 返回 400;文件改走导入接口,链接抓取暂不提供。派生正文统一只读,旧 DOC/PPT 不再转换,不承诺 Markdown 中不存在的原始坐标。
|
||||
**Breaking Changes(正文创建)**:正文创建接口仅接受 `source_type=text`(省略默认 text),显式 file/url 返回 400;文件改走导入接口,链接抓取暂不提供。派生正文统一只读,旧 DOC/PPT 不再转换,不承诺 Markdown 中不存在的原始坐标。
|
||||
|
||||
升级顺序为数据库约束、转换服务/视觉模型、后端和网页,验收后开放入口。常规应用回滚保留字段、约束、原件、正文和索引,关闭旧版本不支持的编辑及重学入口。仅在明确需要回退数据库且已备份元数据时使用 `000062_kb_file_type.down.sql`:它会删除原件键索引和 `file_type` 列,丢失已保存的格式信息。不要为回滚此功能执行 `000061_expert_knowledge.down.sql`。
|
||||
|
||||
@@ -195,7 +256,7 @@ MCP 搜索默认不内联图片,客户端按需调用 `kb_get_document_image`
|
||||
| AnyDoc 依赖 | 移除 PostgreSQL、PGSSLMODE、OSS_MINIO 凭据及 db/rustfs depends_on;不连接数据库、NATS 或对象存储。MonkeyAI 仍使用原有数据库和对象存储。 |
|
||||
| 端口与挂载 | AnyDoc 仅容器内 8080,无宿主机端口或新增持久卷,需可写临时目录。后端 Dockerfile、端口和挂载不变。 |
|
||||
| 网络与实例 | AnyDoc 须能访问后端图片回调;默认单实例。多实例需确保同一任务的提交、查询、删除到达同一实例,重启不恢复内存任务。 |
|
||||
| 图片能力 | 更新后端及网页,复用现有模型协议、凭证及计费;不新增 OCR 服务、镜像、端口或挂载。网关超时及请求预算须覆盖图片输入。 |
|
||||
| 图片能力 | 更新后端及网页,复用现有模型协议与知识库视觉配置,计费边界见模型配置文档;不新增 OCR 服务、镜像、端口或挂载。网关超时及请求预算须覆盖图片输入。 |
|
||||
|
||||
### AnyDoc slim 环境变量
|
||||
|
||||
@@ -224,18 +285,15 @@ environment:
|
||||
|
||||
## 9. 实现状态与验收
|
||||
|
||||
图片回调精简凭证修复通过知识库包测试及 AnyDoc 既有 uploader 校验/回调测试。新增模拟 HTTP 回归覆盖 5000 字中文标题、8192 字节配置上限、最小字段、重试一致性、轮询元数据保留及旧凭证兼容。本次未配置 MONKEYAI_TEST_DATABASE_URL,数据库回调用例跳过,真实双服务转换及入库仍待验收。
|
||||
以下为已有记录摘要,不表示 2026-12-02 文档整理重新执行或通过这些测试;历史 full 链路结果不能证明当前 slim 链路可用。
|
||||
|
||||
统一流程已接入后端、网页、MCP、Python 脚本及 OpenAPI。2026-11-27 修复验证通过隔离 PostgreSQL 知识库全包测试、18 项前端导入测试、后端 go vet 和两份 OpenAPI YAML 解析。数据库用例覆盖 multipart/Base64 同键重传、只保存一份文档与学习任务、图片解析只调用一次,以及 Python 脚本带原键重启。前端覆盖保存结果不确定、本地超时保留身份及明确终态失败重建。
|
||||
|
||||
anydoc parser/replacer 竞态测试通过,覆盖外链零请求、正文/链接/代码保真与 BMP 原格式上传。真实 Office/PDF 转换、两服务最终入库、供应商计费及生产镜像尚未在本轮端到端验证。后端全量的权限范围与错误码翻译测试仍失败,已在原提交 b602a70 重现。下表为既有能力记录,历史结果不作为本轮端到端通过的依据。
|
||||
|
||||
| 范围 | 已记录的验证 | 仍需验收 |
|
||||
| 范围 | 已记录的验证 | 当前验收缺口 |
|
||||
| --- | --- | --- |
|
||||
| 文本及旧 full 转换链路 | 2026-11-23 lt 真实 HTTP/MCP:TXT/MD/HTML/SVG/CSV、DOCX/XLSX/PPTX/PDF 导入,原件读取、含图片结果、只读约束及检索。 | XLS 真实样本、大文件跨网边界、远程网页端到端;旧 full 结果不证明新版 slim 可用。 |
|
||||
| 当前分阶段 slim 适配 | 2026-11-25 单元测试、隔离 PostgreSQL 知识库测试、19 项前端导入测试、vet 和 Compose 检查;HTTP 模拟服务覆盖 multipart、图片回调、大正文、错误状态、同任务恢复及清理。 | 实际 slim 镜像、真实 Office/PDF 转换质量、含图片资源链路及网页端到端。 |
|
||||
| 独立图片 | 已接入模型选择、三种协议、旧流程签名提交、只读预览、格式过滤、原图关联、MCP 图片工具及脚本;固定夹具/模拟上游覆盖用量记录、检索、权限、字节一致性、解析锁和安全文本组装。 | 真实供应商识图与计费、生产部署、目标 MCP 客户端最终回答展示匹配原图。 |
|
||||
| 整体验证 | 记录包含前端编译、构建、116 项测试、vet、sqlc diff 和 OpenAPI 引用检查通过。 | 后端全量仍有既有 `TestEnvironmentScopesAreExplicitAndUnavailableToRuntime`、`TestBusinessErrorCodesHaveTranslations` 失败;全量页面 lint 和旧编辑器回归亦有既有失败,不标记全量通过。 |
|
||||
| 导入与恢复 | 2026-11-27 隔离 PostgreSQL 知识库测试、前端导入测试、vet 与 OpenAPI 检查;覆盖同键重传、单份文档/任务、响应丢失和重试身份保留 | 当前工作区后续变更的数据库回归;真实客户端从上传到学习完成 |
|
||||
| slim 与图片回调 | HTTP 模拟覆盖 multipart、精简凭证、长标题、上下文与重试;AnyDoc parser/replacer 竞态检查覆盖外链边界及正文保真 | 真实 slim 镜像、Office/PDF 转换质量、双服务图片入库、生产部署 |
|
||||
| 原件与图片 | 单元/模拟检查覆盖资源地址、原始字节、只读响应、格式过滤、权限、解析锁;100 MiB 图片校验与存储读回 | 真实供应商识图及费用、100 MiB 全链路、REST 下载与 MCP 最终附图;WebP 当前端到端验收 |
|
||||
| 临时上传凭证 | 单测覆盖过期、篡改、跨库、用途隔离、旧 Key 兼容和缺少签名配置 | 数据库上传及停用用户用例曾因未配置测试库跳过;真实 MCP 客户端直传 |
|
||||
| 已知阻塞与历史限制 | 既有记录包含 `TestEnvironmentScopesAreExplicitAndUnavailableToRuntime`、`TestBusinessErrorCodesHaveTranslations` 失败,旧页面 lint/编辑器回归失败 | 发布前重新确认;不得据局部测试宣称全量通过 |
|
||||
|
||||
发布前重点验收:
|
||||
|
||||
@@ -243,4 +301,4 @@ anydoc parser/replacer 竞态测试通过,覆盖外链零请求、正文/链
|
||||
2. 覆盖非法/伪装格式、大小与编码边界、跨库和撤权、结果篡改、回调路径及日志脱敏、HTML/SVG 安全预览。
|
||||
3. 覆盖重复提交、保存响应丢失、转换重启/过期/失败、信号量等待与取消、释放后上游仍在解析、AnyDoc 容量限制、429/503 退避、页面关闭不再入库、重复查询并发、重试期限、批量部分失败及清理引用检查;模拟测试不能替代真实调用方验证。
|
||||
4. 使用文件名无关键词、无文字的狗/猫图片验证画面检索、普通文档排除、同图去重及最终原图展示;区分“画面有狗”和“文字提到狗”。
|
||||
5. 检查新安装及已迁移环境的实际 CHECK、回滚兼容、共享签名密钥、容器资源和供应商请求限制;学习及重建不重复转换或调用模型。
|
||||
5. 检查新安装及已迁移环境的实际 CHECK、回滚兼容、共享签名密钥、容器资源和供应商请求限制;独立图片重学复用描述,文档内图片重学按模型配置规则重新识别;均不重新转换原件。
|
||||
@@ -1,75 +0,0 @@
|
||||
# 知识库正文图片上传
|
||||
|
||||
本文描述正文插图上传。JPEG/JPG/PNG 作为独立知识文档导入时,由后端调用视觉 LLM 生成画面描述并提取图中文字,描述参与检索,命中后可返回原图;不调用 anydoc;方案与验证范围见 [多格式解析方案第 10 节](knowledge-base-file-parsing.md#10-jpegjpgpng-独立文档导入)。两类入口的入库与学习行为不同。
|
||||
|
||||
管理端:`POST /api/admin/v1/kb/{id}/images/upload`,使用管理员登录 Cookie,仅支持系统知识库。个人知识库在管理端保持只读。
|
||||
|
||||
客户端:`POST /api/v1/kb/{id}/images/upload`,使用 OAuth Bearer access token。知识库必须启用,调用者为个人库所有者或拥有正文 `read_write` 授权的成员。只读成员返回 403,无访问权限返回 404。上传时锁定知识库并检查权限,与权限撤销、删除操作串行。
|
||||
|
||||
请求使用 `multipart/form-data`,通过 `file` 字段上传一张图片。支持 PNG、JPEG、GIF、WebP,最多 32 MiB、2500 万像素。服务端根据真实内容识别格式并完整解码,不信任文件名或客户端 MIME,拒绝 SVG、损坏图片、空文件和多文件。超限请求返回 400。
|
||||
|
||||
```sh
|
||||
# 管理端:使用已登录的 Cookie 文件,并遵守现有管理 API 的来源校验。
|
||||
curl 'https://example.com/api/admin/v1/kb/KB_ID/images/upload' \
|
||||
-b cookies.txt -H 'Origin: https://example.com' -F 'file=@./picture.png'
|
||||
|
||||
# 客户端
|
||||
curl 'https://example.com/api/v1/kb/KB_ID/images/upload' \
|
||||
-H "Authorization: Bearer $ACCESS_TOKEN" -F 'file=@./picture.png'
|
||||
```
|
||||
|
||||
成功返回 HTTP 201:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "<sha256>.png",
|
||||
"url": "/api/kb/<kb-id>/assets/<sha256>.png",
|
||||
"mime_type": "image/png",
|
||||
"size_bytes": 1024,
|
||||
"markdown": ""
|
||||
}
|
||||
```
|
||||
|
||||
调用者将 `markdown` 插入文档正文,再调用原有文档保存接口。上传本身不修改正文或触发知识库学习。编辑器可以通过返回的 `url` 预览图片。
|
||||
|
||||
## MCP 接口范围
|
||||
|
||||
图片上传需求优先调用 `POST /api/v1/kb/{id}/images/upload`,使用 `multipart/form-data` 的 `file` 字段,由客户端直接传输图片字节。不要让大模型通过 tool calling 生成、复制或传递图片 Base64 来调用 `kb_upload_image`。REST 需要 Agent 登录凭证,MCP Key 不能替代;缺少上传能力或登录凭证时,应提示用户使用客户端上传入口,不要回退为模型生成 Base64。`kb_upload_image` 仅供能够在模型上下文之外读取文件并程序化注入 Base64 的客户端使用。
|
||||
|
||||
知识库 MCP 入口为 `POST /mcp/kb`,新增 `kb_upload_image` 工具,使用带 `mcp:invoke` 作用域的平台 API Key。工具以 Key 对应用户检查启用知识库的正文读写权限,复用 REST 上传的图片校验、同库去重、对象存储及审计流程。
|
||||
|
||||
| 参数 | 约束 |
|
||||
| --- | --- |
|
||||
| `kb_id` | 必填,目标知识库 UUID |
|
||||
| `data_base64` | 必填,图片原始字节的标准 Base64 编码,不包含 `data:image/...;base64,` 前缀;原图最多 32 MiB、2500 万像素,支持 PNG、JPEG、GIF、WebP |
|
||||
|
||||
仅接受上述两个参数;不接受文件路径或源站 URL。上传成功的 `structuredContent` 包含与 REST 相同的 `name`、`url`、`mime_type`、`size_bytes` 和 `markdown`,`content` 同时提供结果的 JSON 文本。工具业务错误返回 `isError=true`。
|
||||
|
||||
```json
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "kb_upload_image",
|
||||
"arguments": {
|
||||
"kb_id": "<kb-id>",
|
||||
"data_base64": "<图片原始字节的标准 Base64>"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
上传调用允许的 JSON 请求体上限为 44,804,780 字节(32 MiB 图片的 Base64 长度加 64 KiB 开销);其他 MCP 请求仍最多 1 MiB。先通过 `kb_upload_image` 获得 Markdown,再将其合并到正文,通过 `kb_create_document` 或 `kb_update_document` 保存。上传本身不创建文档或触发学习,文档保存仍受现有请求体大小和版本检查约束。
|
||||
|
||||
知识库 MCP 现共提供 22 个工具,完整清单见 [内置 MCP 工具清单](knowledge-base-technical-design.md#83-内置-mcp)。返回的图片地址仍受阅读权限保护;MCP API Key 用于上传工具调用,浏览器预览或 REST 读取图片需使用浏览器会话或 OAuth access token。
|
||||
|
||||
## 管理端与图片存储
|
||||
|
||||
管理端知识库正文编辑器支持粘贴剪贴板图片,自动调用管理端上传接口并在粘贴位置插入 Markdown 图片。一次粘贴多张图片时依次上传;普通文本粘贴保持原有行为。上传期间可以继续输入,插入位置随文档编辑移动,不覆盖后续输入;页面显示上传状态并暂停手动和自动保存。上传失败提示错误并保留草稿;离开页面时取消未完成上传。只读文档不发起上传。浏览器先校验图片格式和 32 MiB 大小限制,真实图片解码和像素限制由后端执行。
|
||||
|
||||
图片使用对象存储路径 `knowledge/<kb-id>/assets/<sha256>.<ext>` 和读取接口 `GET /api/kb/{id}/assets/{name}`,不新增数据库表。同库同图复用地址,不同知识库分别存储。读取接口支持浏览器 Cookie 和客户端 Bearer token,逐次检查阅读权限,响应禁止缓存,不公开对象存储 URL。
|
||||
|
||||
删除知识库后按 assets 前缀清理对象存储。上传后未引用的图片保留到知识库删除;对象存储写入成功但审计或数据库提交失败时可能留下未引用对象,当前没有自动回收任务。未配置对象存储返回 503,上传失败时不会返回成功地址。
|
||||
|
||||
完整请求和响应契约见 `backend/api/admin.yaml` 与 `backend/api/agent.yaml`。后端沿用项目现有 chi 路由、identity 鉴权和 kb 业务层。
|
||||
@@ -1,6 +1,8 @@
|
||||
# 知识库 MCP 设计
|
||||
|
||||
新增源码能力:JPEG/JPG/PNG 通过视觉 LLM 生成画面描述(含图中文字),支持按描述检索并返回知识库原图。图片格式过滤、检索结果原图引用及新增 `kb_get_document_image` 的方案见 [文件解析方案第 10 节](knowledge-base-file-parsing.md#10-jpegjpgpng-独立文档导入)。下文既有接口清单保留原有能力说明,新增工具与当前 schema 以代码和文件解析方案为准,真实客户端附图验收范围见该方案。
|
||||
Agent 当前多格式接入契约及示例见 [Agent 接入说明](knowledge-base-agent-integration.md)。
|
||||
|
||||
本文维护 MCP 协议、工具边界与传输限制。文件格式和解析流程统一见 [文件解析方案](knowledge-base-file-parsing.md),模型来源见 [模型配置](knowledge-base-models.md)。
|
||||
|
||||
## 1. 入口与调用链
|
||||
|
||||
@@ -35,7 +37,7 @@
|
||||
|
||||
| 接口 | 操作对象 | 功能与调用边界 |
|
||||
| --- | --- | --- |
|
||||
| `kb_list_documents` | doc:文档列表 | 分页读取元数据,不返回正文;支持关键词、学习状态和来源过滤,并校验知识库权限 |
|
||||
| `kb_list_documents` | doc:文档列表 | 分页读取文档元数据,不返回 `content` 字段;支持关键词、学习状态和来源过滤,并校验知识库权限 |
|
||||
| `kb_get_document` | doc:文档 | 默认读取元数据和 revision;include_content=true 兼容全文读取,长文档优先分段读取 |
|
||||
| `kb_read_document` | doc:文档正文 | 按 Unicode 字符分段读取,默认 4000、最多 16000 字符;续读必须提供首页 expected_revision,文件夹不可读取正文 |
|
||||
| `kb_create_folder` | doc:文件夹 | 要求正文读写权限;parent_id 必须为同库文件夹,省略、null 或空字符串表示根目录;返回节点元数据,不进入学习队列 |
|
||||
@@ -45,10 +47,10 @@
|
||||
| `kb_delete_document` | doc:文档或文件夹 | 删除节点并取消活跃学习任务;支持 ids(最多 200 项),协作删除提供 expected_revisions;兼容 document_id/expected_revision,批量结果须逐项检查 succeeded/failed |
|
||||
| `kb_move_document` | doc:文档或文件夹 | 在同库移动及排序,禁止移入自身或子目录;parent_id 省略或 null 表示根目录,prev_id/next_id 仅用于单项排序;支持 ids 和协作 expected_revisions,兼容 document_id/expected_revision,批量结果须逐项检查 |
|
||||
| `kb_restudy_document` | doc:文档 | 要求启用知识库的正文读写权限,取消旧活跃任务后按现有索引状态重新学习;支持 ids,兼容 document_id,文件夹不支持,批量结果须逐项检查 |
|
||||
| `kb_upload_file` | doc:文件导入 | 同 Key 二进制上传后携带 import_context;图片需 model_id,LLM 生成画面描述及图中文字并保存;Office/PDF 走 anydoc,文本直接保存 |
|
||||
| `kb_upload_file` | doc:文件导入 | 只传 kb_id 获取 upload_url/upload_token,由客户端直传文件;可用 import_context 继续处理;图片使用知识库唯一视觉模型,不传 model_id |
|
||||
| `kb_get_file_import_status` | doc:文件导入 | 查询 anydoc 转换并由服务端保存;图片为同步 LLM 解析,不调用此工具 |
|
||||
| `kb_get_document_image` | doc:独立图片原件 | 按 kb_id/document_id 校验阅读权限并返回 MCP image 内容块,原图内联最多8 MiB;客户端须支持展示,超限通过已登录网页获取 |
|
||||
| `kb_search` | doc:文档分片 | 在可访问知识库中检索,kb_ids 限定范围;自动选择全文或混合检索,top_k 默认 8、最多 20;file_types 可限定 jpg/png,在召回前过滤;图片命中返回 image 元数据并按文档去重。泛化 filters 仍不执行过滤并返回 filters_not_applied,不应依赖它约束结果 |
|
||||
| `kb_search` | doc:文档分片 | 在可访问知识库中检索,kb_ids 限定范围;自动选择全文或混合检索,top_k 默认 8、最多 20;file_types 可限定 jpg/png/webp,在召回前过滤;图片命中返回 image 元数据并按文档去重。泛化 filters 仍不执行过滤并返回 filters_not_applied,不应依赖它约束结果 |
|
||||
|
||||
所有工具保留原始 schema,并提供 `readOnlyHint`、`destructiveHint`、`idempotentHint`、`openWorldHint`。annotations 仅为客户端提示,不代替授权。写操作保守标为非幂等;超时或连接中断后先核实实际结果,不盲目重试。批量操作返回 `succeeded/failed`,不能把 HTTP 200 当作全部成功。
|
||||
|
||||
@@ -58,7 +60,7 @@
|
||||
|
||||
1. `kb_list_documents` 定位文档;`kb_get_document` 默认只读取元数据。
|
||||
2. `kb_read_document` 按 Unicode 字符读取正文,默认 4000、最多 16000 字符;文件夹没有正文,读取会被拒绝。返回 `document.revision`、`next_offset`、`has_more`、`total_characters`。续读必须传首页的 `expected_revision`,冲突则重读,不能拼接不同版本。
|
||||
3. `kb_edit_document` 传 `kb_id`、`document_id`、`expected_revision` 和 `edits: [{old_text,new_text}]`。最多 50 项,编辑文本合计最多 256 KiB;精确匹配不做空白归一化,不接受正则或模糊匹配。仅 `source_type=text` 的文档可编辑;文件、链接文档和文件夹直接拒绝,避免正文与原始附件元数据不一致。
|
||||
3. `kb_edit_document` 传 `kb_id`、`document_id`、`expected_revision` 和 `edits: [{old_text,new_text}]`。最多 50 项,编辑文本合计最多 256 KiB;精确匹配不做空白归一化,不接受正则或模糊匹配。按持久化 `file_type` 判断可编辑性,格式规则见文件解析方案;派生正文和文件夹拒绝编辑,避免正文与原始附件元数据不一致。
|
||||
4. 所有操作在文档行锁、当前写权限及版本检查后顺序执行,后续操作匹配前一步结果。每个 old_text 必须非空且唯一,new_text 必须显式提供,允许空字符串删除。任一步失败整批回滚,索引和学习任务同样不发生部分更新。
|
||||
5. 返回文档元数据和新 revision,不复制全文。`text_not_found`、`ambiguous_match` 指示匹配失败;`document_revision_conflict` 表示旧版本不可写;`precondition_required` 表示必须读取版本。失败位置使用 edits 的零基索引,匹配次数按包含重叠在内的实际位置计数;空 old_text 与合计超限分别报错。参数结构错误(缺少 new_text、多余字段等)返回具体原因,而不是笼统的“工具参数无效”。
|
||||
|
||||
@@ -82,17 +84,16 @@ REST 文档创建和更新接口(用户端 `/api/v1/kb/{id}/documents[/{docume
|
||||
| 请求 | HTTP JSON body 上限 |
|
||||
| --- | --- |
|
||||
| 默认(包括普通工具、初始化和工具目录) | 1 MiB |
|
||||
| `tools/call` → `kb_upload_image` | 44,804,780 字节:32 MiB 原图的 Base64 长度 + 64 KiB JSON 开销 |
|
||||
| `tools/call` → `kb_upload_image` / `kb_upload_file` | 139,875,672 字节:100 MiB 原图的 Base64 长度 + 64 KiB JSON 开销 |
|
||||
| `tools/call` → `kb_update` | 2,446,680 字节:1 MiB 图标的 Base64 长度 + 1 MiB 元数据开销 |
|
||||
|
||||
知识库独立 MCP handler 先按图片上传上限限制读取,再按 method 和工具名检查实际请求大小。超过限制返回 HTTP 400 和 JSON-RPC error;图片格式、解码后大小和像素限制由知识库服务检查。
|
||||
|
||||
现有 `POST /api/v1/kb/{id}/images/upload` 接受 multipart/form-data 的 `file` 字段,由客户端读取和上传图片字节,最大 32 MiB。它需要 Agent 登录凭证;只有 MCP Key 的客户端不能直接调用,且纯模型客户端未必具有本地文件读取/上传能力。该通道不等于已实现 MCP 文件引用上传。
|
||||
`kb_upload_image` 仅接受 `kb_id` 和不带 data URL 前缀的标准 `data_base64`;成功返回 `name/url/mime_type/size_bytes/markdown`,上传不创建文档或触发学习。由客户端将 Markdown 写入正文,具体权限、格式、存储和清理见 [正文插图上传](knowledge-base-file-parsing.md#正文插图上传)。
|
||||
|
||||
Base64 原图 32 MiB 编码后约 42.7 MiB,模型输出、客户端和代理可能远早于服务端限制失败。图标更新的 avatar_base64 同样仅适用于程序化注入。此次未新增任意 URL 下载或本地路径读取,以免暴露 SSRF 或服务端文件读取能力。统一的受限上传会话/文件引用需要结合实际 Agent 的文件访问与凭证通道另行实现。
|
||||
文件导入使用 `kb_upload_file` 的完整 `upload_url` 和短期凭证,由客户端直接传输 multipart 字节;凭证用途、失效、重试和回滚规则只在 [文件导入传输契约](knowledge-base-file-parsing.md#mcp-与文件传输) 维护。该凭证不能代替 REST 身份下载原件,也不适用于正文插图上传。
|
||||
|
||||
|
||||
程序化客户端上传后可将返回的 Markdown 写入正文;详情见 [知识库图片上传](knowledge-base-image-upload.md)。客户端和反向代理仍需允许对应请求大小及执行时间。
|
||||
100 MiB 原图 Base64 编码后约 133.3 MiB,客户端、代理和供应商可能先于服务端限制失败。`avatar_base64` 同样只适用于程序化注入。工具不接受服务端本地路径或任意源站 URL;缺少文件读取/上传能力的纯模型客户端不能仅凭路径完成导入。真实客户端传输与最终展示须单独验收。
|
||||
|
||||
## 4. 返回结果、错误和重试
|
||||
|
||||
@@ -100,12 +101,14 @@ Base64 原图 32 MiB 编码后约 42.7 MiB,模型输出、客户端和代理
|
||||
|
||||
认证、协议及请求大小错误使用 JSON-RPC error。工具业务错误(包括未知工具)返回 `isError=true` 结果,包含 code、message 和 references;内部错误隐藏底层细节并记录诊断日志。
|
||||
|
||||
知识库 MCP 不提供持久化 Idempotency-Key 去重保障。写入失败或连接中断后,客户端应根据读取结果、revision 或批量结果确认实际状态,不能把 HTTP 超时等同于没有副作用。协作写入继续遵守 expected_revision / expected_revisions 约束。
|
||||
普通 MCP 写操作不提供通用持久化 Idempotency-Key 去重保障;文件导入另按 `upload_key`、文档 ID 和签名上下文去重,见文件解析方案。写入失败或连接中断后,客户端应根据读取结果、revision 或批量结果确认实际状态,不能把 HTTP 超时等同于没有副作用。协作写入继续遵守 expected_revision / expected_revisions 约束。
|
||||
|
||||
## 5. 验证与兼容性
|
||||
|
||||
旧工具名称、默认全文响应和个人库所有者可省略版本的旧调用保持兼容;新局部编辑对所有调用者强制版本。旧创建/全文更新仍受 JSON 请求大小限制。分段正文读取限制的是输出量,底层仍读取完整文档;
|
||||
工具名称继续保留;正文返回遵循 [Agent 原件读取契约](knowledge-base-file-parsing.md#agent-原件读取契约),不承诺旧默认全文响应兼容。局部编辑对所有调用者强制版本。旧创建/全文更新仍受 JSON 请求大小限制。分段正文读取限制的是输出量,底层仍读取完整文档。本次整理未重新运行这些测试。
|
||||
|
||||
业务测试覆盖 Unicode 分段、越界、匹配歧义(含重叠)、编辑参数/大小、事务回滚、旧版本重放、清空正文、只读权限、元数据省略名称、以及带 Bearer 的 HTTP JSON-RPC 读取。HTTP 使用测试认证器,尚未执行真实模型 Agent 的端到端编辑或二进制上传验证。
|
||||
已有测试记录覆盖 Unicode 分段、越界、匹配歧义(含重叠)、编辑参数/大小、事务回滚、旧版本重放、清空正文、只读权限、元数据省略名称、以及带 Bearer 的 HTTP JSON-RPC 读取。HTTP 使用测试认证器,尚未执行真实模型 Agent 的端到端编辑或二进制上传验证。
|
||||
|
||||
数据库测试与 HTTP 测试用于证明服务端调用链;不能代替真实 Desktop/Agent 从资源目录获取配置到调用的端到端验证,也不能证明线上代理的 body/timeout 设置正确。线上验证需另外确认 `/mcp/kb` 调用和图片传输。
|
||||
|
||||
待同步的描述差异:`mcpfiles.go` 的 `kb_upload_file.description` 仍列出 XLS 并重复 WebP,而同文件返回的 `supported_formats` 已排除 XLS。本文按实际格式校验记录;本次仅整理文档,工具描述尚需随实现修正。
|
||||
@@ -0,0 +1,102 @@
|
||||
# 知识库配置
|
||||
|
||||
本文维护模型配置、调用限流和图片失败处理;文档学习的内容提取与索引机制见 [技术设计](knowledge-base-technical-design.md#62-学习步骤)。
|
||||
|
||||
## 目标与方案
|
||||
|
||||
知识库页面统一管理视觉模型和向量模型。视觉模型独立存入 `knowledge_base_models`,目前最多一条;向量模型继续存入 `models`,不复制、不删除旧记录。普通模型管理隐藏向量模型并拒绝编辑,知识库配置面板读取最新的未删除系统向量模型(created_at DESC、id DESC),没有时首次保存创建。
|
||||
|
||||
已有知识库继续使用原模型绑定;本次迁移不统一切换模型。学习、检索复用原有 models 查询及 embeddings 调用。配置面板管理最新模型,其他历史模型仍可服务原有绑定,不提供历史模型编辑入口。
|
||||
|
||||
模型名称为供应商标识,地址和密钥必填;密钥不回显,更新留空保留。视觉配置名称和协议同一行(窄屏纵向排列);高级选项包含输出上限和代理;向量维度由保存时探测。两类配置均不使用 revision,同类保存由事务锁串行处理,以最后成功提交为准。
|
||||
|
||||
## 数据库变更
|
||||
|
||||
新增 `knowledge_base_models` 表是本方案必需:按要求独立存储知识库视觉配置,避免通用模型授权、标签及计费配置混入。替代方案是将视觉配置也放入 models,但不采用。models 及知识库其他表均不增删字段。
|
||||
|
||||
| 字段名 | 变更类型 | 是否必须变更 | 字段用途 |
|
||||
|---|---|---|---|
|
||||
| id | 新增 | 必须 | 视觉调用需要稳定 UUID 标识及旧配置识别 |
|
||||
| kind | 新增 | 非必须 | 可用固定单例键替代;保留统一配置接口的类型标识,唯一约束及 vision 检查限制最多一行 |
|
||||
| model_id | 新增 | 必须 | 上游模型名称,调用时必需 |
|
||||
| base_url | 新增 | 必须 | 上游请求地址,调用时必需 |
|
||||
| api_key | 新增 | 必须 | 上游调用凭据,沿用现有存储方式,接口不返回 |
|
||||
| protocol | 新增 | 必须 | 决定 Chat Completions、Responses 或 Anthropic 请求格式 |
|
||||
| proxy_id | 新增 | 非必须 | 可仅直连;保留管理员选择网络代理的能力 |
|
||||
| advanced_config | 新增 | 非必须 | 可拆成输出上限字段;复用视觉调用结构 |
|
||||
| enabled | 新增 | 必须 | 支持停用配置并拒绝调用 |
|
||||
| created_at / updated_at | 新增 | 非必须 | 可省略;保留配置时间信息和表单保存后刷新依据 |
|
||||
|
||||
迁移 000068 创建视觉模型表并扩展 WebP 文件类型约束,不复制模型、不取消学习任务、不清理索引。down 删除视觉模型表并恢复文件类型约束;存在 WebP 文档时拒绝回退。
|
||||
|
||||
## 保存和调用
|
||||
|
||||
视觉模型保存到独立表,图片解析读取该配置。缺少配置或停用时明确失败。视觉请求复用已有网关协议和网络策略,不使用通用模型授权或内部账本计费;供应商仍可能收费。内容读取和写入权限照常校验。
|
||||
|
||||
入口及弹窗统一命名“知识库配置”,包含视觉模型、向量模型、并发配置三个页签。并发配置独立保存,无需先填写模型;学习任务和图片识别并发均为整数 1~20,默认 1。管理端 GET/PUT `/kb-concurrency` 读写 `learning_concurrency`、`image_concurrency`,PUT 两项必填。配置读取或保存失败明确报错。
|
||||
|
||||
配置复用现有 `settings.value` JSON,使用 `kb_concurrency` 键,无新增表或字段。迁移 000067 仅扩展 `settings_key_check` 的允许键值,这是持久保存独立配置所必需的约束变更;不创建默认记录。首次读取时学习并发取 1,图片并发沿用原视觉模型 `advanced_config.concurrency`(无配置取 1),首次保存后统一以新配置为准。旧模型接口仍接受 1~20 的 concurrency,但独立配置存在时不覆盖其生效值。
|
||||
|
||||
学习任务由最多 20 个 worker 消费;领取任务前在同一事务中获取固定 PostgreSQL advisory lock,读取上限、统计有效 running 及尚未退出执行的 canceled 租约并领取任务。因此学习任务上限跨服务实例生效,不把单任务内部的图片请求计作独立学习任务。调低上限等待在途任务自然结束,调高后下一轮轮询(约 1 秒)可领取更多任务。重新学习或取消任务时保留旧执行的并发名额,执行与心跳均退出后按任务 ID、attempts 和 worker 释放,清理使用独立超时上下文;进程崩溃或清理失败仍按 5 分钟租约超时恢复。数据库异常停止本次领取,不放行;任务继续沿用租约续期、超时回收及失败重试机制。
|
||||
|
||||
文档内图片(包括历史 XLS 转换正文)由共用批处理器提取引用并去重,有界 worker 读取、校验和识别,全部完成后按原图片位置替换学习副本;原始 `content` 不变。提取范围及资源访问边界见 [学习流程](knowledge-base-technical-design.md#62-学习步骤)。
|
||||
|
||||
| 场景 | 调用与失败规则 |
|
||||
| --- | --- |
|
||||
| 并发准入 | 单图导入和文档图片学习共用每进程门限,多实例各自限流。每次准入读取当前配置;降低上限不中断在途请求,后续请求等待。单篇 worker 数在开始时确定。 |
|
||||
| 独立图片导入 | 请求级预算 100 秒;解析失败不静默自动重试。结果不确定时显式确认后重试,可能再次产生供应商费用。 |
|
||||
| 文档内图片学习 | 每张有效图片最多尝试 3 次(含首次);每次从 worker 开始处理时独立计时 60 秒,包含读取/转存、名额等待和模型请求,并遵守父任务取消。单次学习中成功图片不重跑。 |
|
||||
| 单图最终失败 | 在原位置保留“图片识别失败:已尝试 3 次,未生成描述”占位,继续其他图片、切片和向量化;损坏或不合法图片不发往模型,直接保留失败占位。失败次数和图片序号记入服务端日志。 |
|
||||
| 整篇任务边界 | 单图失败不触发整篇自动重试;父任务取消或租约失效仍中断。租约机制见技术设计,分片保留失败占位,原始正文保留。 |
|
||||
| 费用与重学 | 每次上游调用均可能计费;显式重学文档内图片会重新识别。配置调整不自动重新学习历史文档。 |
|
||||
|
||||
|
||||
向量模型保留原 models ID、归属及其他未编辑配置。新增时为管理员创建系统模型;更新密钥或代理不触发向量重建。模型名称、地址、协议、维度或启停状态改变时,在同一事务内取消受影响任务、清理向量并安排学习;范围为绑定该模型或尚未绑定模型的知识库,不改写绑定其他模型的知识库。旧任务仍通过任务状态与租约校验阻止写回。
|
||||
|
||||
## 用户流程与模块交互
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[管理员打开知识库] --> B[知识库配置]
|
||||
B --> C{选择页签}
|
||||
C --> Limits[并发配置:学习与图片 1~20]
|
||||
Limits --> S
|
||||
C --> V[编辑视觉配置]
|
||||
C --> E[编辑最新系统向量模型]
|
||||
V --> S[保存并刷新]
|
||||
E --> P[探测维度并保存]
|
||||
P --> R[必要时重学受影响知识库]
|
||||
```
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
UI[知识库配置面板] --> API[知识库管理 API]
|
||||
API --> Settings[(settings 并发配置)]
|
||||
Settings --> Admission[事务锁与学习任务准入]
|
||||
Admission --> Worker
|
||||
Gate --> Settings
|
||||
API --> V[(knowledge_base_models)]
|
||||
API --> E[(models)]
|
||||
Image[单图导入与多图学习] --> Gate[共享并发门限]
|
||||
Gate --> V
|
||||
Gate --> Vision[视觉模型]
|
||||
Vision --> Ordered[按原位置替换学习副本]
|
||||
Worker[学习和检索] --> E
|
||||
API --> Jobs[受影响知识库的学习任务]
|
||||
```
|
||||
|
||||
## Breaking Changes、升级与回滚
|
||||
|
||||
通用模型管理不再展示或允许编辑向量模型,改用知识库配置入口。视觉解析改用独立视觉配置。新客户端不传 `model_id`;旧客户端上传时可以继续携带该字段,服务端忽略它,不会按旧字段或导入上下文选模型。升级前须配置并启用知识库视觉模型。
|
||||
|
||||
备份数据库,执行迁移并部署前后端,再配置视觉模型。迁移 000066 管理 API Token 表,000067 管理并发配置,000068 仅负责视觉模型表和 WebP 文件类型约束。回退 68 会删除视觉模型表并恢复文件类型约束,存在 WebP 文档时拒绝回退。
|
||||
|
||||
新增并发配置升级时先执行 000067 再部署后端和前端;回滚时先停止新版 worker,再回滚应用并执行 000067 down(删除并发配置记录并恢复键约束),旧版恢复串行学习及旧视觉并发值。此次不新增数据库表或字段,不涉及 Docker 配置。
|
||||
|
||||
回滚前导出视觉配置,执行 down 并恢复旧服务;独立视觉配置会删除,向量模型及索引不受迁移回滚影响。业务保存已触发的重学不由 down 撤销。无 Docker、端口、环境变量或挂载变更。
|
||||
|
||||
## 验证
|
||||
|
||||
本次已通过前端 TypeScript 构建检查、知识库包测试及 race 检查、全后端 go vet、sqlc/schema 一致性检查及 OpenAPI YAML 解析。新增测试覆盖两项并发值的 1/20 边界、缺失/小数/null/越界请求;数据库用例覆盖默认值、持久化、图片配置读取、学习任务满额拒绝领取,以及慢模型调用期间重新学习不得提前释放名额、旧执行退出后新任务可领取,但因未配置 MONKEYAI_TEST_DATABASE_URL 而跳过。浏览器和真实模型端到端尚未验证。
|
||||
|
||||
全后端测试存在 Firecracker 依赖、runtime 环境权限和业务错误码翻译三个失败项,相关代码未在本次修改。部署前需完成数据库迁移及真实多任务学习验收。
|
||||
@@ -1,6 +1,6 @@
|
||||
# 知识库权限产品方案
|
||||
|
||||
> 更新日期:2026-11-13。状态:权限功能已开发并通过集成验证,尚未发布。
|
||||
> 原方案日期:2026-11-13;整理日期:2026-12-02。原记录为功能已开发、集成验证通过且尚未发布;本次未重新验证发布状态。当前不提供回收站或正文历史版本。
|
||||
>
|
||||
> 本文记录产品目标、操作流程、权限规则、异常体验、验收标准,以及对应的表结构与 migration 调整。不包含接口、业务代码实现、框架选型或技术测试方案。
|
||||
|
||||
@@ -62,11 +62,11 @@
|
||||
|
||||
- 读写成员能够维护和删除该库中其他成员创建的文档,不限于本人创建的内容。
|
||||
- 只读成员即使是文档创建者,也不能修改或删除文档;操作能力取决于当前知识库权限。
|
||||
- 正文编辑和文档删除都可能导致内容丢失,建议分别通过历史版本和回收站提供恢复能力;权限本身不等于内容备份。
|
||||
- 正文编辑和永久删除可能导致内容丢失;权限不提供内容备份或恢复能力。
|
||||
- 本期移动限定在同一个知识库内,不包含跨知识库迁移内容。
|
||||
- 不因本方案新增文件格式解析能力,导入范围以产品已提供的能力为准。
|
||||
|
||||
## 4. 管理端:对象行内授权
|
||||
## 4. 授权管理与有效权限
|
||||
|
||||
### 4.1 入口
|
||||
|
||||
@@ -98,9 +98,9 @@
|
||||
|
||||
例如张三选择只读、产品组选择读写,保存两条独立授权记录。组授权的继承和多来源取最高权限规则不变。
|
||||
|
||||
## 5. 修改、移除与有效权限
|
||||
### 4.4. 修改、移除与有效权限
|
||||
|
||||
### 5.1 修改一条授权
|
||||
#### 4.4.1 修改一条授权
|
||||
|
||||
点击某行“修改权限”,选择新的权限并保存,只影响这一条记录。
|
||||
|
||||
@@ -108,7 +108,7 @@
|
||||
|
||||
列表必须展示保存后的实际权限。操作失败保留原状态,不能先显示成功再让用户误以为已生效。
|
||||
|
||||
### 5.2 移除一条授权
|
||||
#### 4.4.2 移除一条授权
|
||||
|
||||
点击“移除”,确认后取消该对象的这条直接授权。
|
||||
|
||||
@@ -118,7 +118,7 @@
|
||||
|
||||
移除授权不删除该成员已创建的文档,也不改变文档归属。文档仍保留在原知识库中。
|
||||
|
||||
### 5.3 多条来源取最高权限
|
||||
#### 4.4.3 多条来源取最高权限
|
||||
|
||||
同一个人可能同时获得个人、分组和全员授权。最终权限取最高档:
|
||||
|
||||
@@ -134,7 +134,7 @@
|
||||
|
||||
第一版不提供“禁止访问”或“个人授权覆盖组授权”等例外规则。
|
||||
|
||||
### 5.4 查看权限来源
|
||||
#### 4.4.4 查看权限来源
|
||||
|
||||
知识库负责人可以搜索成员,查看其最终权限及来源,例如:
|
||||
|
||||
@@ -142,7 +142,7 @@
|
||||
|
||||
普通成员只需看到自己的最终权限,不展示完整的其他成员授权名单。
|
||||
|
||||
## 6. 分组及全员规则
|
||||
### 4.5. 分组及全员规则
|
||||
|
||||
- 分组授权包含该组和下级分组成员。
|
||||
- 新加入分组的人自动获得对应权限,退出后失去该来源的权限。
|
||||
@@ -152,9 +152,9 @@
|
||||
- 停用或删除的成员不能继续使用知识库,不因仍在某分组中而例外。
|
||||
- 同一个人通过多个分组重复获得权限时,只计算最终最高权限,不在授权列表自动生成重复个人记录。
|
||||
|
||||
## 7. 客户端维护系统知识库
|
||||
## 5. 客户端维护与个人分享
|
||||
|
||||
### 7.1 成员不需要成为管理员
|
||||
### 5.1 成员不需要成为管理员
|
||||
|
||||
管理员在管理端给普通成员授权后,成员直接在客户端使用对应能力。
|
||||
|
||||
@@ -162,7 +162,7 @@
|
||||
|
||||
后台管理员身份与客户端内容权限分开。管理员如果使用普通客户端维护系统库,也按该库授予的内容权限操作。
|
||||
|
||||
### 7.2 列表与详情展示
|
||||
### 5.2 列表与详情展示
|
||||
|
||||
知识库展示两个独立标识:
|
||||
|
||||
@@ -171,7 +171,7 @@
|
||||
|
||||
示例:“产品资料库 · 系统知识库 · 读写”。
|
||||
|
||||
### 7.3 操作入口
|
||||
### 5.3 操作入口
|
||||
|
||||
- 只读成员:查看、搜索、引用,无编辑及删除入口。
|
||||
- 读写成员:增加新建、导入、编辑、重命名、移动、排序、重新学习、单项删除、批量删除和文件夹删除入口。
|
||||
@@ -179,7 +179,7 @@
|
||||
|
||||
通过助手操作知识库时,遵循同样的权限:只读不能要求助手修改或删除内容;读写可以新增、编辑和删除内容,但不能要求助手转授权或删除整个知识库。
|
||||
|
||||
## 8. 个人知识库分享
|
||||
### 5.4. 个人知识库分享
|
||||
|
||||
个人库所有者使用相同的行内交互,在人或组右侧选择只读或读写。
|
||||
|
||||
@@ -189,35 +189,25 @@
|
||||
|
||||
所有者保留知识库管理能力。管理端对个人库仍只读,不因为本方案获得个人库内容写入或授权修改能力。
|
||||
|
||||
## 9. 删除体验
|
||||
## 6. 删除体验
|
||||
|
||||
### 9.1 单文档删除
|
||||
### 6.1 单文档删除
|
||||
|
||||
只有读写成员和知识库负责人可以删除。确认界面展示文档名称及删除后不再用于检索、提问和引用的影响。
|
||||
|
||||
### 9.2 文件夹删除
|
||||
### 6.2 文件夹删除
|
||||
|
||||
删除确认明确提示包含多少子文件夹和文档,说明会一并删除其内容,不能只显示“删除文件夹”而隐藏影响范围。
|
||||
|
||||
### 9.3 批量删除
|
||||
### 6.3 批量删除
|
||||
|
||||
展示选中项及实际受影响的内容数量。父文件夹和子项同时选中时,按实际影响范围去重,避免重复统计。
|
||||
|
||||
没有删除权限时不展示批量删除入口。确认过程中权限变化时停止操作并说明原因。
|
||||
|
||||
### 9.4 配套建议:回收站
|
||||
删除为永久删除,确认时须明确提示“删除后无法恢复”。
|
||||
|
||||
回收站属于建议配套能力,不因开放读写授权就视为已经实现。若纳入本期,采用以下产品规则:
|
||||
|
||||
- 删除的内容进入知识库回收站,保留 30 天;期间不出现在正常目录和检索结果中。
|
||||
- 读写成员和负责人可查看、恢复删除内容。
|
||||
- 提前永久删除和清空回收站仅负责人可执行。
|
||||
- 文件夹按整批恢复其原有子树;原父目录不存在时恢复到知识库根目录并提示。
|
||||
- 到期自动清理;整库删除不由文档回收站提供恢复保证。
|
||||
|
||||
如果本期不包含回收站,删除确认必须明确标注“删除后无法恢复”,不能出现“可在回收站找回”等误导文案。
|
||||
|
||||
## 10. 权限变化和异常体验
|
||||
## 7. 权限变化和异常体验
|
||||
|
||||
| 场景 | 产品行为 |
|
||||
| --- | --- |
|
||||
@@ -234,35 +224,27 @@
|
||||
|
||||
已接受的文档修改,其学习处理可以继续完成;撤销作者权限不删除这份已提交内容。被删除文档不再作为可用知识提供,不能因处理任务完成而重新出现。
|
||||
|
||||
## 11. 协作维护的配套体验
|
||||
### 7.1. 协作维护的配套体验
|
||||
|
||||
### 11.1 修改人及修改时间
|
||||
#### 7.1.1 修改人及修改时间
|
||||
|
||||
文档展示最近一次内容修改人及时间,方便追踪维护者。学习状态变化不应被展示为某个人重新编辑了正文。
|
||||
|
||||
### 11.2 编辑冲突
|
||||
#### 7.1.2 编辑冲突
|
||||
|
||||
两人同时编辑同一文档时,后提交者获知内容已更新,保留本地草稿,查看最新内容后再决定如何合并。不能无提示覆盖他人修改。
|
||||
|
||||
### 11.3 建议配套:文档历史版本
|
||||
|
||||
若纳入本期,保存正文后保留历史版本;可读取者可查看仍保留的历史正文,读写成员可将历史版本恢复为新的当前版本。恢复不会删除中间版本。
|
||||
|
||||
历史版本仍继承当前知识库权限,失去读权限后不能继续查看。永久删除历史版本仅负责人可操作。
|
||||
|
||||
历史版本保留时长、数量及容量限制需要在该配套能力正式立项时确定;不能把尚未实现的历史版本作为当前防丢失承诺。
|
||||
|
||||
### 11.4 操作与授权记录
|
||||
#### 7.1.3 操作与授权记录
|
||||
|
||||
负责人可以查看谁在什么时间新增、修改、移动、删除了哪些内容,以及谁给哪个对象调整了什么权限。
|
||||
|
||||
普通成员不因此获得完整授权名单。操作记录不等同于正文历史版本,不能仅凭操作记录承诺恢复内容。
|
||||
|
||||
## 12. 表结构调整记录
|
||||
## 8. 表结构调整记录
|
||||
|
||||
本节记录产品方案涉及的数据结构变化,并在 12.8 节明确 migration 修改范围。对应 migration 文件已新增;目标环境数据库需随发布执行迁移。
|
||||
本节记录产品方案涉及的数据结构变化,并在 8.6 节明确 migration 修改范围。对应 migration 文件已新增;目标环境数据库需随发布执行迁移。
|
||||
|
||||
### 12.1 授权表 resource_access_grants:必需调整
|
||||
### 8.1 授权表 resource_access_grants:复用现有结构
|
||||
|
||||
复用现有授权表,不新建一套知识库权限表。
|
||||
|
||||
@@ -288,7 +270,7 @@
|
||||
|
||||
历史只读授权保持只读,不自动升级。历史上存在但未实际赋予知识库写能力的其他权限记录,需要逐项确认,不直接让旧值获得新的操作能力。
|
||||
|
||||
### 12.2 knowledge_bases:复用现有版本
|
||||
### 8.2 knowledge_bases:复用现有版本
|
||||
|
||||
| 字段 | 类型 | 设计 |
|
||||
| --- | --- | --- |
|
||||
@@ -300,7 +282,7 @@
|
||||
|
||||
不新增独立授权版本字段或对应的正整数检查约束,沿用现有 revision 及其约束。已有 ownership_type、owner_user_id、enabled 保持原意,授予内容管理权限不改变所有权或启用状态。
|
||||
|
||||
### 12.3 knowledge_base_documents:最近内容修改人
|
||||
### 8.3 knowledge_base_documents:最近内容修改人
|
||||
|
||||
| 字段 | 类型 | 设计 |
|
||||
| --- | --- | --- |
|
||||
@@ -310,58 +292,13 @@
|
||||
|
||||
created_by_user_id 继续记录原创建者;其他人参与编辑不能覆盖它。
|
||||
|
||||
### 12.4 内容和授权变更记录
|
||||
### 8.4 内容和授权变更记录
|
||||
|
||||
复用现有业务审计记录,记录操作者、知识库、目标对象、动作、时间及变更前后权限。当前设计不要求另建一张权限操作日志表。
|
||||
|
||||
删除授权后,历史授权变更仍需可查看,不依赖已删除授权行才能解释记录。正文版本快照不放在普通操作记录中。
|
||||
|
||||
### 12.5 若纳入回收站:删除记录结构
|
||||
|
||||
以下结构仅在回收站确定纳入范围时新增;两档权限本身不要求这些字段。
|
||||
|
||||
新增 `knowledge_base_deletion_batches`,保存一次删除的归属及恢复信息:
|
||||
|
||||
| 字段 | 类型 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| id | uuid | 删除批次标识 |
|
||||
| knowledge_base_id | uuid | 所属知识库 |
|
||||
| deleted_by_user_id | uuid,可空 | 执行删除的人 |
|
||||
| deleted_at | timestamptz | 删除时间 |
|
||||
| expires_at | timestamptz | 到期永久清理时间 |
|
||||
| restored_by_user_id | uuid,可空 | 执行恢复的人 |
|
||||
| restored_at | timestamptz,可空 | 恢复时间 |
|
||||
|
||||
`knowledge_base_documents` 增加:
|
||||
|
||||
| 字段 | 类型 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| deleted_at | timestamptz,可空 | 是否处于回收站 |
|
||||
| deletion_batch_id | uuid,可空 | 所属删除批次,文件夹及其本次删除的后代关联同一批次 |
|
||||
|
||||
恢复整个删除批次,不复活早于该批次已独立删除的文档。原父目录不存在时恢复到根目录。产品要求能按知识库和删除时间浏览回收站、按到期时间清理,结构应支持这两类查找。
|
||||
|
||||
文档分片不增加独立授权。回收站中的文档及其分片不参与正常阅读和检索;恢复后根据需要重新学习。任务表本方案不增加权限角色字段。
|
||||
|
||||
### 12.6 若纳入历史版本:正文版本结构
|
||||
|
||||
新增 `knowledge_base_document_versions`,仅在历史版本功能确定纳入时使用。
|
||||
|
||||
| 字段 | 类型 | 含义 |
|
||||
| --- | --- | --- |
|
||||
| id | uuid | 历史版本标识 |
|
||||
| knowledge_base_id | uuid | 所属知识库 |
|
||||
| document_id | uuid | 所属文档 |
|
||||
| revision | integer | 对应文档版本号,与 document_id 组合唯一 |
|
||||
| title | text | 当时的文档标题 |
|
||||
| content | text | 当时的正文快照 |
|
||||
| changed_by_user_id | uuid,可空 | 修改者,历史未知时允许为空 |
|
||||
| created_at | timestamptz | 版本产生时间 |
|
||||
| restored_from_revision | integer,可空 | 本次保存若来自恢复,记录来源版本 |
|
||||
|
||||
该表记录文档正文历史,不作为文件夹历史或整库备份。原始文件的版本化存储不在本次权限范围内。永久删除文档时,其正文历史同步按删除规则处理。
|
||||
|
||||
### 12.7 结构范围汇总
|
||||
### 8.5 结构范围汇总
|
||||
|
||||
| 范围 | 表结构变化 |
|
||||
| --- | --- |
|
||||
@@ -369,12 +306,10 @@ created_by_user_id 继续记录原创建者;其他人参与编辑不能覆盖
|
||||
| 授权修改冲突提示 | 复用 knowledge_bases.revision,无表结构变化 |
|
||||
| 内容修改人展示 | knowledge_base_documents 增加内容修改人和时间 |
|
||||
| 操作记录 | 复用已有业务审计结构,不新建权限日志表 |
|
||||
| 回收站,建议配套 | 删除批次表 + 文档删除标记及批次关联 |
|
||||
| 历史版本,建议配套 | 新增文档正文版本表 |
|
||||
|
||||
### 12.8 Migration 修改说明
|
||||
### 8.6 Migration 修改说明
|
||||
|
||||
#### 12.8.1 文件与范围
|
||||
#### 8.6.1 文件与范围
|
||||
|
||||
本次权限功能在 `000039_create_kb_tables` 基础上采用增量迁移,已新增:
|
||||
|
||||
@@ -387,9 +322,9 @@ created_by_user_id 继续记录原创建者;其他人参与编辑不能覆盖
|
||||
|
||||
新安装环境按顺序执行原有迁移和本次增量迁移,最终得到相同结构,不需要另外维护一套新安装专用建表定义。
|
||||
|
||||
本次 000041 包含两档权限必需配套字段及知识库自定义图标字段。回收站、历史版本仍为可选能力,确认纳入后各用独立的后续 migration,不混入 000041。
|
||||
本次 000041 包含两档权限必需配套字段及知识库自定义图标字段。000041 不包含回收站或正文历史版本结构。
|
||||
|
||||
#### 12.8.2 Up 必须完成的结构修改
|
||||
#### 8.6.2 Up 必须完成的结构修改
|
||||
|
||||
| 表 | 修改内容 | 存量数据处理 |
|
||||
| --- | --- | --- |
|
||||
@@ -408,7 +343,7 @@ created_by_user_id 继续记录原创建者;其他人参与编辑不能覆盖
|
||||
- knowledge_bases 复用现有 revision 及其约束,不增加独立授权版本字段,不重置已有版本值。
|
||||
- 不修改分片表和学习任务表,不因权限功能重建向量或文档内容。
|
||||
|
||||
#### 12.8.3 存量授权处理
|
||||
#### 8.6.3 存量授权处理
|
||||
|
||||
本次结构迁移不批量修改 access_level,不自动把任何只读授权升级为读写,也不通过删除后重建授权来补字段。
|
||||
|
||||
@@ -421,7 +356,7 @@ created_by_user_id 继续记录原创建者;其他人参与编辑不能覆盖
|
||||
|
||||
结构迁移完成不代表存量异常授权已核实。只有授权核对完成后,才能开放相应知识库的协作写入。
|
||||
|
||||
#### 12.8.4 迁移版本管理
|
||||
#### 8.6.4 迁移版本管理
|
||||
|
||||
沿用项目现有的 golang-migrate 和 `schema_migrations` 管理版本,不再要求额外创建 migrations 表或维护 migrations.name 记录。
|
||||
|
||||
@@ -430,7 +365,7 @@ created_by_user_id 继续记录原创建者;其他人参与编辑不能覆盖
|
||||
- 执行失败后先核对实际结构及工具记录的 dirty 状态,修复后按现有迁移流程恢复;不能直接把失败版本标记为成功。
|
||||
- 不手工删除或改写迁移版本记录来强制重复执行旧建表文件。
|
||||
|
||||
#### 12.8.5 Down 与数据影响
|
||||
#### 8.6.5 Down 与数据影响
|
||||
|
||||
普通应用回退优先保留新增字段,不要求同时执行数据库 down。确需退回本次结构时,先确认已无功能使用新增字段,并保存新增元数据。
|
||||
|
||||
@@ -445,16 +380,7 @@ knowledge_bases 的现有 revision 字段、版本值及其约束全部保留,
|
||||
|
||||
执行 down 会丢失新增的图标关联、最后修改人和内容修改时间;再次 up 只恢复字段及其默认值,不能自动还原这些元数据。正文和既有授权必须保持不变。
|
||||
|
||||
#### 12.8.6 可选能力的独立迁移
|
||||
|
||||
| 可选能力 | 后续独立 migration 的结构范围 | 回退限制 |
|
||||
| --- | --- | --- |
|
||||
| 回收站 | 新增 knowledge_base_deletion_batches;给文档增加 deleted_at、deletion_batch_id;支持按知识库删除时间、批次和到期时间查找 | 有未处理回收站内容时不得直接删除标记,否则内容可能意外重新出现;先明确恢复或永久清理,再回退结构 |
|
||||
| 历史版本 | 新增 knowledge_base_document_versions;增加 document_id + revision 唯一约束 | 删除版本表会丢失历史正文,必须先保存历史数据;当前正文不应随之删除 |
|
||||
|
||||
这些后续 migration 沿用项目现有文件命名和版本管理方式,由 golang-migrate 统一管理。未确认纳入的能力不提前建表。
|
||||
|
||||
## 13. 产品验收标准
|
||||
## 9. 产品验收标准
|
||||
|
||||
| 场景 | 预期结果 |
|
||||
| --- | --- |
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
- 每次新上传确认导入均创建独立系统知识库,即使 ZIP、publisher/release 完全相同;不覆盖已导入或人工编辑的内容。同一次上传的确认重试复用成功回执。
|
||||
- 新库默认启用且不创建成员授权,即仅管理员可见;导入后在知识库页面配置只读/读写授权。
|
||||
|
||||
本次不实现原草案中的字段级增量合并、冲突决策、原库覆盖、缺失节点删除、发布回滚、头像迁移、浏览器 DOM 降级及服务器数据库导出。这些不是本轮功能前提。知识库资源包不沿用 Agent 分区“缺失项停用”的行为。
|
||||
知识库资源包只创建新库,不覆盖、合并或删除既有库内容,也不执行 Agent 分区的“缺失项停用”。
|
||||
|
||||
## 2. 资源包准备
|
||||
|
||||
|
||||
@@ -1,25 +1,40 @@
|
||||
# 百智办公知识库技术设计(按当前实现整理)
|
||||
|
||||
> 更新日期:2026-11-11。本文描述当前工作区代码,包含尚未提交的管理端 Markdown 独立文档页。实现事实以路由、业务代码和 SQL 为准;未落地能力及契约差异单列,不作为已交付功能。
|
||||
> 整理日期:2026-12-02。本文维护总体架构、学习与检索机制;专题契约见 [知识库文档导航](knowledge-base-README.md)。按当前工作区整理不代表已发布或端到端验收通过。
|
||||
|
||||
MCP 相关设计、接口、权限与调用边界统一见 [知识库 MCP 设计](knowledge-base-mcp-design.md)。
|
||||
|
||||
## 1. 功能范围
|
||||
|
||||
视觉模型独立存于 `knowledge_base_models`,向量模型继续使用 `models`;配置入口统一在知识库页面,详见 [知识库专用模型](knowledge-base-models.md)。
|
||||
|
||||
知识库采用 PostgreSQL 持久化文档、分片和异步任务,提供独立于 embedding 的全文检索,并在具备向量能力时执行混合检索。客户端显式调用知识库接口,知识库模块不自动向模型上下文注入内容。
|
||||
|
||||
| 能力 | 当前实现 |
|
||||
| --- | --- |
|
||||
| 知识库管理 | 系统/个人知识库、授权、标签、启停、详情、文档统计和索引任务汇总 |
|
||||
| 文档输入 | JSON 正文,支持 `text` / `file` 来源及文件元数据;管理端在浏览器读取 TXT、MD、Markdown 文件后提交正文 |
|
||||
| 文档输入 | 直接创建文本或统一文件导入;文件保留原件,按格式生成正文,详见文件解析方案 |
|
||||
| 文档学习 | PostgreSQL 持久化队列;切分、分词、全文索引、可选向量化;更新和重试重新入队 |
|
||||
| 向量模型 | 模型模块支持 embedding 配置、维度探测与在线测试;知识库由后端自动选择可用系统向量模型 |
|
||||
| 向量模型 | 知识库配置入口管理向量与视觉模型;绑定及索引维护见下文和模型配置方案 |
|
||||
| 检索 | lexical / hybrid 自动选择、weighted RRF、向量失败降级、多知识库召回和文档去重限制 |
|
||||
| 管理端查看文档 | 独立路由,Markdown 源码/预览/分屏,保存后重新学习;个人知识库只读 |
|
||||
| 第一期未接入 | AnyDoc、原始文件存储、独立 rerank 和向量 ANN 索引 |
|
||||
| 尚未提供 | 独立 rerank 和向量 ANN 索引 |
|
||||
|
||||
管理端批量操作栏在“全选”右侧提供“全选文件”:以当前搜索过滤后的文档树为范围,递归选择所有非文件夹节点(包含折叠目录内的文件),替换原有选择并排除文件夹;无文件或批量请求进行中时禁用。沿用已有批量操作权限和接口,不改变数据库及部署配置。
|
||||
|
||||
全文检索是基础能力:没有可用向量模型时,文档仍可学习并检索。`embedding_model_id` 和 `embedding_dimension` 是后端维护的索引元数据,当前管理端创建/编辑知识库不提供模型选择器。
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[选择有权限的知识库] --> B[创建文本或导入文件]
|
||||
B --> C[保存文档与学习任务]
|
||||
C --> D[查看学习状态]
|
||||
D --> E[检索与引用]
|
||||
E --> F[读取正文或原件]
|
||||
D --> G[按权限编辑或重新学习]
|
||||
G --> C
|
||||
```
|
||||
|
||||
## 2. 模块与依赖
|
||||
|
||||
当前后端使用 chi、pgx 和 sqlc,知识库复用现有 `resource` 基础设施;没有新增 GoFrame controller / logic 层。本文记录仓库现状,不另行引入框架或服务分层。
|
||||
@@ -34,6 +49,13 @@ flowchart LR
|
||||
KB --> Worker[Learning Worker]
|
||||
Worker --> PG[(PostgreSQL + pgvector)]
|
||||
KB --> PG
|
||||
Client --> MCP[MCP]
|
||||
MCP --> KB
|
||||
KB --> Import[文件导入]
|
||||
Import --> AnyDoc[AnyDoc slim]
|
||||
Import --> Storage[私有对象存储]
|
||||
Import --> Vision[知识库视觉模型]
|
||||
Worker --> Vision
|
||||
KB --> Model[internal/model EmbedText]
|
||||
Worker --> Model
|
||||
Model --> Upstream[Embedding 上游]
|
||||
@@ -58,17 +80,9 @@ flowchart LR
|
||||
|
||||
## 3. 所有权与权限
|
||||
|
||||
| 调用端 | 系统知识库 | 本人个人知识库 | 他人分享的个人知识库 |
|
||||
| --- | --- | --- | --- |
|
||||
| 管理端 | 可管理资源、文档、授权、启停和索引 | 可读取和重新学习文档;不能修改、移动或删除内容 | 可读取和重新学习文档;不能修改、移动或删除内容 |
|
||||
| Agent REST | 有访问权限时读取、检索;不可写 | 可创建、更新、删除资源及文档 | 按授权读取、检索;不可写 |
|
||||
| MCP | 按有效授权读取、检索及读写文档;不能管理库信息 | 可创建、更新库信息、查看授权、读写文档 | 按有效授权读取、检索及读写文档;不能管理库信息或查看完整授权 |
|
||||
授权规则、有效权限合并、撤权及协作冲突统一见 [权限方案](knowledge-base-permissions-design.md);REST/MCP 调用示例见 [Agent 接入](knowledge-base-agent-integration.md)。内容读写权限不授予库设置、授权或整库删除权限。格式可编辑性与当前用户写权限须同时成立。
|
||||
|
||||
- 复用 `resource_access_grants`、`resource_tags` 及已有用户/分组授权判定。权限在服务端校验,UI 隐藏按钮仅用于表达可用操作。
|
||||
- 管理端文档、重试、模型切换和索引写路由拒绝个人知识库;资源 CRUD 复用资源层约束。
|
||||
- 文档详情校验文档属于路径中的知识库,不能用其他知识库 ID 读取或修改文档。
|
||||
- 客户端知识库目录、知识库详情及检索要求知识库已启用且可访问;文档列表/详情使用 `accessibleKB` 检查授权,其代码未额外要求知识库已启用。因此不能将所有文档读取描述为“只返回已启用知识库”。
|
||||
- 知识库资源更新、删除及手动模型切换使用 revision / `If-Match`。文档更新不要求 `If-Match`,内部 revision 用于防止旧学习任务覆盖新正文,不能等同于防止多个编辑者互相覆盖。
|
||||
管理端通常只写系统知识库;重新学习是明确例外,管理员可对系统和个人知识库文档执行。服务端逐次检查知识库权限、文档归属及版本;学习任务的 revision/租约检查用于阻止旧任务写回,不代替客户端协作写入的版本条件。
|
||||
|
||||
## 4. 数据结构与迁移
|
||||
|
||||
@@ -77,7 +91,7 @@ flowchart LR
|
||||
| 表 | 主要字段与约束 |
|
||||
| --- | --- |
|
||||
| `knowledge_bases` | UUID 主键;名称、描述、所有权、owner/creator、启停、revision;可空模型 ID/维度;JSONB `fusion_config`;时间戳 |
|
||||
| `knowledge_base_documents` | UUID 主键、`kb_id`、标题、正文、`source_type`、文件名/MIME/大小;状态、错误、chunk 数、revision、学习时间;预留 `storage_key`、`content_sha256` |
|
||||
| `knowledge_base_documents` | UUID 主键、`kb_id`、标题、正文、`source_type`、文件名/MIME/大小;状态、错误、chunk 数、revision、学习时间;`file_type`、原件 `storage_key`、`content_sha256` |
|
||||
| `knowledge_base_chunks` | UUID 主键、知识库/文档 ID、从 0 开始的 `chunk_index`、正文、近似 token 数;`search_tokens`、`search_tsv`;可空 `embedding` / 模型 ID;JSONB metadata 和引用字段 |
|
||||
| `knowledge_base_learning_jobs` | UUID 主键、知识库 ID、可空文档 ID、operation、status、attempts/max_attempts、可执行时间、锁时间/worker、错误与完成时间;可空文档 revision、目标模型 ID 和维度快照 |
|
||||
|
||||
@@ -85,7 +99,9 @@ flowchart LR
|
||||
|
||||
表间没有声明外键级联。服务层显式删除关联任务、分片、文档、授权和标签。SQL 中名为 `SoftDeleteKbDocument` / `SoftDeleteKbDocumentsByKb` 的查询实际执行 `DELETE`,属于硬删除。
|
||||
|
||||
`storage_key`、`content_sha256`、`heading_path`、`page_no`、`source_url` 的存在不表示文件存储或结构化文档解析已接入。当前学习流程不填充页码、标题路径和来源 URL。
|
||||
`storage_key` 与 `content_sha256` 用于原件保存与校验;格式字段及约束迁移见文件解析方案。页码等引用元数据不能仅凭字段存在推断已填充,不从普通 Markdown 猜测原件坐标。
|
||||
|
||||
视觉配置独立表及字段用途见 [模型配置](knowledge-base-models.md#数据库变更);协作权限元数据见 [权限迁移](knowledge-base-permissions-design.md#8-表结构调整记录)。这些专题是各自数据库变更、升级与回滚的维护位置。
|
||||
|
||||
### 4.2 迁移与部署
|
||||
|
||||
@@ -109,9 +125,7 @@ migrate -path migrations -database "$MONKEYAI_DATABASE_URL" version
|
||||
|
||||
### 5.1 模型能力
|
||||
|
||||
模型类型为 `embedding`,协议为 `openai_embeddings`,Provider 为 `passthrough`。创建/更新时探测上游维度,保存至 `models.embedding_config.dimension`;允许范围为 1—16000。
|
||||
|
||||
`EmbedText(ctx, modelID, input)` 校验模型启用、模型类型和非空输入,通过上游返回向量及 token 用量。维度探测超时 15 秒,在线测试和普通 embedding 调用超时 30 秒。在线测试返回实际维度、配置维度、是否一致、前 8 个向量值及 token 用量。
|
||||
配置入口、上游协议、保存探测、模型变更影响及回滚统一见 [模型配置](knowledge-base-models.md)。本节仅维护知识库自动绑定及索引维护机制。
|
||||
|
||||
### 5.2 自动绑定
|
||||
|
||||
@@ -128,19 +142,13 @@ migrate -path migrations -database "$MONKEYAI_DATABASE_URL" version
|
||||
|
||||
任务入队、文档状态和模型绑定在同一事务中完成。逐文档任务避免单篇失败阻塞整库,服务重启后继续消费持久化队列。
|
||||
|
||||
### 5.3 兼容维护接口
|
||||
|
||||
后端仍保留 `embedding-model/switch`:支持模型 UUID 或 `null`,也兼容旧 `model_id` 字段;首选 `embedding_model_id`。切换要求 `If-Match`,相同模型返回 `409 embedding_model_unchanged`。
|
||||
|
||||
切换事务锁定并复核 revision,取消旧任务、更新绑定、清空向量,并逐文档排队:已有分片的文档只补向量,未完成全文学习的文档重新学习。返回知识库详情及 `notice`。
|
||||
|
||||
显式解绑会清空模型和维度、取消旧任务并清空向量;后台同步会把它视为未绑定知识库,在下一次同步时重新选择可用模型。因此解绑不是长期关闭向量检索的产品开关。当前管理端不提供这个兼容接口的操作入口。
|
||||
|
||||
## 6. 文档与异步学习
|
||||
|
||||
### 6.0 统一学习状态与向量模型生命周期
|
||||
|
||||
本节描述 2026-11-11 确定并已实现的统一行为。“学习”指文档切分和检索索引生成,不会训练或修改向量模型。
|
||||
“学习”指文档切分和检索索引生成,不会训练或修改向量模型。
|
||||
|
||||
顶部“已学习”数量仅统计文档节点中 `status = learned` 的记录,总数排除文件夹;待学习、学习中和失败不计入完成数。检索资格仍按已有分块判断,向量补建或失败时保留全文检索能力。
|
||||
|
||||
界面继续使用待学习、学习中、已学习、失败,不增加独立向量化状态;排队中的向量任务也显示“学习中”。没有绑定向量模型时,全文索引完成即为已学习;绑定了向量模型时,全文索引与当前模型对应的向量全部完成才为已学习。
|
||||
|
||||
@@ -153,7 +161,7 @@ migrate -path migrations -database "$MONKEYAI_DATABASE_URL" version
|
||||
| 删除或禁用当前向量模型 | 取消相关向量任务,停用旧向量,退回全文检索;不静默切换到其他模型 | 全文索引已完成的文档显示已学习;全文学习未完成或失败的文档保留对应状态 |
|
||||
| 显式解绑且存在可用模型 | 清空绑定和旧向量,下一次同步自动选择可用模型并逐文档补建向量 | 短暂仅全文检索 → 学习中 → 已学习 |
|
||||
| 删除或禁用后重新启用同一模型、显式重新配置模型 | 为受影响知识库恢复绑定,全部文档排队生成新向量 | 学习中 → 已学习 |
|
||||
| 学习或向量化失败 | 记录错误并显示失败,允许按既有权限重试;重试只补齐未完成的处理 | 失败 → 学习中 → 已学习 |
|
||||
| 学习或向量化失败 | 记录错误并显示失败,允许按既有权限重试;显式重新学习会从原始正文重新切片并生成全部向量 | 失败 → 待学习 → 学习中 → 已学习 |
|
||||
|
||||
执行与一致性要求:
|
||||
|
||||
@@ -165,15 +173,11 @@ migrate -path migrations -database "$MONKEYAI_DATABASE_URL" version
|
||||
- 学习任务记录 `document_revision`、目标 `embedding_model_id` 和 `embedding_dimension`,写回前复核任务租约、文档版本和当前模型绑定。文档修改、模型切换、删除或解绑后,旧任务结果不得覆盖当前内容、恢复旧向量或重新绑定已移除的模型。
|
||||
- 模型绑定、文档状态变化和任务入队应保持事务一致性;服务重启后继续处理持久化队列。
|
||||
|
||||
验证覆盖无模型完成学习后新增模型、已有禁用模型重新启用、切换模型、删除/禁用模型、显式解绑后自动重绑、重新配置、部分向量失败与重试、学习期间全文检索、模型变更期间旧任务写回,以及重复通知和服务重启后的任务恢复。
|
||||
|
||||
### 6.1 文档输入与更新
|
||||
|
||||
管理端添加文本,或使用 `File.text()` 读取 `.txt`、`.md`、`.markdown` 后提交 JSON。空内容被拒绝;多个文件逐个提交,不是批量事务,后续文件失败时已经创建的文档保留。
|
||||
直接创建正文仅接受 `source_type=text`(省略默认);文件使用统一导入入口,格式与大小限制见 [文件解析方案](knowledge-base-file-parsing.md)。直接创建要求标题及非空正文,文档与初始学习任务在同一事务提交。REST 完整 JSON 请求预算及 MCP 传输预算见 [请求体与文件传输](knowledge-base-mcp-design.md#3-请求体与文件传输)。
|
||||
|
||||
新增要求知识库 ID、标题及非空正文;`source_type` 默认 `text`,只接受 `text` / `file`。未提供正数 `size_bytes` 时,服务端按正文 UTF-8 字节数计算。新建文档和 `learn` 任务在同一事务提交,接口返回 `202`、`pending` 文档。REST 通用 JSON 解码上限为 1 MiB,因此正文输入仍受请求大小限制。
|
||||
|
||||
正文实际变化时,更新文档会在同一事务取消旧活跃任务、删除该文档的全部分片并创建 `relearn`,正文保存在 `content`;学习完成前全文和向量都不可检索,旧内容不会被召回。仅更新标题、文件名等元数据时直接保存,不使现有索引失效。空标题/正文会沿用旧值,不能通过传空串清空正文。文件来源不能改为文本来源,原文件名和 MIME 可以保留。重试同样取消旧任务并重新排队。
|
||||
正文实际变化时,更新文档会在同一事务取消旧活跃任务、删除该文档的全部分片并创建 `relearn`,正文保存在 `content`;学习完成前全文和向量都不可检索,旧内容不会被召回。仅更新标题、文件名等元数据时直接保存,不使现有索引失效。空标题/正文会沿用旧值,不能通过传空串清空正文。文件来源不能改为文本来源,原文件名和 MIME 可以保留。显式“重新学习”(单篇、批量、REST/MCP)在同一事务取消旧任务、删除旧分片、递增 revision 并创建 `relearn`,无论此前是否已有分片、是否绑定向量模型,都从原始 `content` 重新进行内容提取、切片和索引构建(文档内图片重新识别,独立图片复用描述);期间不召回旧分片,失败后可再次重新学习。模型配置变化触发的 `rebuild_vector` 仍复用分片。
|
||||
|
||||
### 6.2 学习步骤
|
||||
|
||||
@@ -190,7 +194,16 @@ sequenceDiagram
|
||||
W->>DB: 领取任务,递增 attempts 并记录 worker
|
||||
W->>DB: 同步知识库模型绑定
|
||||
W->>DB: 锁定文档,检查任务,将文档置 learning
|
||||
W->>W: 从 content 切分与分词
|
||||
opt 文档含 Base64 图片或 Office/PDF 存储图片
|
||||
W->>W: 校验并转存 Base64 图片,或读取当前库图片资产
|
||||
W->>M: 视觉模型生成图片描述
|
||||
M-->>W: 描述文本
|
||||
W->>W: 在原图片位置替换为转义后的描述
|
||||
end
|
||||
opt HTML 文档
|
||||
W->>W: 学习副本提取正文,去除标签、CSS 和脚本
|
||||
end
|
||||
W->>W: 从学习副本切分与分词
|
||||
opt 具备向量能力
|
||||
W->>M: 逐片 EmbedText
|
||||
M-->>W: 向量或错误
|
||||
@@ -200,13 +213,21 @@ sequenceDiagram
|
||||
W->>DB: 任务置 succeeded
|
||||
```
|
||||
|
||||
- 新上传 PDF、DOCX、PPTX、XLSX 由 AnyDoc 转换为 Markdown 并将图片保存到知识库存储;学习和重新学习时,从转换正文中的 Markdown 行内/引用式图片与 HTML img 提取当前库资产,在原位置替换视觉描述后再切片、分词和向量化。历史 XLS 继续支持此学习路径。原始文件和已保存的 `content` 不变。只读取 `/api/kb/{当前库}/assets/{合法哈希文件名}`,复用访问权限、对象哈希、大小、真实格式和像素校验,不发起外链下载。跨库、非法引用保留失败占位;失败处理遵循模型配置规则,保留失败占位后继续学习。普通链接和代码示例不触发识图。历史文档重新学习即可应用,无需重新导入。
|
||||
- 图片去重、并发、超时、重试及失败占位统一见 [模型调用规则](knowledge-base-models.md#保存和调用)。存储图片按 worker 逐张读取,不一次加载整篇所有图片字节。
|
||||
- HTML、SVG、Markdown 学习的第一步是提取并校验 Base64 图片,转存后调用全局知识库视觉模型,在原图片位置替换为描述,再切片、分词和向量化。替换仅发生在内存中的学习副本;文档 `content` 始终保留原始内容,分片和向量使用描述文本,写回仍复核任务、revision 和模型绑定。
|
||||
- 支持 HTML `img src`、SVG `image href/xlink:href`、Markdown 行内/引用式图片及内嵌 HTML 图片。 Markdown 与内嵌 HTML 图片统一基于原文定位后替换,生成的描述不参与后续图片扫描,避免描述中的代码围栏导致漏识别;代码示例仍不触发识图。引用定义中的图片数据也从学习副本移除。外链不下载;CSS/srcset 等不支持的内嵌位置明确失败,避免 Base64 进入索引。
|
||||
- 复用正文图片校验及内容哈希存储;显式重学含内嵌图片的文档会重新识别,可能产生供应商费用。独立图片文档复用导入时保存的描述。原始正文不变,回滚学习代码后可重新学习重建索引;此学习调整无需数据库或 Docker 变更。验证摘要见 [模型配置验证](knowledge-base-models.md#验证)。
|
||||
- 按 Unicode rune 切分,每片最多 1200 字符,重叠 200;切片前后去空白。
|
||||
- `token_count` 是 `max(1, rune_count / 4)` 估算值,不是实际模型 tokenizer 结果。
|
||||
- HTML 在图片描述替换后进行正文提取,再切片:移除标签和属性、注释、head/style/script/template/noscript/iframe/object/embed 内容,以及 hidden、aria-hidden=true 子树;保留正文和图片描述,解码实体,段落、换行和表格单元格保留文本边界。CSS 源码不进入分片、词索引或向量输入。此过程不运行浏览器、不下载资源、不计算 CSS 可见性;原始 `content` 不变。历史索引需要显式重新学习才生效,无数据库或部署配置变更。
|
||||
- 每片始终生成词索引;未绑定可用模型时不调用向量服务。已绑定模型但 Embedder 不可用按向量失败处理。
|
||||
- 普通学习中,单片 embedding 调用失败、维度不匹配或非有限数值时,该片保留正文和全文索引,向量为空,错误写入 `metadata.vector_error`(最多 500 字符);其余成功分片保留向量,文档置 `failed` 并记录错误。
|
||||
- 学习时跳过无法生成检索词的分片,不调用向量模型;有效分片连续编号。整篇为空或全部分片无检索词时仍学习成功,状态为 `learned`、分片数为 0,并清除旧分片和错误信息。词索引重建对历史无检索词分片写入空索引,不因此失败。正文更新会先删除旧分片,学习成功后在同一事务原子写入新分片;重新学习完成前不会召回旧分片。
|
||||
- 文档删除会取消活跃任务并硬删除分片和文档;成功写回前检查当前任务、revision 和模型绑定,防止被删除/更新的数据被旧任务写回。
|
||||
|
||||
模型调用失败的 `error_message` 标明“视觉模型”或“向量模型”及已解析的模型名称。服务端日志记录 `model_kind`(`vision` / `embedding`)、模型 ID/名称、协议、HTTP 状态和上游错误响应体(含 HTTP 200 下的空向量、维度不一致或越界等响应校验失败);响应体与错误文本各限制为 4096 字节(保持 UTF-8 完整),响应体超限标记 `upstream_body_truncated`。不主动记录请求正文、图片或认证头;上游回显的配置密钥先脱敏再截断。历史错误信息不回填,无数据库及部署配置变更。
|
||||
|
||||
### 6.3 队列与并发
|
||||
|
||||
| 项目 | 当前值/语义 |
|
||||
@@ -215,12 +236,14 @@ sequenceDiagram
|
||||
| 空闲轮询 | 1 秒;执行过任务后立即尝试领取下一条 |
|
||||
| 任务领取 | `FOR UPDATE SKIP LOCKED`,按创建时间、ID 排序 |
|
||||
| 过期锁 | `running` 且 `locked_at` 超过 5 分钟可重新领取 |
|
||||
| 重试 | 默认最多 3 次;失败后间隔 15 秒再领取 |
|
||||
| 重试 | 学习任务整体共用执行次数,包含视觉及向量失败;默认最多执行 3 次(首次 + 2 次重试),间隔 15 秒,耗尽后为 `failed` |
|
||||
| 写回隔离 | 同时核对任务 ID、`attempts`、`locked_by` 和 `running` 状态 |
|
||||
| 文档状态 | `pending`、`learning`、`learned`、`failed` |
|
||||
| 任务状态 | `pending`、`running`、`succeeded`、`failed`、`canceled` |
|
||||
|
||||
目前没有租约续期心跳。超过 5 分钟的任务可能被其他实例重新领取;写回隔离防止旧尝试覆盖新尝试,但不能消除重复 embedding 调用。文档失败与任务待重试是不同维度:任务重新入队时,文档可能先保持 `failed`,下次开始执行才再次变为 `learning`。
|
||||
任务每 30 秒续租,续期失败或租约失效时取消执行;完成写回前停止并等待心跳退出。过期任务仍可被其他实例领取,写回检查隔离旧尝试;取消不能保证上游已停止或未计费。文档失败与任务待重试是不同维度:任务重新入队时,文档可能先保持 `failed`,下次开始执行才再次变为 `learning`。
|
||||
|
||||
列表与详情的 `index_job_summary.failed` 统计当前 `status=failed` 且无待执行或执行中重试任务的文档,每篇只计一次;学习成功、删除或进入重试后不再计入,历史向量失败但任务成功结束的文档仍计入。历史失败任务保留用于排查,不参与此计数。`by_operation` 的失败数采用同一口径,归入最近关联任务的操作(无记录时为 `learn`);`pending` / `running` 仍统计任务数。无需数据库迁移。
|
||||
|
||||
### 6.4 索引重建
|
||||
|
||||
@@ -233,7 +256,7 @@ sequenceDiagram
|
||||
|
||||
维护接口按知识库调度,没有按 `document_ids` 选择重建的实现。词索引/向量重建与手动切模会恢复未完成全文学习的文档;已有分片的文档不会重复切分。
|
||||
|
||||
向量补建逐文档执行。任一分片失败时保留已成功分片和全文索引,文档显示 `failed`,任务本身成功结束;用户重试只补建缺失或模型不匹配的分片,成功后恢复 `learned`。
|
||||
向量生成失败时保留已成功分片和全文索引,文档记录 `failed` 和失败原因;在同一事务同步当前任务的文档版本快照,避免本次失败写回递增 revision 导致重试被误判为过期。随后将错误返回 worker,按 6.3 节对同一学习任务重试,不单独给向量调用额外重试次数。普通学习/重新学习再次执行完整学习流程;向量补建仍只处理缺失或模型不匹配的分片。用户编辑、删除或取消任务仍受原有版本及租约校验保护。成功后文档恢复 `learned`,任务为 `succeeded`。不改写历史任务,无数据库迁移;回滚代码将恢复旧版本的向量失败处理行为。
|
||||
|
||||
## 7. 检索设计
|
||||
|
||||
@@ -257,12 +280,13 @@ flowchart TD
|
||||
|
||||
### 7.1 输入和可见性
|
||||
|
||||
输入为 `{query, kb_ids?, top_k?, filters?}`:
|
||||
输入为 `{query, kb_ids?, top_k?, file_types?, filters?}`:
|
||||
|
||||
- `query` 去首尾空白,必填,最多 4000 个 Unicode 字符。
|
||||
- `top_k <= 0` 使用默认 8,大于 20 拒绝;最终每个文档最多返回 2 个分片。
|
||||
- 未指定 `kb_ids` 时搜索入口确定的可访问集合,最多 50 个 ID;显式包含无权限 ID 返回未找到。
|
||||
- Agent REST 使用 `SearchLearnedWithResponse`,先限制到至少有一篇存在分片文档的知识库;管理端检索使用 `SearchWithResponse`,不做这个集合预筛选。两处 SQL 都直接按分片检索,不依赖文档展示状态。
|
||||
- 图片 `file_types` 在召回前过滤,图片按文档去重,具体规则见 [独立图片检索](knowledge-base-file-parsing.md#5-独立图片解析与检索)。
|
||||
- `filters` 尚未应用,存在候选通道的正常返回路径会附带 `filters_not_applied`。不要把它作为已生效的业务过滤器。
|
||||
- 不定义 `search_mode`、`channels`、`disable_vector` 控制项;未实现严格拒绝这些未知 JSON 字段,不能宣称传入后必然报错。
|
||||
|
||||
@@ -298,50 +322,11 @@ query embedding 或向量 SQL 失败时,相关知识库保留 lexical,响应
|
||||
|
||||
## 8. REST 契约
|
||||
|
||||
现有接口沿用资源式路径。此处列出实际注册路由,不将新增接口命名规范追溯改写成不存在的 `/list`、`/detail` 等接口。
|
||||
完整接口、字段及状态码维护在 [管理端 OpenAPI](../backend/api/admin.yaml) 和 [Agent OpenAPI](../backend/api/agent.yaml);客户端工作流见 [Agent 接入说明](knowledge-base-agent-integration.md)。沿用既有资源式路由,不为文档命名规则重写接口。
|
||||
|
||||
### 8.1 管理端
|
||||
管理端前缀 `/api/admin/v1`,客户端前缀 `/api/v1`。资源 CRUD、文档读写、文件导入、正文插图、授权及索引维护按对应入口校验权限;客户端 DTO 不暴露私有存储键,完整授权仅向相应所有者提供。正文投影和原件 URL 见 [原件读取契约](knowledge-base-file-parsing.md#agent-原件读取契约)。
|
||||
|
||||
前缀为 `/api/admin/v1`,资源 CRUD 由 `resource.CRUD.Register` 注册,文档与索引接口由 `kb.RegisterAdmin` 注册。
|
||||
|
||||
| 方法 | 相对路径 | 实际行为 |
|
||||
| --- | --- | --- |
|
||||
| GET / POST | `/kb` | 资源列表 / 创建系统知识库;模型由后端选择 |
|
||||
| GET / PUT / DELETE | `/kb/{id}` | 详情 / 更新 / 硬删除;写入遵循资源版本与所有权约束 |
|
||||
| PATCH | `/kb/{id}/enabled` | 启停 |
|
||||
| POST | `/kb/search` | 按当前管理员的可访问知识库集合检索 |
|
||||
| GET / POST | `/kb/{id}/documents` | 完整文档列表(含正文,无分页)/ 创建并入队(202) |
|
||||
| GET / PUT | `/kb/{id}/documents/{documentId}` | 详情 / 更新并重新学习(202) |
|
||||
| POST | `/kb/{id}/documents/delete` | body ids,单条或批量删除,返回 succeeded/failed(200) |
|
||||
| POST | `/kb/{id}/documents/move` | body ids、parent_id,单条或批量移动,返回 succeeded/failed(200) |
|
||||
| POST | `/kb/{id}/documents/restudy` | 重新入队(202) |
|
||||
| GET | `/kb/{id}/documents/{documentId}/chunks` | 分片正文、序号、token 估算、`has_vector` 等 |
|
||||
| POST | `/kb/{id}/embedding-model/switch` | 兼容手动切模/解绑,返回详情和提示(200) |
|
||||
| POST | `/kb/{id}/index/rebuild` | 接收 `operation`、`model_id`,调度全库任务(202) |
|
||||
|
||||
当前没有注册 `/kb/{id}/documents/upload`;请求结构、状态码和字段细节另见 `backend/api/admin.yaml`,与实现的差异见第 10 节。
|
||||
|
||||
### 8.2 Agent REST
|
||||
|
||||
前缀为 `/api/v1`。
|
||||
|
||||
| 方法 | 相对路径 | 实际行为 |
|
||||
| --- | --- | --- |
|
||||
| GET / POST | `/kb` | 可访问且启用的知识库目录 / 创建本人的个人知识库 |
|
||||
| GET | `/kb/tags` | 可访问知识库标签目录 |
|
||||
| GET / PUT / DELETE | `/kb/{id}` | 可访问且启用的详情 / 更新本人个人知识库 / 删除本人个人知识库 |
|
||||
| GET / POST | `/kb/{id}/documents` | 分页文档摘要 / 为本人个人知识库创建文档(202) |
|
||||
| GET / PUT / DELETE | `/kb/{id}/documents/{documentId}` | 可访问文档详情 / 更新本人文档(202)/ 删除本人文档(204) |
|
||||
| POST | `/kb/search` | 可访问且有已学习文档的知识库检索 |
|
||||
|
||||
知识库目录支持 `owner=all|team|mine|shared`、`q`、`tag_id/tag_ids`、`page/page_size`,返回 `knowledge_bases`、总数和页信息。文档列表支持标题/文件名搜索、状态、来源类型,默认 20 条、最多 100 条,返回 `items`、`total_count`、`page`、`page_size`。目录与相关详情使用已有 ETag 机制。
|
||||
|
||||
客户端 DTO 通过白名单投影:
|
||||
|
||||
- 知识库基础字段包括检索能力、模型绑定、融合参数、文档统计、任务汇总、标签等;REST 目录/详情另附所有者 `user`。
|
||||
- `shared_users`、`shared_groups` 及详情 `grants` 仅本人个人知识库所有者可见;不向被分享者暴露内部授权关系。
|
||||
- 文档列表摘要排除 `content`;文档详情可返回正文,排除 `created_by_user_id`、`storage_key`、`content_sha256`。
|
||||
- 管理端返回治理所需字段,不套用完全相同的客户端投影。
|
||||
删除、移动、重新学习使用原生操作接口 body `ids`,单条也用数组,去重后最多 200 项,逐项检查 `succeeded/failed`。删除和移动使用 `/kb/{id}/documents/delete`、`/kb/{id}/documents/move`;管理端重学使用 `/kb/{id}/documents/restudy`,用户端使用 `/kb/documents/restudy` 并传 `kb_id`。协作删除/移动提供 `expected_revisions`;`prev_id/next_id` 仅用于单条排序。不存在 `/documents/batch` 或带文档 ID 路径的 REST 删除/重学入口。
|
||||
|
||||
## 9. 管理端文档页面
|
||||
|
||||
@@ -353,7 +338,7 @@ query embedding 或向量 SQL 失败时,相关知识库保留 lexical,响应
|
||||
|
||||
- 页面并行加载文档详情和知识库详情,刷新或直接访问 URL 均可重新加载,加载失败显示错误,不挂载空编辑器。
|
||||
- 复用 ragcloud 使用的 `@ctzhian/tiptap@3.0.4`,提供 Markdown 编辑、预览及分屏、工具栏和行号;页面通过 React lazy 按路由加载,编辑器主题随管理端明暗切换。
|
||||
- 系统知识库可修改标题和正文;个人知识库只读,默认预览并隐藏编辑工具栏及保存按钮。服务端仍执行独立权限检查。
|
||||
- 系统知识库按格式决定正文可编辑性,派生正文只读;个人知识库只读,默认预览并隐藏编辑工具栏及保存按钮。服务端仍执行独立权限检查。
|
||||
- 保存调用既有文档 PUT,保留来源类型、文件名和 MIME,以 UTF-8 字节数填写大小;成功提示已保存并开始重新学习。
|
||||
- 通过标题/正文与已加载文档比较显示未保存状态;保存期间禁用编辑,失败保留草稿。页面返回按钮遇到未保存修改时要求确认,刷新/关闭通过 `beforeunload` 提示;没有通用 SPA 导航拦截或草稿持久化。
|
||||
- 返回 `/admin/resources/kb?kb=<id>`,列表页重新加载目标知识库与文档,恢复原知识库弹窗,包括个人知识库和不在当前列表页中的知识库。
|
||||
@@ -361,25 +346,13 @@ query embedding 或向量 SQL 失败时,相关知识库保留 lexical,响应
|
||||
|
||||
当前没有搜索测试 UI、融合参数编辑器、模型切换/解绑 UI、索引任务汇总面板和向量降级提示面板。后端返回字段不等于管理端已经展示对应功能。
|
||||
|
||||
## 10. 已知差异与后续边界
|
||||
## 10. 已知边界与验证
|
||||
|
||||
| 项目 | 当前事实与后续要求 |
|
||||
| --- | --- |
|
||||
| AnyDoc / 多格式解析 | 未接入;当前只接受 JSON 正文 |
|
||||
| 原始文件存储 | 数据表预留字段,当前 JSON 输入没有上传/下载原文件链路 |
|
||||
| 模型绑定 | 自动选择与兼容手动切换并存;手动解绑会在后续同步中自动重新绑定,不能作为长期关闭向量的产品开关 |
|
||||
| 重建范围 | 实现只接收 `operation/model_id`,不支持原文中的 `document_ids` |
|
||||
| 重建接口契约 | OpenAPI 对重建统一声明 `If-Match` 和 202;代码仅 `rebuild_model` 分支校验版本,该分支经重建路由返回 202,经专用切模路由返回 200;其他重建分支不校验该请求头 |
|
||||
| API 校验 | 搜索无通道控制字段,但未严格拒绝未知字段;融合参数先归一化,部分非法值回退默认 |
|
||||
| 迁移幂等 | 有名称登记但无 DDL 前名称检查;迁移 CLI 的版本保护与 SQL 自身幂等应分别描述 |
|
||||
| 检索能力状态 | 绑定字段不实时检查上游健康;模型变动到同步发生前,能力目录可能暂时滞后 |
|
||||
| 队列租约 | 无续租,长任务可能重复执行;任务尝试隔离只保证旧尝试不能错误写回 |
|
||||
| 文档并发编辑 | 无文档 `If-Match`,任务 revision 校验不能替代编辑冲突检测 |
|
||||
| 搜索过滤 | `filters` 未落地;没有 rerank、query rewrite、Graph/Wiki 索引和 ANN 索引 |
|
||||
| 前端加载体积 | 编辑器按独立页面懒加载,但编辑器及图形依赖较大;后续优化应以构建产物为依据 |
|
||||
- 全文检索不依赖向量;模型绑定同步和上游健康检查不是实时一致,向量请求失败时按检索规则降级。
|
||||
- 显式解绑仍会被自动绑定机制重新选择模型,不是长期关闭向量检索的开关。全库维护没有按 `document_ids` 筛选重建的能力。
|
||||
- 历史记录指出索引重建 OpenAPI 的 `If-Match` 声明与非 `rebuild_model` 分支校验存在差异;本次未重新验证该接口,发布前需复核契约和实现。
|
||||
- `filters` 不执行通用过滤;没有独立 rerank、query rewrite、Graph/Wiki 或 ANN 索引。
|
||||
- 导入解析由在线客户端查询推进,学习由持久化队列执行,两者生命周期不同;恢复边界见文件解析方案。
|
||||
- 当前不提供回收站和正文历史版本,删除后不能通过知识库恢复。
|
||||
|
||||
后续修改应同时核对 `api/admin.yaml`、`api/agent.yaml`、DTO 和管理端行为,避免只更新契约或设计文案。本文不将上述差异隐含为本次已经修复。
|
||||
|
||||
文档删除、移动、重新学习统一使用原生操作接口的 body `ids`(单条也传数组,去重后最多 200 项),返回 `succeeded/failed`。删除使用 `POST /kb/{id}/documents/delete`;移动使用 `POST /kb/{id}/documents/move`;管理端在文档行的操作菜单点击“重新学习”,系统和用户知识库均可使用(文件夹不支持),使用 `POST /kb/{id}/documents/restudy`,用户端使用 `POST /kb/documents/restudy` 并附带 `kb_id`。协作删除和移动逐项提供 `expected_revisions`;`prev_id/next_id` 仅用于单条排序。
|
||||
|
||||
文档移动、删除、重新学习的 REST 请求统一使用 body `ids`,不再提供 `/documents/batch` 或带文档 ID 路径的删除/重新学习接口。单条操作也传数组(去重后最多 200 项),结果为 `succeeded/failed`。协作移动和删除使用 `expected_revisions`;移动指定 `prev_id/next_id` 时仅接受单条。
|
||||
本次仅整理文档并核对相关源码,未重跑业务测试。文件导入及真实客户端验收见 [解析验收](knowledge-base-file-parsing.md#9-实现状态与验收),模型与图片学习验证见 [模型配置](knowledge-base-models.md#验证),MCP 验证见 [MCP 设计](knowledge-base-mcp-design.md#5-验证与兼容性)。历史局部通过记录不代表当前工作区全量或线上链路通过。
|
||||
Binary file not shown.
@@ -17,8 +17,8 @@ import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
|
||||
LIMIT = 32 * 1024 * 1024
|
||||
FORMATS = {"txt", "md", "markdown", "html", "htm", "svg", "csv", "docx", "xls", "xlsx", "pptx", "pdf", "jpg", "jpeg", "png"}
|
||||
LIMIT = 100 * 1024 * 1024
|
||||
FORMATS = {"txt", "md", "markdown", "html", "htm", "svg", "csv", "docx", "xls", "xlsx", "pptx", "pdf", "jpg", "jpeg", "png", "webp"}
|
||||
|
||||
|
||||
class ImportClient:
|
||||
@@ -56,11 +56,17 @@ class ImportClient:
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def upload(self, kb_id, path, parent_id=None, model_id=None, upload_key=None):
|
||||
def upload(self, kb_id, path, parent_id=None, upload_key=None):
|
||||
# File bytes stream directly to the companion endpoint using the same Key.
|
||||
size = path.stat().st_size
|
||||
if not path.is_file() or not 0 < size <= LIMIT or path.suffix[1:].lower() not in FORMATS:
|
||||
raise ValueError(f"Unsupported format, empty file or file larger than 32 MiB: {path.name}")
|
||||
extension = path.suffix[1:].lower()
|
||||
limit = LIMIT
|
||||
if extension in {"jpg", "jpeg", "png", "webp"}:
|
||||
limit = LIMIT
|
||||
elif extension in {"txt", "md", "markdown", "html", "htm", "svg", "csv"}:
|
||||
limit = 16 * 1024 * 1024
|
||||
if not path.is_file() or not 0 < size <= limit or path.suffix[1:].lower() not in FORMATS:
|
||||
raise ValueError(f"Unsupported format, empty file or file larger than {limit // (1024 * 1024)} MiB: {path.name}")
|
||||
boundary = "monkeyai-" + uuid.uuid4().hex
|
||||
name = path.name
|
||||
if any(c in name for c in ['"', "\\", "\r", "\n"]):
|
||||
@@ -69,8 +75,6 @@ class ImportClient:
|
||||
fields = {"title": path.name, "upload_key": upload_key or uuid.uuid4().hex}
|
||||
if parent_id:
|
||||
fields["parent_id"] = parent_id
|
||||
if model_id:
|
||||
fields["model_id"] = model_id
|
||||
prefix = "".join(f'--{boundary}\r\nContent-Disposition: form-data; name="{key}"\r\n\r\n{value}\r\n' for key, value in fields.items()).encode()
|
||||
head = prefix + (f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="{name}"\r\nContent-Type: {mime}\r\n\r\n').encode()
|
||||
tail = f"\r\n--{boundary}--\r\n".encode()
|
||||
@@ -95,14 +99,11 @@ class ImportClient:
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def import_file(self, kb_id, path, parent_id=None, model_id=None, upload_key=None):
|
||||
image = path.suffix[1:].lower() in {"jpg", "jpeg", "png"}
|
||||
if image and not model_id:
|
||||
raise ValueError("Image import requires --model-id (an accessible vision model)")
|
||||
def import_file(self, kb_id, path, parent_id=None, upload_key=None):
|
||||
upload_key = upload_key or uuid.uuid4().hex
|
||||
# Report before sending bytes so an interrupted process can be resumed.
|
||||
print(json.dumps({"file": path.name, "upload_key": upload_key}, ensure_ascii=False), file=sys.stderr, flush=True)
|
||||
result = self.upload(kb_id, path, parent_id, model_id, upload_key)
|
||||
result = self.upload(kb_id, path, parent_id, upload_key)
|
||||
imported = result.get("import_context")
|
||||
task = result.get("task_context")
|
||||
deadline = time.monotonic() + 30 * 60
|
||||
@@ -140,7 +141,6 @@ def main():
|
||||
parser.add_argument("--kb-id", required=True)
|
||||
parser.add_argument("--parent-id")
|
||||
parser.add_argument("--upload-key", help="32 hex characters reused when retrying one file after a lost response")
|
||||
parser.add_argument("--model-id", help="Vision model UUID required for image descriptions; failed image calls are not automatically retried")
|
||||
parser.add_argument("files", nargs="+", type=Path)
|
||||
args = parser.parse_args()
|
||||
if args.upload_key and (len(args.files) != 1 or len(args.upload_key) != 32 or any(c not in "0123456789abcdefABCDEF" for c in args.upload_key)):
|
||||
@@ -152,7 +152,7 @@ def main():
|
||||
failed = False
|
||||
for path in args.files:
|
||||
try:
|
||||
print(json.dumps(client.import_file(args.kb_id, path, args.parent_id, args.model_id, args.upload_key), ensure_ascii=False), flush=True)
|
||||
print(json.dumps(client.import_file(args.kb_id, path, args.parent_id, args.upload_key), ensure_ascii=False), flush=True)
|
||||
except (ValueError, RuntimeError, OSError, http.client.HTTPException) as error:
|
||||
failed = True
|
||||
print(json.dumps({"file": path.name, "status": "failed", "error": str(error)}, ensure_ascii=False), file=sys.stderr, flush=True)
|
||||
|
||||
@@ -22,6 +22,7 @@ try {
|
||||
locale: "zh-CN",
|
||||
})
|
||||
const errors = []
|
||||
let savedKnowledgeModel = null
|
||||
let batchRestudyCheck = false
|
||||
const restudyRequests = []
|
||||
let documentRequests = 0
|
||||
@@ -49,6 +50,11 @@ try {
|
||||
body = { product_name: "MonkeyAI" }
|
||||
} else if (pathname.endsWith("/license/status")) {
|
||||
body = { state: "valid" }
|
||||
} else if (pathname === "/api/admin/v1/kb-models") {
|
||||
body = {items: []}
|
||||
} else if (pathname === "/api/admin/v1/kb-models/embedding") {
|
||||
savedKnowledgeModel = route.request().postDataJSON()
|
||||
body = {...savedKnowledgeModel, api_key: undefined, id: "configured", kind: "embedding", updated_at: "2026-12-01T00:00:00Z", api_key_configured: true, embedding_config: {dimension: 3}}
|
||||
} else if (pathname.endsWith("/settings")) {
|
||||
body = { settings: [] }
|
||||
} else if (pathname.endsWith("/resources/authorization-subjects")) {
|
||||
@@ -152,6 +158,17 @@ try {
|
||||
await page.goto("http://admin.test/admin/resources/kb", {
|
||||
waitUntil: "networkidle",
|
||||
})
|
||||
await page.getByRole("button", {name: "模型配置", exact: true}).click()
|
||||
await page.getByRole("tab", {name: "向量模型", exact: true}).click()
|
||||
await page.locator("#kb-model-name").fill("embedding-new")
|
||||
await page.locator("#kb-model-url").fill("https://example.test/v1")
|
||||
await page.locator("#kb-model-key").fill("test-secret")
|
||||
await page.getByRole("button", {name: "保存", exact: true}).click()
|
||||
await page.getByRole("dialog").waitFor({ state: "hidden" })
|
||||
assert.equal(savedKnowledgeModel.model_id, "embedding-new")
|
||||
assert.equal(savedKnowledgeModel.enabled, true)
|
||||
assert.equal("revision" in savedKnowledgeModel, false)
|
||||
assert.equal(savedKnowledgeModel.protocol, "openai_embeddings")
|
||||
await page.getByText("测试知识库", { exact: true }).click()
|
||||
await page.waitForURL("**/kb/11111111-1111-4111-8111-111111111111")
|
||||
await page.getByRole("button", { name: "修改信息", exact: true }).waitFor()
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { useState, type FormEvent } from "react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import { api } from "@/lib/api"
|
||||
import { base } from "@/lib/resources"
|
||||
import { loadProxies, type SystemProxy } from "@/lib/proxy-settings"
|
||||
import { SystemProxySelect } from "@/components/proxy-settings"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog"
|
||||
import { Field, FieldGroup, FieldLabel, FieldDescription } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert"
|
||||
import { Switch } from "@/components/ui/switch"
|
||||
|
||||
type Kind = "vision" | "embedding"
|
||||
type Config = {
|
||||
id: string; kind: Kind; model_id: string; base_url: string; protocol: string
|
||||
proxy_id: string; enabled: boolean; updated_at: string; api_key_configured: boolean
|
||||
embedding_config?: { dimension?: number }; advanced_config?: { max_output_tokens?: number; concurrency?: number }
|
||||
}
|
||||
const protocols = [
|
||||
{ value: "openai_chat_completions", label: "OpenAI Chat Completions" },
|
||||
{ value: "openai_responses", label: "OpenAI Responses" },
|
||||
{ value: "anthropic", label: "Anthropic" },
|
||||
]
|
||||
|
||||
export function KbModelSettings() {
|
||||
const { t } = useTranslation()
|
||||
const [open, setOpen] = useState(false)
|
||||
const [kind, setKind] = useState<Kind | "concurrency">("vision")
|
||||
const [concurrency, setConcurrency] = useState({ learning_concurrency: 1, image_concurrency: 1 })
|
||||
const [items, setItems] = useState<Config[]>([])
|
||||
const [proxies, setProxies] = useState<SystemProxy[]>([])
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [ready, setReady] = useState(false)
|
||||
const [error, setError] = useState("")
|
||||
const selected = items.find(item => item.kind === kind)
|
||||
async function show() {
|
||||
setOpen(true); setBusy(true); setReady(false); setError("")
|
||||
try {
|
||||
const [models, network, limits] = await Promise.all([api<{items: Config[]}>(`${base}/kb-models`), loadProxies(), api<typeof concurrency>(`${base}/kb-concurrency`)])
|
||||
setConcurrency(limits); setItems(models.items); setProxies(network); setReady(true)
|
||||
} catch (reason) { setError((reason as Error).message) }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
async function save(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault()
|
||||
const form = new FormData(event.currentTarget)
|
||||
setBusy(true); setError("")
|
||||
try {
|
||||
if (kind === "concurrency") {
|
||||
const saved = await api<typeof concurrency>(`${base}/kb-concurrency`, { method: "PUT", body: JSON.stringify({
|
||||
learning_concurrency: Number(form.get("learning_concurrency")),
|
||||
image_concurrency: Number(form.get("image_concurrency")),
|
||||
}) })
|
||||
setConcurrency(saved)
|
||||
setOpen(false)
|
||||
return
|
||||
}
|
||||
const saved = await api<Config>(`${base}/kb-models/${kind}`, {method: "PUT", body: JSON.stringify({
|
||||
model_id: form.get("model_id"), base_url: form.get("base_url"), api_key: form.get("api_key"),
|
||||
protocol: kind === "embedding" ? "openai_embeddings" : form.get("protocol"),
|
||||
proxy_id: String(form.get("proxyId") ?? "").replace("__direct__", ""),
|
||||
max_output_tokens: kind === "vision" ? Number(form.get("max_output_tokens")) : 0,
|
||||
enabled: form.get("enabled") === "on",
|
||||
})})
|
||||
setItems(current => [...current.filter(item => item.kind !== kind), saved])
|
||||
setOpen(false)
|
||||
} catch (reason) { setError((reason as Error).message) }
|
||||
finally { setBusy(false) }
|
||||
}
|
||||
return <>
|
||||
<Button variant="outline" onClick={() => void show()}>{t("pages.knowledgeBases.settings.title")}</Button>
|
||||
<Dialog open={open} onOpenChange={value => { if (!busy) setOpen(value) }}>
|
||||
<DialogContent className="sm:max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("pages.knowledgeBases.settings.title")}</DialogTitle>
|
||||
<DialogDescription>{t("pages.knowledgeBases.settings.description")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
{error && <Alert variant="destructive"><AlertDescription>{error}</AlertDescription></Alert>}
|
||||
<Tabs value={kind} onValueChange={value => {setKind(value as Kind | "concurrency"); setError("")}}>
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger value="vision" disabled={busy}>{t("pages.knowledgeBases.settings.vision")}</TabsTrigger>
|
||||
<TabsTrigger value="embedding" disabled={busy}>{t("pages.models.embeddingKind")}</TabsTrigger>
|
||||
<TabsTrigger value="concurrency" disabled={busy}>{t("pages.knowledgeBases.settings.concurrency")}</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
{ready && <form key={`${kind}-${selected?.updated_at ?? ""}`} onSubmit={save} className="flex flex-col gap-5">
|
||||
{kind === "concurrency" ? <FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="kb-learning-concurrency">{t("pages.knowledgeBases.settings.learning")}</FieldLabel>
|
||||
<Input id="kb-learning-concurrency" name="learning_concurrency" type="number" min={1} max={20} step={1} defaultValue={concurrency.learning_concurrency} required disabled={busy}/>
|
||||
<FieldDescription>{t("pages.knowledgeBases.settings.learningHint")}</FieldDescription>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="kb-image-concurrency">{t("pages.knowledgeBases.settings.image")}</FieldLabel>
|
||||
<Input id="kb-image-concurrency" name="image_concurrency" type="number" min={1} max={20} step={1} defaultValue={concurrency.image_concurrency} required disabled={busy}/>
|
||||
<FieldDescription>{t("pages.knowledgeBases.settings.imageHint")}</FieldDescription>
|
||||
</Field>
|
||||
</FieldGroup> : <FieldGroup>
|
||||
<FieldGroup className={kind === "vision" ? "grid gap-4 sm:grid-cols-2" : undefined}>
|
||||
<Field><FieldLabel htmlFor="kb-model-name">{t("pages.models.modelId")}</FieldLabel><Input id="kb-model-name" name="model_id" defaultValue={selected?.model_id ?? ""} required maxLength={1024} disabled={busy}/></Field>
|
||||
{kind === "vision" && <Field><FieldLabel>{t("pages.models.protocol")}</FieldLabel><Select name="protocol" items={protocols} defaultValue={selected?.protocol ?? protocols[0].value} disabled={busy}><SelectTrigger className="w-full"><SelectValue/></SelectTrigger><SelectContent><SelectGroup>{protocols.map(p => <SelectItem key={p.value} value={p.value} label={p.label}>{p.label}</SelectItem>)}</SelectGroup></SelectContent></Select></Field>}
|
||||
</FieldGroup>
|
||||
<FieldGroup className="grid sm:grid-cols-2">
|
||||
<Field><FieldLabel htmlFor="kb-model-url">{t("pages.models.baseUrl")}</FieldLabel><Input id="kb-model-url" name="base_url" type="url" placeholder="https://api.example.com/v1" defaultValue={selected?.base_url ?? ""} required disabled={busy}/></Field>
|
||||
<Field><FieldLabel htmlFor="kb-model-key">{t("pages.models.apiKey")}</FieldLabel><Input id="kb-model-key" name="api_key" type="password" autoComplete="new-password" required={!selected?.api_key_configured} placeholder={selected?.api_key_configured ? t("pages.knowledgeBases.settings.keepKey") : ""} disabled={busy}/></Field>
|
||||
</FieldGroup>
|
||||
{kind === "embedding" && <FieldDescription>{t("pages.knowledgeBases.settings.embeddingHint")}{selected?.embedding_config?.dimension ? ` (${selected.embedding_config.dimension})` : ""}</FieldDescription>}
|
||||
<Field orientation="horizontal" className="justify-between">
|
||||
<FieldLabel htmlFor="kb-model-enabled">{t("pages.models.enable")}</FieldLabel>
|
||||
<Switch id="kb-model-enabled" name="enabled" defaultChecked={selected?.enabled ?? true} disabled={busy}/>
|
||||
</Field>
|
||||
<details><summary>{t("pages.models.advancedOptions")}</summary><FieldGroup className="pt-4">
|
||||
{kind === "vision" && <>
|
||||
<Field><FieldLabel htmlFor="kb-model-output">{t("pages.models.maxOutputTokens")}</FieldLabel><Input id="kb-model-output" name="max_output_tokens" type="number" min={1} max={65536} defaultValue={selected?.advanced_config?.max_output_tokens ?? 8192} required disabled={busy}/></Field>
|
||||
</>}
|
||||
<Field><FieldLabel htmlFor="kb-model-proxy">{t("pages.models.networkProxy")}</FieldLabel><SystemProxySelect id="kb-model-proxy" selected={selected?.proxy_id ?? ""} proxies={proxies}/></Field>
|
||||
</FieldGroup></details>
|
||||
</FieldGroup>}
|
||||
<DialogFooter><Button type="button" variant="outline" disabled={busy} onClick={() => setOpen(false)}>{t("pages.models.cancel")}</Button><Button type="submit" disabled={busy}>{busy ? t("resources.saving") : t("pages.models.save")}</Button></DialogFooter>
|
||||
</form>}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
}
|
||||
@@ -2099,7 +2099,7 @@ export const ar = {
|
||||
editorUnsaved: "تغييرات غير محفوظة. سيتم الحفظ تلقائيًا بعد 10 ثوانٍ",
|
||||
imageUploading: "جارٍ رفع الصورة…",
|
||||
imageUploadInvalid: "تُدعم فقط صور PNG وJPEG وGIF وWebP",
|
||||
imageUploadTooLarge: "يجب ألا تكون الصورة فارغة أو تتجاوز 32 MiB",
|
||||
imageUploadTooLarge: "يجب ألا تكون الصورة فارغة أو تتجاوز 100 MiB",
|
||||
editorSaving: "جارٍ الحفظ التلقائي",
|
||||
editorClean: "تم الحفظ",
|
||||
|
||||
@@ -2153,13 +2153,13 @@ export const ar = {
|
||||
textPlaceholder: "أدخل المحتوى المعرفي المراد تعلمه",
|
||||
selectFile: "اختيار ملف",
|
||||
imageModel: "Image description model",
|
||||
imageModelPlaceholder: "Choose a vision model",
|
||||
imageModelHint: "Required for images only. Describes the scene and reads visible text. Model usage is billed; retrying a failed parse may incur another charge.",
|
||||
imageModelUnavailable: "No vision model available. Other file types can still be imported.",
|
||||
imageModelRequired: "Choose an image description model.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG, up to 32 MiB per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "ملفات DOC وPPT غير مدعومة.",
|
||||
importSize: "اختر ملفًا غير فارغ لا يتجاوز 32 MiB.",
|
||||
imageModelPlaceholder: "Automatically use the knowledge base vision model",
|
||||
imageModelHint: "Images automatically use the knowledge base vision model to describe the scene and extract text, without consuming platform credits.",
|
||||
imageModelUnavailable: "The knowledge base vision model is not configured or is disabled. Other file types can still be imported.",
|
||||
imageModelRequired: "The knowledge base vision model is not configured. Contact an administrator.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG/WebP, up to 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "تنسيق غير مدعوم. حوّل ملفات Office القديمة إلى .xlsx أو .pptx أو .docx قبل رفعها.",
|
||||
importSize: "اختر ملفًا غير فارغ لا يتجاوز 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV).",
|
||||
importInvalidResult: "نتيجة التحويل غير صالحة.",
|
||||
importTimeout: "انتهت مهلة التحويل. أعد استيراد الملف.",
|
||||
importFailed: "فشل التحويل.",
|
||||
@@ -2221,6 +2221,19 @@ export const ar = {
|
||||
batchExit: "إنهاء التحديد",
|
||||
batchSelected: "المحدد: {{count}}",
|
||||
batchSelectAll: "تحديد الكل",
|
||||
settings: {
|
||||
title: "إعدادات قاعدة المعرفة",
|
||||
description: "اضبط النماذج وحدود التزامن لمهام التعلّم والتعرّف على الصور.",
|
||||
vision: "نموذج الرؤية",
|
||||
concurrency: "التزامن",
|
||||
learning: "مهام التعلّم المتزامنة",
|
||||
learningHint: "القيمة الافتراضية 1 والحد الأقصى 20. لا يؤدي خفض الحد إلى إيقاف المهام الجارية.",
|
||||
image: "طلبات التعرّف على الصور المتزامنة",
|
||||
imageHint: "لكل مثيل خادم: القيمة الافتراضية 1 والحد الأقصى 20. اضبط القيمة وفق حدود مزوّد النموذج.",
|
||||
keepKey: "اترك الحقل فارغًا للاحتفاظ بالمفتاح الحالي",
|
||||
embeddingHint: "يُكتشف عدد أبعاد المتجهات عند الحفظ. يؤدي تغيير النموذج إلى إعادة إنشاء متجهات قواعد المعرفة التي تستخدمه.",
|
||||
},
|
||||
batchSelectAllFiles: "تحديد جميع الملفات",
|
||||
batchClear: "إلغاء التحديد",
|
||||
batchMove: "نقل",
|
||||
batchMoveTitle: "نقل إلى مجلد",
|
||||
|
||||
@@ -2126,7 +2126,7 @@ export const deDE = {
|
||||
imageUploadInvalid:
|
||||
"Nur PNG-, JPEG-, GIF- und WebP-Bilder werden unterstützt",
|
||||
imageUploadTooLarge:
|
||||
"Bilder dürfen nicht leer oder größer als 32 MiB sein",
|
||||
"Bilder dürfen nicht leer oder größer als 100 MiB sein",
|
||||
editorSaving: "Wird automatisch gespeichert",
|
||||
editorClean: "Gespeichert",
|
||||
|
||||
@@ -2181,13 +2181,13 @@ export const deDE = {
|
||||
textPlaceholder: "Zu lernenden Wissensinhalt eingeben",
|
||||
selectFile: "Datei auswählen",
|
||||
imageModel: "Image description model",
|
||||
imageModelPlaceholder: "Choose a vision model",
|
||||
imageModelHint: "Required for images only. Describes the scene and reads visible text. Model usage is billed; retrying a failed parse may incur another charge.",
|
||||
imageModelUnavailable: "No vision model available. Other file types can still be imported.",
|
||||
imageModelRequired: "Choose an image description model.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG, up to 32 MiB per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "DOC und PPT werden nicht unterstützt.",
|
||||
importSize: "Wählen Sie eine nicht leere Datei bis 32 MiB.",
|
||||
imageModelPlaceholder: "Automatically use the knowledge base vision model",
|
||||
imageModelHint: "Images automatically use the knowledge base vision model to describe the scene and extract text, without consuming platform credits.",
|
||||
imageModelUnavailable: "The knowledge base vision model is not configured or is disabled. Other file types can still be imported.",
|
||||
imageModelRequired: "The knowledge base vision model is not configured. Contact an administrator.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG/WebP, up to 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "Nicht unterstütztes Format. Alte Office-Dateien vor dem Hochladen in .xlsx, .pptx oder .docx konvertieren.",
|
||||
importSize: "Wählen Sie eine nicht leere Datei bis 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV).",
|
||||
importInvalidResult: "Ungültiges Konvertierungsergebnis.",
|
||||
importTimeout: "Zeitüberschreitung. Importieren Sie die Datei erneut.",
|
||||
importFailed: "Konvertierung fehlgeschlagen.",
|
||||
@@ -2251,6 +2251,19 @@ export const deDE = {
|
||||
batchExit: "Stapelmodus beenden",
|
||||
batchSelected: "{{count}} ausgewählt",
|
||||
batchSelectAll: "Alle auswählen",
|
||||
settings: {
|
||||
title: "Wissensdatenbank-Einstellungen",
|
||||
description: "Modelle und Parallelität für Lernaufträge und Bilderkennung konfigurieren.",
|
||||
vision: "Bildanalysemodell",
|
||||
concurrency: "Parallelität",
|
||||
learning: "Gleichzeitige Lernaufträge",
|
||||
learningHint: "Standard: 1, maximal 20. Eine niedrigere Grenze unterbricht laufende Aufträge nicht.",
|
||||
image: "Gleichzeitige Bilderkennungen",
|
||||
imageHint: "Pro Serverinstanz: standardmäßig 1, maximal 20. Beachten Sie das Limit des Modellanbieters.",
|
||||
keepKey: "Leer lassen, um den aktuellen Schlüssel beizubehalten",
|
||||
embeddingHint: "Beim Speichern wird die Vektordimension ermittelt. Ein Modellwechsel berechnet die Vektoren der betroffenen Wissensdatenbanken neu.",
|
||||
},
|
||||
batchSelectAllFiles: "Alle Dateien auswählen",
|
||||
batchClear: "Abwählen",
|
||||
batchMove: "Verschieben",
|
||||
batchMoveTitle: "In Ordner verschieben",
|
||||
|
||||
@@ -2168,7 +2168,7 @@ export const enUS = {
|
||||
editorUnsaved: "Unsaved changes. Autosaving in 10 seconds",
|
||||
imageUploading: "Uploading image…",
|
||||
imageUploadInvalid: "Only PNG, JPEG, GIF, and WebP images are supported",
|
||||
imageUploadTooLarge: "Images must not be empty or exceed 32 MiB",
|
||||
imageUploadTooLarge: "Images must not be empty or exceed 100 MiB",
|
||||
editorSaving: "Autosaving",
|
||||
editorClean: "Saved",
|
||||
|
||||
@@ -2226,13 +2226,13 @@ export const enUS = {
|
||||
textPlaceholder: "Enter the knowledge content to learn",
|
||||
selectFile: "Select file",
|
||||
imageModel: "Image description model",
|
||||
imageModelPlaceholder: "Choose a vision model",
|
||||
imageModelHint: "Required for images only. Describes the scene and reads visible text. Model usage is billed; retrying a failed parse may incur another charge.",
|
||||
imageModelUnavailable: "No vision model available. Other file types can still be imported.",
|
||||
imageModelRequired: "Choose an image description model.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG, up to 32 MiB per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "Unsupported format. DOC and PPT are not supported.",
|
||||
importSize: "Select a nonempty file up to 32 MiB.",
|
||||
imageModelPlaceholder: "Automatically use the knowledge base vision model",
|
||||
imageModelHint: "Images automatically use the knowledge base vision model to describe the scene and extract text, without consuming platform credits.",
|
||||
imageModelUnavailable: "The knowledge base vision model is not configured or is disabled. Other file types can still be imported.",
|
||||
imageModelRequired: "The knowledge base vision model is not configured. Contact an administrator.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG/WebP, up to 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "Unsupported format. Convert legacy Office files to .xlsx, .pptx or .docx before uploading.",
|
||||
importSize: "Select a nonempty file up to 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV).",
|
||||
importInvalidResult: "The conversion service returned an invalid result.",
|
||||
importTimeout: "Conversion timed out. Import this file again.",
|
||||
importFailed: "Conversion failed.",
|
||||
@@ -2303,6 +2303,19 @@ export const enUS = {
|
||||
batchExit: "Exit batch",
|
||||
batchSelected: "{{count}} selected",
|
||||
batchSelectAll: "Select all",
|
||||
settings: {
|
||||
title: "Knowledge base settings",
|
||||
description: "Configure models and concurrency limits for learning and image recognition.",
|
||||
vision: "Vision model",
|
||||
concurrency: "Concurrency",
|
||||
learning: "Concurrent learning jobs",
|
||||
learningHint: "Default: 1. Maximum: 20. Lowering the limit does not interrupt running jobs.",
|
||||
image: "Concurrent image requests",
|
||||
imageHint: "Default: 1. Maximum: 20 per server instance. Use a limit supported by your model provider.",
|
||||
keepKey: "Leave blank to keep the configured key",
|
||||
embeddingHint: "Saving detects the vector dimension. Changing the model rebuilds vectors for knowledge bases that use it.",
|
||||
},
|
||||
batchSelectAllFiles: "Select all files",
|
||||
batchClear: "Clear",
|
||||
batchMove: "Move to",
|
||||
batchMoveTitle: "Move to folder",
|
||||
|
||||
@@ -2121,7 +2121,7 @@ export const es419 = {
|
||||
imageUploading: "Subiendo imagen…",
|
||||
imageUploadInvalid: "Solo se admiten imágenes PNG, JPEG, GIF y WebP",
|
||||
imageUploadTooLarge:
|
||||
"La imagen no debe estar vacía ni superar los 32 MiB",
|
||||
"La imagen no debe estar vacía ni superar los 100 MiB",
|
||||
editorSaving: "Guardando automáticamente",
|
||||
editorClean: "Guardado",
|
||||
|
||||
@@ -2176,13 +2176,13 @@ export const es419 = {
|
||||
textPlaceholder: "Ingresa el conocimiento que se debe aprender",
|
||||
selectFile: "Seleccionar archivo",
|
||||
imageModel: "Image description model",
|
||||
imageModelPlaceholder: "Choose a vision model",
|
||||
imageModelHint: "Required for images only. Describes the scene and reads visible text. Model usage is billed; retrying a failed parse may incur another charge.",
|
||||
imageModelUnavailable: "No vision model available. Other file types can still be imported.",
|
||||
imageModelRequired: "Choose an image description model.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG, up to 32 MiB per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "DOC y PPT no son compatibles.",
|
||||
importSize: "Selecciona un archivo no vacío de hasta 32 MiB.",
|
||||
imageModelPlaceholder: "Automatically use the knowledge base vision model",
|
||||
imageModelHint: "Images automatically use the knowledge base vision model to describe the scene and extract text, without consuming platform credits.",
|
||||
imageModelUnavailable: "The knowledge base vision model is not configured or is disabled. Other file types can still be imported.",
|
||||
imageModelRequired: "The knowledge base vision model is not configured. Contact an administrator.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG/WebP, up to 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "Formato no compatible. Convierte los archivos antiguos de Office a .xlsx, .pptx o .docx antes de subirlos.",
|
||||
importSize: "Selecciona un archivo no vacío de hasta 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV).",
|
||||
importInvalidResult: "Resultado de conversión inválido.",
|
||||
importTimeout: "Se agotó el tiempo. Vuelve a importar el archivo.",
|
||||
importFailed: "Error de conversión.",
|
||||
@@ -2244,6 +2244,19 @@ export const es419 = {
|
||||
batchExit: "Salir de selección",
|
||||
batchSelected: "{{count}} seleccionados",
|
||||
batchSelectAll: "Seleccionar todo",
|
||||
settings: {
|
||||
title: "Configuración de la base de conocimientos",
|
||||
description: "Configura los modelos y los límites de concurrencia del aprendizaje y el reconocimiento de imágenes.",
|
||||
vision: "Modelo de visión",
|
||||
concurrency: "Concurrencia",
|
||||
learning: "Tareas de aprendizaje simultáneas",
|
||||
learningHint: "Valor predeterminado: 1; máximo: 20. Reducir el límite no interrumpe las tareas en curso.",
|
||||
image: "Imágenes procesadas simultáneamente",
|
||||
imageHint: "Por instancia del servidor: 1 de forma predeterminada y hasta 20. Respeta el límite del proveedor del modelo.",
|
||||
keepKey: "Deja el campo vacío para conservar la clave actual",
|
||||
embeddingHint: "Al guardar se detecta la dimensión de los vectores. Cambiar el modelo recalcula los vectores de las bases que lo usan.",
|
||||
},
|
||||
batchSelectAllFiles: "Seleccionar todos los archivos",
|
||||
batchClear: "Desmarcar",
|
||||
batchMove: "Mover",
|
||||
batchMoveTitle: "Mover a carpeta",
|
||||
|
||||
@@ -2129,7 +2129,7 @@ export const frFR = {
|
||||
imageUploading: "Téléversement de l’image…",
|
||||
imageUploadInvalid:
|
||||
"Seules les images PNG, JPEG, GIF et WebP sont acceptées",
|
||||
imageUploadTooLarge: "L’image ne doit pas être vide ni dépasser 32 MiB",
|
||||
imageUploadTooLarge: "L’image ne doit pas être vide ni dépasser 100 MiB",
|
||||
editorSaving: "Enregistrement automatique",
|
||||
editorClean: "Enregistré",
|
||||
|
||||
@@ -2184,13 +2184,13 @@ export const frFR = {
|
||||
textPlaceholder: "Saisissez le contenu à apprendre",
|
||||
selectFile: "Sélectionner un fichier",
|
||||
imageModel: "Image description model",
|
||||
imageModelPlaceholder: "Choose a vision model",
|
||||
imageModelHint: "Required for images only. Describes the scene and reads visible text. Model usage is billed; retrying a failed parse may incur another charge.",
|
||||
imageModelUnavailable: "No vision model available. Other file types can still be imported.",
|
||||
imageModelRequired: "Choose an image description model.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG, up to 32 MiB per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "DOC et PPT ne sont pas pris en charge.",
|
||||
importSize: "Choisissez un fichier non vide de 32 Mio maximum.",
|
||||
imageModelPlaceholder: "Automatically use the knowledge base vision model",
|
||||
imageModelHint: "Images automatically use the knowledge base vision model to describe the scene and extract text, without consuming platform credits.",
|
||||
imageModelUnavailable: "The knowledge base vision model is not configured or is disabled. Other file types can still be imported.",
|
||||
imageModelRequired: "The knowledge base vision model is not configured. Contact an administrator.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG/WebP, up to 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "Format non pris en charge. Convertissez les anciens fichiers Office en .xlsx, .pptx ou .docx avant de les importer.",
|
||||
importSize: "Choisissez un fichier non vide de 100 Mio (PDF/Office), 100 Mio (JPEG/PNG/WebP), 16 Mio (texte) maximum.",
|
||||
importInvalidResult: "Résultat de conversion invalide.",
|
||||
importTimeout: "Délai de conversion dépassé. Importez à nouveau le fichier.",
|
||||
importFailed: "Échec de la conversion.",
|
||||
@@ -2254,6 +2254,19 @@ export const frFR = {
|
||||
batchExit: "Quitter la sélection",
|
||||
batchSelected: "{{count}} sélectionnés",
|
||||
batchSelectAll: "Tout sélectionner",
|
||||
settings: {
|
||||
title: "Paramètres de la base de connaissances",
|
||||
description: "Configurez les modèles et les limites de traitement simultané pour l’apprentissage et la reconnaissance d’images.",
|
||||
vision: "Modèle de vision",
|
||||
concurrency: "Traitements simultanés",
|
||||
learning: "Tâches d’apprentissage simultanées",
|
||||
learningHint: "Par défaut : 1, maximum : 20. Réduire la limite n’interrompt pas les tâches en cours.",
|
||||
image: "Images analysées simultanément",
|
||||
imageHint: "Par instance de serveur : 1 par défaut, 20 au maximum. Respectez la limite du fournisseur du modèle.",
|
||||
keepKey: "Laisser vide pour conserver la clé actuelle",
|
||||
embeddingHint: "La dimension des vecteurs est détectée à l’enregistrement. Changer de modèle recalcule les vecteurs des bases qui l’utilisent.",
|
||||
},
|
||||
batchSelectAllFiles: "Sélectionner tous les fichiers",
|
||||
batchClear: "Désélectionner",
|
||||
batchMove: "Déplacer",
|
||||
batchMoveTitle: "Déplacer vers un dossier",
|
||||
|
||||
@@ -2110,7 +2110,7 @@ export const jaJP = {
|
||||
editorUnsaved: "未保存の変更。10秒後に自動保存します",
|
||||
imageUploading: "画像をアップロード中…",
|
||||
imageUploadInvalid: "PNG、JPEG、GIF、WebP 画像のみ対応しています",
|
||||
imageUploadTooLarge: "画像は空にできず、32 MiB 以下である必要があります",
|
||||
imageUploadTooLarge: "画像は空にできず、100 MiB 以下である必要があります",
|
||||
editorSaving: "自動保存中",
|
||||
editorClean: "保存済み",
|
||||
|
||||
@@ -2164,13 +2164,13 @@ export const jaJP = {
|
||||
textPlaceholder: "学習させるナレッジ内容を入力",
|
||||
selectFile: "ファイルを選択",
|
||||
imageModel: "Image description model",
|
||||
imageModelPlaceholder: "Choose a vision model",
|
||||
imageModelHint: "Required for images only. Describes the scene and reads visible text. Model usage is billed; retrying a failed parse may incur another charge.",
|
||||
imageModelUnavailable: "No vision model available. Other file types can still be imported.",
|
||||
imageModelRequired: "Choose an image description model.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG, up to 32 MiB per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "DOC、PPTは対応していません。",
|
||||
importSize: "空でない32 MiB以下のファイルを選択してください。",
|
||||
imageModelPlaceholder: "Automatically use the knowledge base vision model",
|
||||
imageModelHint: "Images automatically use the knowledge base vision model to describe the scene and extract text, without consuming platform credits.",
|
||||
imageModelUnavailable: "The knowledge base vision model is not configured or is disabled. Other file types can still be imported.",
|
||||
imageModelRequired: "The knowledge base vision model is not configured. Contact an administrator.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG/WebP, up to 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "未対応の形式です。旧 Office ファイルは .xlsx、.pptx、.docx に変換してからアップロードしてください。",
|
||||
importSize: "空でない100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV)以下のファイルを選択してください。",
|
||||
importInvalidResult: "変換結果が無効です。",
|
||||
importTimeout: "変換がタイムアウトしました。再度インポートしてください。",
|
||||
importFailed: "変換に失敗しました。",
|
||||
@@ -2233,6 +2233,19 @@ export const jaJP = {
|
||||
batchExit: "一括操作を終了",
|
||||
batchSelected: "{{count}} 件を選択中",
|
||||
batchSelectAll: "すべて選択",
|
||||
settings: {
|
||||
title: "ナレッジベース設定",
|
||||
description: "モデルと、学習タスク・画像認識の同時実行数を設定します。",
|
||||
vision: "視覚モデル",
|
||||
concurrency: "同時実行設定",
|
||||
learning: "学習タスクの同時実行数",
|
||||
learningHint: "既定値は1、上限は20です。上限を下げても実行中のタスクは中断されません。",
|
||||
image: "画像認識の同時実行数",
|
||||
imageHint: "サーバーインスタンスごとに既定値は1、上限は20です。モデル提供元の制限に合わせてください。",
|
||||
keepKey: "空欄にすると現在のキーを保持します",
|
||||
embeddingHint: "保存時にベクトルの次元数を検出します。モデルを変更すると、そのモデルを使うナレッジベースのベクトルが再構築されます。",
|
||||
},
|
||||
batchSelectAllFiles: "すべてのファイルを選択",
|
||||
batchClear: "クリア",
|
||||
batchMove: "移動",
|
||||
batchMoveTitle: "フォルダへ移動",
|
||||
|
||||
@@ -2100,7 +2100,7 @@ export const koKR = {
|
||||
editorUnsaved: "저장하지 않은 변경 사항. 10초 후 자동 저장",
|
||||
imageUploading: "이미지 업로드 중…",
|
||||
imageUploadInvalid: "PNG, JPEG, GIF, WebP 이미지만 지원합니다",
|
||||
imageUploadTooLarge: "이미지는 비어 있거나 32 MiB를 초과할 수 없습니다",
|
||||
imageUploadTooLarge: "이미지는 비어 있거나 100 MiB를 초과할 수 없습니다",
|
||||
editorSaving: "자동 저장 중",
|
||||
editorClean: "저장됨",
|
||||
|
||||
@@ -2153,13 +2153,13 @@ export const koKR = {
|
||||
textPlaceholder: "학습할 지식 콘텐츠 입력",
|
||||
selectFile: "파일 선택",
|
||||
imageModel: "Image description model",
|
||||
imageModelPlaceholder: "Choose a vision model",
|
||||
imageModelHint: "Required for images only. Describes the scene and reads visible text. Model usage is billed; retrying a failed parse may incur another charge.",
|
||||
imageModelUnavailable: "No vision model available. Other file types can still be imported.",
|
||||
imageModelRequired: "Choose an image description model.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG, up to 32 MiB per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "DOC, PPT는 지원하지 않습니다.",
|
||||
importSize: "비어 있지 않은 32 MiB 이하 파일을 선택하세요.",
|
||||
imageModelPlaceholder: "Automatically use the knowledge base vision model",
|
||||
imageModelHint: "Images automatically use the knowledge base vision model to describe the scene and extract text, without consuming platform credits.",
|
||||
imageModelUnavailable: "The knowledge base vision model is not configured or is disabled. Other file types can still be imported.",
|
||||
imageModelRequired: "The knowledge base vision model is not configured. Contact an administrator.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG/WebP, up to 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "지원하지 않는 형식입니다. 이전 Office 파일을 .xlsx, .pptx 또는 .docx로 변환한 후 업로드하세요.",
|
||||
importSize: "비어 있지 않은 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) 이하 파일을 선택하세요.",
|
||||
importInvalidResult: "변환 결과가 올바르지 않습니다.",
|
||||
importTimeout: "변환 시간이 초과되었습니다. 다시 가져오세요.",
|
||||
importFailed: "변환에 실패했습니다.",
|
||||
@@ -2222,6 +2222,19 @@ export const koKR = {
|
||||
batchExit: "일괄 작업 종료",
|
||||
batchSelected: "{{count}}개 선택됨",
|
||||
batchSelectAll: "모두 선택",
|
||||
settings: {
|
||||
title: "지식 베이스 설정",
|
||||
description: "모델과 학습 작업 및 이미지 인식의 동시 실행 한도를 설정합니다.",
|
||||
vision: "비전 모델",
|
||||
concurrency: "동시 실행 설정",
|
||||
learning: "동시 학습 작업 수",
|
||||
learningHint: "기본값은 1, 최댓값은 20입니다. 한도를 낮춰도 실행 중인 작업은 중단되지 않습니다.",
|
||||
image: "동시 이미지 인식 수",
|
||||
imageHint: "서버 인스턴스당 기본값은 1, 최댓값은 20입니다. 모델 제공업체의 한도에 맞춰 설정하세요.",
|
||||
keepKey: "비워 두면 기존 키가 유지됩니다",
|
||||
embeddingHint: "저장할 때 벡터 차원을 감지합니다. 모델을 변경하면 해당 모델을 사용하는 지식 베이스의 벡터가 다시 생성됩니다.",
|
||||
},
|
||||
batchSelectAllFiles: "모든 파일 선택",
|
||||
batchClear: "선택 해제",
|
||||
batchMove: "이동",
|
||||
batchMoveTitle: "폴더로 이동",
|
||||
|
||||
@@ -2125,7 +2125,7 @@ export const ruRU = {
|
||||
imageUploadInvalid:
|
||||
"Поддерживаются только изображения PNG, JPEG, GIF и WebP",
|
||||
imageUploadTooLarge:
|
||||
"Изображение не должно быть пустым или превышать 32 MiB",
|
||||
"Изображение не должно быть пустым или превышать 100 MiB",
|
||||
editorSaving: "Автосохранение",
|
||||
editorClean: "Сохранено",
|
||||
|
||||
@@ -2180,13 +2180,13 @@ export const ruRU = {
|
||||
textPlaceholder: "Введите текст для изучения",
|
||||
selectFile: "Выбрать файл",
|
||||
imageModel: "Image description model",
|
||||
imageModelPlaceholder: "Choose a vision model",
|
||||
imageModelHint: "Required for images only. Describes the scene and reads visible text. Model usage is billed; retrying a failed parse may incur another charge.",
|
||||
imageModelUnavailable: "No vision model available. Other file types can still be imported.",
|
||||
imageModelRequired: "Choose an image description model.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG, up to 32 MiB per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "DOC и PPT не поддерживаются.",
|
||||
importSize: "Выберите непустой файл размером до 32 МиБ.",
|
||||
imageModelPlaceholder: "Automatically use the knowledge base vision model",
|
||||
imageModelHint: "Images automatically use the knowledge base vision model to describe the scene and extract text, without consuming platform credits.",
|
||||
imageModelUnavailable: "The knowledge base vision model is not configured or is disabled. Other file types can still be imported.",
|
||||
imageModelRequired: "The knowledge base vision model is not configured. Contact an administrator.",
|
||||
importDescription: "Supports TXT, Markdown, HTML, SVG, CSV, Office, PDF and JPEG/JPG/PNG/WebP, up to 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) per file. Images use a vision LLM for descriptions and visible text. Image and Office/PDF derived content is read-only. Leaving the page discards unfinished imports.",
|
||||
importUnsupported: "Неподдерживаемый формат. Перед загрузкой преобразуйте старые файлы Office в .xlsx, .pptx или .docx.",
|
||||
importSize: "Выберите непустой файл размером до 100 МиБ (PDF/Office), 100 МиБ (JPEG/PNG/WebP), 16 МиБ (текст).",
|
||||
importInvalidResult: "Некорректный результат преобразования.",
|
||||
importTimeout: "Время ожидания истекло. Импортируйте файл заново.",
|
||||
importFailed: "Ошибка преобразования.",
|
||||
@@ -2249,6 +2249,19 @@ export const ruRU = {
|
||||
batchExit: "Выйти из выбора",
|
||||
batchSelected: "Выбрано: {{count}}",
|
||||
batchSelectAll: "Выбрать всё",
|
||||
settings: {
|
||||
title: "Настройки базы знаний",
|
||||
description: "Настройте модели и ограничения параллельной обработки для обучения и распознавания изображений.",
|
||||
vision: "Модель распознавания изображений",
|
||||
concurrency: "Параллельная обработка",
|
||||
learning: "Одновременные задачи обучения",
|
||||
learningHint: "По умолчанию — 1, максимум — 20. Снижение лимита не прерывает запущенные задачи.",
|
||||
image: "Одновременные запросы распознавания",
|
||||
imageHint: "На экземпляр сервера: по умолчанию — 1, максимум — 20. Учитывайте лимит поставщика модели.",
|
||||
keepKey: "Оставьте поле пустым, чтобы сохранить текущий ключ",
|
||||
embeddingHint: "При сохранении определяется размерность векторов. Смена модели пересоздаёт векторы баз знаний, которые её используют.",
|
||||
},
|
||||
batchSelectAllFiles: "Выбрать все файлы",
|
||||
batchClear: "Снять выбор",
|
||||
batchMove: "Переместить",
|
||||
batchMoveTitle: "Переместить в папку",
|
||||
|
||||
@@ -2071,7 +2071,7 @@ export const zhCN = {
|
||||
editorUnsaved: "未保存更改,10 秒后自动保存",
|
||||
imageUploading: "图片上传中…",
|
||||
imageUploadInvalid: "仅支持 PNG、JPEG、GIF 或 WebP 图片",
|
||||
imageUploadTooLarge: "图片不能为空且不能超过 32 MiB",
|
||||
imageUploadTooLarge: "图片不能为空且不能超过 100 MiB",
|
||||
editorSaving: "正在自动保存",
|
||||
editorClean: "已保存",
|
||||
|
||||
@@ -2128,13 +2128,13 @@ export const zhCN = {
|
||||
textPlaceholder: "输入需要学习的知识内容",
|
||||
selectFile: "选择文件",
|
||||
imageModel: "图片描述模型",
|
||||
imageModelPlaceholder: "选择支持图片输入的模型",
|
||||
imageModelHint: "仅图片需要选择。生成画面描述并提取图中文字,按模型规则计费;解析失败后重试可能再次计费。",
|
||||
imageModelUnavailable: "没有可用的视觉模型,仍可导入其他格式。",
|
||||
imageModelRequired: "请选择图片描述模型。",
|
||||
importDescription: "支持 TXT、Markdown、HTML、SVG、CSV、Office、PDF、JPEG/JPG/PNG,每个文件最大 32 MiB。图片由 LLM 生成画面描述并提取文字,图片及 Office/PDF 派生正文只读。离开页面将丢失未完成的导入。",
|
||||
importUnsupported: "不支持此格式,DOC 和 PPT 暂不支持。",
|
||||
importSize: "请选择非空且不超过 32 MiB 的文件。",
|
||||
imageModelPlaceholder: "自动使用知识库视觉模型",
|
||||
imageModelHint: "图片自动使用知识库视觉模型生成画面描述并提取文字,不扣除平台额度。",
|
||||
imageModelUnavailable: "知识库视觉模型未配置或已停用,仍可导入其他格式。",
|
||||
imageModelRequired: "知识库视觉模型未配置,请联系管理员。",
|
||||
importDescription: "支持 TXT、Markdown、HTML、SVG、CSV、Office、PDF、JPEG/JPG/PNG/WebP,每个文件最大 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV)。图片由 LLM 生成画面描述并提取文字,图片及 Office/PDF 派生正文只读。离开页面将丢失未完成的导入。",
|
||||
importUnsupported: "不支持此格式。旧版 Office 文件请在客户端转换为 .xlsx、.pptx 或 .docx 后上传。",
|
||||
importSize: "请选择非空且不超过 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) 的文件。",
|
||||
importInvalidResult: "转换服务返回了无效结果。",
|
||||
importTimeout: "转换等待超时,请重新导入该文件。",
|
||||
importFailed: "转换失败。",
|
||||
@@ -2204,6 +2204,19 @@ export const zhCN = {
|
||||
batchExit: "退出批量",
|
||||
batchSelected: "已选择 {{count}} 项",
|
||||
batchSelectAll: "全选",
|
||||
settings: {
|
||||
title: "知识库配置",
|
||||
description: "配置知识库模型以及学习任务和图片识别的并发上限。",
|
||||
vision: "视觉模型",
|
||||
concurrency: "并发配置",
|
||||
learning: "学习任务并发数",
|
||||
learningHint: "默认 1,最多 20。降低上限不会中断进行中的任务。",
|
||||
image: "图片识别并发数",
|
||||
imageHint: "每个服务实例默认 1,最多 20。请按模型服务的限流额度设置。",
|
||||
keepKey: "已配置,留空保留",
|
||||
embeddingHint: "保存时自动检测向量维度。更换模型会重建使用该模型的知识库向量。",
|
||||
},
|
||||
batchSelectAllFiles: "全选文件",
|
||||
batchClear: "清空",
|
||||
batchMove: "移动到",
|
||||
batchMoveTitle: "移动到文件夹",
|
||||
|
||||
@@ -2077,7 +2077,7 @@ export const zhTW = {
|
||||
editorUnsaved: "未儲存變更,10 秒後自動儲存",
|
||||
imageUploading: "圖片上傳中…",
|
||||
imageUploadInvalid: "僅支援 PNG、JPEG、GIF 或 WebP 圖片",
|
||||
imageUploadTooLarge: "圖片不能為空且不能超過 32 MiB",
|
||||
imageUploadTooLarge: "圖片不能為空且不能超過 100 MiB",
|
||||
editorSaving: "正在自動儲存",
|
||||
editorClean: "已儲存",
|
||||
|
||||
@@ -2130,13 +2130,13 @@ export const zhTW = {
|
||||
textPlaceholder: "輸入需要學習的知識內容",
|
||||
selectFile: "選擇檔案",
|
||||
imageModel: "图片描述模型",
|
||||
imageModelPlaceholder: "选择支持图片输入的模型",
|
||||
imageModelHint: "仅图片需要选择。生成画面描述并提取图中文字,按模型规则计费;解析失败后重试可能再次计费。",
|
||||
imageModelUnavailable: "没有可用的视觉模型,仍可导入其他格式。",
|
||||
imageModelRequired: "请选择图片描述模型。",
|
||||
importDescription: "支持 TXT、Markdown、HTML、SVG、CSV、Office、PDF、JPEG/JPG/PNG,每个文件最大 32 MiB。图片由 LLM 生成画面描述并提取文字,图片及 Office/PDF 派生正文只读。离开页面将丢失未完成的导入。",
|
||||
importUnsupported: "不支援此格式,DOC 和 PPT 暫不支援。",
|
||||
importSize: "請選擇非空且不超過 32 MiB 的檔案。",
|
||||
imageModelPlaceholder: "自动使用知识库视觉模型",
|
||||
imageModelHint: "图片自动使用知识库视觉模型生成画面描述并提取文字,不扣除平台额度。",
|
||||
imageModelUnavailable: "知识库视觉模型未配置或已停用,仍可导入其他格式。",
|
||||
imageModelRequired: "知识库视觉模型未配置,请联系管理员。",
|
||||
importDescription: "支持 TXT、Markdown、HTML、SVG、CSV、Office、PDF、JPEG/JPG/PNG/WebP,每个文件最大 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV)。图片由 LLM 生成画面描述并提取文字,图片及 Office/PDF 派生正文只读。离开页面将丢失未完成的导入。",
|
||||
importUnsupported: "不支援此格式。舊版 Office 檔案請在用戶端轉換為 .xlsx、.pptx 或 .docx 後上傳。",
|
||||
importSize: "請選擇非空且不超過 100 MiB (PDF/Office), 100 MiB (JPEG/PNG/WebP), 16 MiB (TXT/Markdown/HTML/SVG/CSV) 的檔案。",
|
||||
importInvalidResult: "轉換服務傳回無效結果。",
|
||||
importTimeout: "轉換等待逾時,請重新匯入此檔案。",
|
||||
importFailed: "轉換失敗。",
|
||||
@@ -2200,6 +2200,19 @@ export const zhTW = {
|
||||
batchExit: "結束批次",
|
||||
batchSelected: "已選擇 {{count}} 項",
|
||||
batchSelectAll: "全選",
|
||||
settings: {
|
||||
title: "知識庫設定",
|
||||
description: "設定知識庫模型,以及學習任務和圖片辨識的並行上限。",
|
||||
vision: "視覺模型",
|
||||
concurrency: "並行設定",
|
||||
learning: "同時執行的學習任務數",
|
||||
learningHint: "預設為 1,最多 20。調低上限不會中斷執行中的任務。",
|
||||
image: "同時辨識的圖片數",
|
||||
imageHint: "每個服務實例預設為 1,最多 20。請依模型服務的流量限制設定。",
|
||||
keepKey: "留白以保留目前的金鑰",
|
||||
embeddingHint: "儲存時會自動偵測向量維度。更換模型會重建使用該模型的知識庫向量。",
|
||||
},
|
||||
batchSelectAllFiles: "全選檔案",
|
||||
batchClear: "清除",
|
||||
batchMove: "移動到",
|
||||
batchMoveTitle: "移動到資料夾",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
export const knowledgeFileAccept = ".txt,.md,.markdown,.html,.htm,.svg,.csv,.docx,.xls,.xlsx,.pptx,.pdf,.jpg,.jpeg,.png"
|
||||
export const knowledgeFileAccept = ".txt,.md,.markdown,.html,.htm,.svg,.csv,.docx,.xlsx,.pptx,.pdf,.jpg,.jpeg,.png,.webp"
|
||||
export type ImportStage = "uploading" | "converting" | "saving" | "completed" | "failed" | "canceled"
|
||||
type ImportReply = {
|
||||
status: "pending" | "completed" | "failed"
|
||||
@@ -20,13 +20,13 @@ export type FileImport = {
|
||||
task?: string
|
||||
uploadKey?: string
|
||||
startedAt?: number
|
||||
modelID?: string
|
||||
documentID?: string
|
||||
}
|
||||
type Request = <T>(path: string, options: RequestInit) => Promise<T>
|
||||
export function validateKnowledgeFile(file: Pick<File, "name" | "size">) {
|
||||
if (!knowledgeFileAccept.split(",").includes(`.${file.name.split(".").pop()?.toLowerCase()}`)) throw new Error("importUnsupported")
|
||||
if (!file.size || file.size > 32 * 1024 * 1024) throw new Error("importSize")
|
||||
const limit = /\.(txt|md|markdown|html|htm|svg|csv)$/i.test(file.name) ? 16 : 100
|
||||
if (!file.size || file.size > limit * 1024 * 1024) throw new Error("importSize")
|
||||
}
|
||||
function delay(signal: AbortSignal, milliseconds: number) {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
@@ -39,14 +39,13 @@ function delay(signal: AbortSignal, milliseconds: number) {
|
||||
// No file contents or derived body pass through client JSON. Pending work lives
|
||||
// only in this page's memory; aborting stops subsequent polling and saving.
|
||||
export async function importKnowledgeFile(item: FileImport, path: string, request: Request, signal: AbortSignal, changed: () => void, interval = 3000) {
|
||||
const image = /\.(jpe?g|png)$/i.test(item.file.name)
|
||||
const uploadTimeout = image ? 180_000 : 120_000
|
||||
const image = /\.(jpe?g|png|webp)$/i.test(item.file.name)
|
||||
const uploadTimeout = image ? 180_000 : 15 * 60_000
|
||||
const post = <T>(action: string, body: unknown) => request<T>(`${path}/${action}`, { method: "POST", body: JSON.stringify(body), signal: AbortSignal.any([signal, AbortSignal.timeout(action === "upload" ? uploadTimeout : 120_000)]) })
|
||||
const stage = (value: ImportStage) => { item.stage = value; item.error = undefined; changed() }
|
||||
signal.throwIfAborted()
|
||||
validateKnowledgeFile(item.file)
|
||||
if (item.documentID) return
|
||||
if (image && !item.modelID) throw new Error("imageModelRequired")
|
||||
item.startedAt ??= Date.now()
|
||||
const budget = () => {
|
||||
signal.throwIfAborted()
|
||||
@@ -71,7 +70,7 @@ export async function importKnowledgeFile(item: FileImport, path: string, reques
|
||||
reply = await post<ImportReply>("query", { task_context: item.task })
|
||||
} else if (item.upload) {
|
||||
stage("converting")
|
||||
reply = await post<ImportReply>("upload", { import_context: item.upload.import_context, title: item.file.name, parent_id: item.parentID, model_id: item.modelID })
|
||||
reply = await post<ImportReply>("upload", { import_context: item.upload.import_context, title: item.file.name, parent_id: item.parentID })
|
||||
} else {
|
||||
stage("uploading")
|
||||
const form = new FormData()
|
||||
@@ -80,7 +79,6 @@ export async function importKnowledgeFile(item: FileImport, path: string, reques
|
||||
form.append("file", item.file)
|
||||
form.append("title", item.file.name)
|
||||
if (item.parentID) form.append("parent_id", item.parentID)
|
||||
if (item.modelID) form.append("model_id", item.modelID)
|
||||
reply = await request<ImportReply>(`${path}/upload`, { method: "POST", body: form, signal: AbortSignal.any([signal, AbortSignal.timeout(uploadTimeout)]) })
|
||||
}
|
||||
signal.throwIfAborted()
|
||||
|
||||
@@ -62,7 +62,6 @@ import {
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
import { Field, FieldDescription, FieldGroup, FieldLabel } from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import {
|
||||
@@ -143,19 +142,7 @@ export default function KbDetailPage() {
|
||||
const [documentMode, setDocumentMode] = useState<KbDocumentSource>("text")
|
||||
const [documentSaving, setDocumentSaving] = useState(false)
|
||||
const [fileImports, setFileImports] = useState<FileImport[]>([])
|
||||
const [hasSelectedImage, setHasSelectedImage] = useState(false)
|
||||
const [imageModels, setImageModels] = useState<{ id: string; display_name: string }[]>([])
|
||||
const [imageModelID, setImageModelID] = useState("")
|
||||
const [imageModelsError, setImageModelsError] = useState("")
|
||||
const importsRef = useRef<FileImport[]>([])
|
||||
useEffect(() => {
|
||||
if (!documentDialogOpen || documentMode !== "file") return
|
||||
const controller = new AbortController()
|
||||
api<{ items: { id: string; display_name: string }[] }>(`${base}/kb/${kbId}/imports/models`, { signal: controller.signal })
|
||||
.then(({ items }) => { setImageModels(items); setImageModelsError("") })
|
||||
.catch((error: unknown) => { if (!controller.signal.aborted) { setImageModels([]); setImageModelsError(error instanceof Error ? error.message : String(error)) } })
|
||||
return () => controller.abort()
|
||||
}, [documentDialogOpen, documentMode, kbId])
|
||||
const importController = useRef<AbortController | null>(null)
|
||||
useEffect(() => {
|
||||
const stop = () => importController.current?.abort()
|
||||
@@ -255,7 +242,6 @@ export default function KbDetailPage() {
|
||||
importController.current?.abort()
|
||||
importsRef.current = []
|
||||
setFileImports([])
|
||||
setHasSelectedImage(false)
|
||||
setDocumentMode("text")
|
||||
setEditingDocumentId(null)
|
||||
setDocumentParentId(null)
|
||||
@@ -299,7 +285,7 @@ export default function KbDetailPage() {
|
||||
if (!title || !content) return
|
||||
await saveDocument({ title, parent_id: documentParentId, source_type: "text", content, size_bytes: content.length })
|
||||
} else {
|
||||
if (!importsRef.current.length) importsRef.current = files.map((file) => ({ file, parentID: documentParentId, stage: "uploading", modelID: imageModelID }))
|
||||
if (!importsRef.current.length) importsRef.current = files.map((file) => ({ file, parentID: documentParentId, stage: "uploading" }))
|
||||
const controller = new AbortController()
|
||||
importController.current = controller
|
||||
const changed = () => setFileImports([...importsRef.current])
|
||||
@@ -308,7 +294,6 @@ export default function KbDetailPage() {
|
||||
if (controller.signal.aborted) break
|
||||
if (item.documentID) continue
|
||||
try {
|
||||
item.modelID = imageModelID
|
||||
await importKnowledgeFile(item, `${base}/kb/${kbId}/imports`, api, controller.signal, changed)
|
||||
reload()
|
||||
} catch (reason) {
|
||||
@@ -337,16 +322,18 @@ export default function KbDetailPage() {
|
||||
setBatchDeleteOpen(false)
|
||||
setBatchMoveOpen(false)
|
||||
}
|
||||
const visibleDocumentIds = useMemo(() => {
|
||||
const { visibleDocumentIds, visibleFileIds } = useMemo(() => {
|
||||
const ids: string[] = []
|
||||
const fileIds: string[] = []
|
||||
const visit = (items: KbDocument[]) => {
|
||||
items.forEach((item) => {
|
||||
ids.push(item.id)
|
||||
if (item.node_type !== "folder") fileIds.push(item.id)
|
||||
if (item.children?.length) visit(item.children)
|
||||
})
|
||||
}
|
||||
visit(visibleDocuments)
|
||||
return ids
|
||||
return { visibleDocumentIds: ids, visibleFileIds: fileIds }
|
||||
}, [visibleDocuments])
|
||||
const toggleBatchDocument = (id: string) => {
|
||||
setBatchSelectedIds((current) => toggleKbSelection(documents, current, id))
|
||||
@@ -615,6 +602,7 @@ export default function KbDetailPage() {
|
||||
<span className="text-sm text-muted-foreground">{t("pages.knowledgeBases.batchSelected", { count: batchSelectedIds.length })}</span>
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant="outline" size="sm" disabled={!visibleDocumentIds.length || batchPending} onClick={() => setBatchSelectedIds(visibleDocumentIds)}>{t("pages.knowledgeBases.batchSelectAll")}</Button>
|
||||
<Button type="button" variant="outline" size="sm" disabled={!visibleFileIds.length || batchPending} onClick={() => setBatchSelectedIds(visibleFileIds)}>{t("pages.knowledgeBases.batchSelectAllFiles")}</Button>
|
||||
<Button type="button" variant="outline" size="sm" disabled={!batchSelectedIds.length || batchPending} onClick={() => setBatchSelectedIds([])}>{t("pages.knowledgeBases.batchClear")}</Button>
|
||||
<Button type="button" variant="outline" size="sm" disabled={!batchSelectedIds.length || batchPending} onClick={() => { setBatchMoveParentId(""); setBatchMoveOpen(true) }}>{t("pages.knowledgeBases.batchMove")}</Button>
|
||||
<Button type="button" variant="outline" size="sm" disabled={!batchSelectedIds.length || batchPending} onClick={() => void submitBatch("restudy")}>{t("pages.knowledgeBases.retryLearning")}</Button>
|
||||
@@ -699,7 +687,7 @@ export default function KbDetailPage() {
|
||||
<DialogTitle>{editingDocument ? t("pages.knowledgeBases.editContentTitle") : t("pages.knowledgeBases.addContentTitle")}</DialogTitle>
|
||||
<DialogDescription>{editingDocument ? t("pages.knowledgeBases.editContentDescription") : t("pages.knowledgeBases.addContentDescription")}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Tabs value={documentMode} onValueChange={(value) => { if (!documentSaving) { setDocumentMode(value as KbDocumentSource); if (!fileImports.length) setHasSelectedImage(false) } }}>
|
||||
<Tabs value={documentMode} onValueChange={(value) => { if (!documentSaving) { setDocumentMode(value as KbDocumentSource) } }}>
|
||||
{!editingDocument && <TabsList className="w-full"><TabsTrigger value="text">{t("pages.knowledgeBases.textContent")}</TabsTrigger><TabsTrigger value="file">{t("pages.knowledgeBases.fileContent")}</TabsTrigger></TabsList>}
|
||||
<TabsContent value="text">
|
||||
<FieldGroup className="gap-4">
|
||||
@@ -707,15 +695,8 @@ export default function KbDetailPage() {
|
||||
<Field><FieldLabel htmlFor="kb-document-body">{t("pages.knowledgeBases.textContent")}</FieldLabel><Textarea id="kb-document-body" name="body" defaultValue={editingDocument?.content} required /></Field>
|
||||
</FieldGroup>
|
||||
</TabsContent>
|
||||
<TabsContent value="file"><FieldGroup><Field><FieldLabel htmlFor="kb-document-file">{t("pages.knowledgeBases.selectFile")}</FieldLabel><Input id="kb-document-file" name="file" type="file" multiple accept={knowledgeFileAccept} onChange={(event) => setHasSelectedImage(Array.from(event.currentTarget.files ?? []).some((file) => /\.(jpe?g|png)$/i.test(file.name)))} disabled={documentSaving || fileImports.length > 0} required={fileImports.length === 0} /><FieldDescription>{t("pages.knowledgeBases.importDescription")}</FieldDescription></Field>
|
||||
{hasSelectedImage && <Field>
|
||||
<FieldLabel htmlFor="kb-image-model">{t("pages.knowledgeBases.imageModel")}</FieldLabel>
|
||||
<Select value={imageModelID} onValueChange={(value) => setImageModelID(value ?? "")} disabled={documentSaving} items={imageModels.map((model) => ({ value: model.id, label: model.display_name }))}>
|
||||
<SelectTrigger id="kb-image-model" className="w-full"><SelectValue placeholder={t("pages.knowledgeBases.imageModelPlaceholder")} /></SelectTrigger>
|
||||
<SelectContent><SelectGroup>{imageModels.map((model) => <SelectItem key={model.id} value={model.id}>{model.display_name}</SelectItem>)}</SelectGroup></SelectContent>
|
||||
</Select>
|
||||
<FieldDescription>{imageModelsError || t(imageModels.length ? "pages.knowledgeBases.imageModelHint" : "pages.knowledgeBases.imageModelUnavailable")}</FieldDescription>
|
||||
</Field>}
|
||||
<TabsContent value="file"><FieldGroup><Field><FieldLabel htmlFor="kb-document-file">{t("pages.knowledgeBases.selectFile")}</FieldLabel><Input id="kb-document-file" name="file" type="file" multiple accept={knowledgeFileAccept} disabled={documentSaving || fileImports.length > 0} required={fileImports.length === 0} /><FieldDescription>{t("pages.knowledgeBases.importDescription")}</FieldDescription></Field>
|
||||
|
||||
</FieldGroup></TabsContent>
|
||||
</Tabs>
|
||||
{fileImports.length > 0 && <ul className="flex flex-col gap-2" aria-live="polite">
|
||||
|
||||
@@ -79,7 +79,7 @@ function DocumentEditorPage({
|
||||
const readOnly = !loaded?.writable
|
||||
const contentReadOnly = readOnly || loaded?.document.content_editable !== true
|
||||
const sourceEditor = ["txt", "html", "svg", "csv"].includes(loaded?.document.file_type ?? "")
|
||||
const imageDocument = Boolean(loaded?.document.has_original && ["jpg", "png"].includes(loaded.document.file_type ?? ""))
|
||||
const imageDocument = Boolean(loaded?.document.has_original && ["jpg", "png", "webp"].includes(loaded.document.file_type ?? ""))
|
||||
const previewable = ["html", "svg"].includes(loaded?.document.file_type ?? "")
|
||||
const preview = useMemo(() => {
|
||||
if (!previewable) return ""
|
||||
@@ -144,7 +144,7 @@ function DocumentEditorPage({
|
||||
)
|
||||
)
|
||||
throw new LocalizedError("pages.knowledgeBases.imageUploadInvalid", t("pages.knowledgeBases.imageUploadInvalid"))
|
||||
if (!file.size || file.size > 32 * 1024 * 1024)
|
||||
if (!file.size || file.size > 100 * 1024 * 1024)
|
||||
throw new LocalizedError("pages.knowledgeBases.imageUploadTooLarge", t("pages.knowledgeBases.imageUploadTooLarge"))
|
||||
const form = new FormData()
|
||||
form.append("file", file)
|
||||
@@ -261,7 +261,7 @@ function DocumentEditorPage({
|
||||
</span>
|
||||
)}
|
||||
{loaded?.document.has_original && <Button variant="outline" render={<a href={`${path}/file/detail`} download />}>{t("pages.knowledgeBases.downloadOriginal")}</Button>}
|
||||
{loaded?.document.has_original && ["pdf", "jpg", "png"].includes(loaded.document.file_type ?? "") && <Button variant="outline" render={<a href={`${path}/file/detail?preview=true`} target="_blank" rel="noopener noreferrer" />}>{t("pages.knowledgeBases.previewOriginal")}</Button>}
|
||||
{loaded?.document.has_original && ["pdf", "jpg", "png", "webp"].includes(loaded.document.file_type ?? "") && <Button variant="outline" render={<a href={`${path}/file/detail?preview=true`} target="_blank" rel="noopener noreferrer" />}>{t("pages.knowledgeBases.previewOriginal")}</Button>}
|
||||
{loaded?.writable && (
|
||||
<Button
|
||||
loading={saving}
|
||||
@@ -290,7 +290,7 @@ function DocumentEditorPage({
|
||||
<div data-kb-image-preview className="flex min-h-0 min-w-0 items-center justify-center overflow-auto rounded-md border p-4">
|
||||
<img src={`${path}/file/detail?preview=true`} alt={loaded.document.title} className="h-full w-full object-contain" />
|
||||
</div>
|
||||
<div data-kb-image-description className="min-h-0 min-w-0 overflow-hidden">
|
||||
<div data-kb-image-description className="min-h-0 min-w-0 overflow-hidden [&_.codeblock-toolbar]:hidden [&_.codeblock-wrapper_code]:!pt-3">
|
||||
<MarkdownEditor key={path} value={content} readOnly={contentReadOnly || saving} onChange={setContent} onSave={() => void save()} onImageUpload={uploadImage} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { KbModelSettings } from "@/components/kb-model-settings"
|
||||
import { useMemo, useState, type FormEvent } from "react"
|
||||
import {
|
||||
BookOpenTextIcon,
|
||||
@@ -220,11 +221,11 @@ export function KbPage() {
|
||||
userLabel={t("pages.knowledgeBases.userKnowledgeBase")}
|
||||
actions={
|
||||
remote.type === "system" ? (
|
||||
<Dialog open={kbDialogOpen} onOpenChange={handleKbDialogOpenChange}>
|
||||
<div className="ms-auto flex shrink-0 items-center gap-2"><KbModelSettings/><Dialog open={kbDialogOpen} onOpenChange={handleKbDialogOpenChange}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button
|
||||
className="ms-auto shrink-0"
|
||||
className="shrink-0"
|
||||
onClick={() => {
|
||||
setEditingKbId(null)
|
||||
resetKbOptions()
|
||||
@@ -349,8 +350,8 @@ export function KbPage() {
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
) : null
|
||||
</Dialog></div>
|
||||
) : <KbModelSettings/>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
|
||||
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user