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:
@@ -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] + "..."
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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 ""
|
||||
}
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user