langfuse

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 7, 2026 License: Apache-2.0 Imports: 12 Imported by: 9

README

Langfuse Callbacks

English | 简体中文

A Langfuse callback implementation for Eino that implements the Handler interface. This enables seamless integration with Eino's application for enhanced observability and tracing.

Features

  • Implements github.com/cloudwego/eino/callbacks.Handler interface
  • Full support for Langfuse trace, span, and generation tracking
  • Automatic handling of streaming inputs and outputs
  • Flexible trace configuration with session, user, and metadata support
  • Built-in error handling and recovery
  • Configurable batching, sampling, and retry mechanisms
  • Easy integration with Eino's application

Installation

go get github.com/cloudwego/eino-ext/callbacks/langfuse

Quick Start

package main

import (
	"context"
	"log"

	"github.com/cloudwego/eino-ext/callbacks/langfuse"
	"github.com/cloudwego/eino/callbacks"
)

func main() {
	ctx := context.Background()
	
	cbh, flusher := langfuse.NewLangfuseHandler(&langfuse.Config{
		Host:        "https://cloud.langfuse.com",
		PublicKey:   "pk-lf-...",
		SecretKey:   "sk-lf-...",
		ServiceName: "eino-app",
		Release:     "v1.0.0",
	})
	
	callbacks.AppendGlobalHandlers(cbh)
	
	g := NewGraph[string, string]()
	runner, _ := g.Compile(ctx)
	
	ctx = langfuse.SetTrace(ctx, 
		langfuse.WithSessionID("session-123"), 
		langfuse.WithUserID("user-456"),
	)
	
	result, _ := runner.Invoke(ctx, "input")
	
	flusher()
}

Configuration

The callback can be configured using the Config struct:

type Config struct {
    // Host is the Langfuse server URL (Required)
    // Example: "https://cloud.langfuse.com"
    Host string
    
    // PublicKey is the public key for authentication (Required)
    // Example: "pk-lf-..."
    PublicKey string
    
    // SecretKey is the secret key for authentication (Required)
    // Example: "sk-lf-..."
    SecretKey string
    
    // Threads is the number of concurrent workers (Optional)
    // Default: 1
    Threads int
    
    // Timeout is the HTTP request timeout (Optional)
    // Default: no timeout
    Timeout time.Duration
    
    // MaxTaskQueueSize is the max number of events to buffer (Optional)
    // Default: 100
    MaxTaskQueueSize int

    // MaxEventSizeBytes is the maximum size of an event before large fields are truncated (Optional)
    // Default: 1_000_000
    MaxEventSizeBytes int
    
    // FlushAt is the number of events to batch before sending (Optional)
    // Default: 15
    FlushAt int
    
    // FlushInterval is how often to flush events automatically (Optional)
    // Default: 500ms
    FlushInterval time.Duration
    
    // SampleRate is the percentage of events to send (Optional)
    // Default: 1.0 (100%)
    SampleRate float64
    
    // LogMessage is the message prefix for logs (Optional)
    LogMessage string
    
    // MaskFunc is a function to mask sensitive data (Optional)
    MaskFunc func(string) string
    
    // MaxRetry is the maximum number of retry attempts (Optional)
    // Default: 3
    MaxRetry uint64
    
    // Name is the default trace name (Optional)
    Name string
    
    // UserID is the default user identifier (Optional)
    UserID string
    
    // SessionID is the default session identifier (Optional)
    SessionID string
    
    // Release is the version identifier (Optional)
    Release string
    
    // Tags are labels attached to traces (Optional)
    Tags []string
    
    // Public determines if traces are publicly accessible (Optional)
    Public bool
}

Trace Options

You can customize individual traces using the SetTrace function:

ctx = langfuse.SetTrace(ctx,
    langfuse.WithID("trace-id"),
    langfuse.WithName("custom-trace"),
    langfuse.WithUserID("user-123"),
    langfuse.WithSessionID("session-456"),
    langfuse.WithTags("production", "feature-x"),
    langfuse.WithMetadata(map[string]string{"key": "value"}),
    langfuse.WithInput("user query text"),
    langfuse.WithEnvironment("production"),
    langfuse.WithVersion("v1.0.0"),
    langfuse.WithPublic(true),
)

For More Details

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetTrace

func SetTrace(ctx context.Context, opts ...TraceOption) context.Context

Types

type CallbackHandler

