2025-08-05 07:08:07 +00:00
// Package container implements dependency injection container setup
// Provides centralized configuration for services, repositories, and handlers
// This package is responsible for wiring up all dependencies and ensuring proper lifecycle management
package container
import (
"context"
2025-12-23 08:56:30 +00:00
"database/sql"
2026-04-27 08:56:30 +00:00
"errors"
2025-08-05 07:08:07 +00:00
"fmt"
2025-11-08 19:27:24 +00:00
"net/url"
2025-08-05 07:08:07 +00:00
"os"
2026-02-28 05:22:07 +00:00
"path/filepath"
2025-08-05 07:08:07 +00:00
"slices"
2025-08-16 05:13:52 +00:00
"strconv"
2025-08-05 07:08:07 +00:00
"strings"
"time"
2026-02-28 05:22:07 +00:00
sqlite_vec "github.com/asg017/sqlite-vec-go-bindings/cgo"
2026-01-05 06:52:11 +00:00
_ "github.com/duckdb/duckdb-go/v2"
2025-08-05 07:08:07 +00:00
esv7 "github.com/elastic/go-elasticsearch/v7"
"github.com/elastic/go-elasticsearch/v8"
feat(retriever): 接入 Apache Doris 4.1 作为向量数据库
为 RetrieveEngine 体系新增 Doris 后端,与现有 Qdrant/Milvus/Weaviate
等保持完整能力对齐:向量检索、关键词检索、健康检查、环境变量与多实例
DB 配置、前端类型注册、单元测试、Docker Compose 模板。
实现要点:
- 协议分工:主链路用 MySQL 协议(database/sql + go-sql-driver/mysql)
做 DDL / 查询 / 删除;批量更新走 Stream Load HTTP API,并启用
partial_update=true、merge_type=APPEND,自动按 1MiB 切分批次并处理
307 重定向。
- 表结构:UNIQUE KEY(id) + enable_unique_key_merge_on_write=true 以
支持 upsert/部分列更新;按维度分表(<base>_<dim>),每张表上建
HNSW ANN 索引(metric_type=cosine_distance)和 INVERTED 索引
(parser=chinese)。
- 分数语义:使用 cosine_distance_approximate,再以 1 - dist 转换为
"越大越相似",与现有 KVHybridRetrieveEngine 约定一致。
- 异步索引:ANN 索引为后台构建,ensureTable 通过轮询 SHOW INDEX 等
待索引就绪后再放行写入,避免首次检索召回为空。
- ARRAY<FLOAT> 序列化:go-sql-driver/mysql 不支持数组占位符,
embeddingLiteral 将 []float32 转成 SQL 字面量字符串再拼接。
新增文件:
- internal/application/repository/retriever/doris/{structs,schema,
query,repository,streamload,repository_test}.go
- scripts/e2e-doris.sh:E2E 验证清单
- docs/wiki/集成扩展/Doris改动与上游同步.md:fork-and-rebase 工作流
与改动清单
修改文件(接线 + 文档):
- internal/types/{retriever,tenant,vectorstore}.go:新增
DorisRetrieverEngineType、env 解析、表单 schema 与索引参数校验
- internal/container/{container,engine_factory}.go:环境变量驱动
与 VectorStore 配置驱动两条路径都支持 Doris
- internal/application/service/vectorstore{,_healthcheck}.go:连接
校验 + Ping/Version 健康检查
- docker-compose.yml:新增 doris-fe / doris-be 服务(profile=doris)
- .env.example:DORIS_* 环境变量与示例
- docs/{使用其他向量数据库,wiki/集成扩展/集成向量数据库}.md:
使用说明与索引/分数行为说明
依赖:go.mod/go.sum 新增 github.com/go-sql-driver/mysql(运行时)和
github.com/DATA-DOG/go-sqlmock(测试)。
测试:repository 层 SQL 形状、Stream Load HTTP 行为、whereBuilder
逻辑、embeddingLiteral 往返、健康检查错误路径均有单测覆盖。
2026-05-07 09:58:37 +00:00
_ "github.com/go-sql-driver/mysql" // 给 Doris (database/sql) 注册 MySQL 协议驱动
2026-02-26 13:48:38 +00:00
"github.com/milvus-io/milvus/client/v2/milvusclient"
2026-04-11 14:06:39 +00:00
"github.com/neo4j/neo4j-go-driver/v6/neo4j"
2025-08-05 07:08:07 +00:00
"github.com/panjf2000/ants/v2"
2025-11-26 10:58:53 +00:00
"github.com/qdrant/go-client/qdrant"
2025-11-06 13:12:26 +00:00
"github.com/redis/go-redis/v9"
2025-08-05 07:08:07 +00:00
"go.uber.org/dig"
2026-02-26 13:48:38 +00:00
"google.golang.org/grpc"
2025-08-05 07:08:07 +00:00
"gorm.io/driver/postgres"
2026-02-28 05:22:07 +00:00
"gorm.io/driver/sqlite"
2025-08-05 07:08:07 +00:00
"gorm.io/gorm"
feat(agent): human-in-the-loop approval for MCP tool calls (#1173)
Add an opt-in human approval gate so Agent runs pause before executing
MCP tools that operators flag as dangerous, surface an approval card in
the chat UI, and only resume after the user approves (optionally with
edited args) or rejects.
Backend
- New mcp_tool_approvals table + repo/service to mark per-tool approval
required (PG migration 000042 + sqlite init).
- approval.Gate coordinates RequestAndWait / Resolve with sync.Once
delivery, configurable timeout, and Redis Pub/Sub fan-out so multi-
replica deployments work without sticky sessions.
- MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx
(without the per-tool 60s timeout) for the wait, and re-derives a
fresh 60s exec ctx after approval so CallTool keeps a full window.
- New SSE response types (tool_approval_required / _resolved) and
EventBus events plumb approval state to AgentStreamDisplay.
- REST: list/set per-tool approval flag, resolve pending approval.
- Configurable via agent.tool_approval_timeout_seconds (yaml) or
WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go
duration).
Frontend
- MCP settings: per-tool "require approval" switch on the test panel.
- Chat: ToolApprovalCard renders the pause point with editable JSON
args, validation feedback, mm:ss countdown that turns warning/danger
near deadline, and a resolved state that retains context.
- i18n strings added for zh-CN / en-US / ko-KR / ru-RU.
Docs
- docs/zh/mcp-approval.md covering behavior, config, API, deployment
considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
"github.com/Tencent/WeKnora/internal/agent/approval"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/application/repository"
2026-02-12 08:02:09 +00:00
memoryRepo "github.com/Tencent/WeKnora/internal/application/repository/memory/neo4j"
feat(retriever): 接入 Apache Doris 4.1 作为向量数据库
为 RetrieveEngine 体系新增 Doris 后端,与现有 Qdrant/Milvus/Weaviate
等保持完整能力对齐:向量检索、关键词检索、健康检查、环境变量与多实例
DB 配置、前端类型注册、单元测试、Docker Compose 模板。
实现要点:
- 协议分工:主链路用 MySQL 协议(database/sql + go-sql-driver/mysql)
做 DDL / 查询 / 删除;批量更新走 Stream Load HTTP API,并启用
partial_update=true、merge_type=APPEND,自动按 1MiB 切分批次并处理
307 重定向。
- 表结构:UNIQUE KEY(id) + enable_unique_key_merge_on_write=true 以
支持 upsert/部分列更新;按维度分表(<base>_<dim>),每张表上建
HNSW ANN 索引(metric_type=cosine_distance)和 INVERTED 索引
(parser=chinese)。
- 分数语义:使用 cosine_distance_approximate,再以 1 - dist 转换为
"越大越相似",与现有 KVHybridRetrieveEngine 约定一致。
- 异步索引:ANN 索引为后台构建,ensureTable 通过轮询 SHOW INDEX 等
待索引就绪后再放行写入,避免首次检索召回为空。
- ARRAY<FLOAT> 序列化:go-sql-driver/mysql 不支持数组占位符,
embeddingLiteral 将 []float32 转成 SQL 字面量字符串再拼接。
新增文件:
- internal/application/repository/retriever/doris/{structs,schema,
query,repository,streamload,repository_test}.go
- scripts/e2e-doris.sh:E2E 验证清单
- docs/wiki/集成扩展/Doris改动与上游同步.md:fork-and-rebase 工作流
与改动清单
修改文件(接线 + 文档):
- internal/types/{retriever,tenant,vectorstore}.go:新增
DorisRetrieverEngineType、env 解析、表单 schema 与索引参数校验
- internal/container/{container,engine_factory}.go:环境变量驱动
与 VectorStore 配置驱动两条路径都支持 Doris
- internal/application/service/vectorstore{,_healthcheck}.go:连接
校验 + Ping/Version 健康检查
- docker-compose.yml:新增 doris-fe / doris-be 服务(profile=doris)
- .env.example:DORIS_* 环境变量与示例
- docs/{使用其他向量数据库,wiki/集成扩展/集成向量数据库}.md:
使用说明与索引/分数行为说明
依赖:go.mod/go.sum 新增 github.com/go-sql-driver/mysql(运行时)和
github.com/DATA-DOG/go-sqlmock(测试)。
测试:repository 层 SQL 形状、Stream Load HTTP 行为、whereBuilder
逻辑、embeddingLiteral 往返、健康检查错误路径均有单测覆盖。
2026-05-07 09:58:37 +00:00
dorisRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/doris"
2025-08-05 07:08:07 +00:00
elasticsearchRepoV7 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v7"
elasticsearchRepoV8 "github.com/Tencent/WeKnora/internal/application/repository/retriever/elasticsearch/v8"
2026-02-26 13:48:38 +00:00
milvusRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/milvus"
2025-09-24 04:15:17 +00:00
neo4jRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/neo4j"
2025-08-05 07:08:07 +00:00
postgresRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/postgres"
2025-11-26 10:58:53 +00:00
qdrantRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/qdrant"
2026-02-28 05:22:07 +00:00
sqliteRetrieverRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/sqlite"
2026-05-08 08:09:55 +00:00
tencentVectorDBRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/tencentvectordb"
2026-03-07 07:17:27 +00:00
weaviateRepo "github.com/Tencent/WeKnora/internal/application/repository/retriever/weaviate"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/application/service"
2026-03-22 17:57:06 +00:00
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/application/service/file"
2026-02-12 08:02:09 +00:00
memoryService "github.com/Tencent/WeKnora/internal/application/service/memory"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/config"
2025-11-08 19:27:24 +00:00
"github.com/Tencent/WeKnora/internal/database"
2026-03-27 07:02:40 +00:00
"github.com/Tencent/WeKnora/internal/datasource"
feishuConnector "github.com/Tencent/WeKnora/internal/datasource/connector/feishu"
2026-04-06 15:31:46 +00:00
notionConnector "github.com/Tencent/WeKnora/internal/datasource/connector/notion"
2026-04-21 09:29:37 +00:00
yuqueConnector "github.com/Tencent/WeKnora/internal/datasource/connector/yuque"
2025-11-05 15:18:44 +00:00
"github.com/Tencent/WeKnora/internal/event"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/handler"
2025-11-08 16:02:31 +00:00
"github.com/Tencent/WeKnora/internal/handler/session"
2026-03-15 10:45:53 +00:00
imPkg "github.com/Tencent/WeKnora/internal/im"
2026-03-24 08:48:34 +00:00
"github.com/Tencent/WeKnora/internal/im/dingtalk"
2026-03-15 10:45:53 +00:00
"github.com/Tencent/WeKnora/internal/im/feishu"
2026-03-27 03:07:09 +00:00
"github.com/Tencent/WeKnora/internal/im/mattermost"
2026-03-18 09:25:06 +00:00
"github.com/Tencent/WeKnora/internal/im/slack"
2026-03-24 08:48:13 +00:00
"github.com/Tencent/WeKnora/internal/im/telegram"
2026-03-23 10:27:21 +00:00
"github.com/Tencent/WeKnora/internal/im/wechat"
2026-03-15 10:45:53 +00:00
"github.com/Tencent/WeKnora/internal/im/wecom"
2026-02-28 05:22:07 +00:00
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
2026-04-08 11:52:28 +00:00
infra_web_search "github.com/Tencent/WeKnora/internal/infrastructure/web_search"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/logger"
2025-11-08 19:27:24 +00:00
"github.com/Tencent/WeKnora/internal/mcp"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/router"
"github.com/Tencent/WeKnora/internal/stream"
"github.com/Tencent/WeKnora/internal/tracing"
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
2025-08-05 07:08:07 +00:00
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
2026-05-08 08:09:55 +00:00
"github.com/tencent/vectordatabase-sdk-go/tcvectordb"
2026-03-07 07:17:27 +00:00
"github.com/weaviate/weaviate-go-client/v5/weaviate"
"github.com/weaviate/weaviate-go-client/v5/weaviate/auth"
wgrpc "github.com/weaviate/weaviate-go-client/v5/weaviate/grpc"
2025-08-05 07:08:07 +00:00
)
// BuildContainer constructs the dependency injection container
// Registers all components, services, repositories and handlers needed by the application
// Creates a fully configured application container with proper dependency resolution
// Parameters:
// - container: Base dig container to add dependencies to
//
// Returns:
// - Configured container with all application dependencies registered
func BuildContainer ( container * dig . Container ) * dig . Container {
2026-01-05 02:15:55 +00:00
ctx := context . Background ( )
logger . Debugf ( ctx , "[Container] Starting container initialization..." )
2025-08-05 07:08:07 +00:00
// Register resource cleaner for proper cleanup of resources
must ( container . Provide ( NewResourceCleaner , dig . As ( new ( interfaces . ResourceCleaner ) ) ) )
// Core infrastructure configuration
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering core infrastructure..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( config . LoadConfig ) )
must ( container . Provide ( initTracer ) )
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
must ( container . Provide ( initLangfuse ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initDatabase ) )
must ( container . Provide ( initFileService ) )
2025-11-06 13:12:26 +00:00
must ( container . Provide ( initRedisClient ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initAntsPool ) )
2026-03-04 09:43:34 +00:00
// Register tracer cleanup handler (tracer needs to be available for cleanup registration)
must ( container . Invoke ( registerTracerCleanup ) )
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
must ( container . Invoke ( registerLangfuseCleanup ) )
2026-03-04 09:43:34 +00:00
2025-08-05 07:08:07 +00:00
// Register goroutine pool cleanup handler
must ( container . Invoke ( registerPoolCleanup ) )
// Initialize retrieval engine registry for search capabilities
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering retrieval engine registry..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initRetrieveEngineRegistry ) )
// External service clients
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering external service clients..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initDocReaderClient ) )
2026-03-03 13:30:27 +00:00
must ( container . Provide ( docparser . NewImageResolver ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( initOllamaService ) )
2025-09-24 04:15:17 +00:00
must ( container . Provide ( initNeo4jClient ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( stream . NewStreamManager ) )
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Initializing DuckDB..." )
2025-12-23 08:56:30 +00:00
must ( container . Provide ( NewDuckDB ) )
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] DuckDB registered" )
2025-08-05 07:08:07 +00:00
// Data repositories layer
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering repositories..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( repository . NewTenantRepository ) )
must ( container . Provide ( repository . NewKnowledgeBaseRepository ) )
must ( container . Provide ( repository . NewKnowledgeRepository ) )
must ( container . Provide ( repository . NewChunkRepository ) )
2025-11-17 10:15:02 +00:00
must ( container . Provide ( repository . NewKnowledgeTagRepository ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( repository . NewSessionRepository ) )
must ( container . Provide ( repository . NewMessageRepository ) )
must ( container . Provide ( repository . NewModelRepository ) )
2025-09-15 18:47:39 +00:00
must ( container . Provide ( repository . NewUserRepository ) )
must ( container . Provide ( repository . NewAuthTokenRepository ) )
2025-09-24 04:15:17 +00:00
must ( container . Provide ( neo4jRepo . NewNeo4jRepository ) )
2026-02-12 08:02:09 +00:00
must ( container . Provide ( memoryRepo . NewMemoryRepository ) )
2025-11-08 19:27:24 +00:00
must ( container . Provide ( repository . NewMCPServiceRepository ) )
feat(agent): human-in-the-loop approval for MCP tool calls (#1173)
Add an opt-in human approval gate so Agent runs pause before executing
MCP tools that operators flag as dangerous, surface an approval card in
the chat UI, and only resume after the user approves (optionally with
edited args) or rejects.
Backend
- New mcp_tool_approvals table + repo/service to mark per-tool approval
required (PG migration 000042 + sqlite init).
- approval.Gate coordinates RequestAndWait / Resolve with sync.Once
delivery, configurable timeout, and Redis Pub/Sub fan-out so multi-
replica deployments work without sticky sessions.
- MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx
(without the per-tool 60s timeout) for the wait, and re-derives a
fresh 60s exec ctx after approval so CallTool keeps a full window.
- New SSE response types (tool_approval_required / _resolved) and
EventBus events plumb approval state to AgentStreamDisplay.
- REST: list/set per-tool approval flag, resolve pending approval.
- Configurable via agent.tool_approval_timeout_seconds (yaml) or
WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go
duration).
Frontend
- MCP settings: per-tool "require approval" switch on the test panel.
- Chat: ToolApprovalCard renders the pause point with editable JSON
args, validation feedback, mm:ss countdown that turns warning/danger
near deadline, and a resolved state that retains context.
- i18n strings added for zh-CN / en-US / ko-KR / ru-RU.
Docs
- docs/zh/mcp-approval.md covering behavior, config, API, deployment
considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
must ( container . Provide ( repository . NewMCPToolApprovalRepository ) )
2025-12-24 02:34:41 +00:00
must ( container . Provide ( repository . NewCustomAgentRepository ) )
2026-01-30 08:28:01 +00:00
must ( container . Provide ( repository . NewOrganizationRepository ) )
must ( container . Provide ( repository . NewKBShareRepository ) )
2026-02-04 12:12:29 +00:00
must ( container . Provide ( repository . NewAgentShareRepository ) )
2026-02-05 08:29:56 +00:00
must ( container . Provide ( repository . NewTenantDisabledSharedAgentRepository ) )
2025-12-23 08:56:30 +00:00
must ( container . Provide ( service . NewWebSearchStateService ) )
2026-03-27 07:02:40 +00:00
must ( container . Provide ( repository . NewDataSourceRepository ) )
must ( container . Provide ( repository . NewSyncLogRepository ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
must ( container . Provide ( repository . NewWikiPageRepository ) )
2026-05-08 13:43:53 +00:00
must ( container . Provide ( repository . NewWikiLogEntryRepository ) )
perf(wiki-ingest): scale to 4w-doc KBs + generic task queue / dead-letter
The wiki ingest post-process pipeline OOM'd and ran for hours on KBs
with ~40k documents. The dominant tail was a per-batch ListAllPages
that pulled every page (multi-MB content blobs) into Go memory, plus a
24h-TTL Redis pending list whose data could be evicted before a long
serialized backlog drained. dedup did O(P × N) Jaccard scoring in Go
on every batch. Lint loaded the full graph. The index page kept the
entire wiki directory in its content column and rewrote the TOAST
chunk on every ingest. None of these survive at 4w docs.
This change reworks the write path end to end and pulls the durable-
queue + dead-letter primitives out of wiki and into shared
infrastructure that every asynq task type now benefits from.
- migration 000041: task_pending_ops + task_dead_letters tables, plus
three GIN indexes on wiki_pages (source_refs jsonb_path_ops,
source_refs text fallback, lower(title) trgm).
- TaskPendingOpsRepository + TaskDeadLetterRepository in
internal/application/repository/task_queue.go: cursor-paginated
list, atomic IncrFailCount via UPDATE…RETURNING, dedup-key scoped
delete that refuses empty keys so a buggy caller can't wipe a KB's
queue.
- internal/middleware/asynqdl: writes a task_dead_letters row when an
asynq task exhausts its retry budget. Payload-agnostic — a small
probe struct extracts TenantID + scope hints across every existing
payload type, so summary:generation / image:multimodal /
faq_import / kb:clone / etc. all dead-letter without per-handler
code. Best-effort: an insert failure never masks the underlying
task error. Installed in router/task.go before the langfuse mw so
it sees raw errors.
- Pending queue moved Redis → PG (no TTL, restart-durable). Redis
keeps just the active-batch lock and the delete tombstone.
- In-batch retry budget (wikiMaxFailRetries=5) tracked via
pendingRepo.IncrFailCount; over the cap the row is moved to
task_dead_letters with task_type=wiki:ingest, related_id=knowledge
id. Asynq retries (10) are handled by the new middleware.
- Removed the per-batch ListAllPages. WikiBatchContext now carries
lazy fetcher closures (SlugTitleMany, SummaryByKnowledgeID) with
mutex-protected caches; reduce reaches for titles / summaries on
demand instead of pre-loading the whole KB.
- getExistingPageSlugsForKnowledge now uses ListSlugsBySourceRef,
which the new GIN index on source_refs serves as a Bitmap Index
Scan instead of a sequential text LIKE.
- Dedup pre-filter uses pg_trgm via FindSimilarPages
(idx_wiki_pages_title_trgm). For each new entity/concept (and each
of its aliases) we ask the DB for the top-K trigram-similar
existing pages and union the results — bounded prompt size, no Go-
side O(P × M) loop. Small KBs (≤25 entities) bypass the pre-filter.
- cleanDeadLinks / injectCrossLinks are scoped to the batch's
affected slugs (a few dozen) instead of every page in the KB. Both
use the new lite ListBySlugs / ExistsSlugs repo methods so they
pull only slug + title + outlinks, not full content.
- Slug fuzzy resolve (slug_fuzzy.go): when the LLM emits
[[bad-slug|display]] the cleanup path now tries display-text
reverse lookup → hyphen/case normalized equality → char-bigram
Jaccard ≥ 0.8 before stripping. Recovers the common pinyin-word-
break drift case ("shang-hai-tower" vs "shanghai-tower") in place
instead of replacing the link with plain text.
- rebuildIndexPage uses ListByTypeRecent(200) for the first-time
intro and drops the full DocumentSummaries blob from the
incremental update prompt, so its context stays bounded regardless
of KB size.
- Concurrency tunables surfaced in WikiConfig: IngestBatchSize /
IngestMapParallel / IngestReduceParallel, with sensible defaults
via OrDefault helpers. scheduleFollowUp drops to ProcessIn(0) so
follow-ups don't waste asynq retry slots bouncing on the active
lock.
- RunLint walks pages via the new ListPagesCursor in 200-page
windows and computes the live-slug set with a one-column
ListAllSlugs Pluck instead of a Limit:0 GetGraph that materialized
every node + edge. Memory is now bounded; 40k pages walks in
constant ~4MB.
- 14 GORM tests for both repos against an in-memory SQLite mirror of
the production DDL (task_queue_test.go).
- 6 tests for the dead-letter middleware covering retry budget
detection, payload-agnostic scope inference, error truncation, and
repo-failure isolation.
- 7 tests for the slug fuzzy resolve helper covering the three
resolution stages, display-text priority over normalized equality,
bigram fallback acceptance, and rejection of unrelated slugs.
- Existing wiki_ingest / wiki_lint / wiki_page tests updated to the
new fetcher / cursor APIs.
2026-05-09 15:42:53 +00:00
must ( container . Provide ( repository . NewTaskPendingOpsRepository ) )
must ( container . Provide ( repository . NewTaskDeadLetterRepository ) )
2025-11-08 19:27:24 +00:00
// MCP manager for managing MCP client connections
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering MCP manager..." )
2025-11-08 19:27:24 +00:00
must ( container . Provide ( mcp . NewMCPManager ) )
2025-08-05 07:08:07 +00:00
// Business service layer
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering business services..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( service . NewTenantService ) )
must ( container . Provide ( service . NewKnowledgeBaseService ) )
2026-01-30 08:28:01 +00:00
must ( container . Provide ( service . NewOrganizationService ) )
must ( container . Provide ( service . NewKBShareService ) ) // KBShareService must be registered before KnowledgeService and KnowledgeTagService
2026-02-04 12:12:29 +00:00
must ( container . Provide ( service . NewAgentShareService ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( service . NewKnowledgeService ) )
must ( container . Provide ( service . NewChunkService ) )
2025-11-17 10:15:02 +00:00
must ( container . Provide ( service . NewKnowledgeTagService ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( embedding . NewBatchEmbedder ) )
must ( container . Provide ( service . NewModelService ) )
must ( container . Provide ( service . NewDatasetService ) )
must ( container . Provide ( service . NewEvaluationService ) )
2025-09-15 18:47:39 +00:00
must ( container . Provide ( service . NewUserService ) )
2026-04-13 09:23:16 +00:00
must ( container . Provide ( service . NewWeKnoraCloudService ) )
2025-12-23 08:56:30 +00:00
// Extract services - register individual extracters with names
2026-02-06 07:05:00 +00:00
must ( container . Provide ( service . NewChunkExtractService , dig . Name ( "chunkExtractor" ) ) )
2025-12-23 08:56:30 +00:00
must ( container . Provide ( service . NewDataTableSummaryService , dig . Name ( "dataTableSummary" ) ) )
2026-02-28 05:22:07 +00:00
must ( container . Provide ( service . NewImageMultimodalService , dig . Name ( "imageMultimodal" ) ) )
2026-04-16 06:59:23 +00:00
must ( container . Provide ( service . NewKnowledgePostProcessService , dig . Name ( "knowledgePostProcess" ) ) )
2025-11-05 15:18:44 +00:00
must ( container . Provide ( service . NewMessageService ) )
2025-11-08 19:27:24 +00:00
must ( container . Provide ( service . NewMCPServiceService ) )
feat(agent): human-in-the-loop approval for MCP tool calls (#1173)
Add an opt-in human approval gate so Agent runs pause before executing
MCP tools that operators flag as dangerous, surface an approval card in
the chat UI, and only resume after the user approves (optionally with
edited args) or rejects.
Backend
- New mcp_tool_approvals table + repo/service to mark per-tool approval
required (PG migration 000042 + sqlite init).
- approval.Gate coordinates RequestAndWait / Resolve with sync.Once
delivery, configurable timeout, and Redis Pub/Sub fan-out so multi-
replica deployments work without sticky sessions.
- MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx
(without the per-tool 60s timeout) for the wait, and re-derives a
fresh 60s exec ctx after approval so CallTool keeps a full window.
- New SSE response types (tool_approval_required / _resolved) and
EventBus events plumb approval state to AgentStreamDisplay.
- REST: list/set per-tool approval flag, resolve pending approval.
- Configurable via agent.tool_approval_timeout_seconds (yaml) or
WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go
duration).
Frontend
- MCP settings: per-tool "require approval" switch on the test panel.
- Chat: ToolApprovalCard renders the pause point with editable JSON
args, validation feedback, mm:ss countdown that turns warning/danger
near deadline, and a resolved state that retains context.
- i18n strings added for zh-CN / en-US / ko-KR / ru-RU.
Docs
- docs/zh/mcp-approval.md covering behavior, config, API, deployment
considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
must ( container . Provide ( service . NewMCPToolApprovalService ) )
2025-12-24 02:34:41 +00:00
must ( container . Provide ( service . NewCustomAgentService ) )
2026-02-12 08:02:09 +00:00
must ( container . Provide ( memoryService . NewMemoryService ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
must ( container . Provide ( service . NewWikiPageService ) )
2026-05-08 13:43:53 +00:00
must ( container . Provide ( service . NewWikiLogEntryService ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
must ( container . Provide ( service . NewWikiIngestService , dig . Name ( "wikiIngest" ) ) )
must ( container . Provide ( service . NewWikiLintService ) )
2025-11-05 15:18:44 +00:00
2025-11-11 06:25:20 +00:00
// Web search service (needed by AgentService)
2026-01-19 12:28:31 +00:00
logger . Debugf ( ctx , "[Container] Registering web search registry and providers..." )
2026-03-31 12:14:26 +00:00
must ( container . Provide ( infra_web_search . NewRegistry ) )
2026-01-19 12:28:31 +00:00
must ( container . Invoke ( registerWebSearchProviders ) )
2026-03-31 12:14:26 +00:00
must ( container . Provide ( repository . NewWebSearchProviderRepository ) )
2026-04-10 00:32:48 +00:00
must ( container . Provide ( repository . NewVectorStoreRepository ) )
2025-11-11 06:25:20 +00:00
must ( container . Provide ( service . NewWebSearchService ) )
2026-03-31 12:14:26 +00:00
must ( container . Provide ( service . NewWebSearchProviderService ) )
2026-04-15 03:44:52 +00:00
must ( container . Provide ( NewEngineFactory ) )
// StoreRegistry: same instance as RetrieveEngineRegistry, exposed as StoreRegistry interface.
// NewRetrieveEngineRegistry always returns *retriever.RetrieveEngineRegistry which implements both.
must ( container . Provide ( func ( r interfaces . RetrieveEngineRegistry ) ( interfaces . StoreRegistry , error ) {
sr , ok := r . ( * retriever . RetrieveEngineRegistry )
if ! ok {
return nil , fmt . Errorf ( "registry does not implement StoreRegistry" )
}
return sr , nil
} ) )
2026-04-10 00:32:48 +00:00
must ( container . Provide ( service . NewVectorStoreService ) )
2025-11-11 06:25:20 +00:00
// Agent service layer (requires event bus, web search service)
// SessionService is passed as parameter to CreateAgentEngine method when creating AgentService
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering event bus and agent service..." )
2025-11-05 15:18:44 +00:00
must ( container . Provide ( event . NewEventBus ) )
feat(agent): human-in-the-loop approval for MCP tool calls (#1173)
Add an opt-in human approval gate so Agent runs pause before executing
MCP tools that operators flag as dangerous, surface an approval card in
the chat UI, and only resume after the user approves (optionally with
edited args) or rejects.
Backend
- New mcp_tool_approvals table + repo/service to mark per-tool approval
required (PG migration 000042 + sqlite init).
- approval.Gate coordinates RequestAndWait / Resolve with sync.Once
delivery, configurable timeout, and Redis Pub/Sub fan-out so multi-
replica deployments work without sticky sessions.
- MCPTool.Execute integrates the gate; uses a round-level ApprovalCtx
(without the per-tool 60s timeout) for the wait, and re-derives a
fresh 60s exec ctx after approval so CallTool keeps a full window.
- New SSE response types (tool_approval_required / _resolved) and
EventBus events plumb approval state to AgentStreamDisplay.
- REST: list/set per-tool approval flag, resolve pending approval.
- Configurable via agent.tool_approval_timeout_seconds (yaml) or
WEKNORA_AGENT_TOOL_APPROVAL_TIMEOUT env (accepts seconds or Go
duration).
Frontend
- MCP settings: per-tool "require approval" switch on the test panel.
- Chat: ToolApprovalCard renders the pause point with editable JSON
args, validation feedback, mm:ss countdown that turns warning/danger
near deadline, and a resolved state that retains context.
- i18n strings added for zh-CN / en-US / ko-KR / ru-RU.
Docs
- docs/zh/mcp-approval.md covering behavior, config, API, deployment
considerations (Redis cross-instance, restart limitations).
2026-05-10 13:23:49 +00:00
must ( container . Provide ( func ( cfg * config . Config , s interfaces . MCPToolApprovalService , rdb * redis . Client ) * approval . Gate {
return approval . NewGate ( cfg , & approval . Adapter { Svc : s } , rdb )
} ) )
// Expose Gate as MCPApproval interface so AgentService and others can depend on the abstraction.
must ( container . Provide ( func ( g * approval . Gate ) approval . MCPApproval { return g } ) )
2025-11-05 15:18:44 +00:00
must ( container . Provide ( service . NewAgentService ) )
// Session service (depends on agent service)
2025-11-11 06:25:20 +00:00
// SessionService is created after AgentService and passes itself to AgentService.CreateAgentEngine when needed
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering session service..." )
2025-11-28 08:10:37 +00:00
must ( container . Provide ( service . NewSessionService ) )
2025-08-05 07:08:07 +00:00
2026-02-28 05:22:07 +00:00
logger . Debugf ( ctx , "[Container] Registering task enqueuer..." )
redisAvailable := os . Getenv ( "REDIS_ADDR" ) != ""
if redisAvailable {
must ( container . Provide ( router . NewAsyncqClient , dig . As ( new ( interfaces . TaskEnqueuer ) ) ) )
must ( container . Provide ( router . NewAsynqServer ) )
} else {
syncExec := router . NewSyncTaskExecutor ( )
must ( container . Provide ( func ( ) interfaces . TaskEnqueuer { return syncExec } ) )
must ( container . Provide ( func ( ) * router . SyncTaskExecutor { return syncExec } ) )
}
2025-11-13 11:34:33 +00:00
// Chat pipeline components for processing chat requests
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering chat pipeline plugins..." )
2026-03-27 07:02:40 +00:00
// Data source sync framework
logger . Debugf ( ctx , "[Container] Registering data source sync framework..." )
must ( container . Provide ( initConnectorRegistry ) )
must ( container . Provide ( datasource . NewScheduler ) )
must ( container . Provide ( service . NewDataSourceService ) )
must ( container . Invoke ( startDataSourceScheduler ) )
logger . Debugf ( ctx , "[Container] Data source sync framework registered" )
2026-03-22 17:57:06 +00:00
must ( container . Provide ( chatpipeline . NewEventManager ) )
must ( container . Invoke ( chatpipeline . NewPluginSearch ) )
must ( container . Invoke ( chatpipeline . NewPluginRerank ) )
2026-03-31 12:14:26 +00:00
must ( container . Invoke ( chatpipeline . NewPluginWebFetch ) )
2026-03-22 17:57:06 +00:00
must ( container . Invoke ( chatpipeline . NewPluginMerge ) )
must ( container . Invoke ( chatpipeline . NewPluginDataAnalysis ) )
must ( container . Invoke ( chatpipeline . NewPluginIntoChatMessage ) )
must ( container . Invoke ( chatpipeline . NewPluginChatCompletion ) )
must ( container . Invoke ( chatpipeline . NewPluginChatCompletionStream ) )
must ( container . Invoke ( chatpipeline . NewPluginFilterTopK ) )
must ( container . Invoke ( chatpipeline . NewPluginQueryUnderstand ) )
must ( container . Invoke ( chatpipeline . NewPluginLoadHistory ) )
must ( container . Invoke ( chatpipeline . NewPluginExtractEntity ) )
must ( container . Invoke ( chatpipeline . NewPluginSearchEntity ) )
must ( container . Invoke ( chatpipeline . NewPluginSearchParallel ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
must ( container . Invoke ( chatpipeline . NewPluginWikiBoost ) )
2026-03-22 17:57:06 +00:00
must ( container . Invoke ( chatpipeline . NewMemoryPlugin ) )
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Chat pipeline plugins registered" )
2025-08-05 07:08:07 +00:00
// HTTP handlers layer
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] Registering HTTP handlers..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( handler . NewTenantHandler ) )
must ( container . Provide ( handler . NewKnowledgeBaseHandler ) )
must ( container . Provide ( handler . NewKnowledgeHandler ) )
must ( container . Provide ( handler . NewChunkHandler ) )
2025-11-14 17:30:17 +00:00
must ( container . Provide ( handler . NewFAQHandler ) )
2025-11-17 10:15:02 +00:00
must ( container . Provide ( handler . NewTagHandler ) )
2025-11-08 16:02:31 +00:00
must ( container . Provide ( session . NewHandler ) )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( handler . NewMessageHandler ) )
must ( container . Provide ( handler . NewModelHandler ) )
must ( container . Provide ( handler . NewEvaluationHandler ) )
2025-08-10 09:04:39 +00:00
must ( container . Provide ( handler . NewInitializationHandler ) )
2025-09-15 18:47:39 +00:00
must ( container . Provide ( handler . NewAuthHandler ) )
2025-09-17 08:02:08 +00:00
must ( container . Provide ( handler . NewSystemHandler ) )
2025-11-08 19:27:24 +00:00
must ( container . Provide ( handler . NewMCPServiceHandler ) )
2025-11-09 19:14:12 +00:00
must ( container . Provide ( handler . NewWebSearchHandler ) )
2026-03-31 12:14:26 +00:00
must ( container . Provide ( handler . NewWebSearchProviderHandler ) )
2026-04-10 00:32:48 +00:00
must ( container . Provide ( handler . NewVectorStoreHandler ) )
2025-12-24 02:34:41 +00:00
must ( container . Provide ( handler . NewCustomAgentHandler ) )
2026-02-03 19:40:09 +00:00
must ( container . Provide ( service . NewSkillService ) )
must ( container . Provide ( handler . NewSkillHandler ) )
2026-01-30 08:28:01 +00:00
must ( container . Provide ( handler . NewOrganizationHandler ) )
2026-03-15 10:45:53 +00:00
2026-03-27 07:02:40 +00:00
// Data source handler
must ( container . Provide ( handler . NewDataSourceHandler ) )
feat: Implement comprehensive wiki feature for knowledge bases
This commit introduces the complete wiki feature for WeKnora, enabling AI-powered wiki page generation and management. The implementation includes:
**Backend Changes:**
- Wiki data model: WikiPage type with support for multiple page types (Summary, Entity, Concept, Index, Log)
- Database schema: wiki_pages table with full migration support
- WikiPageService: CRUD operations and page management
- WikiPageRepository: GORM-based persistence layer
- Wiki ingest pipeline: Automated generation of wiki pages from knowledge documents
* Summary page generation using LLM
* Entity and concept extraction in a single LLM call
* Synthesis opportunity detection
* Index page rebuilding
* Log page maintenance
- Wiki boost feature: Enhance chat retrieval with wiki context
- Wiki linting: Maintenance and validation utilities
- Agent wiki tools: Enable agents to query and interact with wiki pages
- Wiki prompts: Comprehensive LLM prompt templates for all wiki generation tasks
- Language support: Reuse existing middleware language infrastructure for LLM prompts
**Frontend Changes:**
- Wiki browser UI: View all wiki pages with filtering and search
- Wiki API client: Knowledge base wiki management endpoints
- Knowledge base editor: Configure wiki settings (language, auto-ingest, synthesis model)
- i18n updates: Support for English, Korean, Russian, and Chinese interfaces
**Configuration:**
- Container DI: Wire up all wiki services
- Router: Register wiki API endpoints
- Task handling: Support async wiki ingest tasks
**Testing:**
- Unit tests for wiki page types
- Service layer tests
- Endpoint tests for wiki operations
- Integration tests with LLM mocking
**Documentation:**
- Language refactoring analysis and guides
- Implementation completion reports
- Quick reference guides for developers
**Key Features:**
✅ LLM-powered wiki page generation from documents
✅ Multi-language support (9+ languages)
✅ Automatic extraction of entities and concepts
✅ Synthesis opportunity detection
✅ Index and log page maintenance
✅ Progressive wiki building across multiple documents
✅ Agent-based wiki interaction
✅ Chat retrieval enhancement with wiki context
✅ Full frontend UI for wiki browsing
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 05:56:13 +00:00
// Wiki page handler
must ( container . Provide ( handler . NewWikiPageHandler ) )
2026-03-15 10:45:53 +00:00
// IM integration
logger . Debugf ( ctx , "[Container] Registering IM integration..." )
must ( container . Provide ( imPkg . NewService ) )
2026-03-15 18:23:22 +00:00
must ( container . Invoke ( registerIMAdapterFactories ) )
2026-03-15 10:45:53 +00:00
must ( container . Provide ( handler . NewIMHandler ) )
2026-04-13 09:23:16 +00:00
must ( container . Provide ( handler . NewWeKnoraCloudHandler ) )
2026-01-05 02:15:55 +00:00
logger . Debugf ( ctx , "[Container] HTTP handlers registered" )
2025-08-05 07:08:07 +00:00
// Router configuration
2026-02-28 05:22:07 +00:00
logger . Debugf ( ctx , "[Container] Registering router and starting task server..." )
2025-08-05 07:08:07 +00:00
must ( container . Provide ( router . NewRouter ) )
2026-02-28 05:22:07 +00:00
if redisAvailable {
must ( container . Invoke ( router . RunAsynqServer ) )
} else {
must ( container . Invoke ( router . RegisterSyncHandlers ) )
}
2025-08-05 07:08:07 +00:00
2026-01-05 02:15:55 +00:00
logger . Infof ( ctx , "[Container] Container initialization completed successfully" )
2025-08-05 07:08:07 +00:00
return container
}
// must is a helper function for error handling
// Panics if the error is not nil, useful for configuration steps that must succeed
// Parameters:
// - err: Error to check
func must ( err error ) {
if err != nil {
panic ( err )
}
}
// initTracer initializes OpenTelemetry tracer
// Sets up distributed tracing for observability across the application
// Parameters:
// - None
//
// Returns:
// - Configured tracer instance
// - Error if initialization fails
func initTracer ( ) ( * tracing . Tracer , error ) {
return tracing . InitTracer ( )
}
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
// initLangfuse initializes the Langfuse ingestion client.
// Configuration is read from LANGFUSE_* environment variables (see
// docs/langfuse.md). Returns a disabled manager if credentials are absent —
// never an error — so deployments that don't use Langfuse are unaffected.
func initLangfuse ( ) ( * langfuse . Manager , error ) {
cfg := langfuse . LoadConfigFromEnv ( )
return langfuse . Init ( cfg )
}
2025-11-06 13:12:26 +00:00
func initRedisClient ( ) ( * redis . Client , error ) {
2026-02-28 05:22:07 +00:00
redisAddr := os . Getenv ( "REDIS_ADDR" )
if redisAddr == "" {
logger . Infof ( context . Background ( ) , "[Redis] No REDIS_ADDR configured, Redis disabled (Lite mode)" )
return nil , nil
}
2025-11-06 13:12:26 +00:00
db , err := strconv . Atoi ( os . Getenv ( "REDIS_DB" ) )
if err != nil {
2026-02-28 05:22:07 +00:00
db = 0
2025-11-06 13:12:26 +00:00
}
client := redis . NewClient ( & redis . Options {
2026-02-28 05:22:07 +00:00
Addr : redisAddr ,
2026-02-04 10:48:04 +00:00
Username : os . Getenv ( "REDIS_USERNAME" ) ,
2025-11-06 13:12:26 +00:00
Password : os . Getenv ( "REDIS_PASSWORD" ) ,
DB : db ,
} )
_ , err = client . Ping ( context . Background ( ) ) . Result ( )
if err != nil {
return nil , fmt . Errorf ( "连接Redis失败: %w" , err )
}
return client , nil
}
2025-08-05 07:08:07 +00:00
// initDatabase initializes database connection
// Creates and configures database connection based on environment configuration
// Supports multiple database backends (PostgreSQL)
// Parameters:
// - cfg: Application configuration
//
// Returns:
// - Configured database connection
// - Error if connection fails
func initDatabase ( cfg * config . Config ) ( * gorm . DB , error ) {
var dialector gorm . Dialector
2025-11-08 19:27:24 +00:00
var migrateDSN string
2026-04-10 21:48:53 +00:00
var sqliteDBPath string
2025-08-05 07:08:07 +00:00
switch os . Getenv ( "DB_DRIVER" ) {
case "postgres" :
2025-11-08 19:27:24 +00:00
// DSN for GORM (key-value format)
gormDSN := fmt . Sprintf (
2026-03-30 11:33:17 +00:00
"host=%s port=%s user=%s password=%s dbname=%s sslmode=%s TimeZone=UTC" ,
2025-08-05 07:08:07 +00:00
os . Getenv ( "DB_HOST" ) ,
os . Getenv ( "DB_PORT" ) ,
os . Getenv ( "DB_USER" ) ,
os . Getenv ( "DB_PASSWORD" ) ,
os . Getenv ( "DB_NAME" ) ,
"disable" ,
)
2025-11-08 19:27:24 +00:00
dialector = postgres . Open ( gormDSN )
// DSN for golang-migrate (URL format)
// URL-encode password to handle special characters like !@#
dbPassword := os . Getenv ( "DB_PASSWORD" )
encodedPassword := url . QueryEscape ( dbPassword )
2025-12-09 06:20:01 +00:00
// Check if postgres is in RETRIEVE_DRIVER to determine skip_embedding
retrieveDriver := strings . Split ( os . Getenv ( "RETRIEVE_DRIVER" ) , "," )
skipEmbedding := "true"
if slices . Contains ( retrieveDriver , "postgres" ) {
skipEmbedding = "false"
}
logger . Infof ( context . Background ( ) , "Skip embedding: %s" , skipEmbedding )
2025-11-08 19:27:24 +00:00
migrateDSN = fmt . Sprintf (
2025-12-09 06:20:01 +00:00
"postgres://%s:%s@%s:%s/%s?sslmode=disable&options=-c%%20app.skip_embedding=%s" ,
2025-11-08 19:27:24 +00:00
os . Getenv ( "DB_USER" ) ,
encodedPassword , // Use encoded password
os . Getenv ( "DB_HOST" ) ,
os . Getenv ( "DB_PORT" ) ,
os . Getenv ( "DB_NAME" ) ,
2025-12-09 06:20:01 +00:00
skipEmbedding ,
2025-11-08 19:27:24 +00:00
)
// Debug log (don't log password)
logger . Infof ( context . Background ( ) , "DB Config: user=%s host=%s port=%s dbname=%s" ,
os . Getenv ( "DB_USER" ) ,
os . Getenv ( "DB_HOST" ) ,
os . Getenv ( "DB_PORT" ) ,
os . Getenv ( "DB_NAME" ) ,
)
2026-02-28 05:22:07 +00:00
case "sqlite" :
dbPath := os . Getenv ( "DB_PATH" )
if dbPath == "" {
dbPath = "./data/weknora.db"
}
if dir := filepath . Dir ( dbPath ) ; dir != "." && dir != "" {
2026-04-13 09:23:16 +00:00
if err := os . MkdirAll ( dir , 0 o755 ) ; err != nil {
2026-02-28 05:22:07 +00:00
return nil , fmt . Errorf ( "failed to create SQLite data directory %s: %w" , dir , err )
}
}
sqlite_vec . Auto ( )
dsn := dbPath + "?_journal_mode=WAL&_busy_timeout=5000&_foreign_keys=on"
dialector = sqlite . Open ( dsn )
2026-04-10 21:48:53 +00:00
sqliteDBPath = dbPath
2026-02-28 05:22:07 +00:00
migrateDSN = "sqlite3://" + dbPath
logger . Infof ( context . Background ( ) , "DB Config: driver=sqlite path=%s" , dbPath )
2025-08-05 07:08:07 +00:00
default :
return nil , fmt . Errorf ( "unsupported database driver: %s" , os . Getenv ( "DB_DRIVER" ) )
}
2026-03-27 07:02:40 +00:00
db , err := gorm . Open ( dialector , & gorm . Config {
NowFunc : func ( ) time . Time {
return time . Now ( ) . UTC ( )
} ,
} )
2025-08-05 07:08:07 +00:00
if err != nil {
return nil , err
}
2026-02-28 05:22:07 +00:00
if os . Getenv ( "DB_DRIVER" ) == "sqlite" {
sqlDB , err := db . DB ( )
if err != nil {
return nil , fmt . Errorf ( "failed to get underlying sql.DB: %w" , err )
}
if err := sqlDB . Ping ( ) ; err != nil {
return nil , fmt . Errorf ( "failed to ping SQLite database: %w" , err )
}
}
2025-11-08 19:27:24 +00:00
// Run database migrations automatically (optional, can be disabled via env var)
// To disable auto-migration, set AUTO_MIGRATE=false
2025-12-08 09:40:10 +00:00
// To enable auto-recovery from dirty state, set AUTO_RECOVER_DIRTY=true
2025-11-08 19:27:24 +00:00
if os . Getenv ( "AUTO_MIGRATE" ) != "false" {
logger . Infof ( context . Background ( ) , "Running database migrations..." )
2025-12-09 06:20:01 +00:00
2025-12-16 04:07:25 +00:00
autoRecover := os . Getenv ( "AUTO_RECOVER_DIRTY" ) != "false"
2025-12-09 06:20:01 +00:00
migrationOpts := database . MigrationOptions {
2025-12-08 09:40:10 +00:00
AutoRecoverDirty : autoRecover ,
2026-04-10 21:48:53 +00:00
SQLiteDBPath : sqliteDBPath ,
2025-12-09 06:20:01 +00:00
}
// Run base migrations (all versioned migrations including embeddings)
// The embeddings migration will be conditionally executed based on skip_embedding parameter in DSN
if err := database . RunMigrationsWithOptions ( migrateDSN , migrationOpts ) ; err != nil {
2025-11-08 19:27:24 +00:00
// Log warning but don't fail startup - migrations might be handled externally
logger . Warnf ( context . Background ( ) , "Database migration failed: %v" , err )
2025-11-28 08:17:52 +00:00
logger . Warnf (
context . Background ( ) ,
"Continuing with application startup. Please run migrations manually if needed." ,
)
2025-11-08 19:27:24 +00:00
}
2026-03-02 03:02:19 +00:00
// Post-migration: resolve __pending_env__ storage provider markers for historical KBs.
// The SQL migration marks KBs that have documents but no provider with "__pending_env__";
// we replace that with the actual STORAGE_TYPE from the environment.
resolveStorageProviderPending ( db )
2025-11-08 19:27:24 +00:00
} else {
logger . Infof ( context . Background ( ) , "Auto-migration is disabled (AUTO_MIGRATE=false)" )
}
2025-08-05 07:08:07 +00:00
// Get underlying SQL DB object
sqlDB , err := db . DB ( )
if err != nil {
return nil , err
}
// Configure connection pool parameters
2026-02-28 05:22:07 +00:00
if os . Getenv ( "DB_DRIVER" ) == "sqlite" {
// SQLite only supports one concurrent writer even in WAL mode.
// Limiting to a single open connection serialises all DB access and
// prevents "database is locked" errors from concurrent goroutines.
sqlDB . SetMaxOpenConns ( 1 )
} else {
sqlDB . SetMaxIdleConns ( 10 )
}
2025-08-05 07:08:07 +00:00
sqlDB . SetConnMaxLifetime ( time . Duration ( 10 ) * time . Minute )
return db , nil
}
2026-03-02 03:02:19 +00:00
// resolveStorageProviderPending replaces the "__pending_env__" sentinel in
// knowledge_bases.storage_provider_config with the actual STORAGE_TYPE from the environment.
// This runs once after SQL migrations to bind historical KBs to their real storage provider.
func resolveStorageProviderPending ( db * gorm . DB ) {
storageType := strings . TrimSpace ( os . Getenv ( "STORAGE_TYPE" ) )
if storageType == "" {
storageType = "local"
}
storageType = strings . ToLower ( storageType )
result := db . Exec (
` UPDATE knowledge_bases SET storage_provider_config = ? WHERE storage_provider_config IS NOT NULL AND storage_provider_config->>'provider' = '__pending_env__' ` ,
fmt . Sprintf ( ` { "provider":"%s"} ` , storageType ) ,
)
if result . Error != nil {
logger . Warnf ( context . Background ( ) , "Failed to resolve __pending_env__ storage providers: %v" , result . Error )
} else if result . RowsAffected > 0 {
logger . Infof ( context . Background ( ) , "Resolved %d knowledge bases with __pending_env__ storage provider → %s" , result . RowsAffected , storageType )
}
2026-04-10 21:48:53 +00:00
2026-04-16 14:39:10 +00:00
// Sync PostgreSQL sequences with actual MAX values to prevent duplicate key
// errors. The old code assigned seq_id via SELECT MAX()+1 in application
// code, which could push values past the DB sequence counter.
syncSequences ( db )
2026-04-10 21:48:53 +00:00
// Reset any pending tasks left over from previous aborted runs (Lite App mode)
resetPendingTasks ( db )
}
2026-04-16 14:39:10 +00:00
// syncSequences ensures PostgreSQL sequences for auto-increment columns (seq_id)
// are at least as high as the current MAX value in each table. This is needed
// because older code assigned seq_id via application-level MAX()+1, which could
// advance values past the DB sequence counter and cause duplicate key errors.
func syncSequences ( db * gorm . DB ) {
if db . Dialector . Name ( ) != "postgres" {
return
}
pairs := [ ] [ 2 ] string {
{ "chunks" , "chunks_seq_id_seq" } ,
{ "knowledge_tags" , "knowledge_tags_seq_id_seq" } ,
}
for _ , p := range pairs {
table , seq := p [ 0 ] , p [ 1 ]
sql := fmt . Sprintf (
` SELECT setval('%s', GREATEST(nextval('%s'), (SELECT COALESCE(MAX(seq_id), 0) FROM %s))) ` ,
seq , seq , table ,
)
if err := db . Exec ( sql ) . Error ; err != nil {
logger . Warnf ( context . Background ( ) , "Failed to sync sequence %s: %v" , seq , err )
} else {
logger . Infof ( context . Background ( ) , "Synced sequence %s with table %s" , seq , table )
}
}
}
2026-04-10 21:48:53 +00:00
// resetPendingTasks resets the state of any knowledge items or sync logs stuck in processing
// due to an unexpected application restart when using in-memory queues (Lite mode).
func resetPendingTasks ( db * gorm . DB ) {
if os . Getenv ( "REDIS_ADDR" ) != "" {
return // Distributed queue (Asynq) will handle its own retries
}
// 1. Reset knowledge parsing tasks
result := db . Model ( & types . Knowledge { } ) .
Where ( "parse_status IN ?" , [ ] string { types . ParseStatusPending , types . ParseStatusProcessing , types . ParseStatusDeleting } ) .
Updates ( map [ string ] interface { } {
"parse_status" : types . ParseStatusFailed ,
"error_message" : "Task interrupted due to application restart" ,
} )
if result . Error != nil {
logger . Warnf ( context . Background ( ) , "Failed to reset pending knowledge tasks: %v" , result . Error )
} else if result . RowsAffected > 0 {
logger . Infof ( context . Background ( ) , "Reset %d stuck knowledge parsing tasks to failed state" , result . RowsAffected )
}
// 2. Reset knowledge summary tasks
resultSummary := db . Model ( & types . Knowledge { } ) .
Where ( "summary_status IN ?" , [ ] string { types . SummaryStatusPending , types . SummaryStatusProcessing } ) .
Updates ( map [ string ] interface { } {
"summary_status" : types . SummaryStatusFailed ,
} )
if resultSummary . Error != nil {
logger . Warnf ( context . Background ( ) , "Failed to reset pending summary tasks: %v" , resultSummary . Error )
} else if resultSummary . RowsAffected > 0 {
logger . Infof ( context . Background ( ) , "Reset %d stuck summary generation tasks to failed state" , resultSummary . RowsAffected )
}
// 3. Reset data source sync tasks
resultSync := db . Model ( & types . SyncLog { } ) .
Where ( "status IN ?" , [ ] string { types . SyncLogStatusRunning , "pending" } ) .
Updates ( map [ string ] interface { } {
"status" : types . SyncLogStatusFailed ,
"error_message" : "Sync interrupted due to application restart" ,
"end_time" : time . Now ( ) ,
} )
if resultSync . Error != nil {
logger . Warnf ( context . Background ( ) , "Failed to reset pending data source sync tasks: %v" , resultSync . Error )
} else if resultSync . RowsAffected > 0 {
logger . Infof ( context . Background ( ) , "Reset %d stuck data source sync tasks to failed state" , resultSync . RowsAffected )
}
2026-03-02 03:02:19 +00:00
}
2025-08-05 07:08:07 +00:00
// initFileService initializes file storage service
// Creates the appropriate file storage service based on configuration
// Supports multiple storage backends (MinIO, COS, local filesystem)
// Parameters:
// - cfg: Application configuration
//
// Returns:
// - Configured file service implementation
// - Error if initialization fails
func initFileService ( cfg * config . Config ) ( interfaces . FileService , error ) {
2026-02-28 05:22:07 +00:00
storageType := strings . TrimSpace ( os . Getenv ( "STORAGE_TYPE" ) )
if storageType == "" {
storageType = "local"
}
switch storageType {
2025-08-05 07:08:07 +00:00
case "minio" :
if os . Getenv ( "MINIO_ENDPOINT" ) == "" ||
os . Getenv ( "MINIO_ACCESS_KEY_ID" ) == "" ||
os . Getenv ( "MINIO_SECRET_ACCESS_KEY" ) == "" ||
os . Getenv ( "MINIO_BUCKET_NAME" ) == "" {
return nil , fmt . Errorf ( "missing MinIO configuration" )
}
return file . NewMinioFileService (
os . Getenv ( "MINIO_ENDPOINT" ) ,
os . Getenv ( "MINIO_ACCESS_KEY_ID" ) ,
os . Getenv ( "MINIO_SECRET_ACCESS_KEY" ) ,
os . Getenv ( "MINIO_BUCKET_NAME" ) ,
2025-12-09 06:20:01 +00:00
strings . EqualFold ( os . Getenv ( "MINIO_USE_SSL" ) , "true" ) ,
2025-08-05 07:08:07 +00:00
)
case "cos" :
2025-09-15 12:49:34 +00:00
if os . Getenv ( "COS_BUCKET_NAME" ) == "" ||
2025-08-05 07:08:07 +00:00
os . Getenv ( "COS_REGION" ) == "" ||
os . Getenv ( "COS_SECRET_ID" ) == "" ||
os . Getenv ( "COS_SECRET_KEY" ) == "" ||
os . Getenv ( "COS_PATH_PREFIX" ) == "" {
return nil , fmt . Errorf ( "missing COS configuration" )
}
2026-01-06 02:51:40 +00:00
return file . NewCosFileServiceWithTempBucket (
2025-09-15 12:49:34 +00:00
os . Getenv ( "COS_BUCKET_NAME" ) ,
2025-08-05 07:08:07 +00:00
os . Getenv ( "COS_REGION" ) ,
os . Getenv ( "COS_SECRET_ID" ) ,
os . Getenv ( "COS_SECRET_KEY" ) ,
os . Getenv ( "COS_PATH_PREFIX" ) ,
2026-02-28 05:22:07 +00:00
os . Getenv ( "COS_TEMP_BUCKET_NAME" ) ,
os . Getenv ( "COS_TEMP_REGION" ) ,
2025-08-05 07:08:07 +00:00
)
2026-02-24 15:12:28 +00:00
case "tos" :
if os . Getenv ( "TOS_ENDPOINT" ) == "" ||
os . Getenv ( "TOS_REGION" ) == "" ||
os . Getenv ( "TOS_ACCESS_KEY" ) == "" ||
os . Getenv ( "TOS_SECRET_KEY" ) == "" ||
os . Getenv ( "TOS_BUCKET_NAME" ) == "" {
return nil , fmt . Errorf ( "missing TOS configuration" )
}
return file . NewTosFileServiceWithTempBucket (
os . Getenv ( "TOS_ENDPOINT" ) ,
os . Getenv ( "TOS_REGION" ) ,
os . Getenv ( "TOS_ACCESS_KEY" ) ,
os . Getenv ( "TOS_SECRET_KEY" ) ,
os . Getenv ( "TOS_BUCKET_NAME" ) ,
os . Getenv ( "TOS_PATH_PREFIX" ) ,
os . Getenv ( "TOS_TEMP_BUCKET_NAME" ) , // 可选:临时桶名称(桶需配置生命周期规则自动过期)
os . Getenv ( "TOS_TEMP_REGION" ) , // 可选:临时桶 region, 默认与主桶相同
)
2026-03-07 06:01:22 +00:00
case "s3" :
if os . Getenv ( "S3_ENDPOINT" ) == "" ||
os . Getenv ( "S3_REGION" ) == "" ||
os . Getenv ( "S3_ACCESS_KEY" ) == "" ||
os . Getenv ( "S3_SECRET_KEY" ) == "" ||
os . Getenv ( "S3_BUCKET_NAME" ) == "" {
return nil , fmt . Errorf ( "missing S3 configuration" )
}
pathPrefix := os . Getenv ( "S3_PATH_PREFIX" )
if pathPrefix == "" {
pathPrefix = "weknora/"
}
return file . NewS3FileService (
os . Getenv ( "S3_ENDPOINT" ) ,
os . Getenv ( "S3_ACCESS_KEY" ) ,
os . Getenv ( "S3_SECRET_KEY" ) ,
os . Getenv ( "S3_BUCKET_NAME" ) ,
os . Getenv ( "S3_REGION" ) ,
pathPrefix ,
)
2026-04-13 03:57:47 +00:00
case "oss" :
if os . Getenv ( "OSS_ENDPOINT" ) == "" ||
os . Getenv ( "OSS_REGION" ) == "" ||
os . Getenv ( "OSS_ACCESS_KEY" ) == "" ||
os . Getenv ( "OSS_SECRET_KEY" ) == "" ||
os . Getenv ( "OSS_BUCKET_NAME" ) == "" {
return nil , fmt . Errorf ( "missing OSS configuration" )
}
pathPrefix := os . Getenv ( "OSS_PATH_PREFIX" )
if pathPrefix == "" {
pathPrefix = "weknora/"
}
return file . NewOssFileServiceWithTempBucket (
os . Getenv ( "OSS_ENDPOINT" ) ,
os . Getenv ( "OSS_REGION" ) ,
os . Getenv ( "OSS_ACCESS_KEY" ) ,
os . Getenv ( "OSS_SECRET_KEY" ) ,
os . Getenv ( "OSS_BUCKET_NAME" ) ,
pathPrefix ,
os . Getenv ( "OSS_TEMP_BUCKET_NAME" ) ,
os . Getenv ( "OSS_TEMP_REGION" ) ,
)
2025-08-05 07:08:07 +00:00
case "local" :
2026-02-28 05:22:07 +00:00
baseDir := os . Getenv ( "LOCAL_STORAGE_BASE_DIR" )
if baseDir == "" {
baseDir = "/data/files"
}
fix(im): rewrite private storage URLs to HTTP in IM channel replies
IM platforms (Feishu, Slack, Telegram, DingTalk, Mattermost, WeCom) cannot
render provider:// URLs (local://, minio://, s3://, etc.) that appear in
LLM answers containing knowledge base images. The web frontend handles
these via the authenticated /files endpoint, but IM clients need publicly
resolvable HTTP URLs.
Changes:
- Add HMAC-SHA256 presigned URL utility (internal/utils/presign.go) for
generating time-limited, signature-verified file access URLs
- Add GET /api/v1/files/presigned endpoint that serves files without
session auth, verified by HMAC signature and expiry
- Update localFileService.GetFileURL() to return presigned HTTP URLs
when APP_EXTERNAL_URL is configured (cloud backends already return
presigned URLs via their SDKs)
- Add IM content rewriting pipeline: strip <image> XML tags, strip
citation tags, rewrite storage URLs to HTTP — applied at all IM
output points (streaming flush, non-streaming reply, fallback)
- Add holdback buffer in streaming flush to prevent URL/tag splitting
across chunk boundaries
Closes #1058
2026-04-28 12:22:04 +00:00
externalURL := strings . TrimSpace ( os . Getenv ( "APP_EXTERNAL_URL" ) )
return file . NewLocalFileService ( baseDir , externalURL ) , nil
2025-08-05 07:08:07 +00:00
case "dummy" :
return file . NewDummyFileService ( ) , nil
default :
2026-02-28 05:22:07 +00:00
return nil , fmt . Errorf ( "unsupported storage type: %s" , storageType )
2025-08-05 07:08:07 +00:00
}
}
// initRetrieveEngineRegistry initializes the retrieval engine registry
// Sets up and configures various search engine backends based on configuration
// Supports multiple retrieval engines (PostgreSQL, ElasticsearchV7, ElasticsearchV8)
// Parameters:
// - db: Database connection
// - cfg: Application configuration
//
// Returns:
// - Configured retrieval engine registry
// - Error if initialization fails
func initRetrieveEngineRegistry ( db * gorm . DB , cfg * config . Config ) ( interfaces . RetrieveEngineRegistry , error ) {
registry := retriever . NewRetrieveEngineRegistry ( )
retrieveDriver := strings . Split ( os . Getenv ( "RETRIEVE_DRIVER" ) , "," )
log := logger . GetLogger ( context . Background ( ) )
if slices . Contains ( retrieveDriver , "postgres" ) {
postgresRepo := postgresRepo . NewPostgresRetrieveEngineRepository ( db )
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine ( postgresRepo , types . PostgresRetrieverEngineType ) ,
) ; err != nil {
log . Errorf ( "Register postgres retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register postgres retrieve engine success" )
}
}
2026-02-28 05:22:07 +00:00
if slices . Contains ( retrieveDriver , "sqlite" ) {
sqliteRepo := sqliteRetrieverRepo . NewSQLiteRetrieveEngineRepository ( db )
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine ( sqliteRepo , types . SQLiteRetrieverEngineType ) ,
) ; err != nil {
log . Errorf ( "Register sqlite retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register sqlite retrieve engine success" )
}
}
2025-08-05 07:08:07 +00:00
if slices . Contains ( retrieveDriver , "elasticsearch_v8" ) {
client , err := elasticsearch . NewTypedClient ( elasticsearch . Config {
Addresses : [ ] string { os . Getenv ( "ELASTICSEARCH_ADDR" ) } ,
Username : os . Getenv ( "ELASTICSEARCH_USERNAME" ) ,
Password : os . Getenv ( "ELASTICSEARCH_PASSWORD" ) ,
} )
if err != nil {
log . Errorf ( "Create elasticsearch_v8 client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
elasticsearchRepo := elasticsearchRepoV8 . NewElasticsearchEngineRepository ( client , cfg , nil )
2025-08-05 07:08:07 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
elasticsearchRepo , types . ElasticsearchRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register elasticsearch_v8 retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register elasticsearch_v8 retrieve engine success" )
}
}
}
if slices . Contains ( retrieveDriver , "elasticsearch_v7" ) {
client , err := esv7 . NewClient ( esv7 . Config {
Addresses : [ ] string { os . Getenv ( "ELASTICSEARCH_ADDR" ) } ,
Username : os . Getenv ( "ELASTICSEARCH_USERNAME" ) ,
Password : os . Getenv ( "ELASTICSEARCH_PASSWORD" ) ,
} )
if err != nil {
log . Errorf ( "Create elasticsearch_v7 client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
elasticsearchRepo := elasticsearchRepoV7 . NewElasticsearchEngineRepository ( client , cfg , nil )
2025-08-05 07:08:07 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
elasticsearchRepo , types . ElasticsearchRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register elasticsearch_v7 retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register elasticsearch_v7 retrieve engine success" )
}
}
}
2025-11-26 10:58:53 +00:00
if slices . Contains ( retrieveDriver , "qdrant" ) {
qdrantHost := os . Getenv ( "QDRANT_HOST" )
if qdrantHost == "" {
qdrantHost = "localhost"
}
qdrantPort := 6334 // Default port
if portStr := os . Getenv ( "QDRANT_PORT" ) ; portStr != "" {
if port , err := strconv . Atoi ( portStr ) ; err == nil {
qdrantPort = port
}
}
// API key for authentication (optional)
qdrantAPIKey := os . Getenv ( "QDRANT_API_KEY" )
// TLS configuration (optional, defaults to false)
// Enable TLS unless explicitly set to "false" or "0" (case insensitive)
qdrantUseTLS := false
if useTLSStr := os . Getenv ( "QDRANT_USE_TLS" ) ; useTLSStr != "" {
useTLSLower := strings . ToLower ( strings . TrimSpace ( useTLSStr ) )
qdrantUseTLS = useTLSLower != "false" && useTLSLower != "0"
}
log . Infof ( "Connecting to Qdrant at %s:%d (TLS: %v)" , qdrantHost , qdrantPort , qdrantUseTLS )
client , err := qdrant . NewClient ( & qdrant . Config {
Host : qdrantHost ,
Port : qdrantPort ,
APIKey : qdrantAPIKey ,
UseTLS : qdrantUseTLS ,
} )
if err != nil {
log . Errorf ( "Create qdrant client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
qdrantRepository := qdrantRepo . NewQdrantRetrieveEngineRepository ( client , nil )
2025-11-26 10:58:53 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
qdrantRepository , types . QdrantRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register qdrant retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register qdrant retrieve engine success" )
}
}
}
2026-03-07 07:17:27 +00:00
if slices . Contains ( retrieveDriver , "weaviate" ) {
weaviateHost := os . Getenv ( "WEAVIATE_HOST" )
if weaviateHost == "" {
// Docker compose default (service name inside network)
weaviateHost = "weaviate:8080"
}
weaviateGrpcAddress := os . Getenv ( "WEAVIATE_GRPC_ADDRESS" )
if weaviateGrpcAddress == "" {
weaviateGrpcAddress = "weaviate:50051"
}
weaviateScheme := os . Getenv ( "WEAVIATE_SCHEME" )
if weaviateScheme == "" {
weaviateScheme = "http"
}
var authConfig auth . Config
if strings . EqualFold ( strings . TrimSpace ( os . Getenv ( "WEAVIATE_AUTH_ENABLED" ) ) , "true" ) {
if apiKey := strings . TrimSpace ( os . Getenv ( "WEAVIATE_API_KEY" ) ) ; apiKey != "" {
authConfig = auth . ApiKey { Value : apiKey }
}
}
weaviateClient , err := weaviate . NewClient ( weaviate . Config {
Host : weaviateHost ,
GrpcConfig : & wgrpc . Config {
Host : weaviateGrpcAddress ,
} ,
Scheme : weaviateScheme ,
AuthConfig : authConfig ,
} )
if err != nil {
log . Errorf ( "Create weaviate client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
weaviateRepository := weaviateRepo . NewWeaviateRetrieveEngineRepository ( weaviateClient , nil )
2026-03-07 07:17:27 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
weaviateRepository , types . WeaviateRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register weaviate retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register weaviate retrieve engine success" )
}
}
}
2026-02-26 13:48:38 +00:00
if slices . Contains ( retrieveDriver , "milvus" ) {
milvusCfg := milvusclient . ClientConfig {
DialOptions : [ ] grpc . DialOption { grpc . WithTimeout ( 5 * time . Second ) } ,
}
milvusAddress := os . Getenv ( "MILVUS_ADDRESS" )
if milvusAddress == "" {
milvusAddress = "localhost:19530"
}
milvusCfg . Address = milvusAddress
milvusUsername := os . Getenv ( "MILVUS_USERNAME" )
if milvusUsername != "" {
milvusCfg . Username = milvusUsername
}
milvusPassword := os . Getenv ( "MILVUS_PASSWORD" )
if milvusPassword != "" {
milvusCfg . Password = milvusPassword
}
milvusDBName := os . Getenv ( "MILVUS_DB_NAME" )
if milvusDBName != "" {
milvusCfg . DBName = milvusDBName
}
milvusCli , err := milvusclient . New ( context . Background ( ) , & milvusCfg )
if err != nil {
log . Errorf ( "Create milvus client failed: %v" , err )
} else {
2026-04-16 06:12:42 +00:00
milvusRepository := milvusRepo . NewMilvusRetrieveEngineRepository ( milvusCli , nil )
2026-02-26 13:48:38 +00:00
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
milvusRepository , types . MilvusRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register milvus retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register milvus retrieve engine success" )
}
}
}
feat(retriever): 接入 Apache Doris 4.1 作为向量数据库
为 RetrieveEngine 体系新增 Doris 后端,与现有 Qdrant/Milvus/Weaviate
等保持完整能力对齐:向量检索、关键词检索、健康检查、环境变量与多实例
DB 配置、前端类型注册、单元测试、Docker Compose 模板。
实现要点:
- 协议分工:主链路用 MySQL 协议(database/sql + go-sql-driver/mysql)
做 DDL / 查询 / 删除;批量更新走 Stream Load HTTP API,并启用
partial_update=true、merge_type=APPEND,自动按 1MiB 切分批次并处理
307 重定向。
- 表结构:UNIQUE KEY(id) + enable_unique_key_merge_on_write=true 以
支持 upsert/部分列更新;按维度分表(<base>_<dim>),每张表上建
HNSW ANN 索引(metric_type=cosine_distance)和 INVERTED 索引
(parser=chinese)。
- 分数语义:使用 cosine_distance_approximate,再以 1 - dist 转换为
"越大越相似",与现有 KVHybridRetrieveEngine 约定一致。
- 异步索引:ANN 索引为后台构建,ensureTable 通过轮询 SHOW INDEX 等
待索引就绪后再放行写入,避免首次检索召回为空。
- ARRAY<FLOAT> 序列化:go-sql-driver/mysql 不支持数组占位符,
embeddingLiteral 将 []float32 转成 SQL 字面量字符串再拼接。
新增文件:
- internal/application/repository/retriever/doris/{structs,schema,
query,repository,streamload,repository_test}.go
- scripts/e2e-doris.sh:E2E 验证清单
- docs/wiki/集成扩展/Doris改动与上游同步.md:fork-and-rebase 工作流
与改动清单
修改文件(接线 + 文档):
- internal/types/{retriever,tenant,vectorstore}.go:新增
DorisRetrieverEngineType、env 解析、表单 schema 与索引参数校验
- internal/container/{container,engine_factory}.go:环境变量驱动
与 VectorStore 配置驱动两条路径都支持 Doris
- internal/application/service/vectorstore{,_healthcheck}.go:连接
校验 + Ping/Version 健康检查
- docker-compose.yml:新增 doris-fe / doris-be 服务(profile=doris)
- .env.example:DORIS_* 环境变量与示例
- docs/{使用其他向量数据库,wiki/集成扩展/集成向量数据库}.md:
使用说明与索引/分数行为说明
依赖:go.mod/go.sum 新增 github.com/go-sql-driver/mysql(运行时)和
github.com/DATA-DOG/go-sqlmock(测试)。
测试:repository 层 SQL 形状、Stream Load HTTP 行为、whereBuilder
逻辑、embeddingLiteral 往返、健康检查错误路径均有单测覆盖。
2026-05-07 09:58:37 +00:00
if slices . Contains ( retrieveDriver , "doris" ) {
dorisAddr := os . Getenv ( "DORIS_ADDR" )
if dorisAddr == "" {
// docker-compose 默认服务名 + Doris FE MySQL 端口
dorisAddr = "doris-fe:9030"
}
dorisDatabase := os . Getenv ( "DORIS_DATABASE" )
if dorisDatabase == "" {
dorisDatabase = "weknora"
}
dorisUsername := os . Getenv ( "DORIS_USERNAME" )
if dorisUsername == "" {
dorisUsername = "root"
}
dorisPassword := os . Getenv ( "DORIS_PASSWORD" )
dorisHTTPPort := 8030
if portStr := os . Getenv ( "DORIS_HTTP_PORT" ) ; portStr != "" {
if port , err := strconv . Atoi ( portStr ) ; err == nil {
dorisHTTPPort = port
}
}
dsn := fmt . Sprintf ( "%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=true&loc=Local" ,
dorisUsername , dorisPassword , dorisAddr , dorisDatabase )
dorisDB , err := sql . Open ( "mysql" , dsn )
if err != nil {
log . Errorf ( "Create doris client failed: %v" , err )
} else {
dorisDB . SetMaxOpenConns ( 20 )
dorisDB . SetMaxIdleConns ( 5 )
dorisDB . SetConnMaxLifetime ( time . Hour )
httpBase := "http://" + hostFromAddr ( dorisAddr ) + ":" + strconv . Itoa ( dorisHTTPPort )
dorisRepository := dorisRepo . NewDorisRetrieveEngineRepository (
dorisDB , httpBase , dorisUsername , dorisPassword , dorisDatabase , nil ,
)
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
dorisRepository , types . DorisRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register doris retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register doris retrieve engine success: %s db=%s" , dorisAddr , dorisDatabase )
}
}
}
2026-05-08 08:09:55 +00:00
if slices . Contains ( retrieveDriver , "tencent_vectordb" ) {
addr := os . Getenv ( "TENCENT_VECTORDB_ADDR" )
username := os . Getenv ( "TENCENT_VECTORDB_USERNAME" )
apiKey := os . Getenv ( "TENCENT_VECTORDB_API_KEY" )
if addr == "" || username == "" || apiKey == "" {
log . Errorf ( "Missing Tencent VectorDB configuration" )
} else {
client , err := tcvectordb . NewRpcClient ( addr , username , apiKey , & tcvectordb . ClientOption {
ReadConsistency : tcvectordb . EventualConsistency ,
Timeout : 10 * time . Second ,
} )
if err != nil {
log . Errorf ( "Create tencent_vectordb client failed: %v" , err )
} else {
tencentRepository := tencentVectorDBRepo . NewTencentVectorDBRetrieveEngineRepository (
client ,
os . Getenv ( "TENCENT_VECTORDB_DATABASE" ) ,
nil ,
)
if err := registry . Register (
retriever . NewKVHybridRetrieveEngine (
tencentRepository , types . TencentVectorDBRetrieverEngineType ,
) ,
) ; err != nil {
log . Errorf ( "Register tencent_vectordb retrieve engine failed: %v" , err )
} else {
log . Infof ( "Register tencent_vectordb retrieve engine success" )
}
}
}
}
2026-04-15 03:44:52 +00:00
// ─── DB store registration (byStoreID) ───
if storeReg , ok := registry . ( * retriever . RetrieveEngineRegistry ) ; ok {
loadDBStoresIntoRegistry ( storeReg , db , cfg )
}
2025-08-05 07:08:07 +00:00
return registry , nil
}
2026-04-15 03:44:52 +00:00
// loadDBStoresIntoRegistry loads VectorStore records from DB and registers them
// in the registry's byStoreID map. Failures are logged and skipped (non-fatal).
func loadDBStoresIntoRegistry ( storeRegistry interfaces . StoreRegistry , db * gorm . DB , cfg * config . Config ) {
ctx := context . Background ( )
log := logger . GetLogger ( ctx )
var stores [ ] types . VectorStore
// GORM soft delete automatically adds "deleted_at IS NULL" condition
if err := db . Find ( & stores ) . Error ; err != nil {
log . Warnf ( "Failed to load vector stores from DB: %v" , err )
return
}
if len ( stores ) == 0 {
return
}
log . Infof ( "Loading %d vector store(s) from database" , len ( stores ) )
for _ , store := range stores {
svc , err := createEngineServiceFromStore ( ctx , store , db , cfg )
if err != nil {
log . Errorf ( "Failed to create engine for store %s (%s): %v" , store . ID , store . Name , err )
continue
}
storeRegistry . RegisterWithStoreID ( store . ID , svc )
log . Infof ( "Registered DB vector store: id=%s, name=%s, engine=%s" , store . ID , store . Name , store . EngineType )
}
}
2025-08-05 07:08:07 +00:00
// initAntsPool initializes the goroutine pool
// Creates a managed goroutine pool for concurrent task execution
// Parameters:
// - cfg: Application configuration
//
// Returns:
// - Configured goroutine pool
// - Error if initialization fails
func initAntsPool ( cfg * config . Config ) ( * ants . Pool , error ) {
2025-08-16 05:13:52 +00:00
// Default to 5 if not specified in config
poolSize := os . Getenv ( "CONCURRENCY_POOL_SIZE" )
if poolSize == "" {
poolSize = "5"
}
poolSizeInt , err := strconv . Atoi ( poolSize )
if err != nil {
return nil , err
}
2025-08-05 07:08:07 +00:00
// Set up the pool with pre-allocation for better performance
2025-08-16 05:13:52 +00:00
return ants . NewPool ( poolSizeInt , ants . WithPreAlloc ( true ) )
2025-08-05 07:08:07 +00:00
}
// registerPoolCleanup registers the goroutine pool for cleanup
// Ensures proper cleanup of the goroutine pool when application shuts down
// Parameters:
// - pool: Goroutine pool
// - cleaner: Resource cleaner
func registerPoolCleanup ( pool * ants . Pool , cleaner interfaces . ResourceCleaner ) {
cleaner . RegisterWithName ( "AntsPool" , func ( ) error {
pool . Release ( )
return nil
} )
}
2026-03-04 09:43:34 +00:00
// registerTracerCleanup registers the tracer for cleanup
// Ensures proper cleanup of the tracer when application shuts down
// Parameters:
// - tracer: Tracer instance
// - cleaner: Resource cleaner
func registerTracerCleanup ( tracer * tracing . Tracer , cleaner interfaces . ResourceCleaner ) {
// Register the cleanup function - actual context will be provided during cleanup
cleaner . RegisterWithName ( "Tracer" , func ( ) error {
// Create context for cleanup with longer timeout for tracer shutdown
return tracer . Cleanup ( context . Background ( ) )
} )
}
feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).
Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
so logger.CloneContext can preserve it across handler / goroutine
boundaries (otherwise each LLM call auto-created an orphan trace,
fragmenting one request into many)
Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes
Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.
Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
reuses WeKnora's existing PostgreSQL (separate database via an idempotent
init container that fixes ICU collation drift) and Redis (separate DB
number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
to avoid Prisma P1013 when passwords contain @ / # / etc.
Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-23 17:57:12 +00:00
// registerLangfuseCleanup ensures buffered Langfuse events are flushed on
// shutdown. A 5-second timeout matches other external-service cleanups and
// balances data durability against a slow remote endpoint holding up exit.
func registerLangfuseCleanup ( mgr * langfuse . Manager , cleaner interfaces . ResourceCleaner ) {
if mgr == nil {
return
}
cleaner . RegisterWithName ( "Langfuse" , func ( ) error {
ctx , cancel := context . WithTimeout ( context . Background ( ) , 5 * time . Second )
defer cancel ( )
return mgr . Shutdown ( ctx )
} )
}
2026-02-28 05:22:07 +00:00
// initDocReaderClient initializes the DocumentReader client (lightweight API).
func initDocReaderClient ( cfg * config . Config ) ( interfaces . DocumentReader , error ) {
addr := strings . TrimSpace ( os . Getenv ( "DOCREADER_ADDR" ) )
transport := strings . TrimSpace ( os . Getenv ( "DOCREADER_TRANSPORT" ) )
if transport == "" {
transport = "grpc"
}
if addr == "" {
logger . Infof ( context . Background ( ) , "[DocConverter] No DOCREADER_ADDR configured, starting disconnected" )
}
transport = strings . ToLower ( transport )
switch transport {
case "http" , "https" :
if addr != "" && ! strings . HasPrefix ( addr , "http://" ) && ! strings . HasPrefix ( addr , "https://" ) {
addr = "http://" + addr
}
return docparser . NewHTTPDocumentReader ( addr )
default :
return docparser . NewGRPCDocumentReader ( addr )
}
}
2025-08-05 07:08:07 +00:00
// initOllamaService initializes the Ollama service client
// Creates a client for interacting with Ollama API for model inference
// Parameters:
// - None
//
// Returns:
// - Configured Ollama service client
// - Error if initialization fails
func initOllamaService ( ) ( * ollama . OllamaService , error ) {
// Get Ollama service from existing factory function
return ollama . GetOllamaService ( )
}
2025-09-24 04:15:17 +00:00
func initNeo4jClient ( ) ( neo4j . Driver , error ) {
2025-12-08 09:40:10 +00:00
ctx := context . Background ( )
2025-09-24 04:15:17 +00:00
if strings . ToLower ( os . Getenv ( "NEO4J_ENABLE" ) ) != "true" {
2025-12-08 09:40:10 +00:00
logger . Debugf ( ctx , "NOT SUPPORT RETRIEVE GRAPH" )
2025-09-24 04:15:17 +00:00
return nil , nil
}
uri := os . Getenv ( "NEO4J_URI" )
username := os . Getenv ( "NEO4J_USERNAME" )
password := os . Getenv ( "NEO4J_PASSWORD" )
2025-12-08 09:40:10 +00:00
// Retry configuration
maxRetries := 30 // Max retry attempts
retryInterval := 2 * time . Second // Wait between retries
var driver neo4j . Driver
var err error
for attempt := 1 ; attempt <= maxRetries ; attempt ++ {
driver , err = neo4j . NewDriver ( uri , neo4j . BasicAuth ( username , password , "" ) )
if err != nil {
logger . Warnf ( ctx , "Failed to create Neo4j driver (attempt %d/%d): %v" , attempt , maxRetries , err )
time . Sleep ( retryInterval )
continue
}
err = driver . VerifyAuthentication ( ctx , nil )
if err == nil {
if attempt > 1 {
logger . Infof ( ctx , "Successfully connected to Neo4j after %d attempts" , attempt )
}
return driver , nil
}
logger . Warnf ( ctx , "Failed to verify Neo4j authentication (attempt %d/%d): %v" , attempt , maxRetries , err )
driver . Close ( ctx )
time . Sleep ( retryInterval )
2025-09-24 04:15:17 +00:00
}
2025-12-08 09:40:10 +00:00
return nil , fmt . Errorf ( "failed to connect to Neo4j after %d attempts: %w" , maxRetries , err )
2025-09-24 04:15:17 +00:00
}
2025-12-23 08:56:30 +00:00
func NewDuckDB ( ) ( * sql . DB , error ) {
sqlDB , err := sql . Open ( "duckdb" , ":memory:" )
if err != nil {
return nil , fmt . Errorf ( "failed to open duckdb: %w" , err )
}
2026-01-05 02:15:55 +00:00
2026-04-24 11:32:51 +00:00
// Try to install and load required extensions.
// - spatial: used for st_read_meta() to enumerate layer (sheet) names from .xlsx/.xls
// - excel: used for read_xlsx() which gives proper type inference per sheet
bgCtx := context . Background ( )
for _ , ext := range [ ] string { "spatial" , "excel" } {
if _ , err := sqlDB . ExecContext ( bgCtx , fmt . Sprintf ( "INSTALL %s;" , ext ) ) ; err != nil {
logger . Warnf ( bgCtx , "[DuckDB] Failed to install %s extension: %v" , ext , err )
}
if _ , err := sqlDB . ExecContext ( bgCtx , fmt . Sprintf ( "LOAD %s;" , ext ) ) ; err != nil {
logger . Warnf ( bgCtx , "[DuckDB] Failed to load %s extension: %v" , ext , err )
}
2025-12-23 08:56:30 +00:00
}
2026-01-05 02:15:55 +00:00
2025-12-23 08:56:30 +00:00
return sqlDB , nil
}
2026-01-19 12:28:31 +00:00
2026-03-31 12:14:26 +00:00
// registerWebSearchProviders registers all web search provider types to the registry.
// Each provider type is registered with its factory function that accepts parameters.
// Provider instances are created on-demand when tenants configure them.
func registerWebSearchProviders ( registry * infra_web_search . Registry ) {
registry . Register ( "duckduckgo" , infra_web_search . NewDuckDuckGoProvider )
registry . Register ( "google" , infra_web_search . NewGoogleProvider )
registry . Register ( "bing" , infra_web_search . NewBingProvider )
registry . Register ( "tavily" , infra_web_search . NewTavilyProvider )
2026-04-09 13:20:31 +00:00
registry . Register ( "ollama" , infra_web_search . NewOllamaProvider )
2026-04-12 07:58:42 +00:00
registry . Register ( "baidu" , infra_web_search . NewBaiduProvider )
2026-05-10 14:01:28 +00:00
registry . Register ( "searxng" , infra_web_search . NewSearxngProvider )
2026-01-19 12:28:31 +00:00
}
2026-03-15 10:45:53 +00:00
2026-03-15 18:23:22 +00:00
// registerIMAdapterFactories registers adapter factories for each IM platform
refactor(im): move adapter factories into per-platform subpackages
registerIMAdapterFactories in internal/container/container.go had grown
to ~290 lines of platform-specific config parsing and runtime start/stop
logic across 7 IM platforms, plus three private credential helpers. The
container package is meant to wire dependencies, not own each platform's
credentials schema and websocket lifecycle.
Extract each platform's factory into its own subpackage file and expose
the credential helpers on the im package:
- New im.ParseCredentials / im.GetString / im.GetBool (formerly the
unexported parseCredentials / getString / credentialBool in container).
- New im.ResolveMode helper collapses the six identical "default to
websocket when Mode is empty" blocks.
- New {wecom,feishu,slack,telegram,dingtalk,mattermost,wechat}.NewFactory
returns an im.AdapterFactory; container.go now calls each one in a
single line.
Behavior is preserved: adapter construction, goroutine start/stop,
log messages, default modes (mattermost still defaults to "webhook";
others to "websocket"), and error strings are unchanged. The WeCom
corp_agent_id float64/int switch and the WeChat long-poll-only path
are preserved as-is.
Net: container.go drops ~320 lines and no longer needs to be touched
when adding or tuning an IM platform.
2026-04-29 10:27:26 +00:00
// and loads enabled channels from the database. Each platform's factory lives
// in its own subpackage to keep this file focused on wiring.
2026-03-15 18:23:22 +00:00
func registerIMAdapterFactories ( imService * imPkg . Service ) {
refactor(im): move adapter factories into per-platform subpackages
registerIMAdapterFactories in internal/container/container.go had grown
to ~290 lines of platform-specific config parsing and runtime start/stop
logic across 7 IM platforms, plus three private credential helpers. The
container package is meant to wire dependencies, not own each platform's
credentials schema and websocket lifecycle.
Extract each platform's factory into its own subpackage file and expose
the credential helpers on the im package:
- New im.ParseCredentials / im.GetString / im.GetBool (formerly the
unexported parseCredentials / getString / credentialBool in container).
- New im.ResolveMode helper collapses the six identical "default to
websocket when Mode is empty" blocks.
- New {wecom,feishu,slack,telegram,dingtalk,mattermost,wechat}.NewFactory
returns an im.AdapterFactory; container.go now calls each one in a
single line.
Behavior is preserved: adapter construction, goroutine start/stop,
log messages, default modes (mattermost still defaults to "webhook";
others to "websocket"), and error strings are unchanged. The WeCom
corp_agent_id float64/int switch and the WeChat long-poll-only path
are preserved as-is.
Net: container.go drops ~320 lines and no longer needs to be touched
when adding or tuning an IM platform.
2026-04-29 10:27:26 +00:00
imService . RegisterAdapterFactory ( "wecom" , wecom . NewFactory ( ) )
imService . RegisterAdapterFactory ( "feishu" , feishu . NewFactory ( ) )
imService . RegisterAdapterFactory ( "slack" , slack . NewFactory ( ) )
imService . RegisterAdapterFactory ( "telegram" , telegram . NewFactory ( ) )
imService . RegisterAdapterFactory ( "dingtalk" , dingtalk . NewFactory ( ) )
imService . RegisterAdapterFactory ( "mattermost" , mattermost . NewFactory ( ) )
imService . RegisterAdapterFactory ( "wechat" , wechat . NewFactory ( ) )
2026-03-27 03:07:09 +00:00
2026-03-15 18:23:22 +00:00
// Load and start all enabled channels from database
if err := imService . LoadAndStartChannels ( ) ; err != nil {
refactor(im): move adapter factories into per-platform subpackages
registerIMAdapterFactories in internal/container/container.go had grown
to ~290 lines of platform-specific config parsing and runtime start/stop
logic across 7 IM platforms, plus three private credential helpers. The
container package is meant to wire dependencies, not own each platform's
credentials schema and websocket lifecycle.
Extract each platform's factory into its own subpackage file and expose
the credential helpers on the im package:
- New im.ParseCredentials / im.GetString / im.GetBool (formerly the
unexported parseCredentials / getString / credentialBool in container).
- New im.ResolveMode helper collapses the six identical "default to
websocket when Mode is empty" blocks.
- New {wecom,feishu,slack,telegram,dingtalk,mattermost,wechat}.NewFactory
returns an im.AdapterFactory; container.go now calls each one in a
single line.
Behavior is preserved: adapter construction, goroutine start/stop,
log messages, default modes (mattermost still defaults to "webhook";
others to "websocket"), and error strings are unchanged. The WeCom
corp_agent_id float64/int switch and the WeChat long-poll-only path
are preserved as-is.
Net: container.go drops ~320 lines and no longer needs to be touched
when adding or tuning an IM platform.
2026-04-29 10:27:26 +00:00
logger . Warnf ( context . Background ( ) , "[IM] Failed to load channels from database: %v" , err )
2026-03-27 03:07:09 +00:00
}
}
2026-03-27 07:02:40 +00:00
// initConnectorRegistry creates and populates the connector registry with all available connectors.
2026-04-27 08:56:30 +00:00
// Aggregates registration errors via errors.Join so a misconfigured or duplicated connector fails
// container initialization loudly instead of silently disabling the feature at runtime.
func initConnectorRegistry ( ) ( * datasource . ConnectorRegistry , error ) {
2026-03-27 07:02:40 +00:00
registry := datasource . NewConnectorRegistry ( )
2026-04-27 08:56:30 +00:00
var errs error
if err := registry . Register ( feishuConnector . NewConnector ( ) ) ; err != nil {
errs = errors . Join ( errs , fmt . Errorf ( "register feishu connector: %w" , err ) )
}
if err := registry . Register ( notionConnector . NewConnector ( ) ) ; err != nil {
errs = errors . Join ( errs , fmt . Errorf ( "register notion connector: %w" , err ) )
}
if err := registry . Register ( yuqueConnector . NewConnector ( ) ) ; err != nil {
errs = errors . Join ( errs , fmt . Errorf ( "register yuque connector: %w" , err ) )
}
2026-04-21 09:29:37 +00:00
2026-03-27 07:02:40 +00:00
// Future connectors will be registered here:
2026-04-27 08:56:30 +00:00
// if err := registry.Register(confluenceConnector.NewConnector()); err != nil { ... }
// if err := registry.Register(githubConnector.NewConnector()); err != nil { ... }
2026-03-27 07:02:40 +00:00
2026-04-27 08:56:30 +00:00
if errs != nil {
return nil , errs
}
return registry , nil
2026-03-27 07:02:40 +00:00
}
// startDataSourceScheduler starts the data source cron scheduler and registers cleanup.
func startDataSourceScheduler ( scheduler * datasource . Scheduler , cleaner interfaces . ResourceCleaner ) {
if err := scheduler . Start ( context . Background ( ) ) ; err != nil {
logger . Warnf ( context . Background ( ) , "[Container] data source scheduler start failed: %v" , err )
}
cleaner . RegisterWithName ( "DataSourceScheduler" , func ( ) error {
scheduler . Stop ( )
return nil
} )
}