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.
This commit is contained in:
@@ -25,21 +25,21 @@ func generateEventID(suffix string) string {
|
||||
|
||||
// sessionService implements the SessionService interface for managing conversation sessions
|
||||
type sessionService struct {
|
||||
cfg *config.Config // Application configuration
|
||||
sessionRepo interfaces.SessionRepository // Repository for session data
|
||||
messageRepo interfaces.MessageRepository // Repository for message data
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService // Service for knowledge base operations
|
||||
modelService interfaces.ModelService // Service for model operations
|
||||
tenantService interfaces.TenantService // Service for tenant operations
|
||||
eventManager *chatpipeline.EventManager // Event manager for chat pipeline
|
||||
agentService interfaces.AgentService // Service for agent operations
|
||||
sessionStorage llmcontext.ContextStorage // Session storage
|
||||
knowledgeService interfaces.KnowledgeService // Service for knowledge operations
|
||||
chunkService interfaces.ChunkService // Service for chunk operations
|
||||
webSearchStateRepo interfaces.WebSearchStateService // Service for web search state
|
||||
webSearchProviderRepo interfaces.WebSearchProviderRepository // Repository for web search provider entities
|
||||
kbShareService interfaces.KBShareService // Service for KB sharing operations
|
||||
memoryService interfaces.MemoryService // Service for memory operations
|
||||
cfg *config.Config // Application configuration
|
||||
sessionRepo interfaces.SessionRepository // Repository for session data
|
||||
messageRepo interfaces.MessageRepository // Repository for message data
|
||||
knowledgeBaseService interfaces.KnowledgeBaseService // Service for knowledge base operations
|
||||
modelService interfaces.ModelService // Service for model operations
|
||||
tenantService interfaces.TenantService // Service for tenant operations
|
||||
eventManager *chatpipeline.EventManager // Event manager for chat pipeline
|
||||
agentService interfaces.AgentService // Service for agent operations
|
||||
sessionStorage llmcontext.ContextStorage // Session storage
|
||||
knowledgeService interfaces.KnowledgeService // Service for knowledge operations
|
||||
chunkService interfaces.ChunkService // Service for chunk operations
|
||||
webSearchStateRepo interfaces.WebSearchStateService // Service for web search state
|
||||
webSearchProviderRepo interfaces.WebSearchProviderRepository // Repository for web search provider entities
|
||||
kbShareService interfaces.KBShareService // Service for KB sharing operations
|
||||
memoryService interfaces.MemoryService // Service for memory operations
|
||||
}
|
||||
|
||||
// NewSessionService creates a new session service instance with all required dependencies
|
||||
@@ -458,6 +458,9 @@ func (s *sessionService) GenerateTitleAsync(
|
||||
tenantID := ctx.Value(types.TenantIDContextKey)
|
||||
requestID := ctx.Value(types.RequestIDContextKey)
|
||||
language := ctx.Value(types.LanguageContextKey)
|
||||
// Keep the Langfuse trace handle so the async title generation shows up
|
||||
// as a child of the same trace as the originating chat request.
|
||||
langfuseTrace := ctx.Value(types.LangfuseTraceContextKey)
|
||||
go func() {
|
||||
bgCtx := context.Background()
|
||||
if tenantID != nil {
|
||||
@@ -469,6 +472,9 @@ func (s *sessionService) GenerateTitleAsync(
|
||||
if language != nil {
|
||||
bgCtx = context.WithValue(bgCtx, types.LanguageContextKey, language)
|
||||
}
|
||||
if langfuseTrace != nil {
|
||||
bgCtx = context.WithValue(bgCtx, types.LangfuseTraceContextKey, langfuseTrace)
|
||||
}
|
||||
|
||||
// Skip if title already exists
|
||||
if session.Title != "" {
|
||||
|
||||
Reference in New Issue
Block a user