type CallbackHandler struct {
	// contains filtered or unexported fields
}

func NewLangfuseHandler

func NewLangfuseHandler(cfg *Config) (handler *CallbackHandler, flusher func())

func (*CallbackHandler) OnEnd

func (*CallbackHandler) OnEndWithStreamOutput

func (*CallbackHandler) OnError

func (c *CallbackHandler) OnError(ctx context.Context, info *callbacks.RunInfo, err error) context.Context

func (*CallbackHandler) OnStart

func (*CallbackHandler) OnStartWithStreamInput

func (c *CallbackHandler) OnStartWithStreamInput(ctx context.Context, info *callbacks.RunInfo, input *schema.StreamReader[callbacks.CallbackInput]) context.Context

func (*CallbackHandler) UpdateTraceOutput

func (c *CallbackHandler) UpdateTraceOutput(ctx context.Context, traceID string, output string)

UpdateTraceOutput pushes final trace output to Langfuse (via ACL EndTrace). ctx is reserved for future cancellation / deadline propagation; callers may pass context.Background() for now.

type Config

type Config struct {
	// Host is the Langfuse server URL (Required)
	// Example: "https://cloud.langfuse.com"
	Host string

	// PublicKey is the public key for authentication (Required)
	// Example: "pk-lf-..."
	PublicKey string

	// SecretKey is the secret key for authentication (Required)
	// Example: "sk-lf-..."
	SecretKey string

	// Threads is the number of concurrent workers for processing events (Optional)
	// Default: 1
	// Example: 5
	Threads int

	// Timeout is the HTTP request timeout (Optional)
	// Default: no timeout
	// Example: 30 * time.Second
	Timeout time.Duration

	// MaxTaskQueueSize is the maximum number of events to buffer (Optional)
	// Default: 100
	// Example: 1000
	MaxTaskQueueSize int

	// MaxEventSizeBytes is the maximum size of an event before large fields are truncated (Optional)
	// Default: 1_000_000
	// Example: 2_000_000
	MaxEventSizeBytes int

	// FlushAt is the number of events to batch before sending (Optional)
	// Default: 15
	// Example: 50
	FlushAt int

	// FlushInterval is how often to flush events automatically (Optional)
	// Default: 500 * time.MilliSecond
	// Example: 10 * time.Second
	FlushInterval time.Duration

	// SampleRate is the percentage of events to send (Optional)
	// Default: 1.0 (100%)
	// Example: 0.5 (50%)
	SampleRate float64

	// LogMessage is the message to log when events exceed the limit length(1 000 000)  (Optional)
	// Default: ""
	// Example: "langfuse event:"
	LogMessage string

	// MaskFunc is a function to mask sensitive data before sending (Optional)
	// Default: nil
	// Example: func(s string) string { return strings.ReplaceAll(s, "secret", "***") }
	MaskFunc func(string) string

	// MaxRetry is the maximum number of retry attempts for failed requests (Optional)
	// Default: 3
	// Example: 5
	MaxRetry uint64

	// Name is the trace name (Optional)
	// Default: ""
	// Example: "my-app-trace"
	Name string

	// UserID is the user identifier for the trace (Optional)
	// Default: ""
	// Example: "user-123"
	UserID string

	// SessionID is the session identifier for the trace (Optional)
	// Default: ""
	// Example: "session-456"
	SessionID string

	// Release is the version or release identifier (Optional)
	// Default: ""
	// Example: "v1.2.3"
	Release string

	// Tags are labels attached to the trace (Optional)
	// Default: nil
	// Example: []string{"production", "feature-x"}
	Tags []string

	// Public determines if the trace is publicly accessible (Optional)
	// Default: false
	// Example: true
	Public bool
}

type TraceOption

type TraceOption func(*traceOptions)

func WithEnvironment

func WithEnvironment(environment string) TraceOption

func WithID

func WithID(id string) TraceOption

func WithInput

func WithInput(input string) TraceOption

func WithMetadata

func WithMetadata(metadata map[string]string) TraceOption

func WithName

func WithName(name string) TraceOption

func WithPublic

func WithPublic(public bool) TraceOption

func WithRelease

func WithRelease(release string) TraceOption

func WithSessionID

func WithSessionID(sessionID string) TraceOption

func WithTags

func WithTags(tags ...string) TraceOption

func WithUserID

func WithUserID(userID string) TraceOption

func WithVersion

func WithVersion(version string) TraceOption

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL