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:
wizardchen
2026-04-24 01:57:12 +08:00
committed by lyingbug
parent b8c45b173e
commit 492e92580b
29 changed files with 2548 additions and 23 deletions
+2 -1
View File
@@ -60,5 +60,6 @@ func ConfigFromModel(m *types.Model) *Config {
// NewASR creates an ASR instance based on the provided configuration.
// All ASR vendors use the OpenAI-compatible /v1/audio/transcriptions API.
func NewASR(config *Config) (ASR, error) {
return NewOpenAIASR(config)
a, err := NewOpenAIASR(config)
return wrapASRLangfuse(a, err)
}
+79
View File
@@ -0,0 +1,79 @@
package asr
import (
"context"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
)
// langfuseASR wraps an ASR implementation and reports each Transcribe call
// as a Langfuse generation observation. Audio bytes are not uploaded — we
// record file name, audio size and duration (derived from segment end times)
// so usage can be billed by second/minute, which is how most ASR providers
// price their services.
type langfuseASR struct {
inner ASR
}
func (l *langfuseASR) GetModelName() string { return l.inner.GetModelName() }
func (l *langfuseASR) GetModelID() string { return l.inner.GetModelID() }
func (l *langfuseASR) Transcribe(ctx context.Context, audioBytes []byte, fileName string) (*TranscriptionResult, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.Transcribe(ctx, audioBytes, fileName)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "asr.transcribe",
Model: l.inner.GetModelName(),
Input: map[string]interface{}{
"file_name": fileName,
"audio_size": len(audioBytes),
},
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"audio_size": len(audioBytes),
},
})
result, err := l.inner.Transcribe(genCtx, audioBytes, fileName)
output := map[string]interface{}{}
var duration float64
if result != nil {
output["text"] = result.Text
output["segment_count"] = len(result.Segments)
if n := len(result.Segments); n > 0 {
duration = result.Segments[n-1].End
output["duration_seconds"] = duration
}
}
// ASR is billed per second; we emit the audio duration (when available)
// in the "Output" side of usage so users can configure per-model pricing
// in Langfuse (e.g. $0.006 per minute for Whisper-1).
var usage *langfuse.TokenUsage
if duration > 0 {
seconds := int(duration + 0.5)
usage = &langfuse.TokenUsage{
Output: seconds,
Total: seconds,
Unit: "SECONDS",
}
}
gen.Finish(output, usage, err)
return result, err
}
// wrapASRLangfuse applies the Langfuse decorator when the manager is enabled.
func wrapASRLangfuse(a ASR, err error) (ASR, error) {
if err != nil || a == nil {
return a, err
}
if !langfuse.GetManager().Enabled() {
return a, nil
}
return &langfuseASR{inner: a}, nil
}
+2 -1
View File
@@ -141,7 +141,8 @@ func NewChat(config *ChatConfig, ollamaService *ollama.OllamaService) (Chat, err
default:
return nil, fmt.Errorf("unsupported chat model source: %s", config.Source)
}
return wrapChatDebug(c, err)
c, err = wrapChatDebug(c, err)
return wrapChatLangfuse(c, err)
}
// NewRemoteChat 根据 provider 创建远程聊天实例
+210
View File
@@ -0,0 +1,210 @@
package chat
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
)
// langfuseChat wraps a Chat implementation and emits a Langfuse generation
// observation for every Chat/ChatStream call, capturing prompt, response and
// token usage. The wrapper is only installed when the Langfuse manager is
// enabled, so there is no cost for deployments that don't use Langfuse.
type langfuseChat struct {
inner Chat
}
func (l *langfuseChat) GetModelName() string { return l.inner.GetModelName() }
func (l *langfuseChat) GetModelID() string { return l.inner.GetModelID() }
func (l *langfuseChat) Chat(ctx context.Context, messages []Message, opts *ChatOptions) (*types.ChatResponse, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.Chat(ctx, messages, opts)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "chat.completion",
Model: l.inner.GetModelName(),
Input: buildLangfuseMessages(messages),
ModelParameters: buildLangfuseModelParams(opts),
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"streaming": false,
"has_tools": opts != nil && len(opts.Tools) > 0,
},
})
resp, err := l.inner.Chat(genCtx, messages, opts)
var usage *langfuse.TokenUsage
var output interface{}
if resp != nil {
usage = convertUsage(&resp.Usage)
output = map[string]interface{}{
"content": resp.Content,
"tool_calls": resp.ToolCalls,
"finish_reason": resp.FinishReason,
}
}
gen.Finish(output, usage, err)
return resp, err
}
func (l *langfuseChat) ChatStream(ctx context.Context, messages []Message, opts *ChatOptions) (<-chan types.StreamResponse, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.ChatStream(ctx, messages, opts)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "chat.completion.stream",
Model: l.inner.GetModelName(),
Input: buildLangfuseMessages(messages),
ModelParameters: buildLangfuseModelParams(opts),
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"streaming": true,
"has_tools": opts != nil && len(opts.Tools) > 0,
},
})
ch, err := l.inner.ChatStream(genCtx, messages, opts)
if err != nil {
gen.Finish(nil, nil, err)
return ch, err
}
if ch == nil {
gen.Finish(nil, nil, nil)
return nil, nil
}
wrapped := make(chan types.StreamResponse)
go func() {
defer close(wrapped)
var contentBuf []byte
var usage *types.TokenUsage
var toolCalls []types.LLMToolCall
var finishReason string
var firstToken bool
for resp := range ch {
if resp.ResponseType == types.ResponseTypeAnswer && resp.Content != "" {
if !firstToken {
gen.MarkCompletionStart(time.Now())
firstToken = true
}
contentBuf = append(contentBuf, resp.Content...)
}
if resp.Usage != nil {
usage = resp.Usage
}
if len(resp.ToolCalls) > 0 {
toolCalls = resp.ToolCalls
}
if resp.FinishReason != "" {
finishReason = resp.FinishReason
}
wrapped <- resp
}
output := map[string]interface{}{
"content": string(contentBuf),
"tool_calls": toolCalls,
"finish_reason": finishReason,
}
gen.Finish(output, convertUsage(usage), nil)
}()
return wrapped, nil
}
func buildLangfuseMessages(messages []Message) []map[string]interface{} {
out := make([]map[string]interface{}, 0, len(messages))
for _, m := range messages {
entry := map[string]interface{}{
"role": m.Role,
}
if m.Content != "" {
entry["content"] = m.Content
}
if len(m.MultiContent) > 0 {
entry["content"] = m.MultiContent
}
if m.Name != "" {
entry["name"] = m.Name
}
if m.ToolCallID != "" {
entry["tool_call_id"] = m.ToolCallID
}
if len(m.ToolCalls) > 0 {
entry["tool_calls"] = m.ToolCalls
}
out = append(out, entry)
}
return out
}
func buildLangfuseModelParams(opts *ChatOptions) map[string]interface{} {
if opts == nil {
return nil
}
params := map[string]interface{}{}
if opts.Temperature != 0 {
params["temperature"] = opts.Temperature
}
if opts.TopP != 0 {
params["top_p"] = opts.TopP
}
if opts.MaxTokens > 0 {
params["max_tokens"] = opts.MaxTokens
}
if opts.MaxCompletionTokens > 0 {
params["max_completion_tokens"] = opts.MaxCompletionTokens
}
if opts.FrequencyPenalty != 0 {
params["frequency_penalty"] = opts.FrequencyPenalty
}
if opts.PresencePenalty != 0 {
params["presence_penalty"] = opts.PresencePenalty
}
if opts.Seed != 0 {
params["seed"] = opts.Seed
}
if opts.ToolChoice != "" {
params["tool_choice"] = opts.ToolChoice
}
if len(params) == 0 {
return nil
}
return params
}
func convertUsage(u *types.TokenUsage) *langfuse.TokenUsage {
if u == nil {
return nil
}
if u.PromptTokens == 0 && u.CompletionTokens == 0 && u.TotalTokens == 0 {
return nil
}
return &langfuse.TokenUsage{
Input: u.PromptTokens,
Output: u.CompletionTokens,
Total: u.TotalTokens,
Unit: "TOKENS",
}
}
// wrapChatLangfuse wraps a Chat in a Langfuse-aware decorator when the
// manager is enabled. Called from NewChat after the debug wrapper so both
// sinks observe the same call.
func wrapChatLangfuse(c Chat, err error) (Chat, error) {
if err != nil || c == nil {
return c, err
}
if !langfuse.GetManager().Enabled() {
return c, nil
}
return &langfuseChat{inner: c}, nil
}
+9 -2
View File
@@ -8,6 +8,7 @@ import (
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/provider"
"github.com/Tencent/WeKnora/internal/models/utils/ollama"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
)
@@ -81,10 +82,16 @@ func ConfigFromModel(m *types.Model, appID, appSecret string) Config {
// NewEmbedder creates an embedder based on the configuration
func NewEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) {
e, err := newEmbedder(config, pooler, ollamaService)
if err != nil || !logger.LLMDebugEnabled() {
if err != nil {
return e, err
}
return &debugEmbedder{inner: e}, nil
if logger.LLMDebugEnabled() {
e = &debugEmbedder{inner: e}
}
if langfuse.GetManager().Enabled() {
e = &langfuseEmbedder{inner: e}
}
return e, nil
}
func newEmbedder(config Config, pooler EmbedderPooler, ollamaService *ollama.OllamaService) (Embedder, error) {
@@ -0,0 +1,136 @@
package embedding
import (
"context"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
)
// langfuseEmbedder wraps an Embedder and reports each call as a Langfuse
// generation observation. Input token counts are approximated from the text
// lengths when the underlying provider doesn't return usage data, because
// Langfuse's cost reports require non-zero input tokens.
type langfuseEmbedder struct {
inner Embedder
}
func (l *langfuseEmbedder) Embed(ctx context.Context, text string) ([]float32, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.Embed(ctx, text)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "embedding.embed",
Model: l.inner.GetModelName(),
Input: text,
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"dimensions": l.inner.GetDimensions(),
},
})
result, err := l.inner.Embed(genCtx, text)
usage := approxEmbeddingUsage([]string{text})
var out interface{}
if len(result) > 0 {
out = map[string]interface{}{
"dimensions": len(result),
"vector_preview": result[:min(3, len(result))],
}
}
gen.Finish(out, usage, err)
return result, err
}
func (l *langfuseEmbedder) BatchEmbed(ctx context.Context, texts []string) ([][]float32, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.BatchEmbed(ctx, texts)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "embedding.batch_embed",
Model: l.inner.GetModelName(),
Input: map[string]interface{}{
"count": len(texts),
// Avoid sending megabytes of full text — Langfuse truncates but
// the network cost is still real. Keep a short preview instead.
"preview": previewTexts(texts, 5),
},
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"dimensions": l.inner.GetDimensions(),
"batch_size": len(texts),
},
})
result, err := l.inner.BatchEmbed(genCtx, texts)
usage := approxEmbeddingUsage(texts)
var out interface{}
if len(result) > 0 {
out = map[string]interface{}{
"count": len(result),
"dimensions": len(result[0]),
}
}
gen.Finish(out, usage, err)
return result, err
}
func (l *langfuseEmbedder) BatchEmbedWithPool(ctx context.Context, model Embedder, texts []string) ([][]float32, error) {
return l.inner.BatchEmbedWithPool(ctx, l, texts)
}
func (l *langfuseEmbedder) GetModelName() string { return l.inner.GetModelName() }
func (l *langfuseEmbedder) GetDimensions() int { return l.inner.GetDimensions() }
func (l *langfuseEmbedder) GetModelID() string { return l.inner.GetModelID() }
// approxEmbeddingUsage estimates input tokens as ~rune_count / 4, matching the
// rule of thumb OpenAI uses in their tokenizer docs. This is purely for cost
// reporting — Langfuse lets users define per-model cost multipliers, so the
// approximation need only be proportional to length.
func approxEmbeddingUsage(texts []string) *langfuse.TokenUsage {
total := 0
for _, t := range texts {
runes := len([]rune(t))
if runes == 0 {
continue
}
total += runes/4 + 1
}
if total == 0 {
return nil
}
return &langfuse.TokenUsage{
Input: total,
Total: total,
Unit: "TOKENS",
}
}
func previewTexts(texts []string, n int) []string {
if len(texts) <= n {
out := make([]string, len(texts))
for i, t := range texts {
out[i] = truncateRunes(t, 120)
}
return out
}
out := make([]string, n)
for i := 0; i < n; i++ {
out[i] = truncateRunes(texts[i], 120)
}
return out
}
func truncateRunes(s string, maxRunes int) string {
r := []rune(s)
if len(r) <= maxRunes {
return s
}
return string(r[:maxRunes]) + "..."
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
+116
View File
@@ -0,0 +1,116 @@
package rerank
import (
"context"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
)
// langfuseReranker wraps a Reranker and reports each rerank call as a
// Langfuse generation observation. Rerankers don't return token usage, but
// the call still incurs cost (billed per 1K documents by most vendors); we
// estimate input tokens from the query + documents so the Langfuse cost
// dashboard gets a proportional signal.
type langfuseReranker struct {
inner Reranker
}
func (l *langfuseReranker) GetModelName() string { return l.inner.GetModelName() }
func (l *langfuseReranker) GetModelID() string { return l.inner.GetModelID() }
func (l *langfuseReranker) Rerank(ctx context.Context, query string, documents []string) ([]RankResult, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.Rerank(ctx, query, documents)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "rerank",
Model: l.inner.GetModelName(),
Input: map[string]interface{}{
"query": query,
"document_count": len(documents),
// Only send short previews — reranker inputs can be hundreds of
// passages totalling hundreds of KB, which would bloat traces.
"documents_preview": previewDocs(documents, 5),
},
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"num_queries": 1,
},
})
results, err := l.inner.Rerank(genCtx, query, documents)
output := map[string]interface{}{
"results": summarizeResults(results, 10),
"total_count": len(results),
}
gen.Finish(output, approxRerankUsage(query, documents), err)
return results, err
}
func approxRerankUsage(query string, documents []string) *langfuse.TokenUsage {
total := len([]rune(query))/4 + 1
for _, d := range documents {
total += len([]rune(d))/4 + 1
}
if total == 0 {
return nil
}
return &langfuse.TokenUsage{
Input: total,
Total: total,
Unit: "TOKENS",
}
}
func previewDocs(docs []string, n int) []map[string]interface{} {
if len(docs) < n {
n = len(docs)
}
out := make([]map[string]interface{}, 0, n)
for i := 0; i < n; i++ {
out = append(out, map[string]interface{}{
"index": i,
"preview": truncateRunes(docs[i], 160),
"length": len([]rune(docs[i])),
})
}
return out
}
func summarizeResults(results []RankResult, n int) []map[string]interface{} {
if len(results) < n {
n = len(results)
}
out := make([]map[string]interface{}, 0, n)
for i := 0; i < n; i++ {
out = append(out, map[string]interface{}{
"index": results[i].Index,
"score": results[i].RelevanceScore,
})
}
return out
}
func truncateRunes(s string, maxRunes int) string {
r := []rune(s)
if len(r) <= maxRunes {
return s
}
return string(r[:maxRunes]) + "..."
}
// wrapRerankerLangfuse applies the Langfuse decorator when the manager is
// enabled. Called from NewReranker after the debug wrapper so both sinks see
// the same calls.
func wrapRerankerLangfuse(r Reranker, err error) (Reranker, error) {
if err != nil || r == nil {
return r, err
}
if !langfuse.GetManager().Enabled() {
return r, nil
}
return &langfuseReranker{inner: r}, nil
}
+5 -2
View File
@@ -116,10 +116,13 @@ func ConfigFromModel(m *types.Model, appID, appSecret string) *RerankerConfig {
// NewReranker creates a reranker based on the configuration
func NewReranker(config *RerankerConfig) (Reranker, error) {
r, err := newReranker(config)
if err != nil || !logger.LLMDebugEnabled() {
if err != nil {
return r, err
}
return &debugReranker{inner: r}, nil
if logger.LLMDebugEnabled() {
r = &debugReranker{inner: r}
}
return wrapRerankerLangfuse(r, nil)
}
// customHeaderSetter 表示支持注入自定义 HTTP header 的 reranker 实现。
+72
View File
@@ -0,0 +1,72 @@
package vlm
import (
"context"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
)
// langfuseVLM wraps a VLM and reports each Predict call as a Langfuse
// generation. The raw image bytes are NOT uploaded — Langfuse traces are
// designed for text. We include image count and total byte size in the
// metadata, plus the text prompt, which matches how Langfuse's own VLM
// integrations report multimodal calls.
type langfuseVLM struct {
inner VLM
}
func (l *langfuseVLM) GetModelName() string { return l.inner.GetModelName() }
func (l *langfuseVLM) GetModelID() string { return l.inner.GetModelID() }
func (l *langfuseVLM) Predict(ctx context.Context, imgBytes [][]byte, prompt string) (string, error) {
mgr := langfuse.GetManager()
if !mgr.Enabled() {
return l.inner.Predict(ctx, imgBytes, prompt)
}
totalImgSize := 0
for _, b := range imgBytes {
totalImgSize += len(b)
}
genCtx, gen := mgr.StartGeneration(ctx, langfuse.GenerationOptions{
Name: "vlm.predict",
Model: l.inner.GetModelName(),
Input: map[string]interface{}{
"prompt": prompt,
"image_count": len(imgBytes),
},
Metadata: map[string]interface{}{
"model_id": l.inner.GetModelID(),
"image_count": len(imgBytes),
"image_bytes_total": totalImgSize,
},
})
result, err := l.inner.Predict(genCtx, imgBytes, prompt)
// VLMs don't return token usage; approximate prompt tokens for cost
// tracking in Langfuse (users can configure per-model pricing in the UI).
promptTokens := len([]rune(prompt))/4 + 1
outputTokens := len([]rune(result)) / 4
usage := &langfuse.TokenUsage{
Input: promptTokens,
Output: outputTokens,
Total: promptTokens + outputTokens,
Unit: "TOKENS",
}
gen.Finish(result, usage, err)
return result, err
}
// wrapVLMLangfuse applies the Langfuse decorator when the manager is enabled.
func wrapVLMLangfuse(v VLM, err error) (VLM, error) {
if err != nil || v == nil {
return v, err
}
if !langfuse.GetManager().Enabled() {
return v, nil
}
return &langfuseVLM{inner: v}, nil
}
+5 -2
View File
@@ -81,10 +81,13 @@ func stringMapToAnyMap(in map[string]string) map[string]any {
// NewVLM creates a VLM instance based on the provided configuration.
func NewVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {
v, err := newVLM(config, ollamaService)
if err != nil || !logger.LLMDebugEnabled() {
if err != nil {
return v, err
}
return &debugVLM{inner: v}, nil
if logger.LLMDebugEnabled() {
v = &debugVLM{inner: v}
}
return wrapVLMLangfuse(v, nil)
}
func newVLM(config *Config, ollamaService *ollama.OllamaService) (VLM, error) {