Files
Enterprise-Knowledge-Base/internal/tracing/langfuse/client.go
T
wizardchen 492e92580b feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).

Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
  LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
  the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
  so logger.CloneContext can preserve it across handler / goroutine
  boundaries (otherwise each LLM call auto-created an orphan trace,
  fragmenting one request into many)

Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes

Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.

Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
  reuses WeKnora's existing PostgreSQL (separate database via an idempotent
  init container that fixes ICU collation drift) and Redis (separate DB
  number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
  to avoid Prisma P1013 when passwords contain @ / # / etc.

Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-24 10:29:19 +08:00

86 lines
2.3 KiB
Go

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] + "..."
}