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
+21 -15
View File
@@ -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 != "" {
+26
View File
@@ -73,6 +73,7 @@ import (
"github.com/Tencent/WeKnora/internal/router"
"github.com/Tencent/WeKnora/internal/stream"
"github.com/Tencent/WeKnora/internal/tracing"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
slackpkg "github.com/slack-go/slack"
@@ -100,6 +101,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
logger.Debugf(ctx, "[Container] Registering core infrastructure...")
must(container.Provide(config.LoadConfig))
must(container.Provide(initTracer))
must(container.Provide(initLangfuse))
must(container.Provide(initDatabase))
must(container.Provide(initFileService))
must(container.Provide(initRedisClient))
@@ -108,6 +110,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
// Register tracer cleanup handler (tracer needs to be available for cleanup registration)
must(container.Invoke(registerTracerCleanup))
must(container.Invoke(registerLangfuseCleanup))
// Register goroutine pool cleanup handler
must(container.Invoke(registerPoolCleanup))
@@ -329,6 +332,15 @@ func initTracer() (*tracing.Tracer, error) {
return tracing.InitTracer()
}
// 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)
}
func initRedisClient() (*redis.Client, error) {
redisAddr := os.Getenv("REDIS_ADDR")
if redisAddr == "" {
@@ -1024,6 +1036,20 @@ func registerTracerCleanup(tracer *tracing.Tracer, cleaner interfaces.ResourceCl
})
}
// 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)
})
}
// initDocReaderClient initializes the DocumentReader client (lightweight API).
func initDocReaderClient(cfg *config.Config) (interfaces.DocumentReader, error) {
addr := strings.TrimSpace(os.Getenv("DOCREADER_ADDR"))
+5
View File
@@ -398,6 +398,11 @@ func CloneContext(ctx context.Context) context.Context {
types.LanguageContextKey,
types.SessionTenantIDContextKey,
types.EmbedQueryContextKey,
// Keep the Langfuse trace alive across CloneContext boundaries so
// LLM/Embedder/Reranker/VLM/ASR wrappers attach their generations
// to the same trace opened by GinMiddleware, instead of each call
// auto-creating its own orphan trace.
types.LangfuseTraceContextKey,
} {
if v := ctx.Value(k); v != nil {
newCtx = context.WithValue(newCtx, k, v)
+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) {
+5
View File
@@ -21,6 +21,7 @@ import (
"github.com/Tencent/WeKnora/internal/handler/session"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/middleware"
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@@ -122,6 +123,10 @@ func NewRouter(params RouterParams) *gin.Engine {
// 添加OpenTelemetry追踪中间件
// r.Use(middleware.TracingMiddleware())
// Langfuse observability — only active when LANGFUSE_* env vars are set.
// The middleware is registered unconditionally; when disabled it's a no-op.
r.Use(langfuse.GinMiddleware())
// 需要认证的API路由
v1 := r.Group("/api/v1")
{
+85
View File
@@ -0,0 +1,85 @@
package langfuse
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
// client is a thin HTTP client for the Langfuse ingestion API.
type client struct {
host string
auth string // pre-computed "Basic <base64>"
httpClient *http.Client
debug bool
}
func newClient(cfg Config) *client {
credentials := cfg.PublicKey + ":" + cfg.SecretKey
return &client{
host: strings.TrimRight(cfg.Host, "/"),
auth: "Basic " + base64.StdEncoding.EncodeToString([]byte(credentials)),
httpClient: &http.Client{
Timeout: cfg.RequestTimeout,
},
debug: cfg.Debug,
}
}
type ingestionRequest struct {
Batch []ingestionEvent `json:"batch"`
}
// ingest posts a batch of events to Langfuse. The API accepts partial failure:
// individual event errors are returned in a 207 response, which we surface as
// a logged debug message rather than a hard error (the batch as a whole was
// accepted).
func (c *client) ingest(ctx context.Context, events []ingestionEvent) error {
if len(events) == 0 {
return nil
}
body, err := json.Marshal(ingestionRequest{Batch: events})
if err != nil {
return fmt.Errorf("langfuse: marshal batch: %w", err)
}
endpoint := c.host + "/api/public/ingestion"
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("langfuse: build request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", c.auth)
req.Header.Set("User-Agent", "weknora-langfuse/1.0")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("langfuse: ingest request failed: %w", err)
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
// 207 = "multi-status": batch accepted, some events may have failed.
// 2xx = success. Anything else is a transport/auth error worth surfacing.
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
if c.debug && resp.StatusCode == http.StatusMultiStatus {
return fmt.Errorf("langfuse: partial ingest success (207): %s", truncate(string(respBody), 512))
}
return nil
}
return fmt.Errorf("langfuse: ingest failed with status %d: %s", resp.StatusCode, truncate(string(respBody), 512))
}
func truncate(s string, max int) string {
if len(s) <= max {
return s
}
return s[:max] + "..."
}
+140
View File
@@ -0,0 +1,140 @@
// Package langfuse implements a lightweight client for the Langfuse ingestion
// API (https://langfuse.com/docs/api). It lets WeKnora record LLM traces,
// generations and token usage in Langfuse without pulling in a heavy SDK.
//
// The integration is fully opt-in: when disabled (the default), all public
// entry points are cheap no-ops, so callers can wire them unconditionally.
package langfuse
import (
"fmt"
"os"
"strconv"
"strings"
"time"
)
// Config holds the runtime configuration for the Langfuse client.
//
// In practice users enable Langfuse purely through environment variables —
// Host / PublicKey / SecretKey — which matches every other Langfuse SDK and
// keeps WeKnora's YAML config free of secrets.
type Config struct {
// Enabled is the master switch. If false the entire package is a no-op.
Enabled bool
// Host is the Langfuse base URL, e.g. https://cloud.langfuse.com or
// https://us.cloud.langfuse.com or a self-hosted address.
Host string
// PublicKey / SecretKey are the project credentials used for Basic Auth.
PublicKey string
SecretKey string
// FlushAt flushes the queued events once the buffer reaches this size.
FlushAt int
// FlushInterval is the maximum time between automatic flushes.
FlushInterval time.Duration
// QueueSize bounds the in-memory buffer to avoid unbounded growth if the
// Langfuse endpoint is unreachable.
QueueSize int
// RequestTimeout is the HTTP timeout for a single ingestion batch.
RequestTimeout time.Duration
// Release / Environment are attached to every trace for filtering in the
// Langfuse UI (e.g. release="v0.4.2", environment="production").
Release string
Environment string
// SampleRate (0..1) controls trace sampling. 0 means "use 1.0".
SampleRate float64
// Debug enables verbose logging of batch send errors.
Debug bool
}
// LoadConfigFromEnv builds a Config by reading the LANGFUSE_* environment
// variables, mirroring the official Python / JS SDK conventions.
func LoadConfigFromEnv() Config {
cfg := Config{
Host: firstNonEmpty(os.Getenv("LANGFUSE_HOST"), "https://cloud.langfuse.com"),
PublicKey: strings.TrimSpace(os.Getenv("LANGFUSE_PUBLIC_KEY")),
SecretKey: strings.TrimSpace(os.Getenv("LANGFUSE_SECRET_KEY")),
Release: strings.TrimSpace(os.Getenv("LANGFUSE_RELEASE")),
Environment: strings.TrimSpace(os.Getenv("LANGFUSE_ENVIRONMENT")),
FlushAt: 15,
FlushInterval: 3 * time.Second,
QueueSize: 2048,
RequestTimeout: 10 * time.Second,
SampleRate: 1.0,
}
if v := strings.TrimSpace(os.Getenv("LANGFUSE_ENABLED")); v != "" {
cfg.Enabled = parseBool(v)
} else if cfg.PublicKey != "" && cfg.SecretKey != "" {
// Auto-enable when credentials are present — matches the Python SDK.
cfg.Enabled = true
}
if v := strings.TrimSpace(os.Getenv("LANGFUSE_FLUSH_AT")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
cfg.FlushAt = n
}
}
if v := strings.TrimSpace(os.Getenv("LANGFUSE_FLUSH_INTERVAL")); v != "" {
if d, err := time.ParseDuration(v); err == nil && d > 0 {
cfg.FlushInterval = d
} else if n, err := strconv.Atoi(v); err == nil && n > 0 {
cfg.FlushInterval = time.Duration(n) * time.Second
}
}
if v := strings.TrimSpace(os.Getenv("LANGFUSE_QUEUE_SIZE")); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
cfg.QueueSize = n
}
}
if v := strings.TrimSpace(os.Getenv("LANGFUSE_REQUEST_TIMEOUT")); v != "" {
if d, err := time.ParseDuration(v); err == nil && d > 0 {
cfg.RequestTimeout = d
}
}
if v := strings.TrimSpace(os.Getenv("LANGFUSE_SAMPLE_RATE")); v != "" {
if f, err := strconv.ParseFloat(v, 64); err == nil && f >= 0 && f <= 1 {
cfg.SampleRate = f
}
}
if v := strings.TrimSpace(os.Getenv("LANGFUSE_DEBUG")); v != "" {
cfg.Debug = parseBool(v)
}
if cfg.SampleRate == 0 {
cfg.SampleRate = 1.0
}
return cfg
}
// Validate verifies required fields are present when Langfuse is enabled.
func (c Config) Validate() error {
if !c.Enabled {
return nil
}
if strings.TrimSpace(c.Host) == "" {
return fmt.Errorf("langfuse: host is required when enabled")
}
if c.PublicKey == "" || c.SecretKey == "" {
return fmt.Errorf("langfuse: public_key and secret_key are required when enabled")
}
return nil
}
func firstNonEmpty(values ...string) string {
for _, v := range values {
if s := strings.TrimSpace(v); s != "" {
return s
}
}
return ""
}
func parseBool(v string) bool {
switch strings.ToLower(strings.TrimSpace(v)) {
case "1", "true", "t", "yes", "y", "on":
return true
}
return false
}
+84
View File
@@ -0,0 +1,84 @@
package langfuse
import (
"testing"
"time"
)
func TestLoadConfigFromEnv_AutoEnablesWithCredentials(t *testing.T) {
t.Setenv("LANGFUSE_PUBLIC_KEY", "pk-test")
t.Setenv("LANGFUSE_SECRET_KEY", "sk-test")
t.Setenv("LANGFUSE_HOST", "https://example.langfuse.com")
cfg := LoadConfigFromEnv()
if !cfg.Enabled {
t.Fatalf("expected Enabled=true when both keys are set, got false")
}
if cfg.Host != "https://example.langfuse.com" {
t.Errorf("unexpected host: %q", cfg.Host)
}
if cfg.SampleRate != 1.0 {
t.Errorf("expected default SampleRate=1.0, got %v", cfg.SampleRate)
}
}
func TestLoadConfigFromEnv_DisabledWithoutKeys(t *testing.T) {
t.Setenv("LANGFUSE_PUBLIC_KEY", "")
t.Setenv("LANGFUSE_SECRET_KEY", "")
t.Setenv("LANGFUSE_ENABLED", "")
cfg := LoadConfigFromEnv()
if cfg.Enabled {
t.Fatalf("expected Enabled=false when no keys set")
}
}
func TestLoadConfigFromEnv_ExplicitDisableOverridesKeys(t *testing.T) {
t.Setenv("LANGFUSE_PUBLIC_KEY", "pk")
t.Setenv("LANGFUSE_SECRET_KEY", "sk")
t.Setenv("LANGFUSE_ENABLED", "false")
cfg := LoadConfigFromEnv()
if cfg.Enabled {
t.Fatalf("expected Enabled=false when LANGFUSE_ENABLED=false")
}
}
func TestLoadConfigFromEnv_FlushIntervalAcceptsSecondsAndDuration(t *testing.T) {
t.Setenv("LANGFUSE_PUBLIC_KEY", "pk")
t.Setenv("LANGFUSE_SECRET_KEY", "sk")
t.Setenv("LANGFUSE_FLUSH_INTERVAL", "500ms")
cfg := LoadConfigFromEnv()
if cfg.FlushInterval != 500*time.Millisecond {
t.Errorf("expected 500ms, got %v", cfg.FlushInterval)
}
t.Setenv("LANGFUSE_FLUSH_INTERVAL", "7")
cfg = LoadConfigFromEnv()
if cfg.FlushInterval != 7*time.Second {
t.Errorf("expected 7s (bare integer), got %v", cfg.FlushInterval)
}
}
func TestConfigValidate(t *testing.T) {
cases := []struct {
name string
cfg Config
wantErr bool
}{
{"disabled is always valid", Config{Enabled: false}, false},
{"enabled without host fails", Config{Enabled: true, PublicKey: "pk", SecretKey: "sk"}, true},
{"enabled without keys fails", Config{Enabled: true, Host: "https://x"}, true},
{"enabled with all fields passes", Config{Enabled: true, Host: "https://x", PublicKey: "pk", SecretKey: "sk"}, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
err := tc.cfg.Validate()
if (err != nil) != tc.wantErr {
t.Fatalf("err=%v wantErr=%v", err, tc.wantErr)
}
})
}
}
+40
View File
@@ -0,0 +1,40 @@
package langfuse
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// traceCtxKey is the exported context key defined in types/const.go. It lives
// there (not inside this package) so that logger.CloneContext — which rebuilds
// a stripped-down context on every request — can preserve the Langfuse trace
// without importing this package. If we kept the key private here, every
// CloneContext call would drop the trace and downstream LLM wrappers would
// each auto-create their own shallow trace, fragmenting a single HTTP request
// into many unrelated traces in the Langfuse UI.
var traceCtxKey = types.LangfuseTraceContextKey
// withTrace stores a *Trace on the context so downstream LLM wrappers can
// attach their generations to it.
func withTrace(ctx context.Context, t *Trace) context.Context {
if t == nil || ctx == nil {
return ctx
}
return context.WithValue(ctx, traceCtxKey, t)
}
// traceFromCtx retrieves the active trace, if any.
func traceFromCtx(ctx context.Context) (*Trace, bool) {
if ctx == nil {
return nil, false
}
t, ok := ctx.Value(traceCtxKey).(*Trace)
return t, ok && t != nil
}
// TraceFromContext is the public accessor used by HTTP middlewares and
// handlers that want to set the trace input/output on the active trace.
func TraceFromContext(ctx context.Context) (*Trace, bool) {
return traceFromCtx(ctx)
}
+67
View File
@@ -0,0 +1,67 @@
package langfuse
import (
"time"
)
// Langfuse ingestion API event envelope.
// https://api.reference.langfuse.com/#tag/ingestion
type ingestionEvent struct {
ID string `json:"id"`
Timestamp string `json:"timestamp"`
Type string `json:"type"`
Body interface{} `json:"body"`
}
// TokenUsage captures the input/output/total token counts reported by the
// underlying model, in Langfuse's canonical schema.
type TokenUsage struct {
Input int `json:"input,omitempty"`
Output int `json:"output,omitempty"`
Total int `json:"total,omitempty"`
Unit string `json:"unit,omitempty"`
}
// traceBody mirrors the /api/public/ingestion trace-create body.
type traceBody struct {
ID string `json:"id"`
Timestamp string `json:"timestamp,omitempty"`
Name string `json:"name,omitempty"`
UserID string `json:"userId,omitempty"`
SessionID string `json:"sessionId,omitempty"`
Release string `json:"release,omitempty"`
Environment string `json:"environment,omitempty"`
Input interface{} `json:"input,omitempty"`
Output interface{} `json:"output,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Tags []string `json:"tags,omitempty"`
Public bool `json:"public,omitempty"`
}
// observationBody is shared between span-create / generation-create /
// span-update / generation-update events (different fields are populated
// depending on the event type).
type observationBody struct {
ID string `json:"id,omitempty"`
TraceID string `json:"traceId,omitempty"`
ParentObservationID string `json:"parentObservationId,omitempty"`
Type string `json:"type,omitempty"` // SPAN, GENERATION, EVENT
Name string `json:"name,omitempty"`
StartTime string `json:"startTime,omitempty"`
EndTime string `json:"endTime,omitempty"`
Input interface{} `json:"input,omitempty"`
Output interface{} `json:"output,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Level string `json:"level,omitempty"` // DEFAULT | ERROR | WARNING
StatusMessage string `json:"statusMessage,omitempty"` // free-form
// Generation-specific fields
Model string `json:"model,omitempty"`
ModelParameters map[string]interface{} `json:"modelParameters,omitempty"`
Usage *TokenUsage `json:"usage,omitempty"`
CompletionStart string `json:"completionStartTime,omitempty"`
}
func isoTime(t time.Time) string {
return t.UTC().Format("2006-01-02T15:04:05.000Z")
}
+185
View File
@@ -0,0 +1,185 @@
package langfuse
import (
"context"
"math/rand"
"sync"
"sync/atomic"
"time"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/google/uuid"
)
// Manager is the public façade of the langfuse package. A singleton is
// installed via Init(); callers should treat a nil *Manager as "disabled"
// and still invoke methods — every public method tolerates a nil receiver.
type Manager struct {
cfg Config
client *client
queue chan ingestionEvent
done chan struct{}
workerWG sync.WaitGroup
closed atomic.Bool
// rng is used for sampling decisions. Guarded by rngMu because
// math/rand.Source isn't goroutine-safe.
rngMu sync.Mutex
rng *rand.Rand
}
var (
globalMu sync.RWMutex
global *Manager
)
// Init builds a Manager from cfg and installs it as the package-wide
// singleton. When cfg.Enabled is false this returns a disabled manager that
// behaves as a no-op for every public method.
func Init(cfg Config) (*Manager, error) {
if err := cfg.Validate(); err != nil {
return nil, err
}
m := &Manager{cfg: cfg}
if cfg.Enabled {
m.client = newClient(cfg)
m.queue = make(chan ingestionEvent, cfg.QueueSize)
m.done = make(chan struct{})
m.rng = rand.New(rand.NewSource(time.Now().UnixNano()))
m.workerWG.Add(1)
go m.runWorker()
}
globalMu.Lock()
global = m
globalMu.Unlock()
if cfg.Enabled {
logger.Infof(context.Background(),
"[Langfuse] enabled host=%s flush_at=%d flush_interval=%s sample_rate=%.2f",
cfg.Host, cfg.FlushAt, cfg.FlushInterval, cfg.SampleRate,
)
}
return m, nil
}
// GetManager returns the installed singleton, or nil if Init has not been
// called. Callers must tolerate a nil return.
func GetManager() *Manager {
globalMu.RLock()
defer globalMu.RUnlock()
return global
}
// Enabled reports whether the manager would actually emit events.
func (m *Manager) Enabled() bool {
return m != nil && m.cfg.Enabled && !m.closed.Load()
}
// Shutdown drains pending events, signals the worker to stop and waits for it.
// Safe to call multiple times.
func (m *Manager) Shutdown(ctx context.Context) error {
if m == nil || !m.cfg.Enabled {
return nil
}
if !m.closed.CompareAndSwap(false, true) {
return nil
}
close(m.done)
doneCh := make(chan struct{})
go func() {
m.workerWG.Wait()
close(doneCh)
}()
select {
case <-doneCh:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// enqueue drops silently when either disabled, full or closed. Langfuse is
// observability, not business logic — back-pressure or failures must never
// block the request path.
func (m *Manager) enqueue(ev ingestionEvent) {
if !m.Enabled() {
return
}
select {
case m.queue <- ev:
default:
if m.cfg.Debug {
logger.Warnf(context.Background(), "[Langfuse] queue full, dropping event type=%s", ev.Type)
}
}
}
// sample decides whether to emit based on SampleRate. Sampling is applied once
// per trace; observations attached to an already-sampled trace are always kept
// (Langfuse itself would drop orphaned observations anyway).
func (m *Manager) sample() bool {
if !m.Enabled() {
return false
}
if m.cfg.SampleRate >= 1.0 {
return true
}
m.rngMu.Lock()
defer m.rngMu.Unlock()
return m.rng.Float64() < m.cfg.SampleRate
}
// runWorker batches queued events and flushes them either when the batch
// reaches FlushAt, when FlushInterval elapses, or when the manager shuts down.
func (m *Manager) runWorker() {
defer m.workerWG.Done()
ticker := time.NewTicker(m.cfg.FlushInterval)
defer ticker.Stop()
buf := make([]ingestionEvent, 0, m.cfg.FlushAt)
flush := func(reason string) {
if len(buf) == 0 {
return
}
ctx, cancel := context.WithTimeout(context.Background(), m.cfg.RequestTimeout)
defer cancel()
if err := m.client.ingest(ctx, buf); err != nil && m.cfg.Debug {
logger.Warnf(ctx, "[Langfuse] flush (%s) failed: %v", reason, err)
}
buf = buf[:0]
}
for {
select {
case ev := <-m.queue:
buf = append(buf, ev)
if len(buf) >= m.cfg.FlushAt {
flush("batch-full")
}
case <-ticker.C:
flush("interval")
case <-m.done:
// Drain whatever remains in the queue before exiting.
for {
select {
case ev := <-m.queue:
buf = append(buf, ev)
if len(buf) >= m.cfg.FlushAt {
flush("batch-full-on-shutdown")
}
default:
flush("shutdown")
return
}
}
}
}
}
// newID returns a Langfuse-compatible UUIDv4.
func newID() string {
return uuid.New().String()
}
+130
View File
@@ -0,0 +1,130 @@
package langfuse
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"sync"
"testing"
"time"
)
// TestManager_DisabledIsNoop verifies that when the manager is disabled the
// public API is safe to call and produces no side effects.
func TestManager_DisabledIsNoop(t *testing.T) {
m, err := Init(Config{Enabled: false})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if m.Enabled() {
t.Fatal("expected disabled")
}
ctx, trace := m.StartTrace(context.Background(), TraceOptions{Name: "x"})
trace.Finish(nil, nil)
_, gen := m.StartGeneration(ctx, GenerationOptions{Name: "g", Model: "m"})
gen.Finish(nil, nil, nil)
if err := m.Shutdown(context.Background()); err != nil {
t.Fatalf("shutdown: %v", err)
}
}
// TestManager_FullRoundTrip boots a fake Langfuse server, runs a trace +
// generation through the manager, and asserts the ingested payload contains
// the expected ids, model name and usage.
func TestManager_FullRoundTrip(t *testing.T) {
var mu sync.Mutex
var batches []ingestionRequest
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/api/public/ingestion" {
t.Errorf("unexpected path: %s", r.URL.Path)
w.WriteHeader(404)
return
}
if auth := r.Header.Get("Authorization"); auth == "" {
t.Errorf("missing Authorization header")
}
body, _ := io.ReadAll(r.Body)
var req ingestionRequest
if err := json.Unmarshal(body, &req); err != nil {
t.Errorf("decode body: %v", err)
w.WriteHeader(400)
return
}
mu.Lock()
batches = append(batches, req)
mu.Unlock()
w.WriteHeader(200)
w.Write([]byte(`{}`))
}))
defer srv.Close()
m, err := Init(Config{
Enabled: true,
Host: srv.URL,
PublicKey: "pk",
SecretKey: "sk",
FlushAt: 1,
FlushInterval: 10 * time.Millisecond,
QueueSize: 16,
RequestTimeout: 2 * time.Second,
SampleRate: 1.0,
})
if err != nil {
t.Fatalf("init: %v", err)
}
ctx, trace := m.StartTrace(context.Background(), TraceOptions{
Name: "test.trace",
UserID: "user-42",
})
_, gen := m.StartGeneration(ctx, GenerationOptions{
Name: "chat.completion",
Model: "gpt-test",
Input: []map[string]string{{"role": "user", "content": "hi"}},
})
gen.Finish("hello", &TokenUsage{Input: 10, Output: 20, Total: 30, Unit: "TOKENS"}, nil)
trace.Finish("hello", nil)
if err := m.Shutdown(context.Background()); err != nil {
t.Fatalf("shutdown: %v", err)
}
mu.Lock()
defer mu.Unlock()
// We should have received at least:
// trace-create, generation-create, generation-update, trace-create(update)
// possibly split across multiple HTTP calls depending on batching.
var events []ingestionEvent
for _, b := range batches {
events = append(events, b.Batch...)
}
if len(events) < 4 {
t.Fatalf("expected >=4 events, got %d: %+v", len(events), events)
}
var sawGenerationUpdate bool
for _, ev := range events {
if ev.Type != "generation-update" {
continue
}
b, _ := json.Marshal(ev.Body)
var body observationBody
_ = json.Unmarshal(b, &body)
if body.Usage == nil || body.Usage.Total != 30 {
t.Errorf("expected usage total=30, got %+v", body.Usage)
}
if body.TraceID != trace.ID {
t.Errorf("generation trace id mismatch: got %s want %s", body.TraceID, trace.ID)
}
sawGenerationUpdate = true
}
if !sawGenerationUpdate {
t.Fatalf("no generation-update event found")
}
}
+99
View File
@@ -0,0 +1,99 @@
package langfuse
import (
"context"
"strconv"
"strings"
"github.com/Tencent/WeKnora/internal/types"
"github.com/gin-gonic/gin"
)
// GinMiddleware returns a Gin handler that opens a Langfuse trace for each
// incoming request that hits a traced path. The trace is auto-finished when
// the handler chain returns; individual LLM calls inside the handler attach
// their generations to this trace via the request context.
//
// Only paths matching shouldTrace are traced — static assets, health checks
// and polling endpoints are noisy and uninteresting.
func GinMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
mgr := GetManager()
if !mgr.Enabled() || !shouldTrace(c) {
c.Next()
return
}
ctx := c.Request.Context()
userID := extractUserID(ctx)
sessionID := extractSessionID(c)
opts := TraceOptions{
Name: c.Request.Method + " " + c.FullPath(),
UserID: userID,
SessionID: sessionID,
Metadata: map[string]interface{}{
"http.method": c.Request.Method,
"http.path": c.FullPath(),
"http.query": c.Request.URL.RawQuery,
},
Tags: []string{"http", strings.ToLower(c.Request.Method)},
}
if rid, ok := types.RequestIDFromContext(ctx); ok {
opts.Metadata["request_id"] = rid
}
newCtx, trace := mgr.StartTrace(ctx, opts)
c.Request = c.Request.WithContext(newCtx)
c.Next()
trace.Finish(map[string]interface{}{
"status": c.Writer.Status(),
}, map[string]interface{}{
"http.status_code": c.Writer.Status(),
"response.size": c.Writer.Size(),
})
}
}
// shouldTrace restricts tracing to chat / search / agent / evaluation
// endpoints where LLMs run. Everything else (auth, list, config, static…)
// is skipped to keep the Langfuse dashboard signal-to-noise high.
func shouldTrace(c *gin.Context) bool {
path := c.FullPath()
if path == "" {
return false
}
switch {
case strings.HasPrefix(path, "/api/v1/knowledge-chat"),
strings.HasPrefix(path, "/api/v1/agent-chat"),
strings.HasPrefix(path, "/api/v1/knowledge-search"),
strings.HasPrefix(path, "/api/v1/sessions") && strings.Contains(path, "generate_title"),
strings.HasPrefix(path, "/api/v1/initialization/remote/check"),
strings.HasPrefix(path, "/api/v1/initialization/embedding/test"),
strings.HasPrefix(path, "/api/v1/evaluation"):
return true
}
return false
}
func extractUserID(ctx context.Context) string {
if v, ok := ctx.Value(types.UserIDContextKey).(string); ok && v != "" {
return v
}
if v, ok := ctx.Value(types.TenantIDContextKey).(uint64); ok && v != 0 {
return "tenant:" + strconv.FormatUint(v, 10)
}
return ""
}
func extractSessionID(c *gin.Context) string {
if v := c.Param("session_id"); v != "" {
return v
}
if v := c.Param("id"); v != "" && strings.Contains(c.FullPath(), "/sessions/") {
return v
}
return ""
}
+209
View File
@@ -0,0 +1,209 @@
package langfuse
import (
"context"
"time"
)
// Trace represents an active root observation. A Trace is conceptually one
// "request" (e.g. a chat turn). Generations and spans attached to it roll up
// as children in the Langfuse UI.
type Trace struct {
ID string
manager *Manager
sampled bool
}
// Generation represents a single model invocation (LLM / embedding / VLM).
type Generation struct {
ID string
TraceID string
manager *Manager
sampled bool
startTime time.Time
model string
name string
}
// TraceOptions configures a new trace.
type TraceOptions struct {
Name string
UserID string
SessionID string
Input interface{}
Metadata map[string]interface{}
Tags []string
Environment string
Release string
}
// GenerationOptions configures a new generation observation.
type GenerationOptions struct {
Name string
Model string
Input interface{}
Metadata map[string]interface{}
ModelParameters map[string]interface{}
}
// StartTrace opens a new trace, stores its ID in the returned ctx, and returns
// a handle callers can finish with FinishTrace. When the manager is disabled
// or sampling excludes the trace, the returned *Trace is non-nil but all
// methods are no-ops so callers don't need nil checks.
func (m *Manager) StartTrace(ctx context.Context, opts TraceOptions) (context.Context, *Trace) {
if m == nil || !m.cfg.Enabled {
return ctx, &Trace{}
}
sampled := m.sample()
id := newID()
t := &Trace{ID: id, manager: m, sampled: sampled}
if sampled {
env := opts.Environment
if env == "" {
env = m.cfg.Environment
}
release := opts.Release
if release == "" {
release = m.cfg.Release
}
body := traceBody{
ID: id,
Timestamp: isoTime(time.Now()),
Name: opts.Name,
UserID: opts.UserID,
SessionID: opts.SessionID,
Input: opts.Input,
Metadata: opts.Metadata,
Tags: opts.Tags,
Environment: env,
Release: release,
}
m.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(time.Now()),
Type: "trace-create",
Body: body,
})
}
return withTrace(ctx, t), t
}
// Finish updates the trace with its final output. Safe to call on a disabled
// trace (no-op).
func (t *Trace) Finish(output interface{}, metadata map[string]interface{}) {
if t == nil || t.manager == nil || !t.sampled {
return
}
// "trace-create" events are also used to update traces in Langfuse —
// the server merges repeated events by ID. See the ingestion API docs.
body := traceBody{
ID: t.ID,
Output: output,
Metadata: metadata,
}
t.manager.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(time.Now()),
Type: "trace-create",
Body: body,
})
}
// StartGeneration opens a generation observation under the trace carried by
// ctx (or a newly auto-created trace if none is present).
func (m *Manager) StartGeneration(ctx context.Context, opts GenerationOptions) (context.Context, *Generation) {
if m == nil || !m.cfg.Enabled {
return ctx, &Generation{}
}
// If the caller hasn't opened a trace yet, create a shallow auto-trace so
// the generation has a parent. This keeps single-shot internal callers
// (e.g. test connections) observable.
trace, ok := traceFromCtx(ctx)
if !ok || trace == nil {
newCtx, t := m.StartTrace(ctx, TraceOptions{Name: opts.Name})
ctx = newCtx
trace = t
}
if !trace.sampled {
return ctx, &Generation{}
}
now := time.Now()
g := &Generation{
ID: newID(),
TraceID: trace.ID,
manager: m,
sampled: true,
startTime: now,
model: opts.Model,
name: opts.Name,
}
body := observationBody{
ID: g.ID,
TraceID: g.TraceID,
Type: "GENERATION",
Name: opts.Name,
StartTime: isoTime(now),
Input: opts.Input,
Metadata: opts.Metadata,
Model: opts.Model,
ModelParameters: opts.ModelParameters,
}
m.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(now),
Type: "generation-create",
Body: body,
})
return ctx, g
}
// Finish updates a generation with its final output, token usage and any
// error. A non-nil err marks the observation as ERROR level in Langfuse.
func (g *Generation) Finish(output interface{}, usage *TokenUsage, err error) {
if g == nil || g.manager == nil || !g.sampled {
return
}
level := "DEFAULT"
var statusMsg string
if err != nil {
level = "ERROR"
statusMsg = err.Error()
}
body := observationBody{
ID: g.ID,
TraceID: g.TraceID,
Type: "GENERATION",
EndTime: isoTime(time.Now()),
Output: output,
Usage: usage,
Level: level,
StatusMessage: statusMsg,
}
g.manager.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(time.Now()),
Type: "generation-update",
Body: body,
})
}
// MarkCompletionStart records the time at which the first token was received
// in a streaming generation. Langfuse surfaces this as time-to-first-token.
func (g *Generation) MarkCompletionStart(t time.Time) {
if g == nil || g.manager == nil || !g.sampled {
return
}
body := observationBody{
ID: g.ID,
TraceID: g.TraceID,
Type: "GENERATION",
CompletionStart: isoTime(t),
}
g.manager.enqueue(ingestionEvent{
ID: newID(),
Timestamp: isoTime(time.Now()),
Type: "generation-update",
Body: body,
})
}
+4
View File
@@ -23,6 +23,10 @@ const (
EmbedQueryContextKey ContextKey = "EmbedQuery"
// LanguageContextKey is the context key for user language preference (e.g. "zh-CN", "en-US")
LanguageContextKey ContextKey = "Language"
// LangfuseTraceContextKey carries the active Langfuse *Trace across the
// request lifecycle. Defined here (not inside the langfuse package) so
// that logger.CloneContext can preserve it without importing langfuse.
LangfuseTraceContextKey ContextKey = "LangfuseTrace"
)
// String returns the string representation of the context key