{{ $t('settings.storage.defaultEngineDesc') }}
diff --git a/.air.toml b/.air.toml
index cf394665..a19ce720 100644
--- a/.air.toml
+++ b/.air.toml
@@ -5,9 +5,9 @@ tmp_dir = "tmp"
[build]
args_bin = []
bin = "./tmp/main"
- cmd = "CGO_CFLAGS='-Wno-deprecated-declarations -Wno-gnu-folding-constant' CGO_LDFLAGS='-Wl,-no_warn_duplicate_libraries' go build -ldflags=\"$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'\" -o ./tmp/main ./cmd/server"
+ cmd = "go build -ldflags=\"$(./scripts/get_version.sh ldflags) -X 'google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn'\" -o ./tmp/main ./cmd/server"
delay = 1000
- exclude_dir = ["assets", "tmp", "vendor", "testdata", "frontend", "migrations", "node_modules", "docs"]
+ exclude_dir = ["assets", "tmp", "vendor", "testdata", "frontend", "migrations", "node_modules", "docs", "logs", "data", "WeKnora-Chrome-Extension", "Formula", "dataset", "docreader", "docker", "llm_debug", "web", "mcp-server", "misc", "scripts", "dist", "client", "helm"]
exclude_file = []
exclude_regex = ["_test.go"]
exclude_unchanged = false
@@ -23,7 +23,7 @@ tmp_dir = "tmp"
poll_interval = 0
rerun = false
rerun_delay = 500
- send_interrupt = true
+ send_interrupt = false
stop_on_error = false
[color]
@@ -38,7 +38,7 @@ tmp_dir = "tmp"
time = false
[misc]
- clean_on_exit = false
+ clean_on_exit = true
[screen]
clear_on_rebuild = false
diff --git a/.dockerignore b/.dockerignore
index 0c993cf5..85084093 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,2 +1,76 @@
+# VCS / CI
+.git/
+.github/
+.gitignore
+.gitattributes
+
+# 编辑器 / IDE 本地配置
+.cursor/
+.claude/
+.codebuddy/
+.vscode/
+.idea/
+*.swp
+*.swo
+.DS_Store
+
+# Python 虚拟环境 / 缓存
**/.venv/
-**/.python-version
\ No newline at end of file
+.venv_proto/
+**/.python-version
+**/__pycache__/
+**/*.pyc
+
+# Node / 前端
+# 注意:build-ui 用的 context 是 ./frontend,根 .dockerignore 对它无效,
+# 其它镜像(app/docreader/sandbox)的 Dockerfile 都不引用 frontend/,
+# 所以这里可以直接排除整个 frontend/ 目录。
+**/node_modules/
+frontend/
+WeKnora-Chrome-Extension/
+
+# 日志 / 临时文件
+logs/
+tmp/
+temp/
+*.log
+*.pid
+
+# 本地构建产物 / 二进制
+WeKnora
+WeKnora-lite
+/server
+/dist/
+/build/
+cmd/desktop/build/bin/
+
+# 本地数据 / 模型文件
+/models/
+data/files/
+data/*.db
+data/*.db-wal
+data/*.db-shm
+test/data/mswag.txt
+
+# 敏感文件
+.env
+.env.lite
+*.pem
+*.key
+*.crt
+*_key
+*_secret
+
+# 大的归档/压缩包
+packages/protoc-*.zip
+!packages/protoc-*-linux-x86_64.zip
+!packages/protoc-*-linux-aarch_64.zip
+!packages/protoc-*-linux-arm.zip
+
+# 本地测试脚本
+configure-ollama.sh
+fix-docker.sh
+/scripts/scale_dev_jobs.sh
+
+# 注意:不要排除 docs/ —— 里面的 docs.go / swagger.json 是 Go 代码依赖的 swagger 包
+# 注意:不要用 *.md 通配排除 —— skills/preloaded/**/SKILL.md 会被打进镜像给 agent 用
diff --git a/.env.example b/.env.example
index 595153e1..7af81301 100644
--- a/.env.example
+++ b/.env.example
@@ -14,6 +14,92 @@ GIN_MODE=release
# 日志级别,可选值:debug, info, warn, error, fatal,默认为debug
# LOG_LEVEL=debug
+# LLM 调试日志:将每次大模型调用的完整请求和响应写入独立日志文件,便于排查上下文问题
+# 可选值:true(自动放在 LOG_PATH 同目录下 llm_debug.log)、false/空(关闭)、或指定文件路径
+# LLM_DEBUG_LOG=true
+
+# ========== Langfuse 可观测性(可选) ==========
+# 用于追踪 chat / embedding / rerank / VLM / ASR 模型调用,统计 token 消耗。
+# 详细说明:docs/Langfuse集成.md
+#
+# 方案 A:接入 Langfuse Cloud(最简单)
+# 1) 登录 https://cloud.langfuse.com 生成 API Key
+# 2) 填入下方 PUBLIC_KEY / SECRET_KEY
+# 3) docker compose up -d app
+#
+# 方案 B:自建 Langfuse(局域网/内网环境)
+# 1) 启动自建栈:docker compose --profile langfuse up -d
+# 首次启动后 ClickHouse 迁移约 1-2 分钟,耐心等待 langfuse-web 健康
+# 2) 浏览器打开 http://localhost:3000 注册管理员账号并生成 API Key
+# 3) 取消注释下方 LANGFUSE_HOST=http://langfuse-web:3000
+# 填入刚生成的 PUBLIC_KEY / SECRET_KEY
+# 4) docker compose up -d app
+#
+# 只要同时设置了 PUBLIC_KEY + SECRET_KEY 就会自动启用,无需显式开关。
+LANGFUSE_PUBLIC_KEY=pk-lf-xxxxxxxx
+LANGFUSE_SECRET_KEY=sk-lf-xxxxxxxx
+LANGFUSE_HOST=http://langfuse-web:3000
+# 自建模式下改成:LANGFUSE_HOST=http://langfuse-web:3000
+#
+# 可选:显式开关(true/false,默认根据 key 自动判断)
+# LANGFUSE_ENABLED=true
+# 可选:版本 / 环境标签,便于在 Langfuse UI 过滤
+# LANGFUSE_RELEASE=v0.4.2
+# LANGFUSE_ENVIRONMENT=production
+# 可选:批量上报与采样策略(生产高流量建议调大 FLUSH_AT、降低 SAMPLE_RATE)
+# LANGFUSE_FLUSH_AT=15
+# LANGFUSE_FLUSH_INTERVAL=3s
+# LANGFUSE_QUEUE_SIZE=2048
+# LANGFUSE_REQUEST_TIMEOUT=10s
+# LANGFUSE_SAMPLE_RATE=1.0
+# LANGFUSE_DEBUG=false
+
+# ========== Langfuse 自建栈配置(仅在使用 --profile langfuse 时需要) ==========
+# 设计说明:为了最小化资源占用,Langfuse 自建栈会**复用** WeKnora 已有的
+# - postgres:创建独立的 "langfuse" 数据库(由 langfuse-db-init 容器一次性创建)
+# - redis :使用独立的 Redis DB 号(默认 1,WeKnora 用 0)
+# 真正新增的只有 3 个常驻容器:langfuse-web、langfuse-worker、langfuse-clickhouse
+# + 1 个专用 S3:langfuse-minio
+# + 1 个一次性 init:langfuse-db-init
+#
+# Langfuse Web UI 对外端口
+# LANGFUSE_WEB_PORT=3000
+#
+# Langfuse 专用 MinIO 端口(避免和 WeKnora 主 MinIO 9000/9001 冲突)
+# LANGFUSE_MINIO_S3_PORT=9100
+# LANGFUSE_MINIO_CONSOLE_PORT=9101
+#
+# 在 WeKnora-postgres 中创建的 Langfuse 库名
+# LANGFUSE_DB_NAME=langfuse
+#
+# 在 WeKnora-redis 中使用的 DB 号(1~15,不要和 WeKnora 的 0 冲突)
+# LANGFUSE_REDIS_DB=1
+#
+# ClickHouse / Langfuse 专用 MinIO 凭证(生产请务必修改)
+# LANGFUSE_CLICKHOUSE_USER=clickhouse
+# LANGFUSE_CLICKHOUSE_PASSWORD=clickhouse
+# LANGFUSE_MINIO_USER=langfuseminio
+# LANGFUSE_MINIO_PASSWORD=langfuseminiosecret
+#
+# Langfuse 核心安全字段,生产必须重新生成:
+# LANGFUSE_SALT=$(openssl rand -base64 32)
+# LANGFUSE_ENCRYPTION_KEY=$(openssl rand -hex 32)
+# LANGFUSE_NEXTAUTH_SECRET=$(openssl rand -base64 32)
+# LANGFUSE_SALT=
+# LANGFUSE_ENCRYPTION_KEY=
+# LANGFUSE_NEXTAUTH_SECRET=
+# LANGFUSE_NEXTAUTH_URL=http://localhost:3000
+# LANGFUSE_TELEMETRY_ENABLED=false
+#
+# 可选:自动化首次启动(填写后直接注入管理员+项目,跳过 UI 注册)
+# LANGFUSE_INIT_ORG_NAME=WeKnora
+# LANGFUSE_INIT_PROJECT_NAME=WeKnora
+# LANGFUSE_INIT_PROJECT_PUBLIC_KEY=pk-lf-weknora-init
+# LANGFUSE_INIT_PROJECT_SECRET_KEY=sk-lf-weknora-init
+# LANGFUSE_INIT_USER_EMAIL=admin@example.com
+# LANGFUSE_INIT_USER_NAME=Admin
+# LANGFUSE_INIT_USER_PASSWORD=change-me-please
+
# 时区设置,默认为 Asia/Shanghai
# 影响系统时间显示和日志时间戳
# 常用值:Asia/Shanghai, Asia/Tokyo, America/New_York, Europe/London, UTC
@@ -303,9 +389,9 @@ DOCREADER_ADDR=docreader:50051
# Docreader 连接方式
DOCREADER_TRANSPORT=grpc
-# Docreader 中 DOCX 解析的最大页数,默认 100
-# 用于限制超大 Word 文档的解析开销;超过页数的内容将不会继续解析
-# DOCREADER_DOCX_MAX_PAGES=100
+# Docreader 中 DOCX 解析的最大页数,默认 0(不限制)
+# 设为正整数(如 500)可限制超大 Word 文档的解析开销;超过页数的内容将不会继续解析
+# DOCREADER_DOCX_MAX_PAGES=0
# 如果使用Weaviate作为向量存储,需要配置以下参数
# 注意:容器内访问请使用 service:port(不要用 localhost,也不要用宿主机映射端口)
diff --git a/.env.lite.example b/.env.lite.example
index 119a3d67..35614a8d 100644
--- a/.env.lite.example
+++ b/.env.lite.example
@@ -44,6 +44,13 @@ WEKNORA_SANDBOX_MODE=disabled
ENABLE_GRAPH_RAG=false
DISABLE_REGISTRATION=false
+# === Langfuse 可观测性(可选) ===
+# 追踪 chat / embedding / rerank / VLM / ASR 的 prompt、响应与 token 消耗。
+# 同时填了 PUBLIC_KEY 和 SECRET_KEY 就会自动启用,详见 docs/Langfuse集成.md。
+# LANGFUSE_PUBLIC_KEY=pk-lf-xxxxxxxx
+# LANGFUSE_SECRET_KEY=sk-lf-xxxxxxxx
+# LANGFUSE_HOST=https://cloud.langfuse.com
+
# === 性能 ===
CONCURRENCY_POOL_SIZE=3
diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml
index 4e43ecb9..87705fb0 100644
--- a/.github/workflows/docker-image.yml
+++ b/.github/workflows/docker-image.yml
@@ -41,8 +41,8 @@ jobs:
context: ./frontend
labels: ${{ steps.meta.outputs.labels }}
tags: ${{ steps.meta.outputs.tags }}
- cache-from: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-ui:cache
- cache-to: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-ui:cache,mode=max
+ cache-from: type=gha,scope=build-ui
+ cache-to: type=gha,scope=build-ui,mode=max
build-docreader:
runs-on: ubuntu-latest
@@ -90,8 +90,8 @@ jobs:
context: .
labels: ${{ steps.meta.outputs.labels }}
tags: ${{ steps.meta.outputs.tags }}
- cache-from: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-docreader:cache
- cache-to: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-docreader:cache,mode=max
+ cache-from: type=gha,scope=build-docreader
+ cache-to: type=gha,scope=build-docreader,mode=max
build-sandbox:
runs-on: ubuntu-latest
@@ -123,8 +123,8 @@ jobs:
context: .
labels: ${{ steps.meta.outputs.labels }}
tags: ${{ steps.meta.outputs.tags }}
- cache-from: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-sandbox:cache
- cache-to: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-sandbox:cache,mode=max
+ cache-from: type=gha,scope=build-sandbox
+ cache-to: type=gha,scope=build-sandbox,mode=max
build-app:
strategy:
@@ -187,8 +187,8 @@ jobs:
${{ format('GO_VERSION_ARG={0}', steps.version.outputs.go_version) }}
labels: ${{ steps.meta.outputs.labels }}
tags: ${{ secrets.DOCKERHUB_USERNAME }}/weknora-app
- cache-from: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-app:cache-${{ env.PLATFORM_PAIR }}
- cache-to: type=registry,ref=${{ secrets.DOCKERHUB_USERNAME }}/weknora-app:cache-${{ env.PLATFORM_PAIR }},mode=max
+ cache-from: type=gha,scope=build-app-${{ env.PLATFORM_PAIR }}
+ cache-to: type=gha,scope=build-app-${{ env.PLATFORM_PAIR }},mode=max
outputs: type=image,push-by-digest=true,name-canonical=true,push=true
- name: Export digest
diff --git a/.gitignore b/.gitignore
index bae931dc..ca0e52d4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -45,4 +45,14 @@ web/
/server
frontend/.vite
frontend/chrome-extension/
-WeKnora-Chrome-Extension
\ No newline at end of file
+WeKnora-Chrome-Extension
+packages/protoc-3.19.4-linux-x86_64.zip
+
+Claude.md
+
+# 本地测试脚本
+configure-ollama.sh
+fix-docker.sh
+
+# WeChat Mini Program local/private configuration
+miniprogram/project.private.config.json
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 281aaced..65a6b967 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,31 @@
All notable changes to this project will be documented in this file.
+## [0.5.0] - 2026-04-27
+
+### 🚀 New Features
+- **NEW**: Wiki Mode — a brand-new agent-driven Wiki knowledge system that automatically distills raw documents into interlinked markdown pages. It ships with a dedicated WikiBrowser, an interactive knowledge graph visualizing references and relationships between pages, and specialized agent tools, empowering teams to grow a structured, continuously evolving knowledge base from their own materials.
+- **NEW**: Observability — integrated Langfuse for agent ReAct loop, LLM token tracking, tool calls, and asynq pipeline tracing, providing deep visibility into agent reasoning, tool execution, and system performance.
+- **NEW**: Customizable Indexing Strategy — users can now independently toggle Vector Search, Keyword Search, Wiki, and Knowledge Graph indexing on a per-knowledge-base level.
+- **NEW**: Vector Store UI & Per-KB Binding — full frontend management interface for Vector Stores, allowing users to configure connections, test connectivity, and assign specific vector stores to different knowledge bases.
+- **NEW**: Yuque Connector — Yuque data source integration with API client, full and incremental fetch, and resource mapping, enabling seamless synchronization of Yuque documents into the knowledge base.
+- **NEW**: Built-in Agent Skills — added a preloaded `OpenMAIC Classroom` agent skill.
+- **NEW**: Agent Tools — added `json_repair` tool for agents to automatically fix and parse malformed JSON outputs.
+- **NEW**: Frontend — added copy action for model cards in settings.
+- **NEW**: Agent — added support to load all sheets from Excel files for DuckDB data analysis.
+
+### ⚡ Improvements
+- **IMPROVED**: Agent — improved tenant context handling and error reporting.
+- **IMPROVED**: Agent — updated synthesis and issue flagging instructions in system prompt.
+- **IMPROVED**: Debugging — enhanced LLM request logging and debug output (`llm_debug`) across all model providers.
+
+### 🐛 Bug Fixes
+- **FIXED**: Agent — materialized knowledge files to temp path for DuckDB to fix access issues
+- **FIXED**: Agent — removed rerank model requirement for wiki-only agents
+- **FIXED**: Docreader — whitelisted offline protoc zip packages in dockerignore
+- **FIXED**: System — changed hardcoded version to `*` comparison for new Linux version compatibility
+- **FIXED**: Setup — added output if offline protoc install package already exists
+
## [0.4.0] - 2026-04-14
### 🚀 New Features
@@ -897,6 +922,8 @@ All notable changes to this project will be documented in this file.
- Docker Compose for quick startup and service orchestration.
- MCP server support for integrating with MCP-compatible clients.
+[0.5.0]: https://github.com/Tencent/WeKnora/tree/v0.5.0
+[0.4.0]: https://github.com/Tencent/WeKnora/tree/v0.4.0
[0.3.6]: https://github.com/Tencent/WeKnora/tree/v0.3.6
[0.3.5]: https://github.com/Tencent/WeKnora/tree/v0.3.5
[0.3.4]: https://github.com/Tencent/WeKnora/tree/v0.3.4
diff --git a/README.md b/README.md
index 134cc424..22e93f3b 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,7 @@
-
+
💬 Intelligent Q&A Conversation![]() |
+ |
📖 Wiki Browser![]() |
+ 🕸️ Wiki Knowledge Graph![]() |
+
🤖 Agent Mode · Tool Call Process![]() |
+ ⚙️ Conversation Settings![]() |
+
🔭 Observability · Langfuse Tracing![]() |
+ |
Intelligent Q&A Conversation![]() |
- |
Agent Mode Tool Call Process![]() |
- |
Knowledge Base Management![]() |
- Conversation Settings![]() |
-
💬 智能问答对话![]() |
+ |
📖 Wiki 浏览器![]() |
+ 🕸️ Wiki 知识图谱![]() |
+
🤖 Agent 模式 · 工具调用过程![]() |
+ ⚙️ 对话设置![]() |
+
🔭 监控可观测性 · Langfuse Tracing![]() |
+ |
智能问答对话![]() |
- |
Agent模式工具调用过程![]() |
- |
知识库管理![]() |
- 对话设置![]() |
-
💬 インテリジェント Q&A 対話![]() |
+ |
📖 Wiki ブラウザ![]() |
+ 🕸️ Wiki ナレッジグラフ![]() |
+
🤖 Agent モード · ツール呼び出しプロセス![]() |
+ ⚙️ 対話設定![]() |
+
🔭 可観測性 · Langfuse Tracing![]() |
+ |
インテリジェントQ&A対話![]() |
- |
Agentモードツール呼び出しプロセス![]() |
- |
ナレッジベース管理![]() |
- 対話設定![]() |
-
💬 지능형 Q&A 대화![]() |
+ |
📖 Wiki 브라우저![]() |
+ 🕸️ Wiki 지식 그래프![]() |
+
🤖 Agent 모드 · 도구 호출 과정![]() |
+ ⚙️ 대화 설정![]() |
+
🔭 관측 가능성 · Langfuse Tracing![]() |
+ |
지능형 Q&A 대화![]() |
- |
Agent 모드 도구 호출 과정![]() |
- |
지식베이스 관리![]() |
- 대화 설정![]() |
-
{{ $t('agentEditor.agentType.desc') }}
+{{ agentTypePresetDescription(activeAgentTypePreset) }}
+{{ $t('agent.editor.toolsConfigDesc') }}
{{ $t('agentEditor.desc.selectTools') }}
{{ $t('agentEditor.tools.effectiveDesc') }}
+{{ $t('agentEditor.llmCallTimeout.desc') }}
+{{ $t('agentEditor.llmCallTimeout.hint') }}
+{{ $t('knowledgeEditor.indexing.description') }}
+{{ $t('knowledgeEditor.indexing.searchDesc') }}
+{{ $t('knowledgeEditor.indexing.wikiDesc') }}
+{{ $t('knowledgeEditor.indexing.graphDesc') }}
+{{ $t('knowledgeEditor.models.embeddingDesc') }}
-{{ $t('knowledgeEditor.wiki.synthesisModelTip') }}
+{{ $t('settings.storage.defaultEngineDesc') }}
{{ $t('settings.storage.localDesc') }}
+{{ $t('settings.storage.localDesc') }}
{{ $t('settings.storage.minioDesc') }}
+{{ $t('settings.storage.cosDesc') }}
+{{ $t('settings.storage.tosDesc') }}
+{{ $t('settings.storage.s3Desc') }}
+{{ $t('settings.storage.ossDesc') }}
{{ $t('settings.storage.minioDesc') }}
-{{ $t('settings.storage.localDesc') }}
{{ $t('settings.storage.minioDesc') }}
+
+
+
{{ $t('settings.storage.cosDesc') }}
{{ $t('settings.storage.console') }} ↗
{{ $t('settings.storage.docs') }} ↗
+
{{ $t('settings.storage.tosDesc') }} {{ $t('settings.storage.console') }} ↗ {{ $t('settings.storage.docs') }} ↗
+
{{ $t('settings.storage.s3Desc') }} {{ $t('settings.storage.console') }} ↗ {{ $t('settings.storage.docs') }} ↗
+
{{ $t('settings.storage.ossDesc') }} {{ $t('settings.storage.console') }} ↗ {{ $t('settings.storage.docs') }} ↗
raw html
", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + }) + f.handleJSON("/api/v2/repos/docs/502", 200, v2DocDetailResponse{ + Data: v2DocDetail{ID: 502, Title: "OK Doc", Format: "lake", Body: "# ok", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + }) + + items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"13"}), []string{"13"}) + if err != nil { + t.Fatalf("FetchAll: %v", err) + } + if len(items) != 2 { + t.Fatalf("want 2 items (placeholder + ok), got %d", len(items)) + } + var htmlPlaceholder, okItem *types.FetchedItem + for i := range items { + if items[i].ExternalID == "501" { + htmlPlaceholder = &items[i] + } + if items[i].ExternalID == "502" { + okItem = &items[i] + } + } + if htmlPlaceholder == nil || okItem == nil { + t.Fatal("missing one of the items") + } + if htmlPlaceholder.Metadata["skip_reason"] == "" { + t.Errorf("html doc should have skip_reason metadata, got %+v", htmlPlaceholder.Metadata) + } + if len(htmlPlaceholder.Content) != 0 { + t.Errorf("html placeholder should have empty Content") + } + if string(okItem.Content) != "# ok" { + t.Errorf("lake doc Content = %q, want %q", string(okItem.Content), "# ok") + } +} + +func TestConnector_FetchAll_SkipsNonDocTypes(t *testing.T) { + f := newFakeYuque() + defer f.Close() + f.handleJSON("/api/v2/repos/8/docs", 200, v2DocListResponse{Data: []v2Doc{ + {ID: 201, Type: "Sheet", Status: "1", Title: "S"}, + {ID: 202, Type: "Board", Status: "1", Title: "B"}, + {ID: 203, Type: "Thread", Status: "1", Title: "T"}, + {ID: 204, Type: "Doc", Status: "1", Title: "D", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + }}) + f.handleJSON("/api/v2/repos/docs/204", 200, v2DocDetailResponse{ + Data: v2DocDetail{ID: 204, Title: "D", Body: "text", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + }) + + items, err := NewConnector().FetchAll(context.Background(), makeDSConfig(f, []string{"8"}), []string{"8"}) + if err != nil { + t.Fatalf("FetchAll: %v", err) + } + if len(items) != 1 || items[0].ExternalID != "204" { + t.Errorf("expected only the Doc, got %+v", items) + } +} + +func TestConnector_FetchIncremental_FirstSync(t *testing.T) { + f := newFakeYuque() + defer f.Close() + f.handleJSON("/api/v2/repos/10/docs", 200, v2DocListResponse{Data: []v2Doc{ + {ID: 1, Type: "Doc", Status: "1", Title: "A", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + {ID: 2, Type: "Doc", Status: "1", Title: "B", ContentUpdatedAt: "2026-04-20T11:00:00Z"}, + }}) + f.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}}) + f.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 2, Title: "B", Body: "b", Status: "1", ContentUpdatedAt: "2026-04-20T11:00:00Z"}}) + + items, cursor, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f, []string{"10"}), nil) + if err != nil { + t.Fatalf("FetchIncremental: %v", err) + } + if len(items) != 2 { + t.Errorf("items = %d, want 2 on first sync", len(items)) + } + if cursor == nil { + t.Fatal("cursor must not be nil") + } +} + +func TestConnector_FetchIncremental_NoChanges(t *testing.T) { + f := newFakeYuque() + defer f.Close() + f.handleJSON("/api/v2/repos/10/docs", 200, v2DocListResponse{Data: []v2Doc{ + {ID: 1, Type: "Doc", Status: "1", Title: "A", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + }}) + f.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}}) + + // First sync → establish cursor + _, cursor1, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f, []string{"10"}), nil) + if err != nil { + t.Fatalf("first sync: %v", err) + } + + // Second sync with same cursor → 0 items + items, _, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f, []string{"10"}), cursor1) + if err != nil { + t.Fatalf("second sync: %v", err) + } + if len(items) != 0 { + t.Errorf("expected 0 changed items, got %d", len(items)) + } +} + +func TestConnector_FetchIncremental_ReturnsOnlyChanged(t *testing.T) { + // First sync: 2 docs, both at t0. + f1 := newFakeYuque() + f1.handleJSON("/api/v2/repos/11/docs", 200, v2DocListResponse{Data: []v2Doc{ + {ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + {ID: 2, Type: "Doc", Status: "1", Title: "B", Slug: "b", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + }}) + f1.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}}) + f1.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 2, Title: "B", Body: "b", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}}) + + _, cursor1, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f1, []string{"11"}), nil) + if err != nil { + t.Fatalf("first sync: %v", err) + } + f1.Close() + + // Second sync: doc 1 unchanged, doc 2 has a newer ContentUpdatedAt. + f2 := newFakeYuque() + defer f2.Close() + f2.handleJSON("/api/v2/repos/11/docs", 200, v2DocListResponse{Data: []v2Doc{ + {ID: 1, Type: "Doc", Status: "1", Title: "A", Slug: "a", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + {ID: 2, Type: "Doc", Status: "1", Title: "B2", Slug: "b", ContentUpdatedAt: "2026-04-20T12:00:00Z"}, + }}) + // Only doc 2's detail should be fetched; if the implementation incorrectly + // fetches doc 1, the test will still pass metadata-wise — but this handler + // makes the expected single call clear. + f2.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 2, Title: "B2", Body: "b2 updated", Status: "1", ContentUpdatedAt: "2026-04-20T12:00:00Z"}}) + + items, _, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f2, []string{"11"}), cursor1) + if err != nil { + t.Fatalf("second sync: %v", err) + } + if len(items) != 1 { + t.Fatalf("expected exactly 1 changed item, got %d: %+v", len(items), items) + } + if items[0].ExternalID != "2" { + t.Errorf("expected changed item ExternalID=2, got %q", items[0].ExternalID) + } + if string(items[0].Content) != "b2 updated" { + t.Errorf("expected refreshed body, got %q", string(items[0].Content)) + } +} + +func TestConnector_FetchIncremental_DetectsDeletion(t *testing.T) { + // First sync: 2 docs + f1 := newFakeYuque() + f1.handleJSON("/api/v2/repos/10/docs", 200, v2DocListResponse{Data: []v2Doc{ + {ID: 1, Type: "Doc", Status: "1", Title: "A", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + {ID: 2, Type: "Doc", Status: "1", Title: "B", ContentUpdatedAt: "2026-04-20T11:00:00Z"}, + }}) + f1.handleJSON("/api/v2/repos/docs/1", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 1, Title: "A", Body: "a", Status: "1", ContentUpdatedAt: "2026-04-20T10:00:00Z"}}) + f1.handleJSON("/api/v2/repos/docs/2", 200, v2DocDetailResponse{Data: v2DocDetail{ID: 2, Title: "B", Body: "b", Status: "1", ContentUpdatedAt: "2026-04-20T11:00:00Z"}}) + + _, cursor1, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f1, []string{"10"}), nil) + if err != nil { + t.Fatalf("first sync: %v", err) + } + f1.Close() + + // Second sync: doc 2 removed + f2 := newFakeYuque() + defer f2.Close() + f2.handleJSON("/api/v2/repos/10/docs", 200, v2DocListResponse{Data: []v2Doc{ + {ID: 1, Type: "Doc", Status: "1", Title: "A", ContentUpdatedAt: "2026-04-20T10:00:00Z"}, + }}) + + items, _, err := NewConnector().FetchIncremental(context.Background(), makeDSConfig(f2, []string{"10"}), cursor1) + if err != nil { + t.Fatalf("second sync: %v", err) + } + deleted := 0 + for _, it := range items { + if it.IsDeleted && it.ExternalID == "2" { + deleted++ + } + } + if deleted != 1 { + t.Errorf("expected 1 deletion for doc 2, got %d; items=%+v", deleted, items) + } +} + +func TestConnector_ListResources_ContinuesOnGroupFailure(t *testing.T) { + f := newFakeYuque() + defer f.Close() + f.mux = http.NewServeMux() + f.server.Config.Handler = f.mux + f.handleJSON("/api/v2/user", 200, v2UserResponse{Data: v2User{ID: 1, Login: "alice"}}) + f.handleJSON("/api/v2/users/alice/repos", 200, v2RepoListResponse{Data: []v2Repo{ + {ID: 10, Slug: "me", Name: "Mine", Type: "Book", Namespace: "alice/me"}, + }}) + f.handleJSON("/api/v2/users/1/groups", 200, v2GroupListResponse{Data: []v2Group{ + {ID: 100, Login: "team-ok"}, {ID: 101, Login: "team-forbidden"}, + }}) + f.handleJSON("/api/v2/groups/team-ok/repos", 200, v2RepoListResponse{Data: []v2Repo{ + {ID: 20, Slug: "ok", Name: "OK Book", Type: "Book", Namespace: "team-ok/ok"}, + }}) + // team-forbidden returns 403 — should be skipped, not abort the whole call. + f.mux.HandleFunc("/api/v2/groups/team-forbidden/repos", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"message":"forbidden"}`)) + }) + + resources, err := NewConnector().ListResources(context.Background(), makeDSConfig(f, nil)) + if err != nil { + t.Fatalf("ListResources should not fail on per-group error, got %v", err) + } + // Expect the 2 successful repos (personal + team-ok). team-forbidden is skipped. + if len(resources) != 2 { + t.Fatalf("expected 2 resources (personal + team-ok), got %d: %+v", len(resources), resources) + } + names := map[string]bool{} + for _, r := range resources { + names[r.Name] = true + } + if !names["Mine"] || !names["OK Book"] { + t.Errorf("expected Mine + OK Book, got %v", names) + } +} diff --git a/internal/datasource/connector/yuque/types.go b/internal/datasource/connector/yuque/types.go new file mode 100644 index 00000000..3ec19f2e --- /dev/null +++ b/internal/datasource/connector/yuque/types.go @@ -0,0 +1,261 @@ +// Package yuque implements the Yuque (语雀) data source connector for WeKnora. +// +// It syncs documents from personal and group knowledge bases (books/repos) into WeKnora +// knowledge bases, preserving Markdown formatting. +// +// Yuque API docs: +// - Authentication: X-Auth-Token header, personal token from https://www.yuque.com/settings/tokens +// - User: GET /api/v2/user +// - Groups: GET /api/v2/users/{id}/groups +// - Repos: GET /api/v2/users/{login}/repos, GET /api/v2/groups/{login}/repos +// - Docs: GET /api/v2/repos/{book_id}/docs (list), GET /api/v2/repos/docs/{id} (detail) +// +// Known limitations (v1): +// - Only syncs type=Doc (Sheet/Thread/Board/Table skipped) +// - Only syncs status="1" (published), drafts skipped +// - Private-book images (CDN URLs with auth) may fail to load +// - Lake editor may leave non-standard markdown (anchors, sized image attrs) +package yuque + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/Tencent/WeKnora/internal/datasource" + "github.com/Tencent/WeKnora/internal/types" +) + +// DefaultBaseURL is the Yuque public cloud API base URL. +const DefaultBaseURL = "https://www.yuque.com" + +// Config holds Yuque-specific configuration. +type Config struct { + // APIToken is a personal token from Yuque settings → tokens. + APIToken string `json:"api_token"` + + // BaseURL is the Yuque deployment base URL (default: https://www.yuque.com). + // For enterprise/private deployments, use the company's yuque domain. + BaseURL string `json:"base_url,omitempty"` +} + +// GetBaseURL returns the normalized base URL: +// - empty → DefaultBaseURL +// - missing scheme → prepend "https://" +// - trailing slash → stripped +func (c *Config) GetBaseURL() string { + url := strings.TrimSpace(c.BaseURL) + if url == "" { + return DefaultBaseURL + } + if !strings.Contains(url, "://") { + url = "https://" + url + } + url = strings.TrimRight(url, "/") + return url +} + +// parseYuqueConfig extracts and validates Yuque-specific configuration. +// Uses JSON marshal/unmarshal roundtrip (consistent with Feishu's parseFeishuConfig) +// rather than single-field type assertion, because we have multiple fields with +// optional defaults. +func parseYuqueConfig(config *types.DataSourceConfig) (*Config, error) { + if config == nil { + return nil, fmt.Errorf("%w: config is nil", datasource.ErrInvalidConfig) + } + credBytes, err := json.Marshal(config.Credentials) + if err != nil { + return nil, fmt.Errorf("marshal credentials: %w", err) + } + var cfg Config + if err := json.Unmarshal(credBytes, &cfg); err != nil { + return nil, fmt.Errorf("parse yuque credentials: %w", err) + } + if strings.TrimSpace(cfg.APIToken) == "" { + return nil, fmt.Errorf("%w: api_token is required", datasource.ErrInvalidCredentials) + } + return &cfg, nil +} + +// --- Yuque API response types --- + +// flexibleStatus accepts either a string ("1") or a number (1) for the doc +// `status` field. Yuque's OpenAPI spec declares `status` as string, but the +// runtime API returns it as an integer, so unmarshaling into a plain string +// fails with "cannot unmarshal number into Go struct field ... of type string". +// Normalizing to the textual form lets existing comparisons (e.g. != "1") keep +// working for both response shapes. +type flexibleStatus string + +func (s *flexibleStatus) UnmarshalJSON(b []byte) error { + if string(b) == "null" { + *s = "" + return nil + } + if len(b) > 0 && b[0] == '"' { + var str string + if err := json.Unmarshal(b, &str); err != nil { + return err + } + *s = flexibleStatus(str) + return nil + } + // Integer form. We decode to int64 so that floats, booleans, arrays, and + // objects fail loudly instead of being silently stringified — if Yuque + // changes the shape again, we'd rather surface a clear error than feed + // garbage to the Status == "1" comparison. + var i int64 + if err := json.Unmarshal(b, &i); err != nil { + return fmt.Errorf("flexibleStatus: expected string or integer, got %s: %w", b, err) + } + *s = flexibleStatus(strconv.FormatInt(i, 10)) + return nil +} + +// apiErrorBody is the error body shape Yuque sometimes returns on non-2xx. +type apiErrorBody struct { + Message string `json:"message"` + Status int `json:"status"` +} + +// v2UserResponse wraps GET /api/v2/user. +type v2UserResponse struct { + Data v2User `json:"data"` +} + +type v2User struct { + ID int64 `json:"id"` + Login string `json:"login"` + Name string `json:"name"` +} + +// v2GroupListResponse wraps GET /api/v2/users/{id}/groups. +type v2GroupListResponse struct { + Data []v2Group `json:"data"` +} + +type v2Group struct { + ID int64 `json:"id"` + Login string `json:"login"` + Name string `json:"name"` +} + +// v2RepoListResponse wraps GET /api/v2/users/{login}/repos and /groups/{login}/repos. +type v2RepoListResponse struct { + Data []v2Repo `json:"data"` +} + +type v2Repo struct { + ID int64 `json:"id"` + Type string `json:"type"` // "Book" | "Design" (listing filter enum; connector requests type=Book) + Slug string `json:"slug"` + Name string `json:"name"` + UserID int64 `json:"user_id"` + Namespace string `json:"namespace"` // e.g. "group_login/book_slug" + Public int `json:"public"` // 0:private, 1:public, 2:internal + Description string `json:"description"` + UpdatedAt string `json:"updated_at"` // RFC3339 string +} + +// v2DocListResponse wraps GET /api/v2/repos/{book_id}/docs. +type v2DocListResponse struct { + Meta struct { + Total int `json:"total"` + } `json:"meta"` + Data []v2Doc `json:"data"` +} + +// v2Doc is the document summary returned by the list endpoint (no body). +type v2Doc struct { + ID int64 `json:"id"` + Type string `json:"type"` // Doc / Sheet / Thread / Board / Table + Slug string `json:"slug"` + Title string `json:"title"` + BookID int64 `json:"book_id"` + UserID int64 `json:"user_id"` + Status flexibleStatus `json:"status"` // "0" draft, "1" published — API may return int or string + ContentUpdatedAt string `json:"content_updated_at"` // RFC3339 string — use for change detection + UpdatedAt string `json:"updated_at"` + WordCount int `json:"word_count"` +} + +// v2DocDetailResponse wraps GET /api/v2/repos/docs/{id}. +type v2DocDetailResponse struct { + Data v2DocDetail `json:"data"` +} + +type v2DocDetail struct { + ID int64 `json:"id"` + Type string `json:"type"` + Slug string `json:"slug"` + Title string `json:"title"` + BookID int64 `json:"book_id"` + Format string `json:"format"` // "markdown" / "lake" / "html" + Body string `json:"body"` // Markdown content + Status flexibleStatus `json:"status"` // API may return int or string + ContentUpdatedAt string `json:"content_updated_at"` + UpdatedAt string `json:"updated_at"` + WordCount int `json:"word_count"` + Book v2Repo `json:"book"` +} + +// yuqueCursor stores incremental sync state. +// Key1: book_id (string), Key2: doc_id (string), Value: content_updated_at (raw RFC3339 string) +type yuqueCursor struct { + LastSyncTime time.Time `json:"last_sync_time"` + BookDocTimes map[string]map[string]string `json:"book_doc_times,omitempty"` +} + +// parseContentUpdatedAt parses Yuque ISO 8601 timestamp (returns zero time on parse failure). +func parseContentUpdatedAt(ts string) time.Time { + if ts == "" { + return time.Time{} + } + t, err := time.Parse(time.RFC3339, ts) + if err != nil { + return time.Time{} + } + return t +} + +// sanitizeFileName removes characters that are invalid in filenames and +// truncates to a safe length at a UTF-8 rune boundary. Raw byte truncation +// would split a multi-byte codepoint (Chinese characters are 3 bytes in UTF-8) +// and produce an invalid UTF-8 string, which downstream filename validation +// (utf8.ValidString) rejects with "文件名包含非法字符". +func sanitizeFileName(name string) string { + if name == "" { + return "untitled" + } + replacer := strings.NewReplacer( + "/", "_", "\\", "_", ":", "_", "*", "_", + "?", "_", "\"", "_", "<", "_", ">", "_", "|", "_", + ) + result := replacer.Replace(name) + const maxBytes = 200 + if len(result) > maxBytes { + result = result[:maxBytes] + // Peel any trailing bytes that no longer form a complete rune. + // DecodeLastRuneInString returns (RuneError, 1) for a partial UTF-8 + // sequence — at most 3 bytes need peeling since a rune is ≤ 4 bytes. + for len(result) > 0 { + r, size := utf8.DecodeLastRuneInString(result) + if r != utf8.RuneError || size != 1 { + break + } + result = result[:len(result)-1] + } + } + return result +} + +// redactToken returns a masked form of the token for logging (never log the full token). +func redactToken(t string) string { + if len(t) < 12 { + return "***" + } + return t[:6] + "..." + t[len(t)-4:] +} diff --git a/internal/datasource/connector/yuque/types_test.go b/internal/datasource/connector/yuque/types_test.go new file mode 100644 index 00000000..1cf6510c --- /dev/null +++ b/internal/datasource/connector/yuque/types_test.go @@ -0,0 +1,176 @@ +package yuque + +import ( + "encoding/json" + "strings" + "testing" + "unicode/utf8" + + "github.com/Tencent/WeKnora/internal/types" +) + +// Yuque's runtime API returns the doc `status` field as an integer (0 or 1), +// even though its OpenAPI spec declares it as string. We tolerate both forms. +func TestV2Doc_Status_AcceptsNumberAndString(t *testing.T) { + cases := []struct { + name string + body string + want flexibleStatus + }{ + {"number 1", `{"id":1,"status":1}`, "1"}, + {"number 0", `{"id":1,"status":0}`, "0"}, + {"string 1", `{"id":1,"status":"1"}`, "1"}, + {"null", `{"id":1,"status":null}`, ""}, + {"missing", `{"id":1}`, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var d v2Doc + if err := json.Unmarshal([]byte(tc.body), &d); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if d.Status != tc.want { + t.Errorf("Status = %q, want %q", d.Status, tc.want) + } + }) + } +} + +func TestV2DocDetail_Status_AcceptsNumber(t *testing.T) { + var d v2DocDetail + if err := json.Unmarshal([]byte(`{"id":1,"status":1}`), &d); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if d.Status != "1" { + t.Errorf("Status = %q, want %q", d.Status, "1") + } +} + +func TestV2DocListResponse_Status_Number(t *testing.T) { + // Reproduces the real-world failure: + // decode response: json: cannot unmarshal number into Go struct field v2Doc.data.status of type string + body := `{"meta":{"total":1},"data":[{"id":101,"type":"Doc","status":1,"title":"hello"}]}` + var resp v2DocListResponse + if err := json.Unmarshal([]byte(body), &resp); err != nil { + t.Fatalf("unmarshal: %v", err) + } + if len(resp.Data) != 1 { + t.Fatalf("len(Data) = %d", len(resp.Data)) + } + if resp.Data[0].Status != "1" { + t.Errorf("Status = %q, want %q", resp.Data[0].Status, "1") + } +} + +// flexibleStatus deliberately rejects unexpected JSON shapes so a future Yuque +// schema drift (e.g. status becoming a float, bool, array) fails loudly rather +// than being silently stringified and bypassing the `!= "1"` filter. +func TestV2Doc_Status_RejectsUnexpectedShapes(t *testing.T) { + cases := []string{ + `{"id":1,"status":true}`, + `{"id":1,"status":1.5}`, + `{"id":1,"status":[1]}`, + `{"id":1,"status":{"x":1}}`, + } + for _, body := range cases { + t.Run(body, func(t *testing.T) { + var d v2Doc + if err := json.Unmarshal([]byte(body), &d); err == nil { + t.Errorf("expected error for %s, got Status=%q", body, d.Status) + } + }) + } +} + +func TestParseYuqueConfig(t *testing.T) { + t.Run("valid full", func(t *testing.T) { + cfg, err := parseYuqueConfig(&types.DataSourceConfig{ + Credentials: map[string]interface{}{ + "api_token": "tok-123", + "base_url": "https://company.yuque.com", + }, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if cfg.APIToken != "tok-123" { + t.Errorf("APIToken = %q, want tok-123", cfg.APIToken) + } + if cfg.BaseURL != "https://company.yuque.com" { + t.Errorf("BaseURL = %q", cfg.BaseURL) + } + }) + + t.Run("default base_url", func(t *testing.T) { + cfg, err := parseYuqueConfig(&types.DataSourceConfig{ + Credentials: map[string]interface{}{"api_token": "tok-abc"}, + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if cfg.GetBaseURL() != "https://www.yuque.com" { + t.Errorf("GetBaseURL default = %q, want https://www.yuque.com", cfg.GetBaseURL()) + } + }) + + t.Run("missing api_token", func(t *testing.T) { + _, err := parseYuqueConfig(&types.DataSourceConfig{ + Credentials: map[string]interface{}{}, + }) + if err == nil { + t.Fatal("expected error for missing api_token") + } + }) + + t.Run("nil config", func(t *testing.T) { + _, err := parseYuqueConfig(nil) + if err == nil { + t.Fatal("expected error for nil config") + } + }) +} + +func TestGetBaseURL_TrimsTrailingSlash(t *testing.T) { + c := &Config{BaseURL: "https://x.yuque.com/"} + if got := c.GetBaseURL(); got != "https://x.yuque.com" { + t.Errorf("GetBaseURL = %q, want https://x.yuque.com", got) + } +} + +func TestGetBaseURL_AddsSchemeIfMissing(t *testing.T) { + c := &Config{BaseURL: "company.yuque.com"} + if got := c.GetBaseURL(); got != "https://company.yuque.com" { + t.Errorf("GetBaseURL = %q, want https://company.yuque.com", got) + } +} + +func TestGetBaseURL_EmptyUsesDefault(t *testing.T) { + c := &Config{BaseURL: ""} + if got := c.GetBaseURL(); got != "https://www.yuque.com" { + t.Errorf("GetBaseURL = %q, want default", got) + } +} + +func TestGetBaseURL_TrimsWhitespace(t *testing.T) { + c := &Config{BaseURL: " https://x.yuque.com/ "} + if got := c.GetBaseURL(); got != "https://x.yuque.com" { + t.Errorf("GetBaseURL = %q, want https://x.yuque.com", got) + } +} + +func TestSanitizeFileName_TruncatesAtRuneBoundary(t *testing.T) { + // Long Chinese title (each 测 is 3 bytes in UTF-8). Raw byte slicing at 200 + // would split a rune and produce invalid UTF-8 that downstream filename + // validation rejects with "文件名包含非法字符". + long := strings.Repeat("测试", 100) // 600 bytes + got := sanitizeFileName(long) + if !utf8.ValidString(got) { + t.Fatalf("sanitizeFileName produced invalid UTF-8: %q", got) + } + if len(got) > 200 { + t.Errorf("len = %d, want ≤ 200", len(got)) + } + if len(got) == 0 { + t.Error("result is empty") + } +} diff --git a/internal/datasource/scheduler.go b/internal/datasource/scheduler.go index 78c40af2..455f1e6a 100644 --- a/internal/datasource/scheduler.go +++ b/internal/datasource/scheduler.go @@ -8,6 +8,7 @@ import ( "time" "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/tracing/langfuse" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/hibiken/asynq" @@ -168,6 +169,7 @@ func (s *Scheduler) triggerSync(dataSourceID string, tenantID uint64) { SyncLogID: syncLog.ID, ForceFull: false, } + langfuse.InjectTracing(ctx, payload) payloadJSON, _ := json.Marshal(payload) task := asynq.NewTask(types.TypeDataSourceSync, payloadJSON) diff --git a/internal/event/example_test.go b/internal/event/example_test.go index fea5021e..b1d4368a 100644 --- a/internal/event/example_test.go +++ b/internal/event/example_test.go @@ -25,7 +25,7 @@ func ExampleEventBus_basic() { }) _ = bus.Emit(ctx, event) - // Output: Query received: {What is RAG? session-123 map[]} + // Output: Query received: {What is RAG? session-123 map[]} } // Example: Using middleware diff --git a/internal/handler/custom_agent.go b/internal/handler/custom_agent.go index 4bb54d8e..136bc047 100644 --- a/internal/handler/custom_agent.go +++ b/internal/handler/custom_agent.go @@ -166,8 +166,26 @@ func (h *CustomAgentHandler) ListAgents(c *gin.Context) { } // Per-tenant "disabled by me" for own agents (only affects this tenant's conversation dropdown) - tenantID, _ := c.Get(types.TenantIDContextKey.String()) - disabledOwnIDs, _ := h.disabledRepo.ListDisabledOwnAgentIDs(ctx, tenantID.(uint64)) + tenantIDVal, exists := c.Get(types.TenantIDContextKey.String()) + if !exists { + logger.Error(ctx, "Tenant ID not found in context") + c.Error(errors.NewUnauthorizedError("Missing tenant context")) + return + } + tenantID, ok := tenantIDVal.(uint64) + if !ok { + logger.Errorf(ctx, "Tenant ID has unexpected type %T in context", tenantIDVal) + c.Error(errors.NewInternalServerError("Invalid tenant context type")) + return + } + disabledOwnIDs, err := h.disabledRepo.ListDisabledOwnAgentIDs(ctx, tenantID) + if err != nil { + logger.ErrorWithFields(ctx, err, map[string]interface{}{ + "tenant_id": tenantID, + }) + c.Error(errors.NewInternalServerError("Failed to list disabled agent IDs: " + err.Error())) + return + } c.JSON(http.StatusOK, gin.H{ "success": true, @@ -379,6 +397,25 @@ func (h *CustomAgentHandler) GetPlaceholders(c *gin.Context) { }) } +// GetAgentTypePresets godoc +// @Summary 获取智能体类型预设列表 +// @Description 返回所有 smart-reasoning 下可用的智能体类型预设(RAG/Wiki/Hybrid/Custom),用于编辑器自动填充系统提示词、工具和 KB 兼容性 +// @Tags 智能体 +// @Accept json +// @Produce json +// @Success 200 {object} map[string]interface{} "预设列表" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /agents/type-presets [get] +func (h *CustomAgentHandler) GetAgentTypePresets(c *gin.Context) { + ctx := c.Request.Context() + presets := types.ListAgentTypePresetsWithContext(ctx) + c.JSON(http.StatusOK, gin.H{ + "success": true, + "data": presets, + }) +} + // GetSuggestedQuestions godoc // @Summary 获取推荐问题 // @Description 基于智能体关联的知识库,返回推荐问题供用户快捷提问 diff --git a/internal/handler/initialization.go b/internal/handler/initialization.go index b1ab8c82..e6d8e611 100644 --- a/internal/handler/initialization.go +++ b/internal/handler/initialization.go @@ -89,7 +89,7 @@ func NewInitializationHandler( // KBModelConfigRequest 知识库模型配置请求(简化版,只传模型ID) type KBModelConfigRequest struct { LLMModelID string `json:"llmModelId" binding:"required"` - EmbeddingModelID string `json:"embeddingModelId" binding:"required"` + EmbeddingModelID string `json:"embeddingModelId"` // optional when RAG indexing is disabled VLMConfig *types.VLMConfig `json:"vlm_config"` ASRConfig *types.ASRConfig `json:"asr_config"` @@ -236,7 +236,7 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) { } // 检查Embedding模型是否可以修改 - if kb.EmbeddingModelID != "" && kb.EmbeddingModelID != req.EmbeddingModelID { + if kb.EmbeddingModelID != "" && req.EmbeddingModelID != "" && kb.EmbeddingModelID != req.EmbeddingModelID { // 检查是否已有文件 knowledgeList, err := h.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbIdStr, &types.Pagination{ @@ -258,16 +258,21 @@ func (h *InitializationHandler) UpdateKBConfig(c *gin.Context) { return } - embeddingModel, err := h.modelService.GetModelByID(ctx, req.EmbeddingModelID) - if err != nil || embeddingModel == nil { - logger.Error(ctx, "Embedding model not found") - c.Error(errors.NewBadRequestError("Embedding模型不存在")) - return + // Embedding模型仅在需要时验证(RAG检索启用时) + if req.EmbeddingModelID != "" { + embeddingModel, err := h.modelService.GetModelByID(ctx, req.EmbeddingModelID) + if err != nil || embeddingModel == nil { + logger.Error(ctx, "Embedding model not found") + c.Error(errors.NewBadRequestError("Embedding模型不存在")) + return + } } // 更新知识库的模型ID kb.SummaryModelID = req.LLMModelID - kb.EmbeddingModelID = req.EmbeddingModelID + if req.EmbeddingModelID != "" { + kb.EmbeddingModelID = req.EmbeddingModelID + } // 处理多模态模型配置 kb.VLMConfig = types.VLMConfig{} @@ -1467,12 +1472,76 @@ func (h *InitializationHandler) buildConfigResponse(ctx context.Context, models return config } -// RemoteModelCheckRequest 远程模型检查请求结构 -type RemoteModelCheckRequest struct { - ModelName string `json:"modelName" binding:"required"` - BaseURL string `json:"baseUrl" binding:"required"` - APIKey string `json:"apiKey"` - Provider string `json:"provider"` +// ModelTestRequest 统一的"测试连接"请求体。 +// +// 四种模型(chat/embedding/rerank/asr)的测试接口共享同一份结构,以便: +// - 前端只需维护一份表单 → 后端映射。 +// - 后端可以直接把请求转成 *types.Model,再调用各包的 ConfigFromModel, +// 与生产路径(service.modelService.GetXxxModel)走完全相同的装配流程, +// 彻底消除过去每个测试端点手工拼 Config 的样板代码。 +// +// 所有 provider/model 通用字段都在这里集中声明;若未来新增字段(比如现在的 +// custom_headers),只需改一处,生产路径和测试路径会同时生效。 +type ModelTestRequest struct { + Source string `json:"source"` // 为空时按需默认为 "remote" + ModelName string `json:"modelName" binding:"required"` + BaseURL string `json:"baseUrl"` + APIKey string `json:"apiKey"` + Provider string `json:"provider"` + InterfaceType string `json:"interfaceType,omitempty"` + Dimension int `json:"dimension,omitempty"` + CustomHeaders map[string]string `json:"customHeaders,omitempty"` + ExtraConfig map[string]string `json:"extraConfig,omitempty"` +} + +// RemoteModelCheckRequest 兼容旧 swagger 定义。 +// +// Deprecated: 保留是为了不破坏已生成的 API 文档,新代码请直接使用 ModelTestRequest。 +type RemoteModelCheckRequest = ModelTestRequest + +// buildTestModel 把测试连接请求转成一个临时的 *types.Model(不落库), +// 供 ConfigFromModel 使用。source 为空时按 defaultSource 兜底(chat/rerank/asr +// 默认 remote,embedding 会根据前端传入的 source 决定)。 +func (h *InitializationHandler) buildTestModel( + req *ModelTestRequest, modelType types.ModelType, defaultSource types.ModelSource, +) *types.Model { + source := types.ModelSource(strings.ToLower(req.Source)) + if source == "" { + source = defaultSource + } + return &types.Model{ + Name: req.ModelName, + Type: modelType, + Source: source, + Parameters: types.ModelParameters{ + BaseURL: req.BaseURL, + APIKey: req.APIKey, + Provider: req.Provider, + InterfaceType: req.InterfaceType, + ExtraConfig: req.ExtraConfig, + CustomHeaders: req.CustomHeaders, + EmbeddingParameters: types.EmbeddingParameters{ + Dimension: req.Dimension, + TruncatePromptTokens: 256, + }, + }, + } +} + +// resolveTenantWeKnoraCloudCreds 从当前租户上下文里取出 WeKnoraCloud 凭证, +// 供测试连接端点补齐 appID/appSecret。与 service.resolveWeKnoraCloudCredentials +// 对应,但因为 handler 还没有被注入 tenantService(历史原因),暂时从 +// TenantInfoFromContext 读取,等效果相同。 +func (h *InitializationHandler) resolveTenantWeKnoraCloudCreds(ctx context.Context) (string, string, bool) { + tenantInfo, ok := types.TenantInfoFromContext(ctx) + if !ok { + return "", "", false + } + creds := tenantInfo.Credentials.GetWeKnoraCloud() + if creds == nil { + return "", "", true + } + return creds.AppID, creds.AppSecret, true } // CheckRemoteModel godoc @@ -1492,54 +1561,33 @@ func (h *InitializationHandler) CheckRemoteModel(c *gin.Context) { logger.Info(ctx, "Checking remote model connection") - var req RemoteModelCheckRequest + var req ModelTestRequest if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to parse remote model check request", err) c.Error(errors.NewBadRequestError(err.Error())) return } - // 验证请求参数 if req.ModelName == "" || req.BaseURL == "" { logger.Error(ctx, "Model name and base URL are required") c.Error(errors.NewBadRequestError("模型名称和Base URL不能为空")) return } - // SSRF validation if err := utils.ValidateURLForSSRF(req.BaseURL); err != nil { logger.Warnf(ctx, "SSRF validation failed for remote model BaseURL: %v", err) c.Error(errors.NewBadRequestError(fmt.Sprintf("Base URL 未通过安全校验: %v", err))) return } - tenantInfo, ok := types.TenantInfoFromContext(ctx) + appID, appSecret, ok := h.resolveTenantWeKnoraCloudCreds(ctx) if !ok { logger.Error(ctx, "Tenant info not found") c.Error(errors.NewBadRequestError("租户信息未找到")) return } - var appID, appSecret string - if creds := tenantInfo.Credentials.GetWeKnoraCloud(); creds != nil { - appID = creds.AppID - appSecret = creds.AppSecret - } - // 创建模型配置进行测试 - modelConfig := &types.Model{ - Name: req.ModelName, - Source: "remote", - Parameters: types.ModelParameters{ - BaseURL: req.BaseURL, - APIKey: req.APIKey, - Provider: req.Provider, - AppID: appID, - AppSecret: appSecret, - }, - Type: "llm", // 默认类型,实际检查时不区分具体类型 - } - - // 检查远程模型连接 - available, message := h.checkRemoteModelConnection(ctx, modelConfig) + model := h.buildTestModel(&req, types.ModelTypeKnowledgeQA, types.ModelSourceRemote) + available, message := h.checkChatModelConnection(ctx, model, appID, appSecret) logger.Infof(ctx, "Remote model check completed, available: %v, message: %s", available, message) @@ -1569,22 +1617,16 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) { logger.Info(ctx, "Testing embedding model connectivity and functionality") - var req struct { - Source string `json:"source" binding:"required"` - ModelName string `json:"modelName" binding:"required"` - BaseURL string `json:"baseUrl"` - APIKey string `json:"apiKey"` - Dimension int `json:"dimension"` - Provider string `json:"provider"` - } - + var req ModelTestRequest if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to parse embedding test request", err) c.Error(errors.NewBadRequestError(err.Error())) return } + if req.Source == "" { + req.Source = string(types.ModelSourceRemote) + } - // SSRF validation for embedding BaseURL if req.BaseURL != "" { if err := utils.ValidateURLForSSRF(req.BaseURL); err != nil { logger.Warnf(ctx, "SSRF validation failed for embedding BaseURL: %v", err) @@ -1593,7 +1635,7 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) { } } - // 检查是否是阿里云多模态 embedding 模型(暂不支持) + // 阿里云多模态 Embedding 模型暂不支持 if strings.ToLower(req.Provider) == "aliyun" { modelNameLower := strings.ToLower(req.ModelName) if strings.Contains(modelNameLower, "vision") || strings.Contains(modelNameLower, "multimodal") { @@ -1609,33 +1651,16 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) { return } } - tenantInfo, ok := types.TenantInfoFromContext(ctx) + + appID, appSecret, ok := h.resolveTenantWeKnoraCloudCreds(ctx) if !ok { logger.Error(ctx, "Tenant info not found") c.Error(errors.NewBadRequestError("租户信息未找到")) return } - var appID, appSecret string - if creds := tenantInfo.Credentials.GetWeKnoraCloud(); creds != nil { - appID = creds.AppID - appSecret = creds.AppSecret - } - // 构造 embedder 配置 - cfg := embedding.Config{ - Source: types.ModelSource(strings.ToLower(req.Source)), - BaseURL: req.BaseURL, - ModelName: req.ModelName, - APIKey: req.APIKey, - TruncatePromptTokens: 256, - Dimensions: req.Dimension, - ModelID: "", - Provider: req.Provider, - AppID: appID, - AppSecret: appSecret, - } - - emb, err := embedding.NewEmbedder(cfg, h.pooler, h.ollamaService) + model := h.buildTestModel(&req, types.ModelTypeEmbedding, types.ModelSourceRemote) + emb, err := embedding.NewEmbedder(embedding.ConfigFromModel(model, appID, appSecret), h.pooler, h.ollamaService) if err != nil { logger.ErrorWithFields(ctx, err, map[string]interface{}{"model": utils.SanitizeForLog(req.ModelName)}) c.JSON(http.StatusOK, gin.H{ @@ -1645,11 +1670,9 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) { return } - // 执行一次最小化 embedding 调用 - sample := "hello" - vec, err := emb.Embed(ctx, sample) + vec, err := emb.Embed(ctx, "hello") if err != nil { - logger.Error(ctx, "Failed to create embedder", err) + logger.Error(ctx, "Failed to call embedder", err) c.JSON(http.StatusOK, gin.H{ "success": true, "data": gin.H{`available`: false, `message`: fmt.Sprintf("调用Embedding失败: %v", err), `dimension`: 0}, @@ -1664,44 +1687,23 @@ func (h *InitializationHandler) TestEmbeddingModel(c *gin.Context) { }) } -// checkRemoteModelConnection 检查远程模型连接的内部方法 -func (h *InitializationHandler) checkRemoteModelConnection(ctx context.Context, - model *types.Model, +// checkChatModelConnection 使用 chat 模块做一次最小化调用来测试连通性与鉴权。 +// 与生产路径走完全相同的 ConfigFromModel → NewChat 流程,因此 CustomHeaders、 +// ExtraConfig、Provider 等字段都会被正确透传。 +func (h *InitializationHandler) checkChatModelConnection( + ctx context.Context, model *types.Model, appID, appSecret string, ) (bool, string) { - // 使用 models/chat 进行连接检查 - // 创建聊天配置 - chatConfig := &chat.ChatConfig{ - Source: types.ModelSourceRemote, - BaseURL: model.Parameters.BaseURL, - ModelName: model.Name, - APIKey: model.Parameters.APIKey, - ModelID: model.Name, - Provider: model.Parameters.Provider, - AppID: model.Parameters.AppID, - AppSecret: model.Parameters.AppSecret, - } - - // 创建聊天实例 - chatInstance, err := chat.NewChat(chatConfig, h.ollamaService) + chatInstance, err := chat.NewChat(chat.ConfigFromModel(model, appID, appSecret), h.ollamaService) if err != nil { return false, fmt.Sprintf("创建聊天实例失败: %v", err) } - // 构造测试消息 - testMessages := []chat.Message{ - { - Role: "user", - Content: "test", - }, - } - - // 构造测试选项 + testMessages := []chat.Message{{Role: "user", Content: "test"}} testOptions := &chat.ChatOptions{ MaxTokens: 1, Thinking: &[]bool{false}[0], // for dashscope.aliyuncs qwen3-32b } - // 使用聊天实例进行测试 _, err = chatInstance.Chat(ctx, testMessages, testOptions) if err != nil { errMsg := err.Error() @@ -1727,54 +1729,24 @@ func (h *InitializationHandler) checkRemoteModelConnection(ctx context.Context, return true, "连接正常,模型可用" } -// checkRerankModelConnection 检查Rerank模型连接和功能的内部方法 -func (h *InitializationHandler) checkRerankModelConnection(ctx context.Context, - modelName, baseURL, apiKey string, +// checkRerankModelConnection 使用 rerank 模块做一次最小化调用来测试连通性与鉴权。 +// 与生产路径共用 ConfigFromModel,所有字段(CustomHeaders 等)都透传。 +func (h *InitializationHandler) checkRerankModelConnection( + ctx context.Context, model *types.Model, appID, appSecret string, ) (bool, string) { - // 创建Reranker配置 - config := &rerank.RerankerConfig{ - APIKey: apiKey, - BaseURL: baseURL, - ModelName: modelName, - Source: types.ModelSourceRemote, // 默认值,实际会根据URL判断 - } - tenantInfo, ok := types.TenantInfoFromContext(ctx) - if !ok { - logger.Error(ctx, "Tenant info not found") - return false, "租户信息未找到" - } - var appID, appSecret string - if creds := tenantInfo.Credentials.GetWeKnoraCloud(); creds != nil { - appID = creds.AppID - appSecret = creds.AppSecret - } - config.AppID = appID - config.AppSecret = appSecret - - // 创建Reranker实例 - reranker, err := rerank.NewReranker(config) + reranker, err := rerank.NewReranker(rerank.ConfigFromModel(model, appID, appSecret)) if err != nil { return false, fmt.Sprintf("创建Reranker失败: %v", err) } - // 简化的测试数据 - testQuery := "ping" - testDocuments := []string{ - "pong", - } - - // 使用Reranker进行测试 - results, err := reranker.Rerank(ctx, testQuery, testDocuments) + results, err := reranker.Rerank(ctx, "ping", []string{"pong"}) if err != nil { return false, fmt.Sprintf("重排测试失败: %v", err) } - - // 检查结果 if len(results) > 0 { return true, fmt.Sprintf("重排功能正常,返回%d个结果", len(results)) - } else { - return false, "重排接口连接成功,但未返回重排结果" } + return false, "重排接口连接成功,但未返回重排结果" } // CheckRerankModel godoc @@ -1794,36 +1766,34 @@ func (h *InitializationHandler) CheckRerankModel(c *gin.Context) { logger.Info(ctx, "Checking rerank model connection and functionality") - var req struct { - ModelName string `json:"modelName" binding:"required"` - BaseURL string `json:"baseUrl" binding:"required"` - APIKey string `json:"apiKey"` - } - + var req ModelTestRequest if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to parse rerank model check request", err) c.Error(errors.NewBadRequestError(err.Error())) return } - // 验证请求参数 if req.ModelName == "" || req.BaseURL == "" { logger.Error(ctx, "Model name and base URL are required") c.Error(errors.NewBadRequestError("模型名称和Base URL不能为空")) return } - // SSRF validation if err := utils.ValidateURLForSSRF(req.BaseURL); err != nil { logger.Warnf(ctx, "SSRF validation failed for rerank BaseURL: %v", err) c.Error(errors.NewBadRequestError(fmt.Sprintf("Base URL 未通过安全校验: %v", err))) return } - // 检查Rerank模型连接和功能 - available, message := h.checkRerankModelConnection( - ctx, req.ModelName, req.BaseURL, req.APIKey, - ) + appID, appSecret, ok := h.resolveTenantWeKnoraCloudCreds(ctx) + if !ok { + logger.Error(ctx, "Tenant info not found") + c.Error(errors.NewBadRequestError("租户信息未找到")) + return + } + + model := h.buildTestModel(&req, types.ModelTypeRerank, types.ModelSourceRemote) + available, message := h.checkRerankModelConnection(ctx, model, appID, appSecret) logger.Infof(ctx, "Rerank model check completed, available: %v, message: %s", available, message) @@ -1853,12 +1823,7 @@ func (h *InitializationHandler) CheckASRModel(c *gin.Context) { logger.Info(ctx, "Checking ASR model connection") - var req struct { - ModelName string `json:"modelName" binding:"required"` - BaseURL string `json:"baseUrl" binding:"required"` - APIKey string `json:"apiKey"` - } - + var req ModelTestRequest if err := c.ShouldBindJSON(&req); err != nil { logger.Error(ctx, "Failed to parse ASR model check request", err) c.Error(errors.NewBadRequestError(err.Error())) @@ -1871,20 +1836,16 @@ func (h *InitializationHandler) CheckASRModel(c *gin.Context) { return } - // SSRF validation if err := utils.ValidateURLForSSRF(req.BaseURL); err != nil { logger.Warnf(ctx, "SSRF validation failed for ASR BaseURL: %v", err) c.Error(errors.NewBadRequestError(fmt.Sprintf("Base URL 未通过安全校验: %v", err))) return } - // 使用 ASR 模块测试连接:发送一段极短的静默 WAV 音频 - asrInstance, err := asr.NewASR(&asr.Config{ - BaseURL: req.BaseURL, - ModelName: req.ModelName, - APIKey: req.APIKey, - Source: "remote", - }) + // 用统一构造器生成测试用 *types.Model(ASR 不涉及 WeKnoraCloud 凭证), + // 发送一段极短的静默 WAV 音频验证 /v1/audio/transcriptions 端点可达。 + model := h.buildTestModel(&req, types.ModelTypeASR, types.ModelSourceRemote) + asrInstance, err := asr.NewASR(asr.ConfigFromModel(model)) if err != nil { logger.Errorf(ctx, "Failed to create ASR instance for check: %v", err) c.JSON(http.StatusOK, gin.H{ diff --git a/internal/handler/knowledge.go b/internal/handler/knowledge.go index 517abfbf..116cd959 100644 --- a/internal/handler/knowledge.go +++ b/internal/handler/knowledge.go @@ -13,10 +13,12 @@ import ( goerrors "errors" + "github.com/Tencent/WeKnora/internal/agent/tools" "github.com/Tencent/WeKnora/internal/application/repository" "github.com/Tencent/WeKnora/internal/application/service" "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/tracing/langfuse" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/Tencent/WeKnora/internal/utils" @@ -185,6 +187,29 @@ func (h *KnowledgeHandler) handleDuplicateKnowledgeError(c *gin.Context, return false } +// enqueueKnowledgeListDelete enqueues an async batch-delete task for the +// given knowledge IDs and returns the asynq task ID. +func (h *KnowledgeHandler) enqueueKnowledgeListDelete( + ctx context.Context, tenantID uint64, ids []string, +) (string, error) { + payload := types.KnowledgeListDeletePayload{ + TenantID: tenantID, + KnowledgeIDs: ids, + } + langfuse.InjectTracing(ctx, &payload) + payloadBytes, err := json.Marshal(payload) + if err != nil { + return "", fmt.Errorf("marshal payload: %w", err) + } + task := asynq.NewTask(types.TypeKnowledgeListDelete, payloadBytes, + asynq.Queue("low"), asynq.MaxRetry(3)) + info, err := h.asynqClient.Enqueue(task) + if err != nil { + return "", fmt.Errorf("enqueue task: %w", err) + } + return info.ID, nil +} + // CreateKnowledgeFromFile godoc // @Summary 从文件创建知识 // @Description 上传文件并创建知识条目 @@ -627,6 +652,112 @@ func (h *KnowledgeHandler) DeleteKnowledge(c *gin.Context) { }) } +// BatchDeleteKnowledgeRequest is the body schema for POST /knowledge/batch-delete. +type BatchDeleteKnowledgeRequest struct { + KBID string `json:"kb_id" binding:"required"` + IDs []string `json:"ids" binding:"required"` +} + +// BatchDeleteKnowledge godoc +// @Summary 批量删除知识 +// @Description 按 ID 列表批量删除单个知识库下的多个知识条目 +// @Tags 知识管理 +// @Accept json +// @Produce json +// @Param request body BatchDeleteKnowledgeRequest true "批量删除请求" +// @Success 200 {object} map[string]interface{} "删除成功" +// @Failure 400 {object} errors.AppError "请求参数错误" +// @Failure 403 {object} errors.AppError "权限不足" +// @Security Bearer +// @Security ApiKeyAuth +// @Router /knowledge/batch-delete [post] +func (h *KnowledgeHandler) BatchDeleteKnowledge(c *gin.Context) { + ctx := c.Request.Context() + + var req BatchDeleteKnowledgeRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.Error(errors.NewBadRequestError("Invalid request parameters: " + err.Error())) + return + } + + // Deduplicate and drop empty IDs. + seen := make(map[string]struct{}, len(req.IDs)) + ids := make([]string, 0, len(req.IDs)) + for _, raw := range req.IDs { + id := strings.TrimSpace(raw) + if id == "" { + continue + } + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + ids = append(ids, id) + } + if len(ids) == 0 { + c.Error(errors.NewBadRequestError("ids cannot be empty")) + return + } + const maxBatch = 200 + if len(ids) > maxBatch { + c.Error(errors.NewBadRequestError(fmt.Sprintf("too many ids (max %d per batch)", maxBatch))) + return + } + + // Validate KB access (editor or admin) using the kb_id from body. + _, kbID, effectiveTenantID, permission, err := h.validateKnowledgeBaseAccessWithKBID(c, req.KBID) + if err != nil { + c.Error(err) + return + } + if permission != types.OrgRoleAdmin && permission != types.OrgRoleEditor { + c.Error(errors.NewForbiddenError("No permission to delete knowledge")) + return + } + ctx = context.WithValue(ctx, types.TenantIDContextKey, effectiveTenantID) + + // Single batch fetch to validate that every id exists and belongs to the + // requested KB. The service-layer DeleteKnowledgeList only enforces tenant + // scope, not KB scope, so the handler must guard against cross-KB deletion. + knowledgeList, err := h.kgService.GetKnowledgeBatch(ctx, effectiveTenantID, ids) + if err != nil { + logger.ErrorWithFields(ctx, err, nil) + c.Error(errors.NewInternalServerError(err.Error())) + return + } + if len(knowledgeList) != len(ids) { + c.Error(errors.NewBadRequestError("One or more knowledge entries not found")) + return + } + for _, k := range knowledgeList { + if k.KnowledgeBaseID != kbID { + c.Error(errors.NewBadRequestError( + fmt.Sprintf("Knowledge %s does not belong to knowledge base %s", + secutils.SanitizeForLog(k.ID), secutils.SanitizeForLog(kbID)))) + return + } + } + + taskID, err := h.enqueueKnowledgeListDelete(ctx, effectiveTenantID, ids) + if err != nil { + logger.Errorf(ctx, "Failed to enqueue batch knowledge delete task: %v", err) + c.Error(errors.NewInternalServerError("Failed to enqueue batch delete task")) + return + } + + logger.Infof(ctx, "Batch knowledge delete task enqueued: %s, kb_id: %s, count: %d", + taskID, secutils.SanitizeForLog(kbID), len(ids)) + + c.JSON(http.StatusOK, gin.H{ + "success": true, + "message": "Batch delete task submitted", + "data": gin.H{ + "task_id": taskID, + "deleted_count": len(ids), + }, + }) +} + // ClearKnowledgeBaseContents godoc // @Summary 清空知识库内容 // @Description 删除知识库下的所有知识条目(异步任务)。知识库本身保留,仅清空其中的内容 @@ -681,20 +812,7 @@ func (h *KnowledgeHandler) ClearKnowledgeBaseContents(c *gin.Context) { knowledgeIDs = append(knowledgeIDs, knowledge.ID) } - payload := types.KnowledgeListDeletePayload{ - TenantID: effectiveTenantID, - KnowledgeIDs: knowledgeIDs, - } - payloadBytes, err := json.Marshal(payload) - if err != nil { - logger.Errorf(ctx, "Failed to marshal knowledge list delete payload: %v", err) - c.Error(errors.NewInternalServerError("Failed to create cleanup task")) - return - } - - task := asynq.NewTask(types.TypeKnowledgeListDelete, payloadBytes, - asynq.Queue("low"), asynq.MaxRetry(3)) - info, err := h.asynqClient.Enqueue(task) + taskID, err := h.enqueueKnowledgeListDelete(ctx, effectiveTenantID, knowledgeIDs) if err != nil { logger.Errorf(ctx, "Failed to enqueue knowledge list delete task: %v", err) c.Error(errors.NewInternalServerError("Failed to enqueue cleanup task")) @@ -702,7 +820,7 @@ func (h *KnowledgeHandler) ClearKnowledgeBaseContents(c *gin.Context) { } logger.Infof(ctx, "Knowledge base contents clear task enqueued: %s, kb_id: %s, count: %d", - info.ID, secutils.SanitizeForLog(kbID), len(knowledgeIDs)) + taskID, secutils.SanitizeForLog(kbID), len(knowledgeIDs)) c.JSON(http.StatusOK, gin.H{ "success": true, @@ -1397,10 +1515,25 @@ func (h *KnowledgeHandler) SearchKnowledge(c *gin.Context) { c.Error(errors.NewInternalServerError("Failed to list knowledge bases").WithDetails(err.Error())) return } + // `all` mode: authoritative server-side capability filter. Mirrors the + // logic in ListKnowledgeBases so @file search, KB listing, and runtime + // all agree on what "mode=all" actually means for this agent. + filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools) + removed := 0 for _, kb := range kbs { - if kb != nil && kb.Type == types.KnowledgeBaseTypeDocument { - scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kb.ID}) + if kb == nil || kb.Type != types.KnowledgeBaseTypeDocument { + continue } + if !filter.IsEmpty() && !tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) { + removed++ + continue + } + scopes = append(scopes, types.KnowledgeSearchScope{TenantID: sourceTenantID, KBID: kb.ID}) + } + if removed > 0 { + logger.Infof(ctx, + "SearchKnowledge(agent=%s, mode=all): tool-capability filter removed %d KBs", + agentID, removed) } } knowledges, hasMore, err := h.kgService.SearchKnowledgeForScopes(ctx, scopes, keyword, offset, limit, fileTypes) @@ -1543,6 +1676,7 @@ func (h *KnowledgeHandler) MoveKnowledge(c *gin.Context) { TargetKBID: req.TargetKBID, Mode: req.Mode, } + langfuse.InjectTracing(ctx, &payload) payloadBytes, err := json.Marshal(payload) if err != nil { diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go index 94e0b44e..394e50f7 100644 --- a/internal/handler/knowledgebase.go +++ b/internal/handler/knowledgebase.go @@ -8,11 +8,13 @@ import ( "strings" "time" + "github.com/Tencent/WeKnora/internal/agent/tools" "github.com/Tencent/WeKnora/internal/application/repository" "github.com/Tencent/WeKnora/internal/application/service" "github.com/Tencent/WeKnora/internal/errors" apperrors "github.com/Tencent/WeKnora/internal/errors" "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/tracing/langfuse" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/Tencent/WeKnora/internal/utils" @@ -352,6 +354,30 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) { } kbs = filtered } + + // `all` mode: authoritative server-side capability filter so a client + // that bypassed the frontend (old tab, curl, rogue plugin) can't @ a + // KB whose capabilities don't match any allowed tool of this agent. + // Non-`all` modes already constrain the scope explicitly. + if mode == "all" && len(agent.Config.AllowedTools) > 0 { + filter := tools.DeriveKBFilterFromTools(agent.Config.AllowedTools) + if !filter.IsEmpty() { + before := len(kbs) + kept := make([]*types.KnowledgeBase, 0, before) + for _, kb := range kbs { + if tools.KBSatisfiesToolRequirements(kb.Capabilities(), agent.Config.AllowedTools) { + kept = append(kept, kb) + } + } + if removed := before - len(kept); removed > 0 { + logger.Infof(ctx, + "ListKnowledgeBases(agent=%s, mode=all): tool-capability filter removed %d of %d KBs", + agentID, removed, before) + } + kbs = kept + } + } + c.JSON(http.StatusOK, gin.H{ "success": true, "data": kbs, @@ -636,6 +662,7 @@ func (h *KnowledgeBaseHandler) CopyKnowledgeBase(c *gin.Context) { SourceID: req.SourceID, TargetID: req.TargetID, } + langfuse.InjectTracing(ctx, &payload) payloadBytes, err := json.Marshal(payload) if err != nil { @@ -846,4 +873,4 @@ func (h *KnowledgeBaseHandler) ListMoveTargets(c *gin.Context) { "success": true, "data": targets, }) -} \ No newline at end of file +} diff --git a/internal/handler/organization.go b/internal/handler/organization.go index a4286819..38d43043 100644 --- a/internal/handler/organization.go +++ b/internal/handler/organization.go @@ -1262,7 +1262,7 @@ func (h *OrganizationHandler) ShareAgent(c *gin.Context) { return } if errors.Is(err, service.ErrAgentNotConfigured) { - c.Error(apperrors.NewValidationError("Agent is not fully configured. Please set the chat model and, if using knowledge bases, the rerank model in agent settings.")) + c.Error(apperrors.NewValidationError("Agent is not fully configured. Please set the chat model, and set the rerank model if the knowledge_search tool is enabled in agent settings.")) return } c.Error(apperrors.NewForbiddenError("Permission denied or invalid operation")) diff --git a/internal/handler/session/helpers.go b/internal/handler/session/helpers.go index fc68f574..5e5bb06c 100644 --- a/internal/handler/session/helpers.go +++ b/internal/handler/session/helpers.go @@ -213,9 +213,13 @@ func (h *Handler) setupStopEventHandler( eventBus.On(event.EventStop, func(ctx context.Context, evt event.Event) error { logger.Infof(ctx, "Received stop event, cancelling async operations for session: %s", sessionID) cancel() - assistantMessage.Content = "用户停止了本次对话" - // Use session's tenant for message update (ctx may have effectiveTenantID when using shared agent) - updateCtx := context.WithValue(ctx, types.TenantIDContextKey, sessionTenantID) + // Preserve whatever has been streamed so far; do not overwrite Content. + // Use session's tenant for message update (ctx may have effectiveTenantID when using shared agent). + // Use WithoutCancel so the GORM UPDATE survives the upcoming ctx.Done triggered by cancel()/client disconnect. + updateCtx := context.WithValue( + context.WithoutCancel(ctx), + types.TenantIDContextKey, sessionTenantID, + ) h.completeAssistantMessage(updateCtx, assistantMessage, "") // empty query: stopped conversations are not indexed return nil }) diff --git a/internal/handler/session/qa.go b/internal/handler/session/qa.go index 76d8a67d..ea2de39d 100644 --- a/internal/handler/session/qa.go +++ b/internal/handler/session/qa.go @@ -615,7 +615,15 @@ func (h *Handler) executeQA(reqCtx *qaRequestContext, mode qaMode, generateTitle } // Agent mode: complete the assistant message in defer (normal mode does it via event handler) if mode == qaModeAgent { - updateCtx := context.WithValue(streamCtx.asyncCtx, types.TenantIDContextKey, reqCtx.session.TenantID) + // Use WithoutCancel so a user-triggered stop (which cancels + // asyncCtx) doesn't also cancel the GORM UPDATE that persists + // AgentSteps/Content. Without this, cancelled-ctx makes + // GORM skip the write and the agent's intermediate steps + // (thinking / tool_call history) are lost on page refresh. + updateCtx := context.WithValue( + context.WithoutCancel(streamCtx.asyncCtx), + types.TenantIDContextKey, reqCtx.session.TenantID, + ) h.completeAssistantMessage(updateCtx, streamCtx.assistantMessage, reqCtx.query) logger.Infof(streamCtx.asyncCtx, "Agent QA service completed for session: %s", sessionID) } diff --git a/internal/handler/system.go b/internal/handler/system.go index 75d2f0b7..db04afa6 100644 --- a/internal/handler/system.go +++ b/internal/handler/system.go @@ -2,7 +2,6 @@ package handler import ( "context" - "encoding/json" "fmt" "net" "os" @@ -442,18 +441,6 @@ func (h *SystemHandler) isTOSEnvAvailable() bool { os.Getenv("TOS_BUCKET_NAME") != "" } -// MinioBucketInfo represents bucket information with access policy -type MinioBucketInfo struct { - Name string `json:"name"` - Policy string `json:"policy"` // "public", "private", "custom" - CreatedAt string `json:"created_at,omitempty"` -} - -// ListMinioBucketsResponse defines the response structure for listing buckets -type ListMinioBucketsResponse struct { - Buckets []MinioBucketInfo `json:"buckets"` -} - // StorageEngineStatusItem describes one storage engine's availability and description. type StorageEngineStatusItem struct { Name string `json:"name"` // "local", "minio", "cos", "tos" @@ -505,188 +492,7 @@ func (h *SystemHandler) GetStorageEngineStatus(c *gin.Context) { }) } -// ListMinioBuckets godoc -// @Summary 列出 MinIO 存储桶 -// @Description 获取所有 MinIO 存储桶及其访问权限 -// @Tags 系统 -// @Accept json -// @Produce json -// @Success 200 {object} ListMinioBucketsResponse "存储桶列表" -// @Failure 400 {object} map[string]interface{} "MinIO 未启用" -// @Failure 500 {object} map[string]interface{} "服务器错误" -// @Router /system/minio/buckets [get] -func (h *SystemHandler) ListMinioBuckets(c *gin.Context) { - ctx := logger.CloneContext(c.Request.Context()) - - endpoint, accessKeyID, secretAccessKey := h.getMinioConfig(c) - if endpoint == "" || accessKeyID == "" || secretAccessKey == "" { - logger.Warn(ctx, "MinIO is not configured") - c.JSON(400, gin.H{ - "code": 400, - "msg": "MinIO is not configured", - "success": false, - }) - return - } - - useSSL := os.Getenv("MINIO_USE_SSL") == "true" - if v, exists := c.Get(types.TenantInfoContextKey.String()); exists { - if tenant, ok := v.(*types.Tenant); ok && tenant != nil && tenant.StorageEngineConfig != nil && tenant.StorageEngineConfig.MinIO != nil { - useSSL = tenant.StorageEngineConfig.MinIO.UseSSL - } - } - - // Create MinIO client - minioClient, err := minio.New(endpoint, &minio.Options{ - Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""), - Secure: useSSL, - }) - if err != nil { - logger.Error(ctx, "Failed to create MinIO client", "error", err) - c.JSON(500, gin.H{ - "code": 500, - "msg": "Failed to connect to MinIO", - "success": false, - }) - return - } - - // List all buckets - buckets, err := minioClient.ListBuckets(context.Background()) - if err != nil { - logger.Error(ctx, "Failed to list MinIO buckets", "error", err) - c.JSON(500, gin.H{ - "code": 500, - "msg": "Failed to list buckets", - "success": false, - }) - return - } - - // Get policy for each bucket - bucketInfos := make([]MinioBucketInfo, 0, len(buckets)) - for _, bucket := range buckets { - policy := "private" // default: no policy means private - - // Try to get bucket policy - policyStr, err := minioClient.GetBucketPolicy(context.Background(), bucket.Name) - if err == nil && policyStr != "" { - policy = parseBucketPolicy(policyStr) - } - // If err != nil or policyStr is empty, bucket has no policy (private) - - bucketInfos = append(bucketInfos, MinioBucketInfo{ - Name: bucket.Name, - Policy: policy, - CreatedAt: bucket.CreationDate.Format("2006-01-02 15:04:05"), - }) - } - - logger.Info(ctx, "Listed MinIO buckets successfully", "count", len(bucketInfos)) - c.JSON(200, gin.H{ - "code": 0, - "msg": "success", - "success": true, - "data": ListMinioBucketsResponse{Buckets: bucketInfos}, - }) -} - -// BucketPolicy represents the S3 bucket policy structure -type BucketPolicy struct { - Version string `json:"Version"` - Statement []PolicyStatement `json:"Statement"` -} - -// PolicyStatement represents a single statement in the bucket policy -type PolicyStatement struct { - Effect string `json:"Effect"` - Principal interface{} `json:"Principal"` // Can be "*" or {"AWS": [...]} - Action interface{} `json:"Action"` // Can be string or []string - Resource interface{} `json:"Resource"` // Can be string or []string -} - -// parseBucketPolicy parses the policy JSON and determines the access type -func parseBucketPolicy(policyStr string) string { - var policy BucketPolicy - if err := json.Unmarshal([]byte(policyStr), &policy); err != nil { - // If we can't parse the policy, treat it as custom - return "custom" - } - - // Check if any statement grants public read access - hasPublicRead := false - for _, stmt := range policy.Statement { - if stmt.Effect != "Allow" { - continue - } - - // Check if Principal is "*" (public) - if !isPrincipalPublic(stmt.Principal) { - continue - } - - // Check if Action includes s3:GetObject - if !hasGetObjectAction(stmt.Action) { - continue - } - - hasPublicRead = true - break - } - - if hasPublicRead { - return "public" - } - - // Has policy but not public read - return "custom" -} - -// isPrincipalPublic checks if the principal allows public access -func isPrincipalPublic(principal interface{}) bool { - switch p := principal.(type) { - case string: - return p == "*" - case map[string]interface{}: - // Check for {"AWS": "*"} or {"AWS": ["*"]} - if aws, ok := p["AWS"]; ok { - switch a := aws.(type) { - case string: - return a == "*" - case []interface{}: - for _, v := range a { - if s, ok := v.(string); ok && s == "*" { - return true - } - } - } - } - } - return false -} - -// hasGetObjectAction checks if the action includes s3:GetObject -func hasGetObjectAction(action interface{}) bool { - checkAction := func(a string) bool { - a = strings.ToLower(a) - return a == "s3:getobject" || a == "s3:*" || a == "*" - } - - switch act := action.(type) { - case string: - return checkAction(act) - case []interface{}: - for _, v := range act { - if s, ok := v.(string); ok && checkAction(s) { - return true - } - } - } - return false -} - // --- Storage engine helpers --- - // cosFieldPattern validates COS region and bucket name format to prevent URL injection. var cosFieldPattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,62}$`) @@ -849,6 +655,11 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ return } + if cfg.BucketName != "" && !cosFieldPattern.MatchString(cfg.BucketName) { + c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "Bucket 名称格式不正确,仅允许字母、数字、点、连字符"}}) + return + } + endpoint, accessKeyID, secretAccessKey := cfg.Endpoint, cfg.AccessKeyID, cfg.SecretAccessKey if cfg.Mode != "remote" { endpoint = os.Getenv("MINIO_ENDPOINT") @@ -862,7 +673,7 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ if cfg.Mode == "remote" { if blocked, reason := isBlockedStorageEndpoint(endpoint); blocked { - logger.Warnf(ctx, "Storage check: MinIO endpoint blocked by SSRF protection endpoint=%s", endpoint) + logger.Warnf(ctx, "Storage check: MinIO endpoint blocked by SSRF protection, endpoint: %s", endpoint) c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}}) return } @@ -871,7 +682,7 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ err := file.CheckMinioConnectivity(ctx, endpoint, accessKeyID, secretAccessKey, cfg.BucketName, cfg.UseSSL) if err != nil { errMsg := err.Error() - // If bucket does not exist, auto-create it with public-read policy + // If bucket does not exist, auto-create it if strings.Contains(errMsg, "does not exist") && cfg.BucketName != "" { logger.Info(ctx, "Storage check: bucket does not exist, attempting auto-creation", "bucket", cfg.BucketName) minioClient, clientErr := minio.New(endpoint, &minio.Options{ @@ -879,39 +690,16 @@ func (h *SystemHandler) checkMinio(c *gin.Context, ctx context.Context, cfg *typ Secure: cfg.UseSSL, }) if clientErr != nil { - c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("创建 MinIO 客户端失败: %s", sanitizeStorageCheckError(clientErr))}}) + c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Failed to create MinIO client: %s", sanitizeStorageCheckError(clientErr))}}) return } if mkErr := minioClient.MakeBucket(ctx, cfg.BucketName, minio.MakeBucketOptions{}); mkErr != nil { logger.Error(ctx, "Storage check: failed to create bucket", "bucket", cfg.BucketName, "error", mkErr) - c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("自动创建 Bucket「%s」失败: %s", cfg.BucketName, sanitizeStorageCheckError(mkErr))}}) + c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Failed to auto-create Bucket '%s': %s", cfg.BucketName, sanitizeStorageCheckError(mkErr))}}) return } - // Set public-read policy - publicReadPolicy := fmt.Sprintf(`{ - "Version": "2012-10-17", - "Statement": [ - { - "Effect": "Allow", - "Principal": {"AWS": ["*"]}, - "Action": ["s3:GetBucketLocation", "s3:ListBucket"], - "Resource": ["arn:aws:s3:::%s"] - }, - { - "Effect": "Allow", - "Principal": {"AWS": ["*"]}, - "Action": ["s3:GetObject"], - "Resource": ["arn:aws:s3:::%s/*"] - } - ] - }`, cfg.BucketName, cfg.BucketName) - if policyErr := minioClient.SetBucketPolicy(ctx, cfg.BucketName, publicReadPolicy); policyErr != nil { - logger.Error(ctx, "Storage check: bucket created but failed to set public-read policy", "bucket", cfg.BucketName, "error", policyErr) - c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, BucketCreated: true, Message: fmt.Sprintf("Bucket「%s」已自动创建,但设置公有读策略失败,请手动配置权限", cfg.BucketName)}}) - return - } - logger.Info(ctx, "Storage check: bucket created with public-read policy", "bucket", cfg.BucketName) - c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, BucketCreated: true, Message: fmt.Sprintf("Bucket「%s」不存在,已自动创建并设置公有读权限", cfg.BucketName)}}) + logger.Info(ctx, "Storage check: bucket created", "bucket", cfg.BucketName) + c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: true, BucketCreated: true, Message: fmt.Sprintf("Bucket '%s' does not exist, and has been automatically created", cfg.BucketName)}}) return } logger.Error(ctx, "Storage check: MinIO connectivity failed", "error", err) @@ -1045,7 +833,7 @@ func (h *SystemHandler) checkOSS(c *gin.Context, ctx context.Context, cfg *types // Strip URL scheme before SSRF check — OSS endpoint may include http:// or https:// ssrfEndpoint := strings.TrimPrefix(strings.TrimPrefix(endpoint, "https://"), "http://") if blocked, reason := isBlockedStorageEndpoint(ssrfEndpoint); blocked { - logger.Warnf(ctx, "Storage check: OSS endpoint blocked by SSRF protection", "endpoint", endpoint) + logger.Warnf(ctx, "Storage check: OSS endpoint blocked by SSRF protection, endpoint: %s", endpoint) c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: reason}}) return } @@ -1062,16 +850,16 @@ func (h *SystemHandler) checkOSS(c *gin.Context, ctx context.Context, cfg *types if err != nil { errMsg := err.Error() if strings.Contains(errMsg, "403") || strings.Contains(errMsg, "AccessDenied") { - logger.Errorf(ctx, "Storage check: OSS auth failed", "endpoint", endpoint, "bucket", cfg.BucketName) + logger.Errorf(ctx, "Storage check: OSS auth failed, endpoint: %s, bucket: %s", endpoint, cfg.BucketName) c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: "认证失败,请检查 Access Key / Secret Key 是否正确"}}) return } if strings.Contains(errMsg, "404") || strings.Contains(errMsg, "NoSuchBucket") { - logger.Errorf(ctx, "Storage check: OSS bucket not found", "bucket", cfg.BucketName) + logger.Errorf(ctx, "Storage check: OSS bucket not found, bucket: %s", cfg.BucketName) c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("Bucket「%s」不存在", cfg.BucketName)}}) return } - logger.Errorf(ctx, "Storage check: OSS connectivity failed", "endpoint", endpoint, "bucket", cfg.BucketName, "error", err) + logger.Errorf(ctx, "Storage check: OSS connectivity failed, endpoint: %s, bucket: %s, error: %v", endpoint, cfg.BucketName, err) c.JSON(200, gin.H{"code": 0, "data": StorageCheckResponse{OK: false, Message: fmt.Sprintf("OSS 连通性检测失败: %s", sanitizeStorageCheckError(err))}}) return } diff --git a/internal/handler/wiki_page.go b/internal/handler/wiki_page.go new file mode 100644 index 00000000..e24f3588 --- /dev/null +++ b/internal/handler/wiki_page.go @@ -0,0 +1,560 @@ +package handler + +import ( + stderrors "errors" + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/Tencent/WeKnora/internal/application/repository" + "github.com/Tencent/WeKnora/internal/application/service" + "github.com/Tencent/WeKnora/internal/errors" + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" + secutils "github.com/Tencent/WeKnora/internal/utils" + "github.com/gin-gonic/gin" +) + +// WikiPageHandler handles HTTP requests for wiki page operations +type WikiPageHandler struct { + wikiService interfaces.WikiPageService + kbService interfaces.KnowledgeBaseService + lintService *service.WikiLintService +} + +// NewWikiPageHandler creates a new wiki page handler +func NewWikiPageHandler( + wikiService interfaces.WikiPageService, + kbService interfaces.KnowledgeBaseService, + lintService *service.WikiLintService, +) *WikiPageHandler { + return &WikiPageHandler{ + wikiService: wikiService, + kbService: kbService, + lintService: lintService, + } +} + +// validateWikiKB validates that the KB exists and is a wiki type +func (h *WikiPageHandler) validateWikiKB(c *gin.Context) (string, uint64, error) { + ctx := c.Request.Context() + kbID := secutils.SanitizeForLog(c.Param("kb_id")) + tenantID := c.GetUint64(types.TenantIDContextKey.String()) + + if kbID == "" { + return "", 0, errors.NewBadRequestError("Knowledge base ID is required") + } + + kb, err := h.kbService.GetKnowledgeBaseByID(ctx, kbID) + if err != nil { + logger.ErrorWithFields(ctx, err, nil) + return "", 0, errors.NewNotFoundError("Knowledge base not found") + } + + if !kb.IsWikiEnabled() { + return "", 0, errors.NewBadRequestError("Wiki feature is not enabled for this knowledge base") + } + + return kbID, tenantID, nil +} + +// getSlugParam extracts and cleans the slug from gin's wildcard path param +func getSlugParam(c *gin.Context) string { + slug := c.Param("slug") + // gin wildcard params include a leading "/" + slug = strings.TrimPrefix(slug, "/") + return strings.TrimSpace(slug) +} + +// ListPages godoc +// @Summary List wiki pages +// @Description List wiki pages with optional filtering and pagination +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Param page_type query string false "Filter by page type" +// @Param status query string false "Filter by status" +// @Param query query string false "Full-text search" +// @Param page query int false "Page number" +// @Param page_size query int false "Page size" +// @Param sort_by query string false "Sort field" +// @Param sort_order query string false "Sort order (asc/desc)" +// @Success 200 {object} types.WikiPageListResponse +// @Failure 400 {object} errors.AppError +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages [get] +func (h *WikiPageHandler) ListPages(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20")) + + req := &types.WikiPageListRequest{ + KnowledgeBaseID: kbID, + PageType: c.Query("page_type"), + Status: c.Query("status"), + Query: c.Query("query"), + Page: page, + PageSize: pageSize, + SortBy: c.DefaultQuery("sort_by", "updated_at"), + SortOrder: c.DefaultQuery("sort_order", "desc"), + } + + resp, err := h.wikiService.ListPages(c.Request.Context(), req) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, resp) +} + +// CreatePage godoc +// @Summary Create a wiki page +// @Description Create a new wiki page in the knowledge base +// @Tags Wiki +// @Accept json +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Param page body types.WikiPage true "Wiki page data" +// @Success 201 {object} types.WikiPage +// @Failure 400 {object} errors.AppError +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages [post] +func (h *WikiPageHandler) CreatePage(c *gin.Context) { + kbID, tenantID, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + var page types.WikiPage + if err := c.ShouldBindJSON(&page); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()}) + return + } + + page.KnowledgeBaseID = kbID + page.TenantID = tenantID + + created, err := h.wikiService.CreatePage(c.Request.Context(), &page) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusCreated, created) +} + +// GetPage godoc +// @Summary Get a wiki page by slug +// @Description Retrieve a wiki page by its slug +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Param slug path string true "Page slug" +// @Success 200 {object} types.WikiPage +// @Failure 404 {object} errors.AppError +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} [get] +func (h *WikiPageHandler) GetPage(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + slug := getSlugParam(c) + if slug == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"}) + return + } + + page, err := h.wikiService.GetPageBySlug(c.Request.Context(), kbID, slug) + if err != nil { + if stderrors.Is(err, repository.ErrWikiPageNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, page) +} + +// UpdatePage godoc +// @Summary Update a wiki page +// @Description Update an existing wiki page by slug +// @Tags Wiki +// @Accept json +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Param slug path string true "Page slug" +// @Param page body types.WikiPage true "Updated wiki page data" +// @Success 200 {object} types.WikiPage +// @Failure 404 {object} errors.AppError +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} [put] +func (h *WikiPageHandler) UpdatePage(c *gin.Context) { + kbID, tenantID, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + slug := getSlugParam(c) + if slug == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"}) + return + } + + var page types.WikiPage + if err := c.ShouldBindJSON(&page); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()}) + return + } + + page.KnowledgeBaseID = kbID + page.TenantID = tenantID + page.Slug = slug + + updated, err := h.wikiService.UpdatePage(c.Request.Context(), &page) + if err != nil { + if stderrors.Is(err, repository.ErrWikiPageNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, updated) +} + +// DeletePage godoc +// @Summary Delete a wiki page +// @Description Soft-delete a wiki page by slug +// @Tags Wiki +// @Param kb_id path string true "Knowledge base ID" +// @Param slug path string true "Page slug" +// @Success 204 +// @Failure 404 {object} errors.AppError +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/pages/{slug} [delete] +func (h *WikiPageHandler) DeletePage(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + slug := getSlugParam(c) + if slug == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Page slug is required"}) + return + } + + if err := h.wikiService.DeletePage(c.Request.Context(), kbID, slug); err != nil { + if stderrors.Is(err, repository.ErrWikiPageNotFound) { + c.JSON(http.StatusNotFound, gin.H{"error": "Wiki page not found"}) + return + } + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.Status(http.StatusNoContent) +} + +// GetIndex godoc +// @Summary Get wiki index page +// @Description Returns the wiki index page (creates default if not exists) +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Success 200 {object} types.WikiPage +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/index [get] +func (h *WikiPageHandler) GetIndex(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + page, err := h.wikiService.GetIndex(c.Request.Context(), kbID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, page) +} + +// GetLog godoc +// @Summary Get wiki operation log +// @Description Returns the wiki operation log page (creates default if not exists) +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Success 200 {object} types.WikiPage +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/log [get] +func (h *WikiPageHandler) GetLog(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + page, err := h.wikiService.GetLog(c.Request.Context(), kbID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, page) +} + +// GetGraph godoc +// @Summary Get wiki link graph +// @Description Returns the wiki link graph data for visualization +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Success 200 {object} types.WikiGraphData +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/graph [get] +func (h *WikiPageHandler) GetGraph(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + graph, err := h.wikiService.GetGraph(c.Request.Context(), kbID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, graph) +} + +// GetStats godoc +// @Summary Get wiki statistics +// @Description Returns aggregate statistics about the wiki +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Success 200 {object} types.WikiStats +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/stats [get] +func (h *WikiPageHandler) GetStats(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + stats, err := h.wikiService.GetStats(c.Request.Context(), kbID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, stats) +} + +// ListIssues godoc +// @Summary List wiki page issues +// @Description List issues flagged on wiki pages with optional filtering +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Param slug query string false "Filter by page slug" +// @Param status query string false "Filter by status (pending, ignored, resolved)" +// @Success 200 {array} types.WikiPageIssue +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/issues [get] +func (h *WikiPageHandler) ListIssues(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + slug := c.Query("slug") + status := c.Query("status") + + issues, err := h.wikiService.ListIssues(c.Request.Context(), kbID, slug, status) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, issues) +} + +// UpdateIssueStatus godoc +// @Summary Update wiki page issue status +// @Description Update the status of a flagged wiki page issue +// @Tags Wiki +// @Accept json +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Param issue_id path string true "Issue ID" +// @Param status body object true "New status {'status': 'ignored'}" +// @Success 200 {object} map[string]string +// @Failure 400 {object} errors.AppError +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/issues/{issue_id}/status [put] +func (h *WikiPageHandler) UpdateIssueStatus(c *gin.Context) { + _, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + issueID := secutils.SanitizeForLog(c.Param("issue_id")) + if issueID == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Issue ID is required"}) + return + } + + var req struct { + Status string `json:"status" binding:"required"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body: " + err.Error()}) + return + } + + validStatuses := map[string]bool{"pending": true, "ignored": true, "resolved": true} + if !validStatuses[req.Status] { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid status. Must be pending, ignored, or resolved"}) + return + } + + if err := h.wikiService.UpdateIssueStatus(c.Request.Context(), issueID, req.Status); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "Issue status updated successfully"}) +} + +// SearchPages godoc +// @Summary Search wiki pages +// @Description Full-text search over wiki pages +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Param q query string true "Search query" +// @Param limit query int false "Max results (default 10)" +// @Success 200 {array} types.WikiPage +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/search [get] +func (h *WikiPageHandler) SearchPages(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + query := c.Query("q") + if query == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Search query 'q' is required"}) + return + } + + limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10")) + + pages, err := h.wikiService.SearchPages(c.Request.Context(), kbID, query, limit) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"pages": pages}) +} + +// RebuildLinks godoc +// @Summary Rebuild wiki links +// @Description Re-parse all pages and rebuild bidirectional link references +// @Tags Wiki +// @Param kb_id path string true "Knowledge base ID" +// @Success 200 {object} map[string]string +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/rebuild-links [post] +func (h *WikiPageHandler) RebuildLinks(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + if err := h.wikiService.RebuildLinks(c.Request.Context(), kbID); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "Links rebuilt successfully"}) +} + +// Lint godoc +// @Summary Run wiki lint +// @Description Perform a comprehensive health check on the wiki +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Success 200 {object} service.WikiLintReport +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/lint [get] +func (h *WikiPageHandler) Lint(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + report, err := h.lintService.RunLint(c.Request.Context(), kbID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, report) +} + +// AutoFix godoc +// @Summary Auto-fix wiki issues +// @Description Automatically fix fixable wiki issues (broken links, etc.) +// @Tags Wiki +// @Produce json +// @Param kb_id path string true "Knowledge base ID" +// @Success 200 {object} map[string]interface{} +// @Security Bearer +// @Router /api/v1/knowledgebase/{kb_id}/wiki/auto-fix [post] +func (h *WikiPageHandler) AutoFix(c *gin.Context) { + kbID, _, err := h.validateWikiKB(c) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + fixed, err := h.lintService.AutoFix(c.Request.Context(), kbID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.JSON(http.StatusOK, gin.H{"fixed": fixed, "message": fmt.Sprintf("Auto-fixed %d issues", fixed)}) +} diff --git a/internal/im/cmd_search.go b/internal/im/cmd_search.go index 9c3dc309..22b4803c 100644 --- a/internal/im/cmd_search.go +++ b/internal/im/cmd_search.go @@ -5,6 +5,8 @@ import ( "fmt" "strings" + "github.com/Tencent/WeKnora/internal/agent/tools" + "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types/interfaces" ) @@ -50,9 +52,24 @@ func (c *SearchCommand) Execute(ctx context.Context, cmdCtx *CommandContext, arg case "all": allKBs, err := c.kbService.ListKnowledgeBases(ctx) if err == nil { + // Same tool-capability filter as the QA pipeline's + // resolveKnowledgeBasesFromAgent (`all` branch) so `/search` + // agrees with what the agent's tools can actually reach. + filter := tools.DeriveKBFilterFromTools(cmdCtx.CustomAgent.Config.AllowedTools) + skipped := 0 for _, kb := range allKBs { + if !filter.IsEmpty() && + !tools.KBSatisfiesToolRequirements(kb.Capabilities(), cmdCtx.CustomAgent.Config.AllowedTools) { + skipped++ + continue + } kbIDs = append(kbIDs, kb.ID) } + if skipped > 0 { + logger.Infof(ctx, + "/search(agent=%s, mode=all): tool-capability filter removed %d of %d KBs", + cmdCtx.CustomAgent.ID, skipped, len(allKBs)) + } } case "none": // No knowledge bases configured — will return empty results. diff --git a/internal/im/mattermost/client.go b/internal/im/mattermost/client.go index e6df516f..501c3d74 100644 --- a/internal/im/mattermost/client.go +++ b/internal/im/mattermost/client.go @@ -68,7 +68,10 @@ func (c *Client) CreatePost(ctx context.Context, channelID, rootID, message stri } defer resp.Body.Close() - respBody, _ := io.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("read mattermost create post response: %w", err) + } if resp.StatusCode < 200 || resp.StatusCode >= 300 { if resp.StatusCode == http.StatusForbidden { return "", fmt.Errorf("mattermost create post: 403 forbidden — add the bot user to this Mattermost channel (Channel menu → Members → Add); body=%s", truncateForErr(respBody)) @@ -104,7 +107,10 @@ func (c *Client) GetPost(ctx context.Context, postID string) (rootID string, err } defer resp.Body.Close() - respBody, _ := io.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("read mattermost get post response: %w", err) + } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return "", fmt.Errorf("mattermost get post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody)) } @@ -139,7 +145,10 @@ func (c *Client) PatchPostMessage(ctx context.Context, postID, message string) e } defer resp.Body.Close() - respBody, _ := io.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("read mattermost patch post response: %w", err) + } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("mattermost patch post: status=%d body=%s", resp.StatusCode, truncateForErr(respBody)) } @@ -169,7 +178,10 @@ func (c *Client) GetFileInfo(ctx context.Context, fileID string) (*FileInfo, err } defer resp.Body.Close() - respBody, _ := io.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("read mattermost file info response: %w", err) + } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, fmt.Errorf("mattermost file info: status=%d body=%s", resp.StatusCode, truncateForErr(respBody)) } @@ -196,8 +208,11 @@ func (c *Client) GetFileReader(ctx context.Context, fileID string) (io.ReadClose return nil, err } if resp.StatusCode < 200 || resp.StatusCode >= 300 { - body, _ := io.ReadAll(resp.Body) + body, readErr := io.ReadAll(resp.Body) resp.Body.Close() + if readErr != nil { + return nil, fmt.Errorf("read mattermost get file error response (status=%d): %w", resp.StatusCode, readErr) + } return nil, fmt.Errorf("mattermost get file: status=%d body=%s", resp.StatusCode, truncateForErr(body)) } return resp.Body, nil diff --git a/internal/im/service.go b/internal/im/service.go index cec15c1b..0767da77 100644 --- a/internal/im/service.go +++ b/internal/im/service.go @@ -3,6 +3,7 @@ package im import ( "bytes" "context" + "errors" "fmt" "io" "mime/multipart" @@ -28,8 +29,6 @@ import ( ) const ( - // qaTimeout is the maximum time to wait for the QA pipeline to complete. - qaTimeout = 120 * time.Second // dedupTTL is how long processed message IDs are retained. dedupTTL = 5 * time.Minute // dedupCleanupInterval is how often the dedup map is cleaned. @@ -646,7 +645,7 @@ func (s *Service) storeInflightMapping(ctx context.Context, userKey, sessionID, return } val := sessionID + ":" + messageID - if err := s.redis.Set(ctx, RedisKeyInflight+userKey, val, qaTimeout+30*time.Second).Err(); err != nil { + if err := s.redis.Set(ctx, RedisKeyInflight+userKey, val, 10*time.Minute).Err(); err != nil { logger.Warnf(ctx, "[IM] Failed to store inflight mapping: %v", err) } } @@ -925,7 +924,28 @@ func (s *Service) HandleMessage(ctx context.Context, msg *IncomingMessage, chann // 4. Get the WeKnora session session, err := s.sessionService.GetSession(sessionCtx, channelSession.SessionID) if err != nil { - return fmt.Errorf("get session: %w", err) + // The underlying session may have been deleted from the UI while the + // ChannelSession mapping still exists (GORM soft-delete does not trigger + // SQL ON DELETE CASCADE). Recover by soft-deleting the stale mapping and + // re-creating a fresh session so the IM bot doesn't become permanently + // unresponsive. (fixes #1046) + if errors.Is(err, gorm.ErrRecordNotFound) { + logger.Warnf(ctx, "[IM] Session %s not found (deleted?), recycling stale channel session %s", + channelSession.SessionID, channelSession.ID) + if delErr := s.db.Delete(&ChannelSession{}, "id = ?", channelSession.ID).Error; delErr != nil { + logger.Warnf(ctx, "[IM] Failed to delete stale channel session %s: %v", channelSession.ID, delErr) + } + channelSession, err = s.resolveSession(sessionCtx, msg, tenantID, agentID, channelID, channel.SessionMode) + if err != nil { + return fmt.Errorf("resolve session (retry): %w", err) + } + session, err = s.sessionService.GetSession(sessionCtx, channelSession.SessionID) + if err != nil { + return fmt.Errorf("get session (retry): %w", err) + } + } else { + return fmt.Errorf("get session: %w", err) + } } // 5. Enqueue the QA request into the bounded worker pool. @@ -1195,12 +1215,12 @@ func (s *Service) resolveSession(ctx context.Context, msg *IncomingMessage, tena } } -// resolveUserSession finds or creates a ChannelSession keyed by (platform, user_id, chat_id, tenant_id). +// resolveUserSession finds or creates a ChannelSession keyed by (platform, user_id, chat_id, tenant_id, agent_id). // This is the original session resolution strategy. func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage, tenantID uint64, agentID string, imChannelID string) (*ChannelSession, error) { var cs ChannelSession - result := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND deleted_at IS NULL", - string(msg.Platform), msg.UserID, msg.ChatID, tenantID). + result := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND agent_id = ? AND deleted_at IS NULL", + string(msg.Platform), msg.UserID, msg.ChatID, tenantID, agentID). First(&cs) if result.Error == nil { @@ -1244,8 +1264,8 @@ func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage, logger.Warnf(ctx, "[IM] Failed to clean up orphaned session %s: %v", createdSession.ID, delErr) } var existing ChannelSession - if findErr := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND deleted_at IS NULL", - string(msg.Platform), msg.UserID, msg.ChatID, tenantID). + if findErr := s.db.Where("platform = ? AND user_id = ? AND chat_id = ? AND tenant_id = ? AND agent_id = ? AND deleted_at IS NULL", + string(msg.Platform), msg.UserID, msg.ChatID, tenantID, agentID). First(&existing).Error; findErr != nil { return nil, fmt.Errorf("create channel session: %w (lookup fallback: %v)", err, findErr) } @@ -1258,7 +1278,7 @@ func (s *Service) resolveUserSession(ctx context.Context, msg *IncomingMessage, return &cs, nil } -// resolveThreadSession finds or creates a ChannelSession keyed by (platform, chat_id, thread_id, tenant_id). +// resolveThreadSession finds or creates a ChannelSession keyed by (platform, chat_id, thread_id, tenant_id, agent_id). // In thread mode, each message thread gets its own session. Multiple users in the // same thread share the same session. Top-level messages use their own ID as // ThreadID, creating a new session per top-level message. @@ -1274,8 +1294,8 @@ func (s *Service) resolveThreadSession(ctx context.Context, msg *IncomingMessage var cs ChannelSession result := s.db.Where( - "platform = ? AND chat_id = ? AND thread_id = ? AND tenant_id = ? AND deleted_at IS NULL", - string(msg.Platform), threadID, msg.ChatID, tenantID, + "platform = ? AND chat_id = ? AND thread_id = ? AND tenant_id = ? AND agent_id = ? AND deleted_at IS NULL", + string(msg.Platform), msg.ChatID, threadID, tenantID, agentID, ).First(&cs) if result.Error == nil { @@ -1322,8 +1342,8 @@ func (s *Service) resolveThreadSession(ctx context.Context, msg *IncomingMessage } var existing ChannelSession if findErr := s.db.Where( - "platform = ? AND chat_id = ? AND thread_id = ? AND tenant_id = ? AND deleted_at IS NULL", - string(msg.Platform), msg.ChatID, threadID, tenantID, + "platform = ? AND chat_id = ? AND thread_id = ? AND tenant_id = ? AND agent_id = ? AND deleted_at IS NULL", + string(msg.Platform), msg.ChatID, threadID, tenantID, agentID, ).First(&existing).Error; findErr != nil { return nil, fmt.Errorf("create thread session: %w (lookup fallback: %v)", err, findErr) } @@ -1451,7 +1471,9 @@ func (s *Service) handleMessageStream(ctx context.Context, msg *IncomingMessage, } // Prepare the QA pipeline - qaCtx, qaCancel := context.WithTimeout(ctx, qaTimeout) + // No total deadline: each agent round has its own LLMCallTimeout (default 120s). + // A hard pipeline deadline would kill multi-round agent reasoning prematurely. + qaCtx, qaCancel := context.WithCancel(ctx) defer qaCancel() eventBus := event.NewEventBus() @@ -1748,8 +1770,9 @@ func (s *Service) fallbackNonStream(ctx context.Context, msg *IncomingMessage, s // runQA executes the WeKnora QA pipeline and returns the full answer text. func (s *Service) runQA(ctx context.Context, session *types.Session, query string, customAgent *types.CustomAgent, kbIDs []string, userKey string, quote *QuotedMessage) (string, error) { - // Add timeout to prevent indefinite blocking - ctx, cancel := context.WithTimeout(ctx, qaTimeout) + // Cancellable context (no hard deadline): each agent round has its own + // LLMCallTimeout. The context can still be cancelled by /stop. + ctx, cancel := context.WithCancel(ctx) defer cancel() eventBus := event.NewEventBus() @@ -1855,18 +1878,18 @@ func (s *Service) runQA(ctx context.Context, session *types.Session, query strin } }() - // Wait for completion or timeout + // Wait for completion or cancellation (e.g., /stop) select { case <-done: case <-ctx.Done(): // Mark assistant message as completed to avoid dangling incomplete records - assistantMsg.Content = "抱歉,回答超时,请稍后再试。" + assistantMsg.Content = "抱歉,回答已被取消。" assistantMsg.IsCompleted = true // Use a fresh context since the original is cancelled if updateErr := s.messageService.UpdateMessage(context.WithoutCancel(ctx), assistantMsg); updateErr != nil { - logger.Warnf(ctx, "[IM] Failed to update timed-out assistant message: %v", updateErr) + logger.Warnf(ctx, "[IM] Failed to update cancelled assistant message: %v", updateErr) } - return "", fmt.Errorf("QA timed out after %v", qaTimeout) + return "", fmt.Errorf("QA cancelled: %w", ctx.Err()) } answerMu.Lock() diff --git a/internal/infrastructure/chunker/splitter.go b/internal/infrastructure/chunker/splitter.go index a634f2c9..d110e22d 100644 --- a/internal/infrastructure/chunker/splitter.go +++ b/internal/infrastructure/chunker/splitter.go @@ -519,10 +519,18 @@ func SplitTextParentChild(text string, parentCfg, childCfg SplitterConfig) Paren return ParentChildResult{} } + var newParents []Chunk var children []ChildChunk childSeq := 0 - for pi, parent := range parents { + for _, parent := range parents { subs := SplitText(parent.Content, childCfg) + + parentIndex := -1 + if len(subs) > 1 || (len(subs) == 1 && subs[0].Content != parent.Content) { + parentIndex = len(newParents) + newParents = append(newParents, parent) + } + for _, sub := range subs { // Adjust offsets: sub positions are relative to parent content, // shift to document-level offsets. @@ -533,12 +541,12 @@ func SplitTextParentChild(text string, parentCfg, childCfg SplitterConfig) Paren sub.End += parent.Start children = append(children, ChildChunk{ Chunk: sub, - ParentIndex: pi, + ParentIndex: parentIndex, }) childSeq++ } } - return ParentChildResult{Parents: parents, Children: children} + return ParentChildResult{Parents: newParents, Children: children} } // ExtractImageRefs extracts markdown image references from text. diff --git a/internal/infrastructure/docparser/builtin_converter.go b/internal/infrastructure/docparser/builtin_converter.go index 3779cfa7..0cf3860a 100644 --- a/internal/infrastructure/docparser/builtin_converter.go +++ b/internal/infrastructure/docparser/builtin_converter.go @@ -98,6 +98,7 @@ func imageToResult(fileName string, data []byte) *types.ReadResult { OriginalRef: safeRef, MimeType: mime, ImageData: data, + IsOriginal: true, }, }, } @@ -170,6 +171,7 @@ func ensureOriginalImageRef(req *types.ReadRequest, mdContent string, imageRefs OriginalRef: refPath, MimeType: mime, ImageData: req.FileContent, + IsOriginal: true, }) return mdContent, imageRefs diff --git a/internal/infrastructure/docparser/image_resolver.go b/internal/infrastructure/docparser/image_resolver.go index 68908a5d..9c2b35bf 100644 --- a/internal/infrastructure/docparser/image_resolver.go +++ b/internal/infrastructure/docparser/image_resolver.go @@ -29,7 +29,7 @@ import ( const ( // minImageDimension is the minimum width/height in pixels; images smaller // than this on either axis are treated as icons and filtered out. - minImageDimension = 128 + minImageDimension = 64 // minImageBytes is the minimum file size in bytes; very small images are // almost certainly icons or decorative elements. minImageBytes = 512 // 512 bytes @@ -44,7 +44,7 @@ func isIconImage(data []byte) bool { // Cannot decode dimensions — fall back to size-only heuristic. return len(data) < minImageBytes } - if cfg.Width < minImageDimension || cfg.Height < minImageDimension { + if cfg.Width < minImageDimension && cfg.Height < minImageDimension { return true } return false @@ -126,8 +126,11 @@ func (r *ImageResolver) ResolveAndStore( continue } - // Filter out small icons and decorative images - if isIconImage(ref.ImageData) { + // Filter out small icons and decorative images. Skip the filter + // when the reference is the originally uploaded file itself, so + // that a standalone image upload is never silently dropped even + // if its dimensions are below the icon threshold. + if !ref.IsOriginal && isIconImage(ref.ImageData) { // Remove the image reference from markdown entirely markdown = markdown[:m[0]] + markdown[m[1]:] continue diff --git a/internal/infrastructure/docparser/image_resolver_test.go b/internal/infrastructure/docparser/image_resolver_test.go index 8ac889d1..c5a3d96b 100644 --- a/internal/infrastructure/docparser/image_resolver_test.go +++ b/internal/infrastructure/docparser/image_resolver_test.go @@ -37,8 +37,8 @@ func TestIsIconImage(t *testing.T) { expect bool }{ { - name: "tiny bytes (< 2KB)", - data: make([]byte, 1024), + name: "tiny bytes (< 512B)", + data: make([]byte, 256), expect: true, }, { @@ -64,7 +64,7 @@ func TestIsIconImage(t *testing.T) { { name: "wide but short 200x30", data: createTestPNG(200, 30), - expect: true, + expect: false, }, } for _, tt := range tests { diff --git a/internal/infrastructure/docparser/resolve_remote_images_test.go b/internal/infrastructure/docparser/resolve_remote_images_test.go index 88782db5..89bbc1cc 100644 --- a/internal/infrastructure/docparser/resolve_remote_images_test.go +++ b/internal/infrastructure/docparser/resolve_remote_images_test.go @@ -39,6 +39,9 @@ func (m *mockFileService) GetFileURL(ctx context.Context, filePath string) (stri func (m *mockFileService) DeleteFile(ctx context.Context, filePath string) error { return nil } func TestResolveRemoteImages_NormalDownload(t *testing.T) { + // Whitelist localhost for this test so the test server is reachable + t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") + // Create a test HTTP server that serves a real PNG image. pngData := createTestPNG(200, 200) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -101,6 +104,9 @@ func TestResolveRemoteImages_SSRFBlocked(t *testing.T) { } func TestResolveRemoteImages_NonImageContentType(t *testing.T) { + // Whitelist localhost for this test so the test server is reachable + t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html") w.WriteHeader(http.StatusOK) @@ -147,6 +153,9 @@ func TestResolveRemoteImages_ProviderSchemeSkipped(t *testing.T) { } func TestResolveRemoteImages_MultipleImages(t *testing.T) { + // Whitelist localhost for this test so the test server is reachable + t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") + pngData := createTestPNG(256, 256) callCount := 0 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -199,6 +208,9 @@ func TestResolveRemoteImages_NoImages(t *testing.T) { } func TestResolveRemoteImages_Server404(t *testing.T) { + // Whitelist localhost for this test so the test server is reachable + t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost") + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) })) diff --git a/internal/infrastructure/web_search/bing.go b/internal/infrastructure/web_search/bing.go index 68eab98e..b5ba35b4 100644 --- a/internal/infrastructure/web_search/bing.go +++ b/internal/infrastructure/web_search/bing.go @@ -54,8 +54,9 @@ func NewBingProvider(params types.WebSearchProviderParameters) (interfaces.WebSe if params.APIKey == "" { return nil, fmt.Errorf("API key is required for Bing provider") } - client := &http.Client{ - Timeout: defaultBingTimeout, + client, err := NewSearchHTTPClient(defaultBingTimeout, params.ProxyURL) + if err != nil { + return nil, err } return &BingProvider{ client: client, diff --git a/internal/infrastructure/web_search/duckduckgo.go b/internal/infrastructure/web_search/duckduckgo.go index 5a405c18..0eaa8db2 100644 --- a/internal/infrastructure/web_search/duckduckgo.go +++ b/internal/infrastructure/web_search/duckduckgo.go @@ -23,13 +23,13 @@ type DuckDuckGoProvider struct { } // NewDuckDuckGoProvider creates a new DuckDuckGo provider. -// DuckDuckGo is free and requires no API key or configuration. +// DuckDuckGo is free and requires no API key; optional ProxyURL tunnels requests via an HTTP/HTTPS proxy. func NewDuckDuckGoProvider(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error) { - return &DuckDuckGoProvider{ - client: &http.Client{ - Timeout: 30 * time.Second, - }, - }, nil + client, err := NewSearchHTTPClient(30*time.Second, params.ProxyURL) + if err != nil { + return nil, err + } + return &DuckDuckGoProvider{client: client}, nil } // Name returns the provider name diff --git a/internal/infrastructure/web_search/google.go b/internal/infrastructure/web_search/google.go index af355676..2da39288 100644 --- a/internal/infrastructure/web_search/google.go +++ b/internal/infrastructure/web_search/google.go @@ -3,6 +3,7 @@ package web_search import ( "context" "fmt" + "time" "google.golang.org/api/customsearch/v1" "google.golang.org/api/option" @@ -29,8 +30,13 @@ func NewGoogleProvider(params types.WebSearchProviderParameters) (interfaces.Web return nil, fmt.Errorf("engine ID is required for Google provider") } + httpClient, err := NewSearchHTTPClient(30*time.Second, params.ProxyURL) + if err != nil { + return nil, err + } clientOpts := []option.ClientOption{ option.WithAPIKey(params.APIKey), + option.WithHTTPClient(httpClient), } srv, err := customsearch.NewService(context.Background(), clientOpts...) if err != nil { diff --git a/internal/infrastructure/web_search/proxy.go b/internal/infrastructure/web_search/proxy.go new file mode 100644 index 00000000..d7bc0689 --- /dev/null +++ b/internal/infrastructure/web_search/proxy.go @@ -0,0 +1,68 @@ +package web_search + +import ( + "fmt" + "net/http" + "net/url" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/utils" +) + +// ValidateProxyURL delegates to utils.ValidateURLForSSRF (only http/https pass that check). +func ValidateProxyURL(proxyURL string) error { + proxyURL = strings.TrimSpace(proxyURL) + if proxyURL == "" { + return nil + } + return utils.ValidateURLForSSRF(proxyURL) +} + +func ssrfSafeRedirect(maxRedirects int) func(*http.Request, []*http.Request) error { + return func(req *http.Request, via []*http.Request) error { + if len(via) >= maxRedirects { + return fmt.Errorf("stopped after %d redirects", maxRedirects) + } + if err := utils.ValidateURLForSSRF(req.URL.String()); err != nil { + return fmt.Errorf("%w: %v", utils.ErrSSRFRedirectBlocked, err) + } + return nil + } +} + +// NewSearchHTTPClient builds an http.Client for outbound web search requests. +// It uses utils.SSRFSafeDialContext, optional explicit or environment proxy, and +// redirect validation consistent with utils.NewSSRFSafeHTTPClient. +func NewSearchHTTPClient(timeout time.Duration, proxyURL string) (*http.Client, error) { + proxyURL = strings.TrimSpace(proxyURL) + def, ok := http.DefaultTransport.(*http.Transport) + if !ok { + return nil, fmt.Errorf("default HTTP transport is not *http.Transport") + } + t := def.Clone() + t.DialContext = utils.SSRFSafeDialContext + + if proxyURL != "" { + if err := ValidateProxyURL(proxyURL); err != nil { + return nil, err + } + u, err := url.Parse(proxyURL) + if err != nil { + return nil, fmt.Errorf("invalid proxy_url: %w", err) + } + if u.Scheme == "" || u.Host == "" { + return nil, fmt.Errorf("invalid proxy_url: scheme and host are required") + } + t.Proxy = http.ProxyURL(u) + } else { + t.Proxy = http.ProxyFromEnvironment + } + + cfg := utils.DefaultSSRFSafeHTTPClientConfig() + return &http.Client{ + Timeout: timeout, + Transport: t, + CheckRedirect: ssrfSafeRedirect(cfg.MaxRedirects), + }, nil +} diff --git a/internal/infrastructure/web_search/proxy_test.go b/internal/infrastructure/web_search/proxy_test.go new file mode 100644 index 00000000..46f318d1 --- /dev/null +++ b/internal/infrastructure/web_search/proxy_test.go @@ -0,0 +1,78 @@ +package web_search + +import ( + "net/http" + "net/url" + "strings" + "testing" +) + +func TestValidateProxyURL(t *testing.T) { + tests := []struct { + name string + raw string + wantErr bool + }{ + {"empty", "", false}, + {"whitespace only", " ", false}, + {"no scheme private IP bare host:port", "192.168.0.1:3128", true}, + {"localhost http", "http://localhost:3128", true}, + {"direct IPv4 http", "http://192.168.1.1:3128", true}, + {"socks5 to IP blocked", "socks5://10.0.0.1:1080", true}, + {"bad scheme", "ftp://proxy.example:21", true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := ValidateProxyURL(tt.raw) + if tt.wantErr && err == nil { + t.Fatalf("expected error, got nil") + } + if !tt.wantErr && err != nil { + t.Fatalf("unexpected error: %v", err) + } + }) + } +} + +func TestNewSearchHTTPClient_RejectsUnsafeProxy(t *testing.T) { + _, err := NewSearchHTTPClient(0, "http://127.0.0.1:3128") + if err == nil { + t.Fatal("expected error for disallowed proxy URL (127.0.0.1)") + } + if !strings.Contains(err.Error(), "SSRF") { + t.Fatalf("expected SSRF-related error, got: %v", err) + } +} + +func TestNewSearchHTTPClient_AcceptsEmptyProxy(t *testing.T) { + c, err := NewSearchHTTPClient(0, "") + if err != nil { + t.Fatal(err) + } + if c.Transport == nil { + t.Fatal("expected transport") + } + if c.CheckRedirect == nil { + t.Fatal("expected CheckRedirect for SSRF-safe redirects") + } +} + +func TestSsrfSafeRedirect_BlocksNonHTTPSScheme(t *testing.T) { + h := ssrfSafeRedirect(10) + req := &http.Request{URL: mustParse(t, "ftp://evil.com/")} + // len(via)==0 so first redirect + err := h(req, nil) + if err == nil { + t.Fatal("expected error for ftp redirect") + } +} + +func mustParse(t *testing.T, s string) *url.URL { + t.Helper() + u, err := url.Parse(s) + if err != nil { + t.Fatal(err) + } + return u +} diff --git a/internal/infrastructure/web_search/tavily.go b/internal/infrastructure/web_search/tavily.go index 614adfbf..4a1e3526 100644 --- a/internal/infrastructure/web_search/tavily.go +++ b/internal/infrastructure/web_search/tavily.go @@ -36,8 +36,9 @@ func NewTavilyProvider(params types.WebSearchProviderParameters) (interfaces.Web if params.APIKey == "" { return nil, fmt.Errorf("API key is required for Tavily provider") } - client := &http.Client{ - Timeout: defaultTavilyTimeout, + client, err := NewSearchHTTPClient(defaultTavilyTimeout, params.ProxyURL) + if err != nil { + return nil, err } return &TavilyProvider{ client: client, diff --git a/internal/logger/llm_logger.go b/internal/logger/llm_logger.go new file mode 100644 index 00000000..12ddd55b --- /dev/null +++ b/internal/logger/llm_logger.go @@ -0,0 +1,247 @@ +package logger + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +var llmDebug struct { + mu sync.Mutex + enabled bool + dir string +} + +func init() { + configureLLMDebugLog() +} + +func configureLLMDebugLog() { + val := strings.TrimSpace(os.Getenv("LLM_DEBUG_LOG")) + if val == "" || val == "false" || val == "0" { + return + } + + var dir string + if val == "true" || val == "1" { + dir = resolveLLMDebugDir() + } else { + dir = val + } + if dir == "" { + dir = "llm_debug" + } + + if err := os.MkdirAll(dir, 0o755); err != nil { + fmt.Fprintf(os.Stderr, "llm_debug: failed to create dir %s: %v\n", dir, err) + return + } + + llmDebug.dir = dir + llmDebug.enabled = true + + go cleanupOldDebugFiles(dir, 7*24*time.Hour) + + fmt.Fprintf(os.Stderr, "llm_debug: LLM debug log enabled → %s/\n", dir) +} + +func resolveLLMDebugDir() string { + if logPath := strings.TrimSpace(os.Getenv("LOG_PATH")); logPath != "" { + return filepath.Join(filepath.Dir(logPath), "llm_debug") + } + if macPath := defaultMacAppLogPath(); macPath != "" { + return filepath.Join(filepath.Dir(macPath), "llm_debug") + } + return "llm_debug" +} + +// cleanupOldDebugFiles removes files older than maxAge from the debug directory. +func cleanupOldDebugFiles(dir string, maxAge time.Duration) { + entries, err := os.ReadDir(dir) + if err != nil { + return + } + cutoff := time.Now().Add(-maxAge) + for _, e := range entries { + if e.IsDir() { + continue + } + info, err := e.Info() + if err != nil { + continue + } + if info.ModTime().Before(cutoff) { + _ = os.Remove(filepath.Join(dir, e.Name())) + } + } +} + +// LLMDebugEnabled returns true when the dedicated LLM debug log is active. +func LLMDebugEnabled() bool { + return llmDebug.enabled +} + +// LLMDebugLog writes a complete model call record to a per-request log file. +// All calls sharing the same request_id are appended to the same file. +func LLMDebugLog(ctx context.Context, record *LLMCallRecord) { + if !llmDebug.enabled || record == nil { + return + } + + text := formatRecord(record) + + reqID := extractRequestID(ctx) + filename := buildFilename(reqID) + + llmDebug.mu.Lock() + defer llmDebug.mu.Unlock() + + path := filepath.Join(llmDebug.dir, filename) + f, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + fmt.Fprintf(os.Stderr, "llm_debug: open %s: %v\n", path, err) + return + } + defer f.Close() + _, _ = f.WriteString(text) +} + +func buildFilename(reqID string) string { + if reqID != "" { + return reqID + ".log" + } + return time.Now().Format("20060102_150405.000") + ".log" +} + +func formatRecord(r *LLMCallRecord) string { + var b strings.Builder + b.Grow(4096) + + separator := fmt.Sprintf("================ %s ================", r.CallType) + b.WriteString("\n") + b.WriteString(separator) + b.WriteString("\n") + b.WriteString(fmt.Sprintf("Time: %s\n", time.Now().Format("2006-01-02 15:04:05.000"))) + b.WriteString(fmt.Sprintf("Model: %s\n", r.Model)) + if r.Duration > 0 { + b.WriteString(fmt.Sprintf("Duration: %s\n", r.Duration.Round(time.Millisecond))) + } + + for _, s := range r.Sections { + b.WriteString(fmt.Sprintf("\n---------- %s ----------\n", s.Title)) + b.WriteString(s.Content) + if !strings.HasSuffix(s.Content, "\n") { + b.WriteString("\n") + } + } + + if r.Error != "" { + b.WriteString("\n---------- Error ----------\n") + b.WriteString(r.Error) + b.WriteString("\n") + } + + b.WriteString(strings.Repeat("=", len(separator))) + b.WriteString("\n") + + return b.String() +} + +func extractRequestID(ctx context.Context) string { + entry := GetLogger(ctx) + if v, ok := entry.Data["request_id"]; ok { + return fmt.Sprintf("%v", v) + } + return "" +} + +// ---------- Record types ---------- + +// LLMCallRecord holds all information for one model API call. +type LLMCallRecord struct { + CallType string // "Chat", "Chat Stream", "Embedding", "Rerank", "VLM" + Model string + Duration time.Duration + Sections []RecordSection + Error string +} + +// RecordSection is a titled block of text within a call record. +type RecordSection struct { + Title string + Content string +} + +// ---------- Shared helpers for building sections ---------- + +// LLMMessage is a simplified chat message for logging. +type LLMMessage struct { + Role string + Content string + Name string + ToolCallID string + Images []string + ToolCalls []LLMToolCallInfo +} + +// LLMToolCallInfo holds tool call info for logging. +type LLMToolCallInfo struct { + ID string + FuncName string + Arguments string +} + +// FormatMessages formats chat messages into a readable block. +func FormatMessages(messages []LLMMessage) string { + var b strings.Builder + for _, m := range messages { + b.WriteString(fmt.Sprintf("[%s]", m.Role)) + if m.Name != "" { + b.WriteString(fmt.Sprintf(" name=%s", m.Name)) + } + if m.ToolCallID != "" { + b.WriteString(fmt.Sprintf(" tool_call_id=%s", m.ToolCallID)) + } + b.WriteString("\n") + + if m.Content != "" { + b.WriteString(m.Content) + b.WriteString("\n") + } + for _, img := range m.Images { + if len([]rune(img)) > 80 { + b.WriteString(fmt.Sprintf("[image: %s (%d bytes)]\n", TruncateRunes(img, 80), len(img))) + } else { + b.WriteString(fmt.Sprintf("[image: %s]\n", img)) + } + } + for _, tc := range m.ToolCalls { + b.WriteString(fmt.Sprintf(" -> tool_call: id=%s, func=%s, args=%s\n", tc.ID, tc.FuncName, tc.Arguments)) + } + b.WriteString("\n") + } + return b.String() +} + +// FormatToolCalls formats response tool calls into a readable block. +func FormatToolCalls(tcs []LLMToolCallInfo) string { + var b strings.Builder + for _, tc := range tcs { + b.WriteString(fmt.Sprintf("[tool_call] id=%s, func=%s\n%s\n\n", tc.ID, tc.FuncName, tc.Arguments)) + } + return b.String() +} + +// TruncateRunes truncates a string to maxRunes runes, appending "..." if truncated. +// This is safe for multi-byte UTF-8 characters (e.g. Chinese). +func TruncateRunes(s string, maxRunes int) string { + runes := []rune(s) + if len(runes) <= maxRunes { + return s + } + return string(runes[:maxRunes]) + "..." +} diff --git a/internal/logger/logger.go b/internal/logger/logger.go index 884d07a4..92060368 100644 --- a/internal/logger/logger.go +++ b/internal/logger/logger.go @@ -191,6 +191,16 @@ func GetLogger(c context.Context) *logrus.Entry { return logrus.NewEntry(appLogger) } +// SetOutput overrides the internal logger's output destination. +// Intended for use in tests that need to capture and assert on log content +// (e.g. verifying secrets are not written out). Restore the original writer +// (usually os.Stdout) in a defer after the test. +func SetOutput(w io.Writer) { + loggerMu.Lock() + defer loggerMu.Unlock() + appLogger.SetOutput(w) +} + // SetLogLevel 设置日志级别 func SetLogLevel(level LogLevel) { var logLevel logrus.Level @@ -388,6 +398,11 @@ func CloneContext(ctx context.Context) context.Context { types.LanguageContextKey, types.SessionTenantIDContextKey, types.EmbedQueryContextKey, + // Keep the Langfuse trace alive across CloneContext boundaries so + // LLM/Embedder/Reranker/VLM/ASR wrappers attach their generations + // to the same trace opened by GinMiddleware, instead of each call + // auto-creating its own orphan trace. + types.LangfuseTraceContextKey, } { if v := ctx.Value(k); v != nil { newCtx = context.WithValue(newCtx, k, v) diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index e318b637..15c7fcec 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -2,6 +2,7 @@ package middleware import ( "context" + "crypto/subtle" "errors" "fmt" "log" @@ -178,7 +179,7 @@ func Auth( return } - if t == nil || t.APIKey != apiKey { + if t == nil || subtle.ConstantTimeCompare([]byte(t.APIKey), []byte(apiKey)) != 1 { c.JSON(http.StatusUnauthorized, gin.H{ "error": "Unauthorized: invalid API key", }) diff --git a/internal/middleware/logger.go b/internal/middleware/logger.go index 147b13f9..d2c73852 100644 --- a/internal/middleware/logger.go +++ b/internal/middleware/logger.go @@ -143,7 +143,9 @@ func Logger() gin.HandlerFunc { start := time.Now() path := c.Request.URL.Path raw := c.Request.URL.RawQuery - if strings.HasPrefix(path, "/assets/") { + + isWikiStats := strings.HasPrefix(path, "/api/v1/knowledgebase/") && strings.HasSuffix(path, "/wiki/stats") + if strings.HasPrefix(path, "/assets/") || isWikiStats { c.Next() return } diff --git a/internal/models/asr/asr.go b/internal/models/asr/asr.go index 02d70e53..c241d52e 100644 --- a/internal/models/asr/asr.go +++ b/internal/models/asr/asr.go @@ -36,10 +36,30 @@ type Config struct { APIKey string ModelID string Language string // optional: specify language for transcription + // CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 + CustomHeaders map[string]string +} + +// ConfigFromModel 根据 types.Model 构造 asr.Config。 +// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。 +// 当前 ASR 不涉及 WeKnoraCloud 凭证,所以签名不含 appID/appSecret。 +func ConfigFromModel(m *types.Model) *Config { + if m == nil { + return nil + } + return &Config{ + ModelID: m.ID, + APIKey: m.Parameters.APIKey, + BaseURL: m.Parameters.BaseURL, + ModelName: m.Name, + Source: m.Source, + CustomHeaders: m.Parameters.CustomHeaders, + } } // NewASR creates an ASR instance based on the provided configuration. // All ASR vendors use the OpenAI-compatible /v1/audio/transcriptions API. func NewASR(config *Config) (ASR, error) { - return NewOpenAIASR(config) + a, err := NewOpenAIASR(config) + return wrapASRLangfuse(a, err) } diff --git a/internal/models/asr/config_from_model_test.go b/internal/models/asr/config_from_model_test.go new file mode 100644 index 00000000..7d2275ec --- /dev/null +++ b/internal/models/asr/config_from_model_test.go @@ -0,0 +1,36 @@ +package asr + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +func TestConfigFromModel(t *testing.T) { + m := &types.Model{ + ID: "asr-1", + Name: "whisper-1", + Source: types.ModelSourceRemote, + Parameters: types.ModelParameters{ + BaseURL: "https://api.example.com/v1", + APIKey: "sk", + CustomHeaders: map[string]string{"X": "y"}, + }, + } + cfg := ConfigFromModel(m) + if cfg == nil || cfg.ModelID != "asr-1" || cfg.ModelName != "whisper-1" { + t.Fatalf("identity mismatch: %+v", cfg) + } + if cfg.BaseURL != "https://api.example.com/v1" || cfg.APIKey != "sk" { + t.Errorf("connection fields mismatch: %+v", cfg) + } + if cfg.CustomHeaders["X"] != "y" { + t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders) + } +} + +func TestConfigFromModel_Nil(t *testing.T) { + if got := ConfigFromModel(nil); got != nil { + t.Fatalf("expected nil, got %+v", got) + } +} diff --git a/internal/models/asr/langfuse_wrapper.go b/internal/models/asr/langfuse_wrapper.go new file mode 100644 index 00000000..7564c059 --- /dev/null +++ b/internal/models/asr/langfuse_wrapper.go @@ -0,0 +1,79 @@ +package asr + +import ( + "context" + + "github.com/Tencent/WeKnora/internal/tracing/langfuse" +) + +// langfuseASR wraps an ASR implementation and reports each Transcribe call +// as a Langfuse generation observation. Audio bytes are not uploaded — we +// record file name, audio size and duration (derived from segment end times) +// so usage can be billed by second/minute, which is how most ASR providers +// price their services. +type langfuseASR struct { + inner ASR +} + +func (l *langfuseASR) GetModelName() string { return l.inner.GetModelName() } +func (l *langfuseASR) GetModelID() string { return l.inner.GetModelID() } + +func (l *langfuseASR) Transcribe(ctx context.Context, audioBytes []byte, fileName string) (*TranscriptionResult, error) { + mgr := langfuse.GetManager() + if !mgr.Enabled() { + return l.inner.Transcribe(ctx, audioBytes, fileName) + } + + genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{ + Name: "asr.transcribe", + Model: l.inner.GetModelName(), + Input: map[string]interface{}{ + "file_name": fileName, + "audio_size": len(audioBytes), + }, + Metadata: map[string]interface{}{ + "model_id": l.inner.GetModelID(), + "audio_size": len(audioBytes), + }, + }) + + result, err := l.inner.Transcribe(genCtx, audioBytes, fileName) + + output := map[string]interface{}{} + var duration float64 + if result != nil { + output["text"] = result.Text + output["segment_count"] = len(result.Segments) + if n := len(result.Segments); n > 0 { + duration = result.Segments[n-1].End + output["duration_seconds"] = duration + } + } + + // ASR is billed per second; we emit the audio duration (when available) + // in the "Output" side of usage so users can configure per-model pricing + // in Langfuse (e.g. $0.006 per minute for Whisper-1). + var usage *langfuse.TokenUsage + if duration > 0 { + seconds := int(duration + 0.5) + usage = &langfuse.TokenUsage{ + Output: seconds, + Total: seconds, + Unit: "SECONDS", + } + } + + gen.Finish(output, usage, err) + return result, err +} + +// wrapASRLangfuse applies the Langfuse decorator when the manager is enabled. +func wrapASRLangfuse(a ASR, err error) (ASR, error) { + if err != nil || a == nil { + return a, err + } + if !langfuse.GetManager().Enabled() { + return a, nil + } + return &langfuseASR{inner: a}, nil +} diff --git a/internal/models/asr/openai.go b/internal/models/asr/openai.go index ea72756c..6244a5e5 100644 --- a/internal/models/asr/openai.go +++ b/internal/models/asr/openai.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" openai "github.com/sashabaranov/go-openai" ) @@ -33,7 +34,14 @@ func NewOpenAIASR(config *Config) (*OpenAIASR, error) { if config.BaseURL != "" { apiCfg.BaseURL = config.BaseURL } - apiCfg.HTTPClient = &http.Client{Timeout: asrDefaultTimeout} + httpClient := &http.Client{Timeout: asrDefaultTimeout} + + // 注入用户自定义 HTTP header(类似 OpenAI Python SDK 的 extra_headers) + if len(config.CustomHeaders) > 0 { + apiCfg.HTTPClient = secutils.WrapHTTPClientWithHeaders(httpClient, config.CustomHeaders) + } else { + apiCfg.HTTPClient = httpClient + } return &OpenAIASR{ modelName: config.ModelName, diff --git a/internal/models/chat/chat.go b/internal/models/chat/chat.go index f9a2b99c..27d0deda 100644 --- a/internal/models/chat/chat.go +++ b/internal/models/chat/chat.go @@ -101,20 +101,48 @@ type ChatConfig struct { ModelID string Provider string ExtraConfig map[string]string - AppID string - AppSecret string // 加密值,由工厂函数调用方传入,在 NewWeKnoraCloudChat 中使用前已解密 + // CustomHeaders 允许在调用远程 OpenAI 兼容 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 + CustomHeaders map[string]string + AppID string + AppSecret string // 加密值,由工厂函数调用方传入,在 NewWeKnoraCloudChat 中使用前已解密 +} + +// ConfigFromModel 根据 types.Model 构造 ChatConfig。 +// 保证生产路径(service 层根据 DB 中的模型配置拉起实例)和测试路径 +// (handler 层根据前端表单临时拉起实例)走完全相同的字段映射,避免重复样板。 +// appID / appSecret 是已经解密/解析好的 WeKnoraCloud 凭证,调用方负责传入。 +func ConfigFromModel(m *types.Model, appID, appSecret string) *ChatConfig { + if m == nil { + return nil + } + return &ChatConfig{ + ModelID: m.ID, + APIKey: m.Parameters.APIKey, + BaseURL: m.Parameters.BaseURL, + ModelName: m.Name, + Source: m.Source, + Provider: m.Parameters.Provider, + ExtraConfig: m.Parameters.ExtraConfig, + CustomHeaders: m.Parameters.CustomHeaders, + AppID: appID, + AppSecret: appSecret, + } } // NewChat 创建聊天实例 func NewChat(config *ChatConfig, ollamaService *ollama.OllamaService) (Chat, error) { + var c Chat + var err error switch strings.ToLower(string(config.Source)) { case string(types.ModelSourceLocal): - return NewOllamaChat(config, ollamaService) + c, err = NewOllamaChat(config, ollamaService) case string(types.ModelSourceRemote): - return NewRemoteChat(config) + c, err = NewRemoteChat(config) default: return nil, fmt.Errorf("unsupported chat model source: %s", config.Source) } + c, err = wrapChatDebug(c, err) + return wrapChatLangfuse(c, err) } // NewRemoteChat 根据 provider 创建远程聊天实例 diff --git a/internal/models/chat/chat_provider_spec.go b/internal/models/chat/chat_provider_spec.go index b35ebe44..e5df5c0f 100644 --- a/internal/models/chat/chat_provider_spec.go +++ b/internal/models/chat/chat_provider_spec.go @@ -109,32 +109,15 @@ type ThinkingChatCompletionRequest struct { // --- Customizer functions --- -type weKnoraCloudChatRequest struct { - Model string `json:"model"` - Messages []weKnoraCloudMessage `json:"messages"` - Stream bool `json:"stream"` - MaxTokens int `json:"max_tokens,omitempty"` - Temperature float64 `json:"temperature,omitempty"` - TopP float64 `json:"top_p,omitempty"` -} - -type weKnoraCloudMessage struct { - Role string `json:"role"` - Content string `json:"content"` -} - -func weKnoraCloudRequestCustomizer(req *openai.ChatCompletionRequest, opts *ChatOptions, isStream bool) (any, bool) { - weKnoraCloudReq := weKnoraCloudChatRequest{ - Model: req.Model, - Messages: convertToWeKnoraCloudMessagesFromOpenAI(req.Messages), - Stream: isStream, - } - if opts != nil { - weKnoraCloudReq.Temperature = opts.Temperature - weKnoraCloudReq.TopP = opts.TopP - weKnoraCloudReq.MaxTokens = opts.MaxTokens - } - return weKnoraCloudReq, true +// weKnoraCloudRequestCustomizer 构造 WeKnoraCloud 请求。 +// WeKnoraCloud 走 OpenAI 兼容格式,除了 MultiContent 需要降级为纯文本 Content 之外, +// 其他字段(tools / tool_choice / parallel_tool_calls / response_format / stream_options 等)直接透传, +// 以保证 function calling 等能力可用。 +func weKnoraCloudRequestCustomizer(req *openai.ChatCompletionRequest, _ *ChatOptions, isStream bool) (any, bool) { + cloudReq := *req + cloudReq.Stream = isStream + cloudReq.Messages = convertToWeKnoraCloudMessagesFromOpenAI(req.Messages) + return cloudReq, true } func weKnoraCloudHeaderCustomizer(chat *RemoteAPIChat, req *http.Request, body []byte) error { @@ -146,20 +129,23 @@ func weKnoraCloudHeaderCustomizer(chat *RemoteAPIChat, req *http.Request, body [ return nil } -func convertToWeKnoraCloudMessagesFromOpenAI(messages []openai.ChatCompletionMessage) []weKnoraCloudMessage { - result := make([]weKnoraCloudMessage, 0, len(messages)) +// convertToWeKnoraCloudMessagesFromOpenAI 将 MultiContent 降级为纯文本, +// 其它字段(tool_calls / tool_call_id / name 等)完全保留,保证 tool 协议正常。 +func convertToWeKnoraCloudMessagesFromOpenAI(messages []openai.ChatCompletionMessage) []openai.ChatCompletionMessage { + result := make([]openai.ChatCompletionMessage, 0, len(messages)) for _, m := range messages { - content := m.Content - if content == "" && len(m.MultiContent) > 0 { + msg := m + if msg.Content == "" && len(msg.MultiContent) > 0 { var textParts []string - for _, part := range m.MultiContent { + for _, part := range msg.MultiContent { if part.Type == openai.ChatMessagePartTypeText && part.Text != "" { textParts = append(textParts, part.Text) } } - content = strings.Join(textParts, "\n") + msg.Content = strings.Join(textParts, "\n") + msg.MultiContent = nil } - result = append(result, weKnoraCloudMessage{Role: m.Role, Content: content}) + result = append(result, msg) } return result } diff --git a/internal/models/chat/config_from_model_test.go b/internal/models/chat/config_from_model_test.go new file mode 100644 index 00000000..9e0e9fe5 --- /dev/null +++ b/internal/models/chat/config_from_model_test.go @@ -0,0 +1,59 @@ +package chat + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +// TestConfigFromModel 验证 ConfigFromModel 能把 types.Model 完整映射到 ChatConfig, +// 避免后续新加字段时只在生产路径或测试路径其中一侧更新导致功能漏配。 +func TestConfigFromModel(t *testing.T) { + m := &types.Model{ + ID: "model-123", + Name: "gpt-4o-mini", + Source: types.ModelSourceRemote, + Parameters: types.ModelParameters{ + BaseURL: "https://api.example.com/v1", + APIKey: "sk-xxx", + Provider: "openai", + ExtraConfig: map[string]string{ + "deployment": "prod", + }, + CustomHeaders: map[string]string{ + "X-Gateway-Token": "abc", + "X-Trace-ID": "t-1", + }, + }, + } + + cfg := ConfigFromModel(m, "app-id", "app-secret") + if cfg == nil { + t.Fatal("ConfigFromModel returned nil") + } + if cfg.ModelID != "model-123" || cfg.ModelName != "gpt-4o-mini" { + t.Errorf("model identity not propagated: %+v", cfg) + } + if cfg.BaseURL != "https://api.example.com/v1" || cfg.APIKey != "sk-xxx" { + t.Errorf("connection fields not propagated: %+v", cfg) + } + if cfg.Provider != "openai" { + t.Errorf("provider not propagated: %q", cfg.Provider) + } + if cfg.ExtraConfig["deployment"] != "prod" { + t.Errorf("ExtraConfig not propagated: %+v", cfg.ExtraConfig) + } + if cfg.CustomHeaders["X-Gateway-Token"] != "abc" || + cfg.CustomHeaders["X-Trace-ID"] != "t-1" { + t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders) + } + if cfg.AppID != "app-id" || cfg.AppSecret != "app-secret" { + t.Errorf("cloud credentials not propagated: %+v", cfg) + } +} + +func TestConfigFromModel_Nil(t *testing.T) { + if got := ConfigFromModel(nil, "", ""); got != nil { + t.Fatalf("expected nil for nil model, got %+v", got) + } +} diff --git a/internal/models/chat/langfuse_wrapper.go b/internal/models/chat/langfuse_wrapper.go new file mode 100644 index 00000000..e628969f --- /dev/null +++ b/internal/models/chat/langfuse_wrapper.go @@ -0,0 +1,210 @@ +package chat + +import ( + "context" + "time" + + "github.com/Tencent/WeKnora/internal/tracing/langfuse" + "github.com/Tencent/WeKnora/internal/types" +) + +// langfuseChat wraps a Chat implementation and emits a Langfuse generation +// observation for every Chat/ChatStream call, capturing prompt, response and +// token usage. The wrapper is only installed when the Langfuse manager is +// enabled, so there is no cost for deployments that don't use Langfuse. +type langfuseChat struct { + inner Chat +} + +func (l *langfuseChat) GetModelName() string { return l.inner.GetModelName() } +func (l *langfuseChat) GetModelID() string { return l.inner.GetModelID() } + +func (l *langfuseChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) { + mgr := langfuse.GetManager() + if !mgr.Enabled() { + return l.inner.Chat(ctx, messages, opts) + } + + genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{ + Name: "chat.completion", + Model: l.inner.GetModelName(), + Input: buildLangfuseMessages(messages), + ModelParameters: buildLangfuseModelParams(opts), + Metadata: map[string]interface{}{ + "model_id": l.inner.GetModelID(), + "streaming": false, + "has_tools": opts != nil && len(opts.Tools) > 0, + }, + }) + + resp, err := l.inner.Chat(genCtx, messages, opts) + + var usage *langfuse.TokenUsage + var output interface{} + if resp != nil { + usage = convertUsage(&resp.Usage) + output = map[string]interface{}{ + "content": resp.Content, + "tool_calls": resp.ToolCalls, + "finish_reason": resp.FinishReason, + } + } + gen.Finish(output, usage, err) + return resp, err +} + +func (l *langfuseChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) { + mgr := langfuse.GetManager() + if !mgr.Enabled() { + return l.inner.ChatStream(ctx, messages, opts) + } + + genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{ + Name: "chat.completion.stream", + Model: l.inner.GetModelName(), + Input: buildLangfuseMessages(messages), + ModelParameters: buildLangfuseModelParams(opts), + Metadata: map[string]interface{}{ + "model_id": l.inner.GetModelID(), + "streaming": true, + "has_tools": opts != nil && len(opts.Tools) > 0, + }, + }) + + ch, err := l.inner.ChatStream(genCtx, messages, opts) + if err != nil { + gen.Finish(nil, nil, err) + return ch, err + } + if ch == nil { + gen.Finish(nil, nil, nil) + return nil, nil + } + + wrapped := make(chan types.StreamResponse) + go func() { + defer close(wrapped) + var contentBuf []byte + var usage *types.TokenUsage + var toolCalls []types.LLMToolCall + var finishReason string + var firstToken bool + + for resp := range ch { + if resp.ResponseType == types.ResponseTypeAnswer && resp.Content != "" { + if !firstToken { + gen.MarkCompletionStart(time.Now()) + firstToken = true + } + contentBuf = append(contentBuf, resp.Content...) + } + if resp.Usage != nil { + usage = resp.Usage + } + if len(resp.ToolCalls) > 0 { + toolCalls = resp.ToolCalls + } + if resp.FinishReason != "" { + finishReason = resp.FinishReason + } + wrapped <- resp + } + + output := map[string]interface{}{ + "content": string(contentBuf), + "tool_calls": toolCalls, + "finish_reason": finishReason, + } + gen.Finish(output, convertUsage(usage), nil) + }() + return wrapped, nil +} + +func buildLangfuseMessages(messages []Message) []map[string]interface{} { + out := make([]map[string]interface{}, 0, len(messages)) + for _, m := range messages { + entry := map[string]interface{}{ + "role": m.Role, + } + if m.Content != "" { + entry["content"] = m.Content + } + if len(m.MultiContent) > 0 { + entry["content"] = m.MultiContent + } + if m.Name != "" { + entry["name"] = m.Name + } + if m.ToolCallID != "" { + entry["tool_call_id"] = m.ToolCallID + } + if len(m.ToolCalls) > 0 { + entry["tool_calls"] = m.ToolCalls + } + out = append(out, entry) + } + return out +} + +func buildLangfuseModelParams(opts *ChatOptions) map[string]interface{} { + if opts == nil { + return nil + } + params := map[string]interface{}{} + if opts.Temperature != 0 { + params["temperature"] = opts.Temperature + } + if opts.TopP != 0 { + params["top_p"] = opts.TopP + } + if opts.MaxTokens > 0 { + params["max_tokens"] = opts.MaxTokens + } + if opts.MaxCompletionTokens > 0 { + params["max_completion_tokens"] = opts.MaxCompletionTokens + } + if opts.FrequencyPenalty != 0 { + params["frequency_penalty"] = opts.FrequencyPenalty + } + if opts.PresencePenalty != 0 { + params["presence_penalty"] = opts.PresencePenalty + } + if opts.Seed != 0 { + params["seed"] = opts.Seed + } + if opts.ToolChoice != "" { + params["tool_choice"] = opts.ToolChoice + } + if len(params) == 0 { + return nil + } + return params +} + +func convertUsage(u *types.TokenUsage) *langfuse.TokenUsage { + if u == nil { + return nil + } + if u.PromptTokens == 0 && u.CompletionTokens == 0 && u.TotalTokens == 0 { + return nil + } + return &langfuse.TokenUsage{ + Input: u.PromptTokens, + Output: u.CompletionTokens, + Total: u.TotalTokens, + Unit: "TOKENS", + } +} + +// wrapChatLangfuse wraps a Chat in a Langfuse-aware decorator when the +// manager is enabled. Called from NewChat after the debug wrapper so both +// sinks observe the same call. +func wrapChatLangfuse(c Chat, err error) (Chat, error) { + if err != nil || c == nil { + return c, err + } + if !langfuse.GetManager().Enabled() { + return c, nil + } + return &langfuseChat{inner: c}, nil +} diff --git a/internal/models/chat/llm_debug.go b/internal/models/chat/llm_debug.go new file mode 100644 index 00000000..698a6193 --- /dev/null +++ b/internal/models/chat/llm_debug.go @@ -0,0 +1,214 @@ +package chat + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" +) + +func buildLLMMessages(messages []Message) []logger.LLMMessage { + out := make([]logger.LLMMessage, 0, len(messages)) + for _, m := range messages { + lm := logger.LLMMessage{ + Role: m.Role, + Content: m.Content, + Name: m.Name, + ToolCallID: m.ToolCallID, + Images: m.Images, + } + + if lm.Content == "" && len(m.MultiContent) > 0 { + var parts []string + for _, mc := range m.MultiContent { + switch mc.Type { + case "text": + parts = append(parts, mc.Text) + case "image_url": + if mc.ImageURL != nil { + parts = append(parts, fmt.Sprintf("[image_url: %s]", truncateForDebug(mc.ImageURL.URL, 120))) + } + } + } + lm.Content = strings.Join(parts, "\n") + } + + for _, tc := range m.ToolCalls { + lm.ToolCalls = append(lm.ToolCalls, logger.LLMToolCallInfo{ + ID: tc.ID, + FuncName: tc.Function.Name, + Arguments: tc.Function.Arguments, + }) + } + out = append(out, lm) + } + return out +} + +func buildOptionsSection(opts *ChatOptions) string { + if opts == nil { + return "" + } + var parts []string + parts = append(parts, fmt.Sprintf("Temperature=%.2f", opts.Temperature)) + if opts.TopP > 0 { + parts = append(parts, fmt.Sprintf("TopP=%.2f", opts.TopP)) + } + if opts.MaxTokens > 0 { + parts = append(parts, fmt.Sprintf("MaxTokens=%d", opts.MaxTokens)) + } + if opts.MaxCompletionTokens > 0 { + parts = append(parts, fmt.Sprintf("MaxCompletionTokens=%d", opts.MaxCompletionTokens)) + } + if opts.FrequencyPenalty > 0 { + parts = append(parts, fmt.Sprintf("FrequencyPenalty=%.2f", opts.FrequencyPenalty)) + } + if opts.PresencePenalty > 0 { + parts = append(parts, fmt.Sprintf("PresencePenalty=%.2f", opts.PresencePenalty)) + } + if opts.ToolChoice != "" { + parts = append(parts, fmt.Sprintf("ToolChoice=%s", opts.ToolChoice)) + } + if len(opts.Format) > 0 { + parts = append(parts, "ResponseFormat=json_object") + } + return strings.Join(parts, ", ") +} + +func buildToolsSection(opts *ChatOptions) string { + if opts == nil || len(opts.Tools) == 0 { + return "" + } + var b strings.Builder + for i, t := range opts.Tools { + if i > 0 { + b.WriteString("\n") + } + b.WriteString(fmt.Sprintf("- %s: %s", t.Function.Name, t.Function.Description)) + } + return b.String() +} + +func buildResponseToolCalls(tcs []types.LLMToolCall) []logger.LLMToolCallInfo { + if len(tcs) == 0 { + return nil + } + out := make([]logger.LLMToolCallInfo, 0, len(tcs)) + for _, tc := range tcs { + out = append(out, logger.LLMToolCallInfo{ + ID: tc.ID, + FuncName: tc.Function.Name, + Arguments: tc.Function.Arguments, + }) + } + return out +} + +func usageString(u types.TokenUsage) string { + return fmt.Sprintf("Prompt: %d, Completion: %d, Total: %d", + u.PromptTokens, u.CompletionTokens, u.TotalTokens) +} + +// logLLMDebugCall logs a complete non-stream LLM chat call. +func logLLMDebugCall(ctx context.Context, model string, messages []Message, opts *ChatOptions, resp *types.ChatResponse, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "Chat", + Model: model, + Duration: dur, + } + + record.Sections = append(record.Sections, logger.RecordSection{ + Title: "Messages", + Content: logger.FormatMessages(buildLLMMessages(messages)), + }) + if s := buildOptionsSection(opts); s != "" { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Options", Content: s}) + } + if s := buildToolsSection(opts); s != "" { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Tools", Content: s}) + } + + if resp != nil { + var respText strings.Builder + if resp.Content != "" { + respText.WriteString("[assistant]\n") + respText.WriteString(resp.Content) + respText.WriteString("\n") + } + tcs := buildResponseToolCalls(resp.ToolCalls) + if len(tcs) > 0 { + respText.WriteString(logger.FormatToolCalls(tcs)) + } + if respText.Len() > 0 { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Response", Content: respText.String()}) + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Usage", Content: usageString(resp.Usage)}) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} + +// logLLMDebugStream logs a complete stream LLM chat call after all chunks have been received. +func logLLMDebugStream(ctx context.Context, model string, messages []Message, opts *ChatOptions, fullContent string, toolCalls []types.LLMToolCall, usage *types.TokenUsage, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "Chat Stream", + Model: model, + Duration: dur, + } + + record.Sections = append(record.Sections, logger.RecordSection{ + Title: "Messages", + Content: logger.FormatMessages(buildLLMMessages(messages)), + }) + if s := buildOptionsSection(opts); s != "" { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Options", Content: s}) + } + if s := buildToolsSection(opts); s != "" { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Tools", Content: s}) + } + + var respText strings.Builder + if fullContent != "" { + respText.WriteString("[assistant]\n") + respText.WriteString(fullContent) + respText.WriteString("\n") + } + tcs := buildResponseToolCalls(toolCalls) + if len(tcs) > 0 { + respText.WriteString(logger.FormatToolCalls(tcs)) + } + if respText.Len() > 0 { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Response", Content: respText.String()}) + } + + if usage != nil { + record.Sections = append(record.Sections, logger.RecordSection{Title: "Usage", Content: usageString(*usage)}) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} + +func truncateForDebug(s string, maxRunes int) string { + runes := []rune(s) + if len(runes) <= maxRunes { + return s + } + return string(runes[:maxRunes]) + fmt.Sprintf("...(%d chars)", len(runes)) +} diff --git a/internal/models/chat/llm_debug_wrapper.go b/internal/models/chat/llm_debug_wrapper.go new file mode 100644 index 00000000..a676ef94 --- /dev/null +++ b/internal/models/chat/llm_debug_wrapper.go @@ -0,0 +1,77 @@ +package chat + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" + "github.com/Tencent/WeKnora/internal/types" +) + +// debugChat wraps a Chat implementation and logs all calls to the LLM debug log. +// It works with both RemoteAPIChat and OllamaChat (or any future Chat impl). +type debugChat struct { + inner Chat +} + +func (d *debugChat) GetModelName() string { return d.inner.GetModelName() } +func (d *debugChat) GetModelID() string { return d.inner.GetModelID() } + +func (d *debugChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) { + callStart := time.Now() + resp, err := d.inner.Chat(ctx, messages, opts) + logLLMDebugCall(ctx, d.inner.GetModelName(), messages, opts, resp, err, time.Since(callStart)) + return resp, err +} + +func (d *debugChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) { + callStart := time.Now() + ch, err := d.inner.ChatStream(ctx, messages, opts) + if err != nil { + logLLMDebugStream(ctx, d.inner.GetModelName(), messages, opts, "", nil, nil, err, time.Since(callStart)) + return ch, err + } + if ch == nil { + return nil, nil + } + + wrapped := make(chan types.StreamResponse) + go func() { + defer close(wrapped) + var content strings.Builder + var usage *types.TokenUsage + var toolCalls []types.LLMToolCall + var streamErr error + + for resp := range ch { + if resp.ResponseType == types.ResponseTypeAnswer && resp.Content != "" { + content.WriteString(resp.Content) + } + if resp.ResponseType == types.ResponseTypeError { + streamErr = fmt.Errorf("%s", resp.Content) + } + if resp.Usage != nil { + usage = resp.Usage + } + if len(resp.ToolCalls) > 0 { + toolCalls = resp.ToolCalls + } + wrapped <- resp + } + + logLLMDebugStream(ctx, d.inner.GetModelName(), messages, opts, + content.String(), toolCalls, usage, streamErr, time.Since(callStart)) + }() + + return wrapped, nil +} + +// wrapChatDebug wraps a Chat if LLM debug logging is enabled. +func wrapChatDebug(c Chat, err error) (Chat, error) { + if err != nil || !logger.LLMDebugEnabled() { + return c, err + } + return &debugChat{inner: c}, nil +} diff --git a/internal/models/chat/remote_api.go b/internal/models/chat/remote_api.go index 1c7dde33..1f06facc 100644 --- a/internal/models/chat/remote_api.go +++ b/internal/models/chat/remote_api.go @@ -41,6 +41,8 @@ type RemoteAPIChat struct { provider provider.ProviderName appID string appSecret string + // customHeaders 为用户在模型配置中指定的自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 + customHeaders map[string]string // requestCustomizer 允许子类自定义请求 // 返回自定义请求体(如果为 nil 则使用标准请求)和是否需要使用原始 HTTP 请求 @@ -86,6 +88,17 @@ func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) { } } + // 如果指定了 CustomHeaders,则给 SDK 使用的 HTTPClient 挂一层 RoundTripper, + // 在每个请求上自动注入这些 header(raw HTTP 路径会在发送前单独处理)。 + if len(chatConfig.CustomHeaders) > 0 { + if httpClient, ok := config.HTTPClient.(*http.Client); ok { + config.HTTPClient = secutils.WrapHTTPClientWithHeaders(httpClient, chatConfig.CustomHeaders) + } else { + // SDK 默认未显式设置时 HTTPClient 为 nil,此时构造一个新的注入了 header 的 client。 + config.HTTPClient = secutils.WrapHTTPClientWithHeaders(nil, chatConfig.CustomHeaders) + } + } + modelName := chatConfig.ModelName if chatConfig.ExtraConfig != nil { if override := strings.TrimSpace(chatConfig.ExtraConfig["remote_model_name"]); override != "" { @@ -102,14 +115,15 @@ func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) { } return &RemoteAPIChat{ - modelName: modelName, - client: openai.NewClientWithConfig(config), - modelID: chatConfig.ModelID, - baseURL: chatConfig.BaseURL, - apiKey: apiKey, - provider: providerName, - appID: chatConfig.AppID, - appSecret: chatConfig.AppSecret, + modelName: modelName, + client: openai.NewClientWithConfig(config), + modelID: chatConfig.ModelID, + baseURL: chatConfig.BaseURL, + apiKey: apiKey, + provider: providerName, + appID: chatConfig.AppID, + appSecret: chatConfig.AppSecret, + customHeaders: chatConfig.CustomHeaders, }, nil } @@ -255,7 +269,8 @@ func (c *RemoteAPIChat) BuildChatCompletionRequest(messages []Message, opts *Cha // 处理 ParallelToolCalls if opts.ParallelToolCalls != nil { - req.ParallelToolCalls = *opts.ParallelToolCalls + val := *opts.ParallelToolCalls + req.ParallelToolCalls = val } // 处理 ToolChoice(标准实现) @@ -367,13 +382,11 @@ func (c *RemoteAPIChat) chatWithRawHTTP(ctx context.Context, endpoint string, cu httpReq.Header.Set("Authorization", "Bearer "+c.apiKey) } - // print headers - headers, err := json.Marshal(httpReq.Header) - if err != nil { - return nil, fmt.Errorf("marshal headers: %w", err) - } - logger.Infof(ctx, "[LLM Request] Remote HTTP, endpoint=%s, model=%s, headers: %s", - endpoint, c.modelName, string(headers)) + // 注入用户自定义 header(保留头会在工具内部自动跳过) + secutils.ApplyCustomHeaders(httpReq, c.customHeaders) + + logger.Infof(ctx, "[LLM Request] Remote HTTP, endpoint=%s, model=%s", + endpoint, c.modelName) resp, err := rawHTTPClient.Do(httpReq) if err != nil { @@ -511,14 +524,19 @@ func (c *RemoteAPIChat) chatStreamWithRawHTTP(ctx context.Context, endpoint stri return nil, fmt.Errorf("marshal request: %w", err) } - logger.Infof(ctx, "[LLM Stream] model=%s", c.modelName) - if endpoint == "" { endpoint = c.baseURL + "/chat/completions" } if err := secutils.ValidateURLForSSRF(endpoint); err != nil { return nil, fmt.Errorf("endpoint SSRF check failed: %w", err) } + + if prettyJSON, pErr := json.MarshalIndent(customReq, "", " "); pErr == nil { + logger.Infof(ctx, "[LLM Stream Request] endpoint=%s, model=%s, stream=true, request:\n%s", + endpoint, c.modelName, secutils.CompactImageDataURLForLog(string(prettyJSON))) + } else { + logger.Infof(ctx, "[LLM Stream] endpoint=%s, model=%s", endpoint, c.modelName) + } httpReq, err := http.NewRequestWithContext(ctx, "POST", endpoint, bytes.NewBuffer(jsonData)) if err != nil { return nil, fmt.Errorf("create request: %w", err) @@ -537,6 +555,9 @@ func (c *RemoteAPIChat) chatStreamWithRawHTTP(ctx context.Context, endpoint stri } httpReq.Header.Set("Accept", "text/event-stream") + // 注入用户自定义 header(保留头会在工具内部自动跳过) + secutils.ApplyCustomHeaders(httpReq, c.customHeaders) + resp, err := rawHTTPClient.Do(httpReq) if err != nil { return nil, fmt.Errorf("send request: %w", err) @@ -570,11 +591,12 @@ func (c *RemoteAPIChat) processStream(ctx context.Context, stream *openai.ChatCo logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d", c.modelName, state.usage.PromptTokens, state.usage.CompletionTokens, state.usage.TotalTokens) } + toolCalls := state.buildOrderedToolCalls() streamChan <- types.StreamResponse{ ResponseType: types.ResponseTypeAnswer, Content: "", Done: true, - ToolCalls: state.buildOrderedToolCalls(), + ToolCalls: toolCalls, Usage: state.usage, FinishReason: state.lastFinishReason, } @@ -614,16 +636,16 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res event, err := reader.ReadEvent() if err != nil { if err == io.EOF { - // 部分模型不发送 [DONE] 标记,直接关闭连接,视为正常结束 if state.usage != nil { logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d", c.modelName, state.usage.PromptTokens, state.usage.CompletionTokens, state.usage.TotalTokens) } + toolCalls := state.buildOrderedToolCalls() streamChan <- types.StreamResponse{ ResponseType: types.ResponseTypeAnswer, Content: "", Done: true, - ToolCalls: state.buildOrderedToolCalls(), + ToolCalls: toolCalls, Usage: state.usage, } } else { @@ -646,11 +668,12 @@ func (c *RemoteAPIChat) processRawHTTPStream(ctx context.Context, resp *http.Res logger.Infof(ctx, "[LLM Usage] model=%s, prompt_tokens=%d, completion_tokens=%d, total_tokens=%d", c.modelName, state.usage.PromptTokens, state.usage.CompletionTokens, state.usage.TotalTokens) } + toolCalls := state.buildOrderedToolCalls() streamChan <- types.StreamResponse{ ResponseType: types.ResponseTypeAnswer, Content: "", Done: true, - ToolCalls: state.buildOrderedToolCalls(), + ToolCalls: toolCalls, Usage: state.usage, } return diff --git a/internal/models/chat/remote_api_test.go b/internal/models/chat/remote_api_test.go index 85a410b8..ae54e9c7 100644 --- a/internal/models/chat/remote_api_test.go +++ b/internal/models/chat/remote_api_test.go @@ -17,7 +17,7 @@ func newTestRemoteChat(t *testing.T) *RemoteAPIChat { chat, err := NewRemoteAPIChat(&ChatConfig{ Source: types.ModelSourceRemote, - BaseURL: "https://example.com/v1", + BaseURL: "", ModelName: "test-model", APIKey: "test-key", ModelID: "test-model", @@ -51,7 +51,15 @@ func TestBuildChatCompletionRequest_ParallelToolCalls(t *testing.T) { }}, } req := chat.BuildChatCompletionRequest(messages, opts, true) - assert.Equal(t, true, req.ParallelToolCalls) + assert.NotNil(t, req.ParallelToolCalls) + + val, ok := req.ParallelToolCalls.(bool) + if ok { + assert.Equal(t, true, val) + } else { + assert.Equal(t, true, req.ParallelToolCalls) + } + assert.Len(t, req.Tools, 1) assert.Equal(t, "mcp_weather_getforecast", req.Tools[0].Function.Name) }) @@ -63,7 +71,14 @@ func TestBuildChatCompletionRequest_ParallelToolCalls(t *testing.T) { ParallelToolCalls: &ptc, } req := chat.BuildChatCompletionRequest(messages, opts, false) - assert.Equal(t, false, req.ParallelToolCalls) + assert.NotNil(t, req.ParallelToolCalls) + + val, ok := req.ParallelToolCalls.(bool) + if ok { + assert.Equal(t, false, val) + } else { + assert.Equal(t, false, req.ParallelToolCalls) + } }) } diff --git a/internal/models/chat/sse_reader.go b/internal/models/chat/sse_reader.go index 6877be27..838c4d8a 100644 --- a/internal/models/chat/sse_reader.go +++ b/internal/models/chat/sse_reader.go @@ -47,6 +47,12 @@ func (r *SSEReader) ReadEvent() (*SSEEvent, error) { return &SSEEvent{Data: []byte(jsonStr)}, nil } + // 增强兼容性(data:后面没有紧接着一个空格) + if strings.HasPrefix(line, "data:") { + jsonStr := line[5:] + return &SSEEvent{Data: []byte(jsonStr)}, nil + } + // 其他行(如 event:, id: 等)跳过 } diff --git a/internal/models/embedding/aliyun.go b/internal/models/embedding/aliyun.go index 68246f14..0505fd21 100644 --- a/internal/models/embedding/aliyun.go +++ b/internal/models/embedding/aliyun.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) const ( @@ -29,9 +30,15 @@ type AliyunEmbedder struct { httpClient *http.Client timeout time.Duration maxRetries int + customHeaders map[string]string EmbedderPooler } +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (e *AliyunEmbedder) SetCustomHeaders(headers map[string]string) { + e.customHeaders = headers +} + // AliyunEmbedRequest represents an Aliyun DashScope multimodal embedding request type AliyunEmbedRequest struct { Model string `json:"model"` @@ -154,6 +161,7 @@ func (e *AliyunEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+e.apiKey) + secutils.ApplyCustomHeaders(req, e.customHeaders) resp, err = e.httpClient.Do(req) if err == nil { diff --git a/internal/models/embedding/azure_openai.go b/internal/models/embedding/azure_openai.go index f4dcbe3f..1a3d58bf 100644 --- a/internal/models/embedding/azure_openai.go +++ b/internal/models/embedding/azure_openai.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) // AzureOpenAIEmbedder implements text vectorization using Azure OpenAI API @@ -24,9 +25,15 @@ type AzureOpenAIEmbedder struct { apiVersion string httpClient *http.Client maxRetries int + customHeaders map[string]string EmbedderPooler } +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (e *AzureOpenAIEmbedder) SetCustomHeaders(headers map[string]string) { + e.customHeaders = headers +} + type azureOpenAIEmbedRequest struct { Model string `json:"model"` Input []string `json:"input"` @@ -157,6 +164,7 @@ func (e *AzureOpenAIEmbedder) doRequestWithRetry(ctx context.Context, jsonData [ } req.Header.Set("Content-Type", "application/json") req.Header.Set("api-key", e.apiKey) + secutils.ApplyCustomHeaders(req, e.customHeaders) resp, err = e.httpClient.Do(req) if err == nil { diff --git a/internal/models/embedding/config_from_model_test.go b/internal/models/embedding/config_from_model_test.go new file mode 100644 index 00000000..dc4a335e --- /dev/null +++ b/internal/models/embedding/config_from_model_test.go @@ -0,0 +1,43 @@ +package embedding + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +func TestConfigFromModel(t *testing.T) { + m := &types.Model{ + ID: "emb-1", + Name: "text-embedding-3-small", + Source: types.ModelSourceRemote, + Parameters: types.ModelParameters{ + BaseURL: "https://api.example.com/v1", + APIKey: "sk-xxx", + Provider: "openai", + EmbeddingParameters: types.EmbeddingParameters{ + Dimension: 1536, + TruncatePromptTokens: 512, + }, + ExtraConfig: map[string]string{"region": "us-east"}, + CustomHeaders: map[string]string{"X-Gateway": "g1"}, + }, + } + + cfg := ConfigFromModel(m, "app", "secret") + if cfg.ModelID != "emb-1" || cfg.ModelName != "text-embedding-3-small" { + t.Errorf("identity mismatch: %+v", cfg) + } + if cfg.Dimensions != 1536 || cfg.TruncatePromptTokens != 512 { + t.Errorf("embedding params mismatch: %+v", cfg) + } + if cfg.CustomHeaders["X-Gateway"] != "g1" { + t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders) + } + if cfg.ExtraConfig["region"] != "us-east" { + t.Errorf("ExtraConfig not propagated: %+v", cfg.ExtraConfig) + } + if cfg.AppID != "app" || cfg.AppSecret != "secret" { + t.Errorf("cloud creds mismatch: %+v", cfg) + } +} diff --git a/internal/models/embedding/embedder.go b/internal/models/embedding/embedder.go index a73d3208..68cd8c9e 100644 --- a/internal/models/embedding/embedder.go +++ b/internal/models/embedding/embedder.go @@ -5,8 +5,10 @@ import ( "fmt" "strings" + "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/models/provider" "github.com/Tencent/WeKnora/internal/models/utils/ollama" + "github.com/Tencent/WeKnora/internal/tracing/langfuse" "github.com/Tencent/WeKnora/internal/types" ) @@ -48,12 +50,51 @@ type Config struct { ModelID string `json:"model_id"` Provider string `json:"provider"` ExtraConfig map[string]string `json:"extra_config"` - AppID string - AppSecret string // 加密值,工厂函数调用方传入,使用前已解密 + // CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 + CustomHeaders map[string]string `json:"custom_headers"` + AppID string + AppSecret string // 加密值,工厂函数调用方传入,使用前已解密 +} + +// ConfigFromModel 根据 types.Model 构造 embedding.Config。 +// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。 +// appID / appSecret 是已解密的 WeKnoraCloud 凭证,调用方负责传入。 +func ConfigFromModel(m *types.Model, appID, appSecret string) Config { + if m == nil { + return Config{} + } + return Config{ + Source: m.Source, + BaseURL: m.Parameters.BaseURL, + APIKey: m.Parameters.APIKey, + ModelID: m.ID, + ModelName: m.Name, + Dimensions: m.Parameters.EmbeddingParameters.Dimension, + TruncatePromptTokens: m.Parameters.EmbeddingParameters.TruncatePromptTokens, + Provider: m.Parameters.Provider, + ExtraConfig: m.Parameters.ExtraConfig, + CustomHeaders: m.Parameters.CustomHeaders, + AppID: appID, + AppSecret: appSecret, + } } // NewEmbedder creates an embedder based on the configuration func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) { + e, err := newEmbedder(config, pooler, ollamaService) + if err != nil { + return e, err + } + if logger.LLMDebugEnabled() { + e = &debugEmbedder{inner: e} + } + if langfuse.GetManager().Enabled() { + e = &langfuseEmbedder{inner: e} + } + return e, nil +} + +func newEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) { var embedder Embedder var err error switch strings.ToLower(string(config.Source)) { @@ -88,46 +129,62 @@ func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll baseURL = strings.Replace(baseURL, "/compatible-mode/v1", "", 1) baseURL = strings.Replace(baseURL, "/compatible-mode", "", 1) } - embedder, err = NewAliyunEmbedder(config.APIKey, + aliyunEmb, aErr := NewAliyunEmbedder(config.APIKey, baseURL, config.ModelName, config.TruncatePromptTokens, config.Dimensions, config.ModelID, pooler) + if aliyunEmb != nil { + aliyunEmb.SetCustomHeaders(config.CustomHeaders) + } + embedder, err = aliyunEmb, aErr } else { baseURL := config.BaseURL if baseURL == "" || !strings.Contains(baseURL, "/compatible-mode/") { baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1" } - embedder, err = NewOpenAIEmbedder(config.APIKey, + openaiEmb, oErr := NewOpenAIEmbedder(config.APIKey, baseURL, config.ModelName, config.TruncatePromptTokens, config.Dimensions, config.ModelID, pooler) + if openaiEmb != nil { + openaiEmb.SetCustomHeaders(config.CustomHeaders) + } + embedder, err = openaiEmb, oErr } return embedder, err case provider.ProviderVolcengine: // Volcengine Ark uses multimodal embedding API - embedder, err = NewVolcengineEmbedder(config.APIKey, + volcEmb, vErr := NewVolcengineEmbedder(config.APIKey, config.BaseURL, config.ModelName, config.TruncatePromptTokens, config.Dimensions, config.ModelID, pooler) + if volcEmb != nil { + volcEmb.SetCustomHeaders(config.CustomHeaders) + } + embedder, err = volcEmb, vErr return embedder, err case provider.ProviderJina: // Jina AI uses different API format (truncate instead of truncate_prompt_tokens) - embedder, err = NewJinaEmbedder(config.APIKey, + jinaEmb, jErr := NewJinaEmbedder(config.APIKey, config.BaseURL, config.ModelName, config.TruncatePromptTokens, config.Dimensions, config.ModelID, pooler) + if jinaEmb != nil { + jinaEmb.SetCustomHeaders(config.CustomHeaders) + } + embedder, err = jinaEmb, jErr return embedder, err case provider.ProviderAzureOpenAI: apiVersion := "2024-10-21" @@ -136,7 +193,7 @@ func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll apiVersion = v } } - embedder, err = NewAzureOpenAIEmbedder(config.APIKey, + azureEmb, azErr := NewAzureOpenAIEmbedder(config.APIKey, config.BaseURL, config.ModelName, config.TruncatePromptTokens, @@ -144,27 +201,39 @@ func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.Oll config.ModelID, apiVersion, pooler) + if azureEmb != nil { + azureEmb.SetCustomHeaders(config.CustomHeaders) + } + embedder, err = azureEmb, azErr return embedder, err case provider.ProviderNvidia: - embedder, err = NewNvidiaEmbedder(config.APIKey, + nvEmb, nErr := NewNvidiaEmbedder(config.APIKey, config.BaseURL, config.ModelName, config.Dimensions, config.ModelID, pooler) + if nvEmb != nil { + nvEmb.SetCustomHeaders(config.CustomHeaders) + } + embedder, err = nvEmb, nErr return embedder, err case provider.ProviderWeKnoraCloud: embedder, err = NewWeKnoraCloudEmbedder(config) return embedder, err default: // Use OpenAI-compatible embedder for other providers - embedder, err = NewOpenAIEmbedder(config.APIKey, + openaiEmb, oErr := NewOpenAIEmbedder(config.APIKey, config.BaseURL, config.ModelName, config.TruncatePromptTokens, config.Dimensions, config.ModelID, pooler) + if openaiEmb != nil { + openaiEmb.SetCustomHeaders(config.CustomHeaders) + } + embedder, err = openaiEmb, oErr return embedder, err } default: diff --git a/internal/models/embedding/jina.go b/internal/models/embedding/jina.go index c19dd33a..78711db1 100644 --- a/internal/models/embedding/jina.go +++ b/internal/models/embedding/jina.go @@ -10,22 +10,29 @@ import ( "time" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) // JinaEmbedder implements text vectorization functionality using Jina AI API // Jina API is mostly OpenAI-compatible but does NOT support truncate_prompt_tokens type JinaEmbedder struct { - apiKey string - baseURL string - modelName string - dimensions int - modelID string - httpClient *http.Client - timeout time.Duration - maxRetries int + apiKey string + baseURL string + modelName string + dimensions int + modelID string + httpClient *http.Client + timeout time.Duration + maxRetries int + customHeaders map[string]string EmbedderPooler } +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (e *JinaEmbedder) SetCustomHeaders(headers map[string]string) { + e.customHeaders = headers +} + // JinaEmbedRequest represents a Jina embedding request // Note: Jina uses 'truncate' (boolean) instead of 'truncate_prompt_tokens' (integer) type JinaEmbedRequest struct { @@ -118,6 +125,7 @@ func (e *JinaEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+e.apiKey) + secutils.ApplyCustomHeaders(req, e.customHeaders) resp, err = e.httpClient.Do(req) if err == nil { diff --git a/internal/models/embedding/langfuse_wrapper.go b/internal/models/embedding/langfuse_wrapper.go new file mode 100644 index 00000000..41585b27 --- /dev/null +++ b/internal/models/embedding/langfuse_wrapper.go @@ -0,0 +1,136 @@ +package embedding + +import ( + "context" + + "github.com/Tencent/WeKnora/internal/tracing/langfuse" +) + +// langfuseEmbedder wraps an Embedder and reports each call as a Langfuse +// generation observation. Input token counts are approximated from the text +// lengths when the underlying provider doesn't return usage data, because +// Langfuse's cost reports require non-zero input tokens. +type langfuseEmbedder struct { + inner Embedder +} + +func (l *langfuseEmbedder) Embed(ctx context.Context, text string) ([]float32, error) { + mgr := langfuse.GetManager() + if !mgr.Enabled() { + return l.inner.Embed(ctx, text) + } + genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{ + Name: "embedding.embed", + Model: l.inner.GetModelName(), + Input: text, + Metadata: map[string]interface{}{ + "model_id": l.inner.GetModelID(), + "dimensions": l.inner.GetDimensions(), + }, + }) + result, err := l.inner.Embed(genCtx, text) + usage := approxEmbeddingUsage([]string{text}) + var out interface{} + if len(result) > 0 { + out = map[string]interface{}{ + "dimensions": len(result), + "vector_preview": result[:min(3, len(result))], + } + } + gen.Finish(out, usage, err) + return result, err +} + +func (l *langfuseEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) { + mgr := langfuse.GetManager() + if !mgr.Enabled() { + return l.inner.BatchEmbed(ctx, texts) + } + genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{ + Name: "embedding.batch_embed", + Model: l.inner.GetModelName(), + Input: map[string]interface{}{ + "count": len(texts), + // Avoid sending megabytes of full text — Langfuse truncates but + // the network cost is still real. Keep a short preview instead. + "preview": previewTexts(texts, 5), + }, + Metadata: map[string]interface{}{ + "model_id": l.inner.GetModelID(), + "dimensions": l.inner.GetDimensions(), + "batch_size": len(texts), + }, + }) + result, err := l.inner.BatchEmbed(genCtx, texts) + usage := approxEmbeddingUsage(texts) + var out interface{} + if len(result) > 0 { + out = map[string]interface{}{ + "count": len(result), + "dimensions": len(result[0]), + } + } + gen.Finish(out, usage, err) + return result, err +} + +func (l *langfuseEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) { + return l.inner.BatchEmbedWithPool(ctx, l, texts) +} + +func (l *langfuseEmbedder) GetModelName() string { return l.inner.GetModelName() } +func (l *langfuseEmbedder) GetDimensions() int { return l.inner.GetDimensions() } +func (l *langfuseEmbedder) GetModelID() string { return l.inner.GetModelID() } + +// approxEmbeddingUsage estimates input tokens as ~rune_count / 4, matching the +// rule of thumb OpenAI uses in their tokenizer docs. This is purely for cost +// reporting — Langfuse lets users define per-model cost multipliers, so the +// approximation need only be proportional to length. +func approxEmbeddingUsage(texts []string) *langfuse.TokenUsage { + total := 0 + for _, t := range texts { + runes := len([]rune(t)) + if runes == 0 { + continue + } + total += runes/4 + 1 + } + if total == 0 { + return nil + } + return &langfuse.TokenUsage{ + Input: total, + Total: total, + Unit: "TOKENS", + } +} + +func previewTexts(texts []string, n int) []string { + if len(texts) <= n { + out := make([]string, len(texts)) + for i, t := range texts { + out[i] = truncateRunes(t, 120) + } + return out + } + out := make([]string, n) + for i := 0; i < n; i++ { + out[i] = truncateRunes(texts[i], 120) + } + return out +} + +func truncateRunes(s string, maxRunes int) string { + r := []rune(s) + if len(r) <= maxRunes { + return s + } + return string(r[:maxRunes]) + "..." +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} diff --git a/internal/models/embedding/llm_debug.go b/internal/models/embedding/llm_debug.go new file mode 100644 index 00000000..1900d268 --- /dev/null +++ b/internal/models/embedding/llm_debug.go @@ -0,0 +1,93 @@ +package embedding + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// debugEmbedder wraps an Embedder with LLM debug logging. +type debugEmbedder struct { + inner Embedder +} + +func (d *debugEmbedder) Embed(ctx context.Context, text string) ([]float32, error) { + start := time.Now() + result, err := d.inner.Embed(ctx, text) + logEmbeddingDebug(ctx, d.inner.GetModelName(), []string{text}, singleToDouble(result), err, time.Since(start)) + return result, err +} + +func (d *debugEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) { + start := time.Now() + result, err := d.inner.BatchEmbed(ctx, texts) + logEmbeddingDebug(ctx, d.inner.GetModelName(), texts, result, err, time.Since(start)) + return result, err +} + +func (d *debugEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) { + return d.inner.BatchEmbedWithPool(ctx, d, texts) +} + +func (d *debugEmbedder) GetModelName() string { return d.inner.GetModelName() } +func (d *debugEmbedder) GetDimensions() int { return d.inner.GetDimensions() } +func (d *debugEmbedder) GetModelID() string { return d.inner.GetModelID() } + +func singleToDouble(v []float32) [][]float32 { + if v == nil { + return nil + } + return [][]float32{v} +} + +func logEmbeddingDebug(ctx context.Context, model string, inputs []string, outputs [][]float32, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "Embedding", + Model: model, + Duration: dur, + } + + // Input section: show each text with a preview + var inputBuf strings.Builder + inputBuf.WriteString(fmt.Sprintf("count=%d\n", len(inputs))) + for i, t := range inputs { + preview := strings.ReplaceAll(t, "\n", "\\n") + preview = logger.TruncateRunes(preview, 200) + inputBuf.WriteString(fmt.Sprintf("[%d] (len=%d) %s\n", i, len([]rune(t)), preview)) + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Input", Content: inputBuf.String()}) + + // Output section + if outputs != nil { + var outBuf strings.Builder + outBuf.WriteString(fmt.Sprintf("count=%d\n", len(outputs))) + for i, vec := range outputs { + if len(vec) > 0 { + outBuf.WriteString(fmt.Sprintf("[%d] dims=%d, first_3=[%.6f, %.6f, %.6f]\n", i, len(vec), + safeIdx(vec, 0), safeIdx(vec, 1), safeIdx(vec, 2))) + } else { + outBuf.WriteString(fmt.Sprintf("[%d] empty\n", i)) + } + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Output", Content: outBuf.String()}) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} + +func safeIdx(v []float32, i int) float32 { + if i < len(v) { + return v[i] + } + return 0 +} diff --git a/internal/models/embedding/nvidia.go b/internal/models/embedding/nvidia.go index 2c37dbbd..f645da79 100644 --- a/internal/models/embedding/nvidia.go +++ b/internal/models/embedding/nvidia.go @@ -11,21 +11,28 @@ import ( "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/types" + secutils "github.com/Tencent/WeKnora/internal/utils" ) // NvidiaEmbedder implements text vectorization functionality using NVIDIA API type NvidiaEmbedder struct { - apiKey string - baseURL string - modelName string - dimensions int - modelID string - httpClient *http.Client - timeout time.Duration - maxRetries int + apiKey string + baseURL string + modelName string + dimensions int + modelID string + httpClient *http.Client + timeout time.Duration + maxRetries int + customHeaders map[string]string EmbedderPooler } +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (e *NvidiaEmbedder) SetCustomHeaders(headers map[string]string) { + e.customHeaders = headers +} + // NvidiaEmbedRequest represents an NVIDIA embedding request type NvidiaEmbedRequest struct { Model string `json:"model"` @@ -118,6 +125,7 @@ func (e *NvidiaEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+e.apiKey) + secutils.ApplyCustomHeaders(req, e.customHeaders) resp, err = e.httpClient.Do(req) if err == nil { diff --git a/internal/models/embedding/openai.go b/internal/models/embedding/openai.go index 7e495e13..0c70bfd8 100644 --- a/internal/models/embedding/openai.go +++ b/internal/models/embedding/openai.go @@ -10,6 +10,7 @@ import ( "time" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) // OpenAIEmbedder implements text vectorization functionality using OpenAI API @@ -23,6 +24,7 @@ type OpenAIEmbedder struct { httpClient *http.Client timeout time.Duration maxRetries int + customHeaders map[string]string EmbedderPooler } @@ -79,6 +81,12 @@ func NewOpenAIEmbedder(apiKey, baseURL, modelName string, }, nil } +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +// 保留头(Authorization、Content-Type 等)会在发送时被自动跳过。 +func (e *OpenAIEmbedder) SetCustomHeaders(headers map[string]string) { + e.customHeaders = headers +} + // Embed converts text to vector func (e *OpenAIEmbedder) Embed(ctx context.Context, text string) ([]float32, error) { for range 3 { @@ -122,6 +130,7 @@ func (e *OpenAIEmbedder) doRequestWithRetry(ctx context.Context, jsonData []byte } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+e.apiKey) + secutils.ApplyCustomHeaders(req, e.customHeaders) resp, err = e.httpClient.Do(req) if err == nil { diff --git a/internal/models/embedding/volcengine.go b/internal/models/embedding/volcengine.go index 369def29..c5a3e617 100644 --- a/internal/models/embedding/volcengine.go +++ b/internal/models/embedding/volcengine.go @@ -11,6 +11,7 @@ import ( "time" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) const ( @@ -29,9 +30,15 @@ type VolcengineEmbedder struct { httpClient *http.Client timeout time.Duration maxRetries int + customHeaders map[string]string EmbedderPooler } +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (e *VolcengineEmbedder) SetCustomHeaders(headers map[string]string) { + e.customHeaders = headers +} + // VolcengineEmbedRequest represents a Volcengine Ark multimodal embedding request type VolcengineEmbedRequest struct { Model string `json:"model"` @@ -165,6 +172,7 @@ func (e *VolcengineEmbedder) doRequestWithRetry(ctx context.Context, jsonData [] } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+e.apiKey) + secutils.ApplyCustomHeaders(req, e.customHeaders) resp, err = e.httpClient.Do(req) if err == nil { diff --git a/internal/models/rerank/aliyun_reranker.go b/internal/models/rerank/aliyun_reranker.go index 75103c87..ccd0c307 100644 --- a/internal/models/rerank/aliyun_reranker.go +++ b/internal/models/rerank/aliyun_reranker.go @@ -9,15 +9,22 @@ import ( "net/http" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) // AliyunReranker implements a reranking system based on Aliyun DashScope models type AliyunReranker struct { - modelName string // Name of the model used for reranking - modelID string // Unique identifier of the model - apiKey string // API key for authentication - baseURL string // Base URL for API requests - client *http.Client // HTTP client for making API requests + modelName string // Name of the model used for reranking + modelID string // Unique identifier of the model + apiKey string // API key for authentication + baseURL string // Base URL for API requests + client *http.Client // HTTP client for making API requests + customHeaders map[string]string +} + +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (r *AliyunReranker) SetCustomHeaders(headers map[string]string) { + r.customHeaders = headers } // AliyunRerankRequest represents a request to rerank documents using Aliyun DashScope API @@ -111,6 +118,7 @@ func (r *AliyunReranker) Rerank(ctx context.Context, query string, documents []s } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey)) + secutils.ApplyCustomHeaders(req, r.customHeaders) logger.Debugf(ctx, "%s", buildRerankRequestDebug(r.modelName, r.baseURL, query, documents)) diff --git a/internal/models/rerank/config_from_model_test.go b/internal/models/rerank/config_from_model_test.go new file mode 100644 index 00000000..39085ac1 --- /dev/null +++ b/internal/models/rerank/config_from_model_test.go @@ -0,0 +1,32 @@ +package rerank + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +func TestConfigFromModel(t *testing.T) { + m := &types.Model{ + ID: "rr-1", + Name: "bge-reranker-v2-m3", + Source: types.ModelSourceRemote, + Parameters: types.ModelParameters{ + BaseURL: "https://api.example.com/v1", + APIKey: "sk-xxx", + Provider: "siliconflow", + ExtraConfig: map[string]string{"flag": "on"}, + CustomHeaders: map[string]string{"X-Gateway": "g"}, + }, + } + cfg := ConfigFromModel(m, "app", "secret") + if cfg == nil || cfg.ModelID != "rr-1" || cfg.ModelName != "bge-reranker-v2-m3" { + t.Fatalf("identity mismatch: %+v", cfg) + } + if cfg.Provider != "siliconflow" || cfg.CustomHeaders["X-Gateway"] != "g" { + t.Errorf("provider/headers not propagated: %+v", cfg) + } + if cfg.AppID != "app" || cfg.AppSecret != "secret" { + t.Errorf("cloud creds mismatch: %+v", cfg) + } +} diff --git a/internal/models/rerank/jina_reranker.go b/internal/models/rerank/jina_reranker.go index 5067123e..27f93af6 100644 --- a/internal/models/rerank/jina_reranker.go +++ b/internal/models/rerank/jina_reranker.go @@ -9,16 +9,23 @@ import ( "net/http" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) // JinaReranker implements a reranking system using Jina AI API // Jina API uses different parameters than standard OpenAI-compatible APIs type JinaReranker struct { - modelName string // Name of the model used for reranking - modelID string // Unique identifier of the model - apiKey string // API key for authentication - baseURL string // Base URL for API requests - client *http.Client // HTTP client for making API requests + modelName string // Name of the model used for reranking + modelID string // Unique identifier of the model + apiKey string // API key for authentication + baseURL string // Base URL for API requests + client *http.Client // HTTP client for making API requests + customHeaders map[string]string +} + +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (r *JinaReranker) SetCustomHeaders(headers map[string]string) { + r.customHeaders = headers } // JinaRerankRequest represents a Jina rerank request @@ -79,6 +86,7 @@ func (r *JinaReranker) Rerank(ctx context.Context, query string, documents []str } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey)) + secutils.ApplyCustomHeaders(req, r.customHeaders) logger.Debugf(ctx, "%s", buildRerankRequestDebug(r.modelName, fmt.Sprintf("%s/rerank", r.baseURL), query, documents)) diff --git a/internal/models/rerank/langfuse_wrapper.go b/internal/models/rerank/langfuse_wrapper.go new file mode 100644 index 00000000..ba8fa78c --- /dev/null +++ b/internal/models/rerank/langfuse_wrapper.go @@ -0,0 +1,116 @@ +package rerank + +import ( + "context" + + "github.com/Tencent/WeKnora/internal/tracing/langfuse" +) + +// langfuseReranker wraps a Reranker and reports each rerank call as a +// Langfuse generation observation. Rerankers don't return token usage, but +// the call still incurs cost (billed per 1K documents by most vendors); we +// estimate input tokens from the query + documents so the Langfuse cost +// dashboard gets a proportional signal. +type langfuseReranker struct { + inner Reranker +} + +func (l *langfuseReranker) GetModelName() string { return l.inner.GetModelName() } +func (l *langfuseReranker) GetModelID() string { return l.inner.GetModelID() } + +func (l *langfuseReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) { + mgr := langfuse.GetManager() + if !mgr.Enabled() { + return l.inner.Rerank(ctx, query, documents) + } + + genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{ + Name: "rerank", + Model: l.inner.GetModelName(), + Input: map[string]interface{}{ + "query": query, + "document_count": len(documents), + // Only send short previews — reranker inputs can be hundreds of + // passages totalling hundreds of KB, which would bloat traces. + "documents_preview": previewDocs(documents, 5), + }, + Metadata: map[string]interface{}{ + "model_id": l.inner.GetModelID(), + "num_queries": 1, + }, + }) + + results, err := l.inner.Rerank(genCtx, query, documents) + + output := map[string]interface{}{ + "results": summarizeResults(results, 10), + "total_count": len(results), + } + gen.Finish(output, approxRerankUsage(query, documents), err) + return results, err +} + +func approxRerankUsage(query string, documents []string) *langfuse.TokenUsage { + total := len([]rune(query))/4 + 1 + for _, d := range documents { + total += len([]rune(d))/4 + 1 + } + if total == 0 { + return nil + } + return &langfuse.TokenUsage{ + Input: total, + Total: total, + Unit: "TOKENS", + } +} + +func previewDocs(docs []string, n int) []map[string]interface{} { + if len(docs) < n { + n = len(docs) + } + out := make([]map[string]interface{}, 0, n) + for i := 0; i < n; i++ { + out = append(out, map[string]interface{}{ + "index": i, + "preview": truncateRunes(docs[i], 160), + "length": len([]rune(docs[i])), + }) + } + return out +} + +func summarizeResults(results []RankResult, n int) []map[string]interface{} { + if len(results) < n { + n = len(results) + } + out := make([]map[string]interface{}, 0, n) + for i := 0; i < n; i++ { + out = append(out, map[string]interface{}{ + "index": results[i].Index, + "score": results[i].RelevanceScore, + }) + } + return out +} + +func truncateRunes(s string, maxRunes int) string { + r := []rune(s) + if len(r) <= maxRunes { + return s + } + return string(r[:maxRunes]) + "..." +} + +// wrapRerankerLangfuse applies the Langfuse decorator when the manager is +// enabled. Called from NewReranker after the debug wrapper so both sinks see +// the same calls. +func wrapRerankerLangfuse(r Reranker, err error) (Reranker, error) { + if err != nil || r == nil { + return r, err + } + if !langfuse.GetManager().Enabled() { + return r, nil + } + return &langfuseReranker{inner: r}, nil +} diff --git a/internal/models/rerank/llm_debug.go b/internal/models/rerank/llm_debug.go new file mode 100644 index 00000000..5abc2731 --- /dev/null +++ b/internal/models/rerank/llm_debug.go @@ -0,0 +1,70 @@ +package rerank + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// debugReranker wraps a Reranker with LLM debug logging. +type debugReranker struct { + inner Reranker +} + +func (d *debugReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) { + start := time.Now() + result, err := d.inner.Rerank(ctx, query, documents) + logRerankDebug(ctx, d.inner.GetModelName(), query, documents, result, err, time.Since(start)) + return result, err +} + +func (d *debugReranker) GetModelName() string { return d.inner.GetModelName() } +func (d *debugReranker) GetModelID() string { return d.inner.GetModelID() } + +func logRerankDebug(ctx context.Context, model string, query string, documents []string, results []RankResult, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "Rerank", + Model: model, + Duration: dur, + } + + // Query section + record.Sections = append(record.Sections, logger.RecordSection{ + Title: "Query", + Content: query, + }) + + // Documents section + var docBuf strings.Builder + docBuf.WriteString(fmt.Sprintf("count=%d\n", len(documents))) + for i, doc := range documents { + preview := strings.ReplaceAll(doc, "\n", "\\n") + preview = logger.TruncateRunes(preview, 200) + docBuf.WriteString(fmt.Sprintf("[%d] (len=%d) %s\n", i, len([]rune(doc)), preview)) + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Documents", Content: docBuf.String()}) + + // Results section + if results != nil { + var resBuf strings.Builder + resBuf.WriteString(fmt.Sprintf("count=%d\n", len(results))) + for _, r := range results { + docPreview := strings.ReplaceAll(r.Document.Text, "\n", "\\n") + docPreview = logger.TruncateRunes(docPreview, 200) + resBuf.WriteString(fmt.Sprintf(" [%d] score=%.6f %s\n", r.Index, r.RelevanceScore, docPreview)) + } + record.Sections = append(record.Sections, logger.RecordSection{Title: "Results", Content: resBuf.String()}) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} diff --git a/internal/models/rerank/nvidia_reranker.go b/internal/models/rerank/nvidia_reranker.go index 13097ed8..bdc8bd72 100644 --- a/internal/models/rerank/nvidia_reranker.go +++ b/internal/models/rerank/nvidia_reranker.go @@ -9,16 +9,23 @@ import ( "net/http" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) // NvidiaReranker implements a reranking system using Jina AI API // Jina API uses different parameters than standard OpenAI-compatible APIs type NvidiaReranker struct { - modelName string // Name of the model used for reranking - modelID string // Unique identifier of the model - apiKey string // API key for authentication - baseURL string // Base URL for API requests - client *http.Client // HTTP client for making API requests + modelName string // Name of the model used for reranking + modelID string // Unique identifier of the model + apiKey string // API key for authentication + baseURL string // Base URL for API requests + client *http.Client // HTTP client for making API requests + customHeaders map[string]string +} + +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (r *NvidiaReranker) SetCustomHeaders(headers map[string]string) { + r.customHeaders = headers } type NvidiaRerankDocument struct { Text string `json:"text"` @@ -88,6 +95,7 @@ func (r *NvidiaReranker) Rerank(ctx context.Context, query string, documents []s } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey)) + secutils.ApplyCustomHeaders(req, r.customHeaders) // Log the curl equivalent for debugging (API key masked for security) logger.GetLogger(ctx).Infof( diff --git a/internal/models/rerank/remote_api.go b/internal/models/rerank/remote_api.go index d9b77771..ce78be20 100644 --- a/internal/models/rerank/remote_api.go +++ b/internal/models/rerank/remote_api.go @@ -9,15 +9,22 @@ import ( "net/http" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) // OpenAIReranker implements a reranking system based on OpenAI models type OpenAIReranker struct { - modelName string // Name of the model used for reranking - modelID string // Unique identifier of the model - apiKey string // API key for authentication - baseURL string // Base URL for API requests - client *http.Client // HTTP client for making API requests + modelName string // Name of the model used for reranking + modelID string // Unique identifier of the model + apiKey string // API key for authentication + baseURL string // Base URL for API requests + client *http.Client // HTTP client for making API requests + customHeaders map[string]string +} + +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (r *OpenAIReranker) SetCustomHeaders(headers map[string]string) { + r.customHeaders = headers } // RerankRequest represents a request to rerank documents based on relevance to a query @@ -81,6 +88,7 @@ func (r *OpenAIReranker) Rerank(ctx context.Context, query string, documents []s } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey)) + secutils.ApplyCustomHeaders(req, r.customHeaders) logger.Debugf(ctx, "%s", buildRerankRequestDebug(r.modelName, fmt.Sprintf("%s/rerank", r.baseURL), query, documents)) diff --git a/internal/models/rerank/reranker.go b/internal/models/rerank/reranker.go index 2c5a1ba2..d6e40910 100644 --- a/internal/models/rerank/reranker.go +++ b/internal/models/rerank/reranker.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" + "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/models/provider" "github.com/Tencent/WeKnora/internal/types" ) @@ -85,30 +86,80 @@ type RerankerConfig struct { ModelID string Provider string // Provider identifier: openai, aliyun, zhipu, siliconflow, jina, generic ExtraConfig map[string]string - AppID string - AppSecret string // 加密值,工厂函数调用方传入,使用前已解密 + // CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 + CustomHeaders map[string]string + AppID string + AppSecret string // 加密值,工厂函数调用方传入,使用前已解密 +} + +// ConfigFromModel 根据 types.Model 构造 RerankerConfig。 +// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。 +// appID / appSecret 是已解密的 WeKnoraCloud 凭证,调用方负责传入。 +func ConfigFromModel(m *types.Model, appID, appSecret string) *RerankerConfig { + if m == nil { + return nil + } + return &RerankerConfig{ + ModelID: m.ID, + APIKey: m.Parameters.APIKey, + BaseURL: m.Parameters.BaseURL, + ModelName: m.Name, + Source: m.Source, + Provider: m.Parameters.Provider, + ExtraConfig: m.Parameters.ExtraConfig, + CustomHeaders: m.Parameters.CustomHeaders, + AppID: appID, + AppSecret: appSecret, + } } // NewReranker creates a reranker based on the configuration func NewReranker(config *RerankerConfig) (Reranker, error) { + r, err := newReranker(config) + if err != nil { + return r, err + } + if logger.LLMDebugEnabled() { + r = &debugReranker{inner: r} + } + return wrapRerankerLangfuse(r, nil) +} + +// customHeaderSetter 表示支持注入自定义 HTTP header 的 reranker 实现。 +type customHeaderSetter interface { + SetCustomHeaders(map[string]string) +} + +func newReranker(config *RerankerConfig) (Reranker, error) { // Use provider field if set, otherwise detect from URL using provider registry providerName := provider.ProviderName(config.Provider) if providerName == "" { providerName = provider.DetectProvider(config.BaseURL) } + var ( + reranker Reranker + err error + ) switch providerName { case provider.ProviderAliyun: - return NewAliyunReranker(config) + reranker, err = NewAliyunReranker(config) case provider.ProviderZhipu: - return NewZhipuReranker(config) + reranker, err = NewZhipuReranker(config) case provider.ProviderJina: - return NewJinaReranker(config) + reranker, err = NewJinaReranker(config) case provider.ProviderNvidia: - return NewNvidiaReranker(config) + reranker, err = NewNvidiaReranker(config) case provider.ProviderWeKnoraCloud: - return NewWeKnoraCloudReranker(config) + reranker, err = NewWeKnoraCloudReranker(config) default: - return NewOpenAIReranker(config) + reranker, err = NewOpenAIReranker(config) } + if err != nil { + return nil, err + } + if setter, ok := reranker.(customHeaderSetter); ok { + setter.SetCustomHeaders(config.CustomHeaders) + } + return reranker, nil } diff --git a/internal/models/rerank/zhipu_reranker.go b/internal/models/rerank/zhipu_reranker.go index ad0d801c..2e2553f2 100644 --- a/internal/models/rerank/zhipu_reranker.go +++ b/internal/models/rerank/zhipu_reranker.go @@ -9,15 +9,22 @@ import ( "net/http" "github.com/Tencent/WeKnora/internal/logger" + secutils "github.com/Tencent/WeKnora/internal/utils" ) // ZhipuReranker implements a reranking system based on Zhipu AI models type ZhipuReranker struct { - modelName string // Name of the model used for reranking - modelID string // Unique identifier of the model - apiKey string // API key for authentication - baseURL string // Base URL for API requests - client *http.Client // HTTP client for making API requests + modelName string // Name of the model used for reranking + modelID string // Unique identifier of the model + apiKey string // API key for authentication + baseURL string // Base URL for API requests + client *http.Client // HTTP client for making API requests + customHeaders map[string]string +} + +// SetCustomHeaders 设置用户自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 +func (r *ZhipuReranker) SetCustomHeaders(headers map[string]string) { + r.customHeaders = headers } // ZhipuRerankRequest represents a request to rerank documents using Zhipu AI API @@ -92,6 +99,7 @@ func (r *ZhipuReranker) Rerank(ctx context.Context, query string, documents []st } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", r.apiKey)) + secutils.ApplyCustomHeaders(req, r.customHeaders) logger.Debugf(ctx, "%s", buildRerankRequestDebug(r.modelName, r.baseURL, query, documents)) diff --git a/internal/models/vlm/config_from_model_test.go b/internal/models/vlm/config_from_model_test.go new file mode 100644 index 00000000..fd71db2e --- /dev/null +++ b/internal/models/vlm/config_from_model_test.go @@ -0,0 +1,59 @@ +package vlm + +import ( + "testing" + + "github.com/Tencent/WeKnora/internal/types" +) + +func TestConfigFromModel_RemoteDefaultsToOpenAI(t *testing.T) { + m := &types.Model{ + ID: "v1", + Name: "gpt-4o", + Source: types.ModelSourceRemote, + Parameters: types.ModelParameters{ + BaseURL: "https://api.example.com/v1", + APIKey: "sk", + Provider: "openai", + ExtraConfig: map[string]string{"x": "y"}, + CustomHeaders: map[string]string{"H": "v"}, + }, + } + cfg := ConfigFromModel(m, "app", "secret") + if cfg.InterfaceType != "openai" { + t.Errorf("expected openai default for remote, got %q", cfg.InterfaceType) + } + if cfg.CustomHeaders["H"] != "v" { + t.Errorf("CustomHeaders not propagated: %+v", cfg.CustomHeaders) + } + if cfg.Extra["x"] != "y" { + t.Errorf("ExtraConfig not propagated as Extra: %+v", cfg.Extra) + } + if cfg.AppID != "app" || cfg.AppSecret != "secret" { + t.Errorf("cloud creds mismatch: %+v", cfg) + } +} + +func TestConfigFromModel_LocalDefaultsToOllama(t *testing.T) { + m := &types.Model{ + Name: "qwen2-vl", + Source: types.ModelSourceLocal, + } + cfg := ConfigFromModel(m, "", "") + if cfg.InterfaceType != "ollama" { + t.Errorf("expected ollama default for local, got %q", cfg.InterfaceType) + } +} + +func TestConfigFromModel_RespectsExplicitInterface(t *testing.T) { + m := &types.Model{ + Name: "qwen2-vl", + Source: types.ModelSourceRemote, + Parameters: types.ModelParameters{ + InterfaceType: "ollama", + }, + } + if got := ConfigFromModel(m, "", "").InterfaceType; got != "ollama" { + t.Errorf("expected explicit interface to win, got %q", got) + } +} diff --git a/internal/models/vlm/langfuse_wrapper.go b/internal/models/vlm/langfuse_wrapper.go new file mode 100644 index 00000000..c707ca41 --- /dev/null +++ b/internal/models/vlm/langfuse_wrapper.go @@ -0,0 +1,72 @@ +package vlm + +import ( + "context" + + "github.com/Tencent/WeKnora/internal/tracing/langfuse" +) + +// langfuseVLM wraps a VLM and reports each Predict call as a Langfuse +// generation. The raw image bytes are NOT uploaded — Langfuse traces are +// designed for text. We include image count and total byte size in the +// metadata, plus the text prompt, which matches how Langfuse's own VLM +// integrations report multimodal calls. +type langfuseVLM struct { + inner VLM +} + +func (l *langfuseVLM) GetModelName() string { return l.inner.GetModelName() } +func (l *langfuseVLM) GetModelID() string { return l.inner.GetModelID() } + +func (l *langfuseVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) { + mgr := langfuse.GetManager() + if !mgr.Enabled() { + return l.inner.Predict(ctx, imgBytes, prompt) + } + + totalImgSize := 0 + for _, b := range imgBytes { + totalImgSize += len(b) + } + + genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{ + Name: "vlm.predict", + Model: l.inner.GetModelName(), + Input: map[string]interface{}{ + "prompt": prompt, + "image_count": len(imgBytes), + }, + Metadata: map[string]interface{}{ + "model_id": l.inner.GetModelID(), + "image_count": len(imgBytes), + "image_bytes_total": totalImgSize, + }, + }) + + result, err := l.inner.Predict(genCtx, imgBytes, prompt) + + // VLMs don't return token usage; approximate prompt tokens for cost + // tracking in Langfuse (users can configure per-model pricing in the UI). + promptTokens := len([]rune(prompt))/4 + 1 + outputTokens := len([]rune(result)) / 4 + usage := &langfuse.TokenUsage{ + Input: promptTokens, + Output: outputTokens, + Total: promptTokens + outputTokens, + Unit: "TOKENS", + } + + gen.Finish(result, usage, err) + return result, err +} + +// wrapVLMLangfuse applies the Langfuse decorator when the manager is enabled. +func wrapVLMLangfuse(v VLM, err error) (VLM, error) { + if err != nil || v == nil { + return v, err + } + if !langfuse.GetManager().Enabled() { + return v, nil + } + return &langfuseVLM{inner: v}, nil +} diff --git a/internal/models/vlm/llm_debug.go b/internal/models/vlm/llm_debug.go new file mode 100644 index 00000000..18c1a5ca --- /dev/null +++ b/internal/models/vlm/llm_debug.go @@ -0,0 +1,63 @@ +package vlm + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/Tencent/WeKnora/internal/logger" +) + +// debugVLM wraps a VLM with LLM debug logging. +type debugVLM struct { + inner VLM +} + +func (d *debugVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) { + start := time.Now() + result, err := d.inner.Predict(ctx, imgBytes, prompt) + logVLMDebug(ctx, d.inner.GetModelName(), imgBytes, prompt, result, err, time.Since(start)) + return result, err +} + +func (d *debugVLM) GetModelName() string { return d.inner.GetModelName() } +func (d *debugVLM) GetModelID() string { return d.inner.GetModelID() } + +func logVLMDebug(ctx context.Context, model string, imgBytes [][]byte, prompt string, response string, callErr error, dur time.Duration) { + if !logger.LLMDebugEnabled() { + return + } + + record := &logger.LLMCallRecord{ + CallType: "VLM", + Model: model, + Duration: dur, + } + + // Input section + var inputBuf strings.Builder + inputBuf.WriteString(fmt.Sprintf("Images: count=%d", len(imgBytes))) + totalSize := 0 + for _, img := range imgBytes { + totalSize += len(img) + } + inputBuf.WriteString(fmt.Sprintf(", total_size=%d bytes\n\n", totalSize)) + inputBuf.WriteString("[prompt]\n") + inputBuf.WriteString(prompt) + inputBuf.WriteString("\n") + record.Sections = append(record.Sections, logger.RecordSection{Title: "Input", Content: inputBuf.String()}) + + // Response section + if response != "" { + record.Sections = append(record.Sections, logger.RecordSection{ + Title: "Response", + Content: response, + }) + } + + if callErr != nil { + record.Error = callErr.Error() + } + logger.LLMDebugLog(ctx, record) +} diff --git a/internal/models/vlm/remote_api.go b/internal/models/vlm/remote_api.go index 3c31aa5e..03feba4f 100644 --- a/internal/models/vlm/remote_api.go +++ b/internal/models/vlm/remote_api.go @@ -10,6 +10,7 @@ import ( "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/models/provider" + secutils "github.com/Tencent/WeKnora/internal/utils" openai "github.com/sashabaranov/go-openai" ) @@ -53,7 +54,14 @@ func NewRemoteAPIVLM(config *Config) (*RemoteAPIVLM, error) { apiCfg.BaseURL = config.BaseURL } } - apiCfg.HTTPClient = &http.Client{Timeout: defaultTimeout} + httpClient := &http.Client{Timeout: defaultTimeout} + + // 注入用户自定义 HTTP header(类似 OpenAI Python SDK 的 extra_headers) + if len(config.CustomHeaders) > 0 { + apiCfg.HTTPClient = secutils.WrapHTTPClientWithHeaders(httpClient, config.CustomHeaders) + } else { + apiCfg.HTTPClient = httpClient + } return &RemoteAPIVLM{ modelName: config.ModelName, diff --git a/internal/models/vlm/vlm.go b/internal/models/vlm/vlm.go index 3281240a..a33eeebb 100644 --- a/internal/models/vlm/vlm.go +++ b/internal/models/vlm/vlm.go @@ -5,6 +5,7 @@ import ( "fmt" "strings" + "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/models/provider" "github.com/Tencent/WeKnora/internal/models/utils/ollama" "github.com/Tencent/WeKnora/internal/types" @@ -29,12 +30,67 @@ type Config struct { InterfaceType string // "ollama" or "openai" (default) Provider string Extra map[string]any + // CustomHeaders 允许在调用远程 API 时附加自定义 HTTP 请求头(类似 OpenAI Python SDK 的 extra_headers)。 + CustomHeaders map[string]string AppID string AppSecret string } +// ConfigFromModel 根据 types.Model 构造 vlm.Config。 +// 生产路径(从 DB 拉起)和测试连接路径(临时表单)共享这份映射。 +// appID / appSecret 是已解密的 WeKnoraCloud 凭证,调用方负责传入。 +// InterfaceType 会根据 source / 模型参数自动回退到合理默认值。 +func ConfigFromModel(m *types.Model, appID, appSecret string) *Config { + if m == nil { + return nil + } + ifType := m.Parameters.InterfaceType + if ifType == "" { + if m.Source == types.ModelSourceLocal { + ifType = "ollama" + } else { + ifType = "openai" + } + } + return &Config{ + ModelID: m.ID, + APIKey: m.Parameters.APIKey, + BaseURL: m.Parameters.BaseURL, + ModelName: m.Name, + Source: m.Source, + InterfaceType: ifType, + Provider: m.Parameters.Provider, + Extra: stringMapToAnyMap(m.Parameters.ExtraConfig), + CustomHeaders: m.Parameters.CustomHeaders, + AppID: appID, + AppSecret: appSecret, + } +} + +func stringMapToAnyMap(in map[string]string) map[string]any { + if in == nil { + return nil + } + out := make(map[string]any, len(in)) + for k, v := range in { + out[k] = v + } + return out +} + // NewVLM creates a VLM instance based on the provided configuration. func NewVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) { + v, err := newVLM(config, ollamaService) + if err != nil { + return v, err + } + if logger.LLMDebugEnabled() { + v = &debugVLM{inner: v} + } + return wrapVLMLangfuse(v, nil) +} + +func newVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) { ifType := strings.ToLower(config.InterfaceType) if ifType == "ollama" || config.Source == types.ModelSourceLocal { diff --git a/internal/router/router.go b/internal/router/router.go index cfa37736..7c514845 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -21,6 +21,7 @@ import ( "github.com/Tencent/WeKnora/internal/handler/session" "github.com/Tencent/WeKnora/internal/logger" "github.com/Tencent/WeKnora/internal/middleware" + "github.com/Tencent/WeKnora/internal/tracing/langfuse" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" @@ -64,6 +65,7 @@ type RouterParams struct { IMHandler *handler.IMHandler DataSourceHandler *handler.DataSourceHandler WeKnoraCloudHandler *handler.WeKnoraCloudHandler + WikiPageHandler *handler.WikiPageHandler } // NewRouter 创建新的路由 @@ -121,6 +123,10 @@ func NewRouter(params RouterParams) *gin.Engine { // 添加OpenTelemetry追踪中间件 // r.Use(middleware.TracingMiddleware()) + // Langfuse observability — only active when LANGFUSE_* env vars are set. + // The middleware is registered unconditionally; when disabled it's a no-op. + r.Use(langfuse.GinMiddleware()) + // 需要认证的API路由 v1 := r.Group("/api/v1") { @@ -148,6 +154,7 @@ func NewRouter(params RouterParams) *gin.Engine { RegisterIMChannelRoutes(v1, params.IMHandler) RegisterDataSourceRoutes(v1, params.DataSourceHandler) RegisterWeKnoraCloudRoutes(v1, params.WeKnoraCloudHandler) + RegisterWikiPageRoutes(v1, params.WikiPageHandler) } return r @@ -215,6 +222,8 @@ func RegisterKnowledgeRoutes(r *gin.RouterGroup, handler *handler.KnowledgeHandl k.PUT("/tags", handler.UpdateKnowledgeTagBatch) // 搜索知识 k.GET("/search", handler.SearchKnowledge) + // 批量删除知识(同一知识库内) + k.POST("/batch-delete", handler.BatchDeleteKnowledge) // 移动知识到其他知识库 k.POST("/move", handler.MoveKnowledge) // 获取知识移动进度 @@ -448,7 +457,6 @@ func RegisterSystemRoutes(r *gin.RouterGroup, handler *handler.SystemHandler) { systemRoutes.POST("/docreader/reconnect", handler.ReconnectDocReader) systemRoutes.GET("/storage-engine-status", handler.GetStorageEngineStatus) systemRoutes.POST("/storage-engine-check", handler.CheckStorageEngine) - systemRoutes.GET("/minio/buckets", handler.ListMinioBuckets) } } @@ -529,6 +537,8 @@ func RegisterCustomAgentRoutes(r *gin.RouterGroup, agentHandler *handler.CustomA { // Get placeholder definitions (must be before /:id to avoid conflict) agents.GET("/placeholders", agentHandler.GetPlaceholders) + // List smart-reasoning agent type presets (rag-qa / wiki-qa / hybrid / custom) + agents.GET("/type-presets", agentHandler.GetAgentTypePresets) // Create custom agent agents.POST("", agentHandler.CreateAgent) // List all agents (including built-in) @@ -834,3 +844,34 @@ func RegisterWeKnoraCloudRoutes(r *gin.RouterGroup, handler *handler.WeKnoraClou r.POST("/weknoracloud/credentials", handler.SaveCredentials) r.GET("/models/weknoracloud/status", handler.Status) } + +// RegisterWikiPageRoutes registers wiki page related routes +func RegisterWikiPageRoutes(r *gin.RouterGroup, wikiHandler *handler.WikiPageHandler) { + wiki := r.Group("/knowledgebase/:kb_id/wiki") + { + // Page CRUD + wiki.GET("/pages", wikiHandler.ListPages) + wiki.POST("/pages", wikiHandler.CreatePage) + wiki.GET("/pages/*slug", wikiHandler.GetPage) + wiki.PUT("/pages/*slug", wikiHandler.UpdatePage) + wiki.DELETE("/pages/*slug", wikiHandler.DeletePage) + + // Special pages + wiki.GET("/index", wikiHandler.GetIndex) + wiki.GET("/log", wikiHandler.GetLog) + + // Graph and stats + wiki.GET("/graph", wikiHandler.GetGraph) + wiki.GET("/stats", wikiHandler.GetStats) + + // Search and maintenance + wiki.GET("/search", wikiHandler.SearchPages) + wiki.POST("/rebuild-links", wikiHandler.RebuildLinks) + wiki.GET("/lint", wikiHandler.Lint) + wiki.POST("/auto-fix", wikiHandler.AutoFix) + + // Issues + wiki.GET("/issues", wikiHandler.ListIssues) + wiki.PUT("/issues/:issue_id/status", wikiHandler.UpdateIssueStatus) + } +} diff --git a/internal/router/sync_task.go b/internal/router/sync_task.go index de851c70..dacc9bd0 100644 --- a/internal/router/sync_task.go +++ b/internal/router/sync_task.go @@ -36,7 +36,8 @@ func (e *SyncTaskExecutor) RegisterHandler(pattern string, handler func(context. // Enqueue satisfies interfaces.TaskEnqueuer. // Instead of queuing to Redis, it dispatches the task to a goroutine. -func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, _ ...asynq.Option) (*asynq.TaskInfo, error) { +// Supports ProcessIn (delay) and MaxRetry options for parity with asynq. +func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, opts ...asynq.Option) (*asynq.TaskInfo, error) { e.mu.RLock() handler, ok := e.handlers[task.Type()] e.mu.RUnlock() @@ -45,6 +46,28 @@ func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, _ ...asynq.Option) (*asynq. return nil, fmt.Errorf("sync task executor: no handler registered for type %q", task.Type()) } + var delay time.Duration + maxRetry := 25 // asynq default + maxRetrySet := false + for _, opt := range opts { + switch opt.Type() { + case asynq.ProcessInOpt: + if d, ok := opt.Value().(time.Duration); ok { + delay = d + } + case asynq.MaxRetryOpt: + if n, ok := opt.Value().(int); ok { + maxRetry = n + maxRetrySet = true + } + } + } + // Callers that explicitly pass MaxRetry(0) want no retries. + // Without the flag we can't distinguish "not set" from "set to 0". + if maxRetrySet && maxRetry < 0 { + maxRetry = 0 + } + taskID := uuid.New().String() info := &asynq.TaskInfo{ ID: taskID, @@ -53,16 +76,36 @@ func (e *SyncTaskExecutor) Enqueue(task *asynq.Task, _ ...asynq.Option) (*asynq. } go func() { + if delay > 0 { + time.Sleep(delay) + } + ctx := context.Background() start := time.Now() logger.Infof(ctx, "[SyncTask] Executing task type=%s id=%s", task.Type(), taskID) - if err := handler(ctx, task); err != nil { - logger.Errorf(ctx, "[SyncTask] Task failed type=%s id=%s elapsed=%v err=%v", - task.Type(), taskID, time.Since(start), err) - } else { - logger.Infof(ctx, "[SyncTask] Task completed type=%s id=%s elapsed=%v", - task.Type(), taskID, time.Since(start)) + + var lastErr error + for attempt := 0; attempt <= maxRetry; attempt++ { + if attempt > 0 { + backoff := time.Duration(attempt) * 5 * time.Second + if backoff > 30*time.Second { + backoff = 30 * time.Second + } + logger.Infof(ctx, "[SyncTask] Retrying task type=%s id=%s attempt=%d/%d backoff=%s", + task.Type(), taskID, attempt, maxRetry, backoff) + time.Sleep(backoff) + } + + lastErr = handler(ctx, task) + if lastErr == nil { + logger.Infof(ctx, "[SyncTask] Task completed type=%s id=%s elapsed=%v", + task.Type(), taskID, time.Since(start)) + return + } } + + logger.Errorf(ctx, "[SyncTask] Task failed (exhausted retries) type=%s id=%s elapsed=%v err=%v", + task.Type(), taskID, time.Since(start), lastErr) }() return info, nil @@ -79,6 +122,8 @@ type SyncTaskParams struct { ChunkExtractor interfaces.TaskHandler `name:"chunkExtractor"` DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"` ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"` + KnowledgePostProcess interfaces.TaskHandler `name:"knowledgePostProcess"` + WikiIngest interfaces.TaskHandler `name:"wikiIngest"` } // RegisterSyncHandlers registers all task handlers on the SyncTaskExecutor. @@ -97,6 +142,8 @@ func RegisterSyncHandlers(params SyncTaskParams) { params.Executor.RegisterHandler(types.TypeIndexDelete, params.TagService.ProcessIndexDelete) params.Executor.RegisterHandler(types.TypeKBDelete, params.KnowledgeBaseService.ProcessKBDelete) params.Executor.RegisterHandler(types.TypeImageMultimodal, params.ImageMultimodal.Handle) + params.Executor.RegisterHandler(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle) params.Executor.RegisterHandler(types.TypeDataSourceSync, params.DataSourceService.ProcessSync) + params.Executor.RegisterHandler(types.TypeWikiIngest, params.WikiIngest.Handle) logger.Infof(context.Background(), "[SyncTask] All task handlers registered (Lite mode, no Redis)") } diff --git a/internal/router/task.go b/internal/router/task.go index ff4e99fe..ca2dbb58 100644 --- a/internal/router/task.go +++ b/internal/router/task.go @@ -1,11 +1,14 @@ package router import ( + "errors" "log" "os" "strconv" "time" + "github.com/Tencent/WeKnora/internal/application/service" + "github.com/Tencent/WeKnora/internal/tracing/langfuse" "github.com/Tencent/WeKnora/internal/types" "github.com/Tencent/WeKnora/internal/types/interfaces" "github.com/hibiken/asynq" @@ -23,6 +26,8 @@ type AsynqTaskParams struct { ChunkExtractor interfaces.TaskHandler `name:"chunkExtractor"` DataTableSummary interfaces.TaskHandler `name:"dataTableSummary"` ImageMultimodal interfaces.TaskHandler `name:"imageMultimodal"` + KnowledgePostProcess interfaces.TaskHandler `name:"knowledgePostProcess"` + WikiIngest interfaces.TaskHandler `name:"wikiIngest"` } func getAsynqRedisClientOpt() *asynq.RedisClientOpt { @@ -53,6 +58,29 @@ func NewAsyncqClient() (*asynq.Client, error) { return client, nil } +// wikiIngestRetryDelay is a fixed, short backoff for wiki ingest lock +// conflicts. Must be slightly longer than the active-lock TTL's worst-case +// "just got set" window so the retry is highly likely to succeed without +// burning through retries; but short enough that users don't feel the stall. +const wikiIngestRetryDelay = 15 * time.Second + +// asynqRetryDelayFunc customizes per-task retry backoff. +// +// Default asynq backoff is exponential (≈10s, 40s, 90s, 2.5m, ...), which +// is appropriate for transient errors like remote HTTP failures. But for +// wiki ingest lock conflicts (ErrWikiIngestConcurrent), exponential +// backoff is harmful: a freshly orphaned lock expires in ≤60s, so a 15s +// fixed retry virtually guarantees the next attempt succeeds. Without +// this override, a crash-restart cycle can leave a KB unable to make +// progress for 7–10 minutes while the orphan lock expires AND the retry +// schedule catches up. +func asynqRetryDelayFunc(n int, e error, t *asynq.Task) time.Duration { + if errors.Is(e, service.ErrWikiIngestConcurrent) { + return wikiIngestRetryDelay + } + return asynq.DefaultRetryDelayFunc(n, e, t) +} + func NewAsynqServer() *asynq.Server { opt := getAsynqRedisClientOpt() srv := asynq.NewServer( @@ -63,6 +91,7 @@ func NewAsynqServer() *asynq.Server { "default": 3, // Default priority queue "low": 1, // Lowest priority queue }, + RetryDelayFunc: asynqRetryDelayFunc, }, ) return srv @@ -72,6 +101,14 @@ func RunAsynqServer(params AsynqTaskParams) *asynq.ServeMux { // Create a new mux and register all handlers mux := asynq.NewServeMux() + // Install Langfuse middleware BEFORE handler registration so every task + // type is automatically wrapped. When Langfuse is disabled the middleware + // is a pass-through; when enabled it resumes the upstream HTTP trace (if + // the payload carries one) or opens a standalone trace, then wraps the + // handler execution in a SPAN so all child generations (embedding / VLM / + // chat / rerank / ASR) nest correctly in the Langfuse UI. + mux.Use(langfuse.AsynqMiddleware()) + // Register extract handlers - router will dispatch to appropriate handler mux.HandleFunc(types.TypeChunkExtract, params.ChunkExtractor.Handle) mux.HandleFunc(types.TypeDataTableSummary, params.DataTableSummary.Handle) @@ -109,9 +146,15 @@ func RunAsynqServer(params AsynqTaskParams) *asynq.ServeMux { // Register image multimodal handler mux.HandleFunc(types.TypeImageMultimodal, params.ImageMultimodal.Handle) + // Register knowledge post process handler + mux.HandleFunc(types.TypeKnowledgePostProcess, params.KnowledgePostProcess.Handle) + // Register data source sync handler mux.HandleFunc(types.TypeDataSourceSync, params.DataSourceService.ProcessSync) + // Register wiki ingest handler + mux.HandleFunc(types.TypeWikiIngest, params.WikiIngest.Handle) + go func() { // Start the server if err := params.Server.Run(mux); err != nil { diff --git a/internal/searchutil/imageinfo.go b/internal/searchutil/imageinfo.go new file mode 100644 index 00000000..b526ff91 --- /dev/null +++ b/internal/searchutil/imageinfo.go @@ -0,0 +1,340 @@ +package searchutil + +import ( + "context" + "encoding/json" + "fmt" + "regexp" + "strings" + + "github.com/Tencent/WeKnora/internal/types" + "github.com/Tencent/WeKnora/internal/types/interfaces" +) + +// MarkdownImageRegex matches Markdown image links:  +var MarkdownImageRegex = regexp.MustCompile(`!\[([^\]]*)\]\(([^)]+)\)`) + +// CollectImageInfoByChunkIDs collects merged image_info JSON for each given +// chunk ID by querying child chunks (image_ocr / image_caption). It supports +// two-level resolution: +// - If chunkIDs are text chunks, their direct children are image chunks → one query. +// - If chunkIDs are parent_text chunks, their children are text chunks +// whose children are image chunks → two queries. +// +// Returns a map of input chunkID → merged image_info JSON string. +func CollectImageInfoByChunkIDs( + ctx context.Context, + chunkRepo interfaces.ChunkRepository, + tenantID uint64, + chunkIDs []string, +) map[string]string { + if len(chunkIDs) == 0 { + return nil + } + + children, err := chunkRepo.ListChunksByParentIDs(ctx, tenantID, chunkIDs) + if err != nil || len(children) == 0 { + return nil + } + + type imageAgg struct { + byURL map[string]types.ImageInfo + } + aggMap := make(map[string]*imageAgg) + + addInfo := func(targetID string, child *types.Chunk) { + if child.ImageInfo == "" { + return + } + var infos []types.ImageInfo + if err := json.Unmarshal([]byte(child.ImageInfo), &infos); err != nil || len(infos) == 0 { + return + } + agg, ok := aggMap[targetID] + if !ok { + agg = &imageAgg{byURL: make(map[string]types.ImageInfo)} + aggMap[targetID] = agg + } + for _, info := range infos { + key := info.URL + if key == "" { + key = info.OriginalURL + } + if key == "" { + continue + } + existing, exists := agg.byURL[key] + if !exists { + agg.byURL[key] = info + } else { + if info.OCRText != "" { + existing.OCRText = info.OCRText + } + if info.Caption != "" { + existing.Caption = info.Caption + } + agg.byURL[key] = existing + } + } + } + + var textChildIDs []string + textToParent := make(map[string]string) + + for _, child := range children { + switch child.ChunkType { + case types.ChunkTypeImageOCR, types.ChunkTypeImageCaption: + addInfo(child.ParentChunkID, child) + case types.ChunkTypeText: + textChildIDs = append(textChildIDs, child.ID) + textToParent[child.ID] = child.ParentChunkID + } + } + + if len(textChildIDs) > 0 { + grandChildren, err := chunkRepo.ListChunksByParentIDs(ctx, tenantID, textChildIDs) + if err == nil { + for _, gc := range grandChildren { + if gc.ChunkType != types.ChunkTypeImageOCR && gc.ChunkType != types.ChunkTypeImageCaption { + continue + } + if parentTextID, ok := textToParent[gc.ParentChunkID]; ok { + addInfo(parentTextID, gc) + } + } + } + } + + out := make(map[string]string, len(aggMap)) + for id, agg := range aggMap { + if len(agg.byURL) == 0 { + continue + } + merged := make([]types.ImageInfo, 0, len(agg.byURL)) + for _, info := range agg.byURL { + merged = append(merged, info) + } + data, err := json.Marshal(merged) + if err != nil { + continue + } + out[id] = string(data) + } + return out +} + +// EnrichSearchResultsImageInfo fills in ImageInfo for SearchResults that have +// none by batch-querying child image chunks. +func EnrichSearchResultsImageInfo( + ctx context.Context, + chunkRepo interfaces.ChunkRepository, + tenantID uint64, + results []*types.SearchResult, +) { + var chunkIDs []string + seen := make(map[string]bool) + for _, r := range results { + if r.ImageInfo != "" { + continue + } + if !seen[r.ID] { + seen[r.ID] = true + chunkIDs = append(chunkIDs, r.ID) + } + } + if len(chunkIDs) == 0 { + return + } + + infoMap := CollectImageInfoByChunkIDs(ctx, chunkRepo, tenantID, chunkIDs) + if len(infoMap) == 0 { + return + } + + for _, r := range results { + if r.ImageInfo != "" { + continue + } + if merged, ok := infoMap[r.ID]; ok { + r.ImageInfo = merged + } + } +} + +// MergeImageInfoJSON combines per-chunk image_info JSON strings (from +// CollectImageInfoByChunkIDs) into a single JSON array, deduplicating by URL. +func MergeImageInfoJSON(perChunk map[string]string) string { + if len(perChunk) == 0 { + return "" + } + seen := make(map[string]bool) + var all []types.ImageInfo + for _, raw := range perChunk { + var infos []types.ImageInfo + if err := json.Unmarshal([]byte(raw), &infos); err != nil { + continue + } + for _, info := range infos { + key := info.URL + if key == "" { + key = info.OriginalURL + } + if key != "" && !seen[key] { + seen[key] = true + all = append(all, info) + } + } + } + if len(all) == 0 { + return "" + } + data, err := json.Marshal(all) + if err != nil { + return "" + } + return string(data) +} + +// EnrichContentWithImageInfo embeds image info as XML tags into text content. +// Inline Markdown image links get wrapped in", "error": "", "details?": "" }
+```
+
+---
+
+## 核心端点
+
+### 1. 健康检查
+
+```
+GET {base_url}/api/health
+```
+
+响应:
+```json
+{
+ "success": true,
+ "status": "ok",
+ "version": "0.1.0",
+ "capabilities": {
+ "webSearch": true,
+ "imageGeneration": false,
+ "videoGeneration": false,
+ "tts": true
+ }
+}
+```
+
+> `capabilities` 用于功能检测,只在返回此字段时才启用对应的可选功能。
+
+---
+
+### 2. 生成课程(异步任务)
+
+#### 2a. 创建生成任务
+
+```
+POST {base_url}/api/generate-classroom
+Content-Type: application/json
+```
+
+请求体:
+```json
+{
+ "requirement": "教学主题描述",
+ "pdfContent": { "text": "PDF文本内容", "images": [] },
+ "enableWebSearch": false,
+ "enableImageGeneration": false,
+ "enableVideoGeneration": false,
+ "enableTTS": false,
+ "agentMode": "default"
+}
+```
+
+成功响应 (202):
+```json
+{
+ "success": true,
+ "jobId": "abc123xyz",
+ "status": "queued",
+ "step": "queued",
+ "message": "Classroom generation job queued",
+ "pollUrl": "{base_url}/api/generate-classroom/abc123xyz",
+ "pollIntervalMs": 5000
+}
+```
+
+错误:
+- `400`: `requirement` 字段缺失
+- `500`: 内部错误
+
+#### 2b. 轮询任务状态
+
+```
+GET {pollUrl}
+```
+
+响应:
+```json
+{
+ "success": true,
+ "jobId": "abc123xyz",
+ "status": "running",
+ "step": "generating_outlines",
+ "progress": 35,
+ "message": "Generating scene outlines...",
+ "pollUrl": "...",
+ "pollIntervalMs": 5000,
+ "scenesGenerated": 2,
+ "totalScenes": 6,
+ "result": null,
+ "error": null,
+ "done": false
+}
+```
+
+最终成功响应:
+```json
+{
+ "success": true,
+ "status": "succeeded",
+ "result": {
+ "classroomId": "Uyh82Y32ZK",
+ "url": "{base_url}/classroom/Uyh82Y32ZK",
+ "scenesCount": 6
+ },
+ "done": true
+}
+```
+
+最终失败响应:
+```json
+{
+ "success": true,
+ "status": "failed",
+ "error": "具体错误信息",
+ "done": true
+}
+```
+
+---
+
+### 3. 解析 PDF
+
+```
+POST {base_url}/api/parse-pdf
+Content-Type: multipart/form-data
+```
+
+表单字段:
+- `pdf`(文件,必填): PDF 文件
+- `providerId`(可选): PDF 提供商,默认 `"unpdf"`
+- `apiKey`(可选): 提供商 API Key
+- `baseUrl`(可选): 提供商基础 URL
+
+响应:
+```json
+{
+ "success": true,
+ "data": {
+ "text": "提取的文本内容",
+ "images": [],
+ "metadata": {
+ "pageCount": 10,
+ "fileName": "document.pdf",
+ "fileSize": 1024000
+ }
+ }
+}
+```
+
+---
+
+### 4. 课程存储
+
+#### 4a. 获取课程
+
+```
+GET {base_url}/api/classroom?id=
+```
+
+#### 4b. 持久化课程
+
+```
+POST {base_url}/api/classroom
+Content-Type: application/json
+
+{ "stage": {...}, "scenes": [...] }
+```
+
+---
+
+### 5. Web 搜索
+
+```
+POST {base_url}/api/web-search
+Content-Type: application/json
+
+{ "query": "搜索关键词", "pdfText": "PDF上下文", "apiKey": "Tavily Key" }
+```
+
+---
+
+### 6. 验证 LLM 连接
+
+```
+POST {base_url}/api/verify-model
+Content-Type: application/json
+
+{ "model": "openai:gpt-4o", "apiKey": "...", "baseUrl": "..." }
+```
+
+---
+
+## 生成管线(逐步调用)
+
+如果需要更细粒度的控制,可以使用以下逐步生成端点代替 `/api/generate-classroom`:
+
+### A. 生成场景大纲(SSE 流)
+
+```
+POST {base_url}/api/generate/scene-outlines-stream
+```
+
+请求体:
+```json
+{
+ "requirements": { "requirement": "主题", "userNickname": "用户昵称" },
+ "pdfText": "PDF文本",
+ "pdfImages": [],
+ "researchContext": "网络搜索结果",
+ "agents": []
+}
+```
+
+Headers:
+- `x-image-generation-enabled`: `"true"` 或 `"false"`
+- `x-video-generation-enabled`: `"true"` 或 `"false"`
+
+SSE 事件类型:`languageDirective`、`outline`、`done`、`error`、`retry`
+
+### B. 生成场景内容
+
+```
+POST {base_url}/api/generate/scene-content
+Content-Type: application/json
+
+{
+ "outline": {...},
+ "allOutlines": [...],
+ "stageId": "stage-1",
+ "pdfImages": [],
+ "agents": [],
+ "languageDirective": "使用简体中文"
+}
+```
+
+### C. 生成场景动作
+
+```
+POST {base_url}/api/generate/scene-actions
+Content-Type: application/json
+
+{
+ "outline": {...},
+ "allOutlines": [...],
+ "content": {...},
+ "stageId": "stage-1",
+ "agents": [],
+ "languageDirective": "使用简体中文"
+}
+```
+
+### D. 生成 Agent 画像
+
+```
+POST {base_url}/api/generate/agent-profiles
+Content-Type: application/json
+
+{
+ "stageInfo": { "name": "入门阶段", "description": "..." },
+ "sceneOutlines": [{ "title": "...", "description": "..." }],
+ "languageDirective": "使用简体中文",
+ "availableAvatars": [],
+ "avatarDescriptions": []
+}
+```
diff --git a/skills/preloaded/openmaic-classroom/references/requirement-builder.md b/skills/preloaded/openmaic-classroom/references/requirement-builder.md
new file mode 100644
index 00000000..c023e6d5
--- /dev/null
+++ b/skills/preloaded/openmaic-classroom/references/requirement-builder.md
@@ -0,0 +1,135 @@
+# 需求构建指南
+
+将 WeKnora RAG 检索结果转换为 OpenMAIC 课程生成所需的 `requirement` 格式。
+
+## 核心原则
+
+OpenMAIC 的 `requirement` 字段需要是**结构化的教学需求描述**,而不是原始文档片段。构建时需考虑:
+
+1. **教学主题**: 明确要教什么
+2. **目标受众**: 面向谁教学(如:初学者、专业人士、学生等)
+3. **教学深度**: 入门级、中级、高级
+4. **内容范围**: 基于哪些知识源构建
+
+## 转换模板
+
+### 模板 1: 纯需求(无检索结果)
+
+用户直接描述需求时,直接使用用户描述作为 requirement:
+
+```
+用户: "帮我创建一个关于量子力学的入门课程"
+→ requirement: "Create an introductory classroom on quantum mechanics for beginners"
+```
+
+### 模板 2: 基于 RAG 检索结果
+
+```
+步骤:
+1. 使用 knowledge_search 检索相关知识
+2. 从检索结果中提取:
+ - 核心主题/概念
+ - 关键知识点
+ - 文档来源信息
+3. 构建结构化 requirement
+```
+
+构建格式:
+```
+基于以下知识内容,创建一个面向[目标受众]的[深度级别]课程:
+
+核心主题:[从检索结果提取的主要概念]
+关键知识点:
+- [知识点1]
+- [知识点2]
+- ...
+内容来源:[文档名称列表]
+```
+
+### 模板 3: 基于单个文档
+
+```
+基于文档《[文档名称]》的内容,创建一个面向[目标受众]的课程,
+重点讲解以下方面:
+- [用户指定的重点1]
+- [用户指定的重点2]
+```
+
+### 模板 4: 基于多个文档/知识块
+
+```
+综合以下文档内容,创建一个系统的课程:
+
+文档1《[名称1]》: [简要内容摘要]
+文档2《[名称2]》: [简要内容摘要]
+文档3《[名称3]》: [简要内容摘要]
+
+要求:
+- 教学深度:[级别]
+- 目标受众:[描述]
+- 重点覆盖:[关键主题列表]
+```
+
+## 示例
+
+### 示例 1: 技术文档 → 课程
+
+```
+检索结果:
+- 文档: "Kubernetes 部署指南.pdf"
+- 关键内容: Pod 管理、Service 配置、Ingress 路由、存储卷
+
+构建的 requirement:
+"基于 Kubernetes 部署指南,创建一个面向 DevOps 工程师的中级课程。
+重点涵盖:Pod 生命周期管理、Service 和 Ingress 网络配置、持久化存储卷管理。
+课程应包含实践操作环节。"
+```
+
+### 示例 2: 产品手册 → 入门课程
+
+```
+检索结果:
+- 文档: "产品使用手册 v2.0.pdf"
+- 关键内容: 产品概述、快速开始、核心功能、常见问题
+
+构建的 requirement:
+"基于产品使用手册 v2.0,为新用户创建一个入门课程。
+帮助用户快速了解产品核心功能,掌握基本操作方法,
+并能够独立完成常见任务。课程语言为中文。"
+```
+
+### 示例 3: 研究论文 → 高级课程
+
+```
+检索结果:
+- 文档: "Transformer 架构研究综述.pdf"
+- 关键内容: Attention 机制、位置编码、多头注意力、训练技巧
+
+构建的 requirement:
+"基于 Transformer 架构研究综述,为具有深度学习基础的研究人员
+创建高级课程。深入讲解 Attention 机制的数学原理、位置编码的
+各种变体、多头注意力的设计动机,以及训练大模型时的实践技巧。"
+```
+
+## 可选功能配置建议
+
+在构建 request 时,根据用户需求推荐可选功能:
+
+| 场景 | 推荐功能 |
+|------|----------|
+| 技术培训 | `enableWebSearch: true`(补充最新技术动态) |
+| 产品介绍 | `enableImageGeneration: true`(生成产品截图/界面图) |
+| 市场营销 | `enableImageGeneration: true, enableVideoGeneration: true` |
+| 语言教学 | `enableTTS: true`(语音朗读) |
+| 学术研究 | 默认配置即可(不需要多媒体) |
+
+## 多文档处理
+
+当需要将多个独立文档分别生成课程时:
+
+1. 为每个文档单独构建 requirement
+2. 依次调用生成 API(不可并行)
+3. 每完成一个即返回 URL,继续下一个
+4. 最终汇总所有 Classroom URL
+
+> 注意:OpenMAIC 托管模式每天最多 10 次生成配额,本地模式取决于 LLM Provider 配额。
diff --git a/skills/preloaded/openmaic-classroom/scripts/rag-to-requirement.py b/skills/preloaded/openmaic-classroom/scripts/rag-to-requirement.py
new file mode 100644
index 00000000..f37290a7
--- /dev/null
+++ b/skills/preloaded/openmaic-classroom/scripts/rag-to-requirement.py
@@ -0,0 +1,194 @@
+#!/usr/bin/env python3
+"""
+RAG 检索结果 → OpenMAIC Requirement 转换器
+
+将 WeKnora RAG 检索结果转换为结构化的 OpenMAIC 课程生成需求描述。
+此脚本仅做数据转换,不涉及网络调用。
+
+用法:
+ echo '{"chunks": [...], "audience": "初学者"}' | python scripts/rag-to-requirement.py
+ python scripts/rag-to-requirement.py --file results.json
+
+输入格式 (JSON):
+{
+ "chunks": [
+ {
+ "document_name": "文档A.pdf",
+ "content": "文档内容片段...",
+ "metadata": {"page": 5, "section": "第三章"}
+ }
+ ],
+ "query": "用户原始查询(可选)",
+ "audience": "目标受众描述(可选,默认'相关领域的学习者')",
+ "depth": "教学深度: beginner|intermediate|advanced(可选,默认'intermediate')",
+ "language": "zh-CN|en-US(可选,默认'zh-CN')",
+ "focus_areas": ["重点领域1", "重点领域2"] # 可选
+}
+
+输出格式 (JSON):
+{
+ "requirement": "结构化的教学需求描述",
+ "metadata": {
+ "source_documents": ["文档A.pdf", "文档B.pdf"],
+ "total_chunks": 5,
+ "audience": "初学者",
+ "depth": "intermediate",
+ "language": "zh-CN"
+ }
+}
+"""
+
+import json
+import sys
+from typing import Any
+
+
+def extract_key_topics(chunks: list[dict], max_topics: int = 5) -> list[str]:
+ """从文档块中提取关键主题(基于内容摘要和 section 信息)。"""
+ topics = []
+ seen = set()
+
+ for chunk in chunks:
+ metadata = chunk.get("metadata", {})
+ # 优先使用 section/chapter 信息
+ for key in ("section", "chapter", "heading", "title"):
+ if key in metadata and metadata[key] not in seen:
+ topics.append(metadata[key])
+ seen.add(metadata[key])
+ if len(topics) >= max_topics:
+ return topics
+
+ # 如果 section 信息不足,从内容前 50 字提取
+ for chunk in chunks:
+ content = chunk.get("content", "")[:50].strip()
+ if content and content not in seen:
+ topics.append(content + "...")
+ seen.add(content)
+ if len(topics) >= max_topics:
+ break
+
+ return topics
+
+
+def build_requirement(data: dict[str, Any]) -> str:
+ """将 RAG 结果构建为 OpenMAIC requirement 字符串。"""
+ chunks = data.get("chunks", [])
+ query = data.get("query", "")
+ audience = data.get("audience", "相关领域的学习者")
+ depth = data.get("depth", "intermediate")
+ language = data.get("language", "zh-CN")
+ focus_areas = data.get("focus_areas", [])
+
+ depth_map = {
+ "beginner": "入门",
+ "intermediate": "中级",
+ "advanced": "高级",
+ }
+ depth_cn = depth_map.get(depth, "中级")
+
+ # 提取文档名称
+ source_docs = list({c.get("document_name", "未知文档") for c in chunks})
+
+ # 提取关键主题
+ key_topics = extract_key_topics(chunks)
+
+ # 构建 requirement
+ parts = []
+
+ # 开头:基于什么内容,为谁创建什么课程
+ if query:
+ parts.append(f"基于以下知识库内容,为{audience}创建一个{depth_cn}课程。")
+ parts.append(f"用户原始需求:{query}")
+ else:
+ parts.append(f"基于以下知识库内容,为{audience}创建一个{depth_cn}课程。")
+
+ # 内容来源
+ if source_docs:
+ docs_str = "、".join(source_docs[:5])
+ if len(source_docs) > 5:
+ docs_str += f" 等{len(source_docs)}个文档"
+ parts.append(f"\n内容来源:{docs_str}")
+
+ # 关键主题
+ if key_topics:
+ parts.append("\n核心主题:")
+ for i, topic in enumerate(key_topics, 1):
+ parts.append(f" {i}. {topic}")
+
+ # 重点领域
+ if focus_areas:
+ parts.append("\n重点覆盖:")
+ for area in focus_areas:
+ parts.append(f" - {area}")
+
+ # 语言要求
+ if language == "zh-CN":
+ parts.append("\n请使用中文生成课程内容。")
+
+ return "\n".join(parts)
+
+
+def process(input_data: dict[str, Any]) -> dict[str, Any]:
+ """主处理函数。"""
+ chunks = input_data.get("chunks", [])
+ if not chunks:
+ return {
+ "requirement": input_data.get("query", ""),
+ "metadata": {
+ "source_documents": [],
+ "total_chunks": 0,
+ "error": "未提供检索结果,使用原始查询作为 requirement",
+ },
+ }
+
+ requirement = build_requirement(input_data)
+
+ source_docs = list({c.get("document_name", "未知文档") for c in chunks})
+
+ return {
+ "requirement": requirement,
+ "metadata": {
+ "source_documents": source_docs,
+ "total_chunks": len(chunks),
+ "audience": input_data.get("audience", "相关领域的学习者"),
+ "depth": input_data.get("depth", "intermediate"),
+ "language": input_data.get("language", "zh-CN"),
+ },
+ }
+
+
+def main() -> None:
+ """入口:从 stdin 或文件读取输入,输出 JSON 结果。"""
+ import argparse
+
+ parser = argparse.ArgumentParser(description="RAG 结果 → OpenMAIC Requirement 转换器")
+ parser.add_argument("--file", "-f", help="输入 JSON 文件路径")
+ args = parser.parse_args()
+
+ # 读取输入
+ if args.file:
+ with open(args.file, "r", encoding="utf-8") as f:
+ input_data = json.load(f)
+ else:
+ input_text = sys.stdin.read()
+ if not input_text.strip():
+ print(
+ "错误: 未提供输入数据。用法:\n"
+ " echo '{\"chunks\": [...]}' | python rag-to-requirement.py\n"
+ " python rag-to-requirement.py --file input.json",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+ try:
+ input_data = json.loads(input_text)
+ except json.JSONDecodeError as e:
+ print(f"错误: 输入 JSON 解析失败: {e}", file=sys.stderr)
+ sys.exit(1)
+
+ # 处理并输出
+ result = process(input_data)
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/testdata/wiki_test/doc1_stardust_memo.md b/testdata/wiki_test/doc1_stardust_memo.md
new file mode 100644
index 00000000..e21a37ad
--- /dev/null
+++ b/testdata/wiki_test/doc1_stardust_memo.md
@@ -0,0 +1,11 @@
+# 星尘计划启动备忘录
+**机密级别**:极密
+**发布机构**:天穹财团 (SkyVault Consortium) 董事会
+**项目代号**:星尘计划 (Project Stardust)
+**首席科学家**:艾琳·科尔博士 (Dr. Elara Cole)
+
+**项目概述**:
+星尘计划旨在开发一种革命性的推进系统——“幽能引擎 (Psionic Engine)”。该引擎将利用非牛顿物理学框架,突破目前星际航行的光速壁垒。
+
+**资源分配**:
+天穹财团将调拨“深渊之门”实验室的全部资源供艾琳·科尔博士使用。项目资金不设上限,以确保幽能引擎能够在 2150 年前进入原型机测试阶段。
diff --git a/testdata/wiki_test/doc2_psionic_engine.md b/testdata/wiki_test/doc2_psionic_engine.md
new file mode 100644
index 00000000..18ac2423
--- /dev/null
+++ b/testdata/wiki_test/doc2_psionic_engine.md
@@ -0,0 +1,12 @@
+# 幽能引擎技术白皮书
+
+## 引言
+幽能引擎 (Psionic Engine) 代表着我们对宇宙认知的范式转移。它的核心原理并非燃烧燃料或喷射粒子,而是建立在备受争议的**虚空共振理论 (Void Resonance Theory)** 之上。
+
+## 虚空共振理论
+该理论假设宇宙的真空中充满了低能级的波谱,通过特定频率的干涉,可以在空间中制造“引力滑流”。
+
+## 催化剂:星晶 (StarQuartz)
+要在宏观尺度上触发并维持“虚空共振理论”所描述的引力滑流,必须使用一种极端稀有的矿物作为反应堆核心的催化剂。这种矿物被称为**星晶 (StarQuartz)**。
+
+星晶具有在室温下超导并在特定频段下自发振荡的特性。目前,地球上唯一能稳定合成并从陨石中提纯出工业级星晶的实体,是拥有庞大资本和尖端技术的**天穹财团 (SkyVault Consortium)**。
diff --git a/testdata/wiki_test/doc3_dr_cole_log.md b/testdata/wiki_test/doc3_dr_cole_log.md
new file mode 100644
index 00000000..8e032445
--- /dev/null
+++ b/testdata/wiki_test/doc3_dr_cole_log.md
@@ -0,0 +1,17 @@
+# 个人日志 (节选) - 2148年
+**作者**:艾琳·科尔博士 (Dr. Elara Cole)
+
+...
+**日志条目 #402**
+我不明白。为什么我的研究团队里会有人听到不存在的低语?
+就在上周,反应堆进行了一次全负荷测试,旨在验证“虚空共振理论”。为了达到那该死的输出功率,我们往堆芯里添加了未经稀释的**星晶 (StarQuartz)**。
+
+**日志条目 #403**
+辐射数值正常,但某种“东西”渗透了我们的实验室。今天又有两个工程师因为极度幻觉被送去医务室了。这就是高纯度星晶催化带来的不可见副作用吗?
+
+**日志条目 #404**
+我已经向天穹财团的董事会提交了紧急备忘录。我建议立即暂停所有引擎相关的实验,并在解决星晶的神经干扰效应前封锁所有原型机。
+
+他们拒绝了。他们说,只要测试人员的死亡率不超过 15%,项目推进的优先级依然最高。
+他们根本不在乎。
+...
diff --git a/tests/miniprogram/miniprogram.test.js b/tests/miniprogram/miniprogram.test.js
new file mode 100644
index 00000000..4c61657f
--- /dev/null
+++ b/tests/miniprogram/miniprogram.test.js
@@ -0,0 +1,208 @@
+const assert = require("node:assert/strict");
+const test = require("node:test");
+const { createKnowledgeFromURL, knowledgeChat, listKnowledgeBases } = require("../../miniprogram/utils/request");
+const { collectAnswerFromSSE, parseSSE } = require("../../miniprogram/utils/sse");
+const { normalizeBaseUrl } = require("../../miniprogram/utils/config");
+
+test("parseSSE extracts event payloads", () => {
+ const events = parseSSE('event: message\ndata: {"content":"hi"}\n\n');
+
+ assert.equal(events.length, 1);
+ assert.equal(events[0].event, "message");
+ assert.equal(events[0].data, '{"content":"hi"}');
+});
+
+test("collectAnswerFromSSE joins answer chunks and skips references", () => {
+ const raw = [
+ 'event: message\ndata: {"response_type":"references","content":"skip","done":false}',
+ 'event: message\ndata: {"response_type":"answer","content":"Hel","done":false}',
+ 'event: message\ndata: {"response_type":"answer","content":"lo","done":true}'
+ ].join("\n\n");
+
+ assert.equal(collectAnswerFromSSE(raw), "Hello");
+});
+
+test("normalizeBaseUrl trims trailing slashes", () => {
+ assert.equal(normalizeBaseUrl(" https://example.com/// "), "https://example.com");
+});
+
+test("API helpers send WeKnora auth headers", async () => {
+ let capturedRequest;
+ global.wx = {
+ getStorageSync() {
+ return {
+ apiKey: "sk-test",
+ baseUrl: "https://weknora.example.com/",
+ selectedKnowledgeBaseId: "kb-1"
+ };
+ },
+ request(options) {
+ capturedRequest = options;
+ options.success({
+ statusCode: 200,
+ data: {
+ data: []
+ }
+ });
+ }
+ };
+
+ await listKnowledgeBases();
+
+ assert.equal(capturedRequest.url, "https://weknora.example.com/api/v1/knowledge-bases");
+ assert.equal(capturedRequest.header["X-API-Key"], "sk-test");
+ assert.match(capturedRequest.header["X-Request-ID"], /^mp-/);
+});
+
+test("URL import helper posts the selected URL payload", async () => {
+ let capturedRequest;
+ global.wx = {
+ getStorageSync() {
+ return {
+ apiKey: "sk-test",
+ baseUrl: "https://weknora.example.com",
+ selectedKnowledgeBaseId: "kb-1"
+ };
+ },
+ request(options) {
+ capturedRequest = options;
+ options.success({
+ statusCode: 201,
+ data: {
+ success: true
+ }
+ });
+ }
+ };
+
+ await createKnowledgeFromURL("kb-1", "https://github.com/Tencent/WeKnora", true);
+
+ assert.equal(capturedRequest.method, "POST");
+ assert.equal(capturedRequest.url, "https://weknora.example.com/api/v1/knowledge-bases/kb-1/knowledge/url");
+ assert.deepEqual(capturedRequest.data, {
+ url: "https://github.com/Tencent/WeKnora",
+ enable_multimodel: true
+ });
+});
+
+test("chat helper includes selected knowledge base ids", async () => {
+ let capturedRequest;
+ global.wx = {
+ getStorageSync() {
+ return {
+ apiKey: "sk-test",
+ baseUrl: "https://weknora.example.com"
+ };
+ },
+ request(options) {
+ capturedRequest = options;
+ options.success({
+ statusCode: 200,
+ data: "event: message\ndata: {}\n\n"
+ });
+ }
+ };
+
+ await knowledgeChat("session-1", "hello", "kb-1");
+
+ assert.equal(capturedRequest.method, "POST");
+ assert.equal(capturedRequest.url, "https://weknora.example.com/api/v1/knowledge-chat/session-1");
+ assert.deepEqual(capturedRequest.data, {
+ query: "hello",
+ knowledge_base_ids: ["kb-1"]
+ });
+});
+
+test("knowledge page skips API loading until settings are configured", async () => {
+ const calls = [];
+ const pageDefinitions = [];
+ const originalPage = global.Page;
+ const originalWx = global.wx;
+
+ try {
+ global.Page = (definition) => {
+ pageDefinitions.push(definition);
+ };
+ global.wx = {
+ getStorageSync() {
+ return {};
+ },
+ request() {
+ calls.push("request");
+ },
+ switchTab() {}
+ };
+
+ delete require.cache[require.resolve("../../miniprogram/pages/index/index.js")];
+ require("../../miniprogram/pages/index/index.js");
+ const page = {
+ data: { ...pageDefinitions[0].data },
+ setData(nextData) {
+ this.data = { ...this.data, ...nextData };
+ }
+ };
+
+ await pageDefinitions[0].onShow.call(page);
+
+ assert.equal(page.data.needsSettings, true);
+ assert.deepEqual(calls, []);
+ } finally {
+ global.Page = originalPage;
+ global.wx = originalWx;
+ }
+});
+
+test("knowledge page maps API results to picker labels", async () => {
+ const pageDefinitions = [];
+ const originalPage = global.Page;
+ const originalWx = global.wx;
+ let savedSettings;
+
+ try {
+ global.Page = (definition) => {
+ pageDefinitions.push(definition);
+ };
+ global.wx = {
+ getStorageSync() {
+ return {
+ apiKey: "sk-test",
+ baseUrl: "https://weknora.example.com"
+ };
+ },
+ request(options) {
+ options.success({
+ statusCode: 200,
+ data: {
+ data: [
+ { id: "kb-1", name: "Compliance KB" },
+ { id: "kb-2", name: "Docs KB" }
+ ]
+ }
+ });
+ },
+ setStorageSync(key, value) {
+ savedSettings = { key, value };
+ },
+ switchTab() {}
+ };
+
+ delete require.cache[require.resolve("../../miniprogram/pages/index/index.js")];
+ require("../../miniprogram/pages/index/index.js");
+ const page = {
+ data: { ...pageDefinitions[0].data },
+ setData(nextData) {
+ this.data = { ...this.data, ...nextData };
+ }
+ };
+
+ await pageDefinitions[0].loadKnowledgeBases.call(page);
+
+ assert.deepEqual(page.data.knowledgeBaseNames, ["Compliance KB", "Docs KB"]);
+ assert.equal(page.data.selectedKnowledgeBaseId, "kb-1");
+ assert.equal(page.data.selectedKnowledgeBaseName, "Compliance KB");
+ assert.equal(savedSettings.value.selectedKnowledgeBaseId, "kb-1");
+ } finally {
+ global.Page = originalPage;
+ global.wx = originalWx;
+ }
+});