langfuse

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 15 Imported by: 0

README

Langfuse Go SDK

Langfuse Go SDK

Go Test Coverage Go Report Card Go Reference

Unofficial Go SDK for Langfuse - an open-source LLM engineering platform.

Installation

go get github.com/AEKurt/langfuse-go

Quick Start

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/AEKurt/langfuse-go"
)

func main() {
    // Initialize the client
    client, err := langfuse.NewClient(langfuse.Config{
        PublicKey: "your-public-key",
        SecretKey: "your-secret-key",
        // Optional: BaseURL defaults to https://cloud.langfuse.com
        // BaseURL: "https://cloud.langfuse.com",
    })
    if err != nil {
        log.Fatal(err)
    }

    // Create a trace
    ctx := context.Background()
    now := time.Now()
    trace, err := client.CreateTrace(ctx, langfuse.Trace{
        Name:      "my-trace",
        UserID:    "user-123",
        Metadata:  map[string]interface{}{
            "environment": "production",
        },
        Tags:      []string{"important", "test"},
        Timestamp: &now,
    })
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Created trace: %s\n", trace.ID)

    // Create a generation (LLM call)
    startTime := time.Now()
    generation, err := client.CreateGeneration(ctx, langfuse.Generation{
        TraceID: trace.ID,
        Name:    "chat-completion",
        Model:   "gpt-4",
        StartTime: &startTime,
        Input: map[string]interface{}{
            "messages": []map[string]interface{}{
                {"role": "user", "content": "Hello!"},
            },
        },
        Usage: &langfuse.Usage{
            Input:  10,
            Output: 20,
            Total:  30,
            Unit:   "TOKENS",
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    // Update the generation with output
    endTime := time.Now()
    _, err = client.UpdateGeneration(ctx, generation.ID, langfuse.GenerationUpdate{
        EndTime: &endTime,
        Output: map[string]interface{}{
            "messages": []map[string]interface{}{
                {"role": "assistant", "content": "Hi there!"},
            },
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    // Create a span
    spanStart := time.Now()
    span, err := client.CreateSpan(ctx, langfuse.Span{
        TraceID: trace.ID,
        Name:    "database-query",
        StartTime: &spanStart,
        Input: map[string]interface{}{
            "query": "SELECT * FROM users",
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    // Update span with output
    spanEnd := time.Now()
    _, err = client.UpdateSpan(ctx, span.ID, langfuse.SpanUpdate{
        EndTime: &spanEnd,
        Output: map[string]interface{}{
            "rows": 42,
        },
    })
    if err != nil {
        log.Fatal(err)
    }

    // Create a score
    _, err = client.Score(ctx, langfuse.Score{
        TraceID: trace.ID,
        Name:    "quality",
        Value:   0.95,
        Comment: "High quality response",
    })
    if err != nil {
        log.Fatal(err)
    }
}

API Reference

Client

NewClient(config Config) (*Client, error)

Creates a new Langfuse client.

Parameters:

  • config.PublicKey (string, required): Your Langfuse public key
  • config.SecretKey (string, required): Your Langfuse secret key
  • config.BaseURL (string, optional): Base URL for Langfuse API (defaults to https://cloud.langfuse.com)
  • config.HTTPClient (*http.Client, optional): Custom HTTP client
  • config.Logger (Logger, optional): Logger interface for debugging requests/responses

Traces

CreateTrace(ctx context.Context, trace Trace) (*TraceResponse, error)

Creates a new trace.

UpdateTrace(ctx context.Context, traceID string, trace TraceUpdate) (*TraceResponse, error)

Updates an existing trace.

Spans

CreateSpan(ctx context.Context, span Span) (*SpanResponse, error)

Creates a new span.

UpdateSpan(ctx context.Context, spanID string, span SpanUpdate) (*SpanResponse, error)

Updates an existing span.

Generations

CreateGeneration(ctx context.Context, generation Generation) (*GenerationResponse, error)

Creates a new generation (LLM call).

UpdateGeneration(ctx context.Context, generationID string, generation GenerationUpdate) (*GenerationResponse, error)

Updates an existing generation.

Events

CreateEvent(ctx context.Context, event Event) (*EventResponse, error)

Creates a new event.

Scores

Score(ctx context.Context, score Score) (*ScoreResponse, error)

Creates a score for a trace or observation.

Examples

Getting Started

See the examples/getting_started/ directory for a simple step-by-step example.

Basic Examples

See the examples/basic/ directory for basic usage examples.

Advanced Examples

See the examples/advanced/ directory for advanced features including:

  • W3C Trace Context support
  • Context manager pattern (Go equivalent of Python's with blocks)
  • Trace context propagation
  • Nested observations
  • Different observation types

Observe Wrapper Examples

See the examples/observe_wrapper/ directory for examples of wrapping functions with automatic observation tracking.

Error Handling Examples

See the examples/error_handling/ directory for examples of handling errors and edge cases.

Logger Examples

See the examples/logger/ directory for examples of using the logger interface for debugging.

Context Propagation Examples

See the examples/context_propagation/ directory for examples of propagating trace context across services.

Async/Batch Processing Examples

See the examples/async_batch/ directory for examples of high-performance async batch processing:

  • Background batch processing with configurable settings
  • High-volume concurrent writes
  • Manual flush and graceful shutdown

Specialized Observation Types Examples

See the examples/observation_types/ directory for examples of specialized observation types:

  • Agent, Tool, Chain, Retriever
  • Embedding, Evaluator, Guardrail
  • Context management with StartAsCurrent* methods

Advanced Features

W3C Trace Context

Generate W3C-compliant trace and observation IDs:

// Generate deterministic trace ID from external ID
externalID := "req_12345"
traceID := langfuse.CreateTraceID(externalID)

// Generate observation ID
obsID := langfuse.CreateObservationID()

// Get current trace/observation from context
if traceID, ok := langfuse.GetCurrentTraceID(ctx); ok {
    fmt.Printf("Current trace: %s\n", traceID)
}

Context Manager Pattern

Use StartObservation for automatic parent-child relationships:

// Start a root span
rootSpan, err := client.StartObservation(ctx, langfuse.ObservationTypeSpan, "my-operation", input)
if err != nil {
    return err
}
defer rootSpan.End()

// Create child observations
child, err := rootSpan.StartChildObservation(langfuse.ObservationTypeGeneration, "llm-call", prompt)
if err != nil {
    return err
}
defer child.End()

// Update observations
rootSpan.Update(langfuse.SpanUpdate{
    Output: result,
})

Trace Context Propagation

Propagate trace context across services:

// Create trace context
traceCtx := langfuse.TraceContext{
    TraceID: "existing-trace-id",
    SpanID:  "parent-span-id",
}
ctx := langfuse.WithTraceContext(ctx, traceCtx)

// New observations will join the existing trace
span, err := client.StartObservation(ctx, langfuse.ObservationTypeSpan, "downstream-task", input)

Async/Batch Processing

Use AsyncClient for high-performance production workloads:

// Create async client with batch processing
client, err := langfuse.NewAsyncClient(
    langfuse.Config{
        PublicKey: "pk-xxx",
        SecretKey: "sk-xxx",
    },
    langfuse.BatchConfig{
        MaxBatchSize:    100,              // Flush when 100 events queued
        FlushInterval:   5 * time.Second,  // Or flush every 5 seconds
        MaxRetries:      3,                // Retry failed requests
        ShutdownTimeout: 30 * time.Second, // Max wait on shutdown
        OnError: func(err error, events []langfuse.BatchEvent) {
            log.Printf("Failed to send %d events: %v", len(events), err)
        },
    },
)
if err != nil {
    log.Fatal(err)
}
defer func() { _ = client.Shutdown() }() // Always shutdown to flush pending events

// Async operations return immediately
traceID, _ := client.CreateTraceAsync(langfuse.Trace{Name: "my-trace"})
spanID, _ := client.CreateSpanAsync(langfuse.Span{TraceID: traceID, Name: "my-span"})

// Force flush when needed (e.g., before a response)
// Note: Flush() drains the queue channel; use Shutdown() for a guaranteed full flush.
if err := client.Flush(); err != nil {
    log.Printf("Flush error: %v", err)
}

Specialized Observation Types

Use specialized observation types for better categorization:

// Agent - reasoning blocks using LLM guidance
agent, _ := client.StartAgent(ctx, "my-agent", input)
defer agent.End()

// Tool - external tool calls (e.g., APIs)
tool, _ := client.StartTool(ctx, "api-call", input)
tool.Update(langfuse.SpanUpdate{Output: response})
tool.End()

// Chain - connecting LLM application steps
chain, _ := client.StartChain(ctx, "rag-chain", input)

// Retriever - data retrieval (e.g., vector stores)
retriever, _ := client.StartRetriever(ctx, "vector-search", query)

// Embedding - LLM embedding calls
embedding, _ := client.StartEmbedding(ctx, "embed", "text-embedding-3-small", text)

// Evaluator - assessing LLM outputs
evaluator, _ := client.StartEvaluator(ctx, "quality-check", response)

// Guardrail - protection against jailbreaks
guardrail, _ := client.StartGuardrail(ctx, "safety-filter", content)

Context-aware variants store the observation in context:

// Returns new context with observation stored
ctx, agent, _ := client.StartAsCurrentAgent(ctx, "my-agent", input)
defer agent.End()

// Get current observation from context
if obs, ok := langfuse.GetCurrentObservation(ctx); ok {
    fmt.Printf("Current: %s\n", obs.ID)
}

// Update current span via context
client.UpdateCurrentSpan(ctx, output, metadata)

Observe Wrapper

Wrap any function to automatically capture inputs, outputs, timings, and errors:

result, err := client.Observe(ctx, func(ctx context.Context) (string, error) {
    // Your function body — ctx carries the active trace
    return callLLM(ctx, prompt)
}, &langfuse.ObserveOptions{
    Name:          "llm-call",
    AsType:        langfuse.ObservationTypeGeneration,
    CaptureInput:  true,
    CaptureOutput: true,
})

The wrapper automatically records start/end time, output, and any error as a statusMessage.

Propagated Attributes

Attach session/user metadata once and have it flow automatically to all child spans:

// Set attributes that propagate to all observations created in this context
ctx = langfuse.WithPropagatedAttributes(ctx, langfuse.PropagatedAttributes{
    SessionID: "session-abc",
    UserID:    "user-123",
    Tags:      []string{"production"},
    Metadata:  map[string]interface{}{"region": "us-east-1"},
})

// Merge additional attributes without losing existing ones
ctx = langfuse.MergePropagatedAttributes(ctx, langfuse.PropagatedAttributes{
    Tags: []string{"feature-flag-x"},
})

// StartAsCurrentSpan picks up propagated attributes automatically
ctx, span, err := client.StartAsCurrentSpan(ctx, "my-op", input)

Development

Prerequisites

Testing

Run the test suite:

go test ./...
# or using make
make test

Run tests with race detector:

go test -v -race ./...
# or using make
make test-race

Coverage

Generate coverage report (opens HTML in browser):

make coverage

Check coverage against thresholds:

make check-coverage

View coverage in terminal:

go test -cover ./...

Linting

Run linter:

make lint

Available Make Commands

make help  # Show all available commands

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Before submitting:

  1. Run make test to ensure tests pass
  2. Run make lint to check for code issues
  3. Run make check-coverage to ensure coverage thresholds are met

Documentation

Index

Constants

View Source
const (
	// SDKVersion is the version of this SDK
	SDKVersion = "0.1.6"
	// DefaultBaseURL is the default Langfuse API base URL
	DefaultBaseURL = "https://cloud.langfuse.com"
	// DefaultTimeout is the default HTTP client timeout
	DefaultTimeout = 30 * time.Second
)

Variables

This section is empty.

Functions

func CreateObservationID

func CreateObservationID(seed ...string) string

CreateObservationID generates a W3C-compliant observation ID If seed is provided, the ID is deterministic (same seed = same ID)

func CreateTraceID

func CreateTraceID(seed ...string) string

CreateTraceID generates a W3C-compliant trace ID If seed is provided, the ID is deterministic (same seed = same ID) This is useful for correlating external IDs with Langfuse traces

func GetCurrentObservationID

func GetCurrentObservationID(ctx context.Context) (string, bool)

GetCurrentObservationID gets the current observation ID from context

func GetCurrentTraceID

func GetCurrentTraceID(ctx context.Context) (string, bool)

GetCurrentTraceID gets the current trace ID from context

func IsAPIError

func IsAPIError(err error) bool

IsAPIError checks if an error is an APIError It uses errors.As to properly handle wrapped errors

func MergePropagatedAttributes added in v0.1.4

func MergePropagatedAttributes(ctx context.Context, newAttrs PropagatedAttributes) context.Context

MergePropagatedAttributes merges existing propagated attributes with new ones New values override existing ones, tags and metadata are merged

func WithCurrentObservation added in v0.1.4

func WithCurrentObservation(ctx context.Context, obs *Observation) context.Context

WithCurrentObservation stores the current observation in context

func WithPropagatedAttributes added in v0.1.4

func WithPropagatedAttributes(ctx context.Context, attrs PropagatedAttributes) context.Context

WithPropagatedAttributes adds propagated attributes to context These attributes will be automatically applied to all child spans/generations

func WithTraceContext

func WithTraceContext(ctx context.Context, traceCtx TraceContext) context.Context

WithTraceContext adds trace context to a Go context

Types

type APIError

type APIError struct {
	StatusCode int
	Message    string
	Body       string
}

APIError represents an error returned by the Langfuse API

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

Unwrap returns nil as APIError is a leaf error type

type AsyncClient added in v0.1.4

type AsyncClient struct {
	*Client
	// contains filtered or unexported fields
}

AsyncClient wraps a Client with async batch processing

func NewAsyncClient added in v0.1.4

func NewAsyncClient(config Config, batchConfig BatchConfig) (*AsyncClient, error)

NewAsyncClient creates a new async client with batch processing

func (*AsyncClient) BatchProcessor added in v0.1.4

func (ac *AsyncClient) BatchProcessor() *BatchProcessor

BatchProcessor returns the underlying batch processor

func (*AsyncClient) CreateEventAsync added in v0.1.4

func (ac *AsyncClient) CreateEventAsync(event Event) (string, error)

CreateEventAsync creates an event asynchronously

func (*AsyncClient) CreateGenerationAsync added in v0.1.4

func (ac *AsyncClient) CreateGenerationAsync(gen Generation) (string, error)

CreateGenerationAsync creates a generation asynchronously

func (*AsyncClient) CreateSpanAsync added in v0.1.4

func (ac *AsyncClient) CreateSpanAsync(span Span) (string, error)

CreateSpanAsync creates a span asynchronously

func (*AsyncClient) CreateTraceAsync added in v0.1.4

func (ac *AsyncClient) CreateTraceAsync(trace Trace) (string, error)

CreateTraceAsync creates a trace asynchronously

func (*AsyncClient) Flush added in v0.1.4

func (ac *AsyncClient) Flush() error

Flush flushes all pending events synchronously

func (*AsyncClient) QueueLength added in v0.1.4

func (ac *AsyncClient) QueueLength() int

QueueLength returns the number of pending events

func (*AsyncClient) ScoreAsync added in v0.1.4

func (ac *AsyncClient) ScoreAsync(score Score) (string, error)

ScoreAsync creates a score asynchronously

func (*AsyncClient) Shutdown added in v0.1.4

func (ac *AsyncClient) Shutdown() error

Shutdown gracefully shuts down the async client

func (*AsyncClient) UpdateGenerationAsync added in v0.1.4

func (ac *AsyncClient) UpdateGenerationAsync(genID string, update GenerationUpdate) error

UpdateGenerationAsync updates a generation asynchronously

func (*AsyncClient) UpdateSpanAsync added in v0.1.4

func (ac *AsyncClient) UpdateSpanAsync(spanID string, update SpanUpdate) error

UpdateSpanAsync updates a span asynchronously

type BatchConfig added in v0.1.4

type BatchConfig struct {
	// MaxBatchSize is the maximum number of events to batch together (default: 100)
	MaxBatchSize int
	// FlushInterval is how often to flush the batch (default: 5 seconds)
	FlushInterval time.Duration
	// MaxRetries is the maximum number of retries for failed requests (default: 3)
	MaxRetries int
	// RetryDelay is the initial delay between retries (default: 1 second, exponential backoff)
	RetryDelay time.Duration
	// QueueSize is the size of the event queue (default: 10000)
	QueueSize int
	// OnError is called when an error occurs during batch processing
	OnError func(err error, events []BatchEvent)
	// ShutdownTimeout is the maximum time to wait for pending events during shutdown (default: 30 seconds)
	ShutdownTimeout time.Duration
}

BatchConfig holds configuration for the batch processor

func DefaultBatchConfig added in v0.1.4

func DefaultBatchConfig() BatchConfig

DefaultBatchConfig returns the default batch configuration

type BatchEvent added in v0.1.4

type BatchEvent struct {
	ID        string         `json:"id"`
	Type      BatchEventType `json:"type"`
	Timestamp time.Time      `json:"timestamp"`
	Body      interface{}    `json:"body"`
}

BatchEvent represents a single event in the batch

type BatchEventType added in v0.1.4

type BatchEventType string

BatchEventType represents the type of event in a batch

const (
	BatchEventTypeTrace            BatchEventType = "trace-create"
	BatchEventTypeSpan             BatchEventType = "span-create"
	BatchEventTypeSpanUpdate       BatchEventType = "span-update"
	BatchEventTypeGeneration       BatchEventType = "generation-create"
	BatchEventTypeGenerationUpdate BatchEventType = "generation-update"
	BatchEventTypeEvent            BatchEventType = "event-create"
	BatchEventTypeScore            BatchEventType = "score-create"
)

type BatchProcessor added in v0.1.4

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

BatchProcessor handles async batching of Langfuse events

func NewBatchProcessor added in v0.1.4

func NewBatchProcessor(client *Client, config BatchConfig) *BatchProcessor

NewBatchProcessor creates a new batch processor

func (*BatchProcessor) Enqueue added in v0.1.4

func (bp *BatchProcessor) Enqueue(event BatchEvent) error

Enqueue adds an event to the batch queue

func (*BatchProcessor) EnqueueEvent added in v0.1.4

func (bp *BatchProcessor) EnqueueEvent(event Event) error

EnqueueEvent enqueues an event creation

func (*BatchProcessor) EnqueueGeneration added in v0.1.4

func (bp *BatchProcessor) EnqueueGeneration(gen Generation) error

EnqueueGeneration enqueues a generation creation event

func (*BatchProcessor) EnqueueGenerationUpdate added in v0.1.4

func (bp *BatchProcessor) EnqueueGenerationUpdate(genID string, update GenerationUpdate) error

EnqueueGenerationUpdate enqueues a generation update event

func (*BatchProcessor) EnqueueScore added in v0.1.4

func (bp *BatchProcessor) EnqueueScore(score Score) error

EnqueueScore enqueues a score creation event

func (*BatchProcessor) EnqueueSpan added in v0.1.4

func (bp *BatchProcessor) EnqueueSpan(span Span) error

EnqueueSpan enqueues a span creation event

func (*BatchProcessor) EnqueueSpanUpdate added in v0.1.4

func (bp *BatchProcessor) EnqueueSpanUpdate(spanID string, update SpanUpdate) error

EnqueueSpanUpdate enqueues a span update event

func (*BatchProcessor) EnqueueTrace added in v0.1.4

func (bp *BatchProcessor) EnqueueTrace(trace Trace) error

EnqueueTrace enqueues a trace creation event

func (*BatchProcessor) Flush added in v0.1.4

func (bp *BatchProcessor) Flush() error

Flush forces an immediate flush of events currently in the queue channel. Note: events already consumed by the background processLoop into its local batch buffer are not captured here. For a guaranteed full flush, use Stop().

func (*BatchProcessor) QueueLength added in v0.1.4

func (bp *BatchProcessor) QueueLength() int

QueueLength returns the current number of events in the queue

func (*BatchProcessor) Start added in v0.1.4

func (bp *BatchProcessor) Start()

Start starts the batch processor

func (*BatchProcessor) Stop added in v0.1.4

func (bp *BatchProcessor) Stop() error

Stop stops the batch processor and waits for pending events to be flushed

type BatchRequest added in v0.1.4

type BatchRequest struct {
	Batch    []BatchEvent      `json:"batch"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

BatchRequest represents the batch API request

type BatchResponse added in v0.1.4

type BatchResponse struct {
	Successes int      `json:"successes"`
	Errors    []string `json:"errors,omitempty"`
}

BatchResponse represents the batch API response

type Client

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

Client represents the Langfuse client WARNING: Do not log or expose the secretKey field as it contains sensitive credentials.

func NewClient

func NewClient(config Config) (*Client, error)

NewClient creates a new Langfuse client

func (*Client) CreateEvent

func (c *Client) CreateEvent(ctx context.Context, event Event) (*EventResponse, error)

CreateEvent creates a new event

func (*Client) CreateGeneration

func (c *Client) CreateGeneration(ctx context.Context, generation Generation) (*GenerationResponse, error)

CreateGeneration creates a new generation

func (*Client) CreateSpan

func (c *Client) CreateSpan(ctx context.Context, span Span) (*SpanResponse, error)

CreateSpan creates a new span

func (*Client) CreateTrace

func (c *Client) CreateTrace(ctx context.Context, trace Trace) (*TraceResponse, error)

CreateTrace creates a new trace

func (*Client) Flush

func (c *Client) Flush() error

Flush flushes any pending events (for async implementations)

func (*Client) Observe

func (c *Client) Observe(ctx context.Context, fn interface{}, opts *ObserveOptions) (interface{}, error)

Observe wraps a function to automatically capture inputs, outputs, timings, and errors This is the Go equivalent of the observe decorator pattern

func (*Client) Score

func (c *Client) Score(ctx context.Context, score Score) (*ScoreResponse, error)

Score creates a score for a trace

func (*Client) Shutdown

func (c *Client) Shutdown() error

Shutdown gracefully shuts down the client

func (*Client) StartAgent added in v0.1.4

func (c *Client) StartAgent(ctx context.Context, name string, input interface{}) (*Observation, error)

StartAgent starts an agent observation (reasoning blocks using LLM guidance)

func (*Client) StartAsCurrentAgent added in v0.1.4

func (c *Client) StartAsCurrentAgent(ctx context.Context, name string, input interface{}) (context.Context, *Observation, error)

StartAsCurrentAgent starts an agent and stores it as the current observation

func (*Client) StartAsCurrentChain added in v0.1.4

func (c *Client) StartAsCurrentChain(ctx context.Context, name string, input interface{}) (context.Context, *Observation, error)

StartAsCurrentChain starts a chain and stores it as the current observation

func (*Client) StartAsCurrentEmbedding added in v0.1.4

func (c *Client) StartAsCurrentEmbedding(ctx context.Context, name string, model string, input interface{}) (context.Context, *Observation, error)

StartAsCurrentEmbedding starts an embedding and stores it as the current observation

func (*Client) StartAsCurrentEvaluator added in v0.1.4

func (c *Client) StartAsCurrentEvaluator(ctx context.Context, name string, input interface{}) (context.Context, *Observation, error)

StartAsCurrentEvaluator starts an evaluator and stores it as the current observation

func (*Client) StartAsCurrentGeneration added in v0.1.4

func (c *Client) StartAsCurrentGeneration(ctx context.Context, name string, model string, input interface{}) (context.Context, *Observation, error)

StartAsCurrentGeneration starts a generation and stores it as the current observation

func (*Client) StartAsCurrentGuardrail added in v0.1.4

func (c *Client) StartAsCurrentGuardrail(ctx context.Context, name string, input interface{}) (context.Context, *Observation, error)

StartAsCurrentGuardrail starts a guardrail and stores it as the current observation

func (*Client) StartAsCurrentRetriever added in v0.1.4

func (c *Client) StartAsCurrentRetriever(ctx context.Context, name string, input interface{}) (context.Context, *Observation, error)

StartAsCurrentRetriever starts a retriever and stores it as the current observation

func (*Client) StartAsCurrentSpan added in v0.1.4

func (c *Client) StartAsCurrentSpan(ctx context.Context, name string, input interface{}) (context.Context, *Observation, error)

StartAsCurrentSpan starts a span and stores it as the current observation in context

func (*Client) StartAsCurrentTool added in v0.1.4

func (c *Client) StartAsCurrentTool(ctx context.Context, name string, input interface{}) (context.Context, *Observation, error)

StartAsCurrentTool starts a tool and stores it as the current observation

func (*Client) StartChain added in v0.1.4

func (c *Client) StartChain(ctx context.Context, name string, input interface{}) (*Observation, error)

StartChain starts a chain observation (connecting LLM application steps)

func (*Client) StartEmbedding added in v0.1.4

func (c *Client) StartEmbedding(ctx context.Context, name string, model string, input interface{}) (*Observation, error)

StartEmbedding starts an embedding observation (LLM embedding calls)

func (*Client) StartEvaluator added in v0.1.4

func (c *Client) StartEvaluator(ctx context.Context, name string, input interface{}) (*Observation, error)

StartEvaluator starts an evaluator observation (assessing LLM outputs)

func (*Client) StartGuardrail added in v0.1.4

func (c *Client) StartGuardrail(ctx context.Context, name string, input interface{}) (*Observation, error)

StartGuardrail starts a guardrail observation (protection against jailbreaks, etc.)

func (*Client) StartObservation

func (c *Client) StartObservation(ctx context.Context, obsType ObservationType, name string, input interface{}) (*Observation, error)

StartObservation starts a new observation and returns an Observation handle This is the Go equivalent of the context manager pattern

func (*Client) StartRetriever added in v0.1.4

func (c *Client) StartRetriever(ctx context.Context, name string, input interface{}) (*Observation, error)

StartRetriever starts a retriever observation (data retrieval, e.g., vector stores)

func (*Client) StartTool added in v0.1.4

func (c *Client) StartTool(ctx context.Context, name string, input interface{}) (*Observation, error)

StartTool starts a tool observation (external tool calls, e.g., APIs)

func (*Client) UpdateCurrentSpan added in v0.1.4

func (c *Client) UpdateCurrentSpan(ctx context.Context, output interface{}, metadata map[string]interface{}) error

UpdateCurrentSpan updates the current span/observation from context

func (*Client) UpdateGeneration

func (c *Client) UpdateGeneration(ctx context.Context, generationID string, generation GenerationUpdate) (*GenerationResponse, error)

UpdateGeneration updates an existing generation by posting with the same ID (upsert)

func (*Client) UpdateSpan

func (c *Client) UpdateSpan(ctx context.Context, spanID string, span SpanUpdate) (*SpanResponse, error)

UpdateSpan updates an existing span by posting with the same ID (upsert)

func (*Client) UpdateTrace

func (c *Client) UpdateTrace(ctx context.Context, traceID string, trace TraceUpdate) (*TraceResponse, error)

UpdateTrace updates an existing trace by posting with the same ID (upsert)

type Completion

type Completion struct {
	Raw      string                   `json:"raw,omitempty"`
	Messages []map[string]interface{} `json:"messages,omitempty"`
}

Completion represents completion information

type Config

type Config struct {
	PublicKey  string
	SecretKey  string
	BaseURL    string // Optional, defaults to https://cloud.langfuse.com
	HTTPClient *http.Client
	Logger     Logger // Optional logger for debugging
}

Config holds the configuration for the Langfuse client

type CurrentObservationKey added in v0.1.4

type CurrentObservationKey struct{}

CurrentObservationKey is the context key for storing current observation

type Event

type Event struct {
	ID                  string                 `json:"id,omitempty"`
	TraceID             string                 `json:"traceId,omitempty"`
	Name                string                 `json:"name,omitempty"`
	StartTime           *time.Time             `json:"startTime,omitempty"`
	Metadata            map[string]interface{} `json:"metadata,omitempty"`
	Input               interface{}            `json:"input,omitempty"`
	Output              interface{}            `json:"output,omitempty"`
	Level               Level                  `json:"level,omitempty"`
	ParentObservationID string                 `json:"parentObservationId,omitempty"`
}

Event represents an event in Langfuse

func NewEvent

func NewEvent(traceID, name string) Event

NewEvent creates a new event with a generated ID

type EventResponse

type EventResponse struct {
	ID string `json:"id"`
}

EventResponse represents the response from creating an event

type Generation

type Generation struct {
	ID                  string                 `json:"id,omitempty"`
	TraceID             string                 `json:"traceId,omitempty"`
	Name                string                 `json:"name,omitempty"`
	StartTime           *time.Time             `json:"startTime,omitempty"`
	EndTime             *time.Time             `json:"endTime,omitempty"`
	Model               string                 `json:"model,omitempty"`
	ModelParameters     map[string]interface{} `json:"modelParameters,omitempty"`
	Input               interface{}            `json:"input,omitempty"`
	Output              interface{}            `json:"output,omitempty"`
	Metadata            map[string]interface{} `json:"metadata,omitempty"`
	Level               Level                  `json:"level,omitempty"`
	StatusMessage       string                 `json:"statusMessage,omitempty"`
	ParentObservationID string                 `json:"parentObservationId,omitempty"`
	Usage               *Usage                 `json:"usage,omitempty"`
	Prompt              *Prompt                `json:"prompt,omitempty"`
	Completion          *Completion            `json:"completion,omitempty"`
}

Generation represents a generation (LLM call) in Langfuse

func NewGeneration

func NewGeneration(traceID, name string) Generation

NewGeneration creates a new generation with a generated ID

type GenerationResponse

type GenerationResponse struct {
	ID string `json:"id"`
}

GenerationResponse represents the response from creating/updating a generation

type GenerationUpdate

type GenerationUpdate struct {
	Name            *string                `json:"name,omitempty"`
	EndTime         *time.Time             `json:"endTime,omitempty"`
	Model           *string                `json:"model,omitempty"`
	ModelParameters map[string]interface{} `json:"modelParameters,omitempty"`
	Input           interface{}            `json:"input,omitempty"`
	Output          interface{}            `json:"output,omitempty"`
	Metadata        map[string]interface{} `json:"metadata,omitempty"`
	Level           *Level                 `json:"level,omitempty"`
	StatusMessage   *string                `json:"statusMessage,omitempty"`
	Usage           *Usage                 `json:"usage,omitempty"`
	Prompt          *Prompt                `json:"prompt,omitempty"`
	Completion      *Completion            `json:"completion,omitempty"`
}

GenerationUpdate represents an update to a generation

type Level

type Level string

Level represents the log level for traces and observations

const (
	// LevelDefault is the default level
	LevelDefault Level = "DEFAULT"
	// LevelDebug is for debug messages
	LevelDebug Level = "DEBUG"
	// LevelInfo is for informational messages
	LevelInfo Level = "INFO"
	// LevelWarning is for warning messages
	LevelWarning Level = "WARNING"
	// LevelError is for error messages
	LevelError Level = "ERROR"
)

type Logger

type Logger interface {
	LogRequest(method, url string, body interface{})
	LogResponse(statusCode int, body []byte, err error)
}

Logger is an interface for logging requests and responses

type Observation

type Observation struct {
	Type         ObservationType
	ID           string
	TraceID      string
	ParentSpanID string
	// contains filtered or unexported fields
}

Observation represents an active observation that can be updated

func GetCurrentObservation added in v0.1.4

func GetCurrentObservation(ctx context.Context) (*Observation, bool)

GetCurrentObservation retrieves the current observation from context

func (*Observation) Context

func (o *Observation) Context() context.Context

Context returns the context with trace information

func (*Observation) End

func (o *Observation) End() error

End ends the observation by updating it with end time

func (*Observation) StartChildObservation

func (o *Observation) StartChildObservation(obsType ObservationType, name string, input interface{}) (*Observation, error)

StartChildObservation starts a child observation within this observation's context

func (*Observation) Update

func (o *Observation) Update(update interface{}) error

Update updates the observation with new data

type ObservationType

type ObservationType string

ObservationType represents the type of observation

const (
	// ObservationTypeSpan represents a span observation
	ObservationTypeSpan ObservationType = "span"
	// ObservationTypeGeneration represents a generation observation
	ObservationTypeGeneration ObservationType = "generation"
	// ObservationTypeEvent represents an event observation
	ObservationTypeEvent ObservationType = "event"
	// ObservationTypeAgent represents an agent observation (reasoning blocks using LLM guidance)
	ObservationTypeAgent ObservationType = "agent"
	// ObservationTypeTool represents a tool observation (external tool calls, e.g., APIs)
	ObservationTypeTool ObservationType = "tool"
	// ObservationTypeChain represents a chain observation (connecting LLM application steps)
	ObservationTypeChain ObservationType = "chain"
	// ObservationTypeRetriever represents a retriever observation (data retrieval, e.g., vector stores)
	ObservationTypeRetriever ObservationType = "retriever"
	// ObservationTypeEmbedding represents an embedding observation (LLM embedding calls)
	ObservationTypeEmbedding ObservationType = "embedding"
	// ObservationTypeEvaluator represents an evaluator observation (assessing LLM outputs)
	ObservationTypeEvaluator ObservationType = "evaluator"
	// ObservationTypeGuardrail represents a guardrail observation (protection against jailbreaks, etc.)
	ObservationTypeGuardrail ObservationType = "guardrail"
)

type ObserveOptions

type ObserveOptions struct {
	Name          string
	AsType        ObservationType
	CaptureInput  bool
	CaptureOutput bool
}

ObserveOptions configures the observe wrapper behavior

type Prompt

type Prompt struct {
	Raw      string                   `json:"raw,omitempty"`
	Messages []map[string]interface{} `json:"messages,omitempty"`
}

Prompt represents prompt information

type PropagatedAttributes added in v0.1.4

type PropagatedAttributes struct {
	SessionID string
	UserID    string
	Tags      []string
	Metadata  map[string]interface{}
}

PropagatedAttributes holds attributes that propagate to all child spans

func GetPropagatedAttributes added in v0.1.4

func GetPropagatedAttributes(ctx context.Context) (PropagatedAttributes, bool)

GetPropagatedAttributes retrieves propagated attributes from context

type PropagatedAttributesKey added in v0.1.4

type PropagatedAttributesKey struct{}

PropagatedAttributesKey is the context key for storing propagated attributes

type Score

type Score struct {
	ID            string  `json:"id,omitempty"`
	TraceID       string  `json:"traceId,omitempty"`
	Name          string  `json:"name"`
	Value         float64 `json:"value"`
	ObservationID string  `json:"observationId,omitempty"`
	Comment       string  `json:"comment,omitempty"`
}

Score represents a score in Langfuse

func NewScore

func NewScore(traceID, name string, value float64) Score

NewScore creates a new score with a generated ID

type ScoreResponse

type ScoreResponse struct {
	ID string `json:"id"`
}

ScoreResponse represents the response from creating a score

type Span

type Span struct {
	ID                  string                 `json:"id,omitempty"`
	TraceID             string                 `json:"traceId,omitempty"`
	Name                string                 `json:"name,omitempty"`
	StartTime           *time.Time             `json:"startTime,omitempty"`
	EndTime             *time.Time             `json:"endTime,omitempty"`
	Metadata            map[string]interface{} `json:"metadata,omitempty"`
	Input               interface{}            `json:"input,omitempty"`
	Output              interface{}            `json:"output,omitempty"`
	Level               Level                  `json:"level,omitempty"`
	StatusMessage       string                 `json:"statusMessage,omitempty"`
	ParentObservationID string                 `json:"parentObservationId,omitempty"`
}

Span represents a span in Langfuse

func NewSpan

func NewSpan(traceID, name string) Span

NewSpan creates a new span with a generated ID

type SpanResponse

type SpanResponse struct {
	ID string `json:"id"`
}

SpanResponse represents the response from creating/updating a span

type SpanUpdate

type SpanUpdate struct {
	Name          *string                `json:"name,omitempty"`
	EndTime       *time.Time             `json:"endTime,omitempty"`
	Metadata      map[string]interface{} `json:"metadata,omitempty"`
	Input         interface{}            `json:"input,omitempty"`
	Output        interface{}            `json:"output,omitempty"`
	Level         *Level                 `json:"level,omitempty"`
	StatusMessage *string                `json:"statusMessage,omitempty"`
}

SpanUpdate represents an update to a span

type Trace

type Trace struct {
	ID         string                 `json:"id,omitempty"`
	Name       string                 `json:"name,omitempty"`
	UserID     string                 `json:"userId,omitempty"`
	SessionID  string                 `json:"sessionId,omitempty"`
	Version    string                 `json:"version,omitempty"`
	Release    string                 `json:"release,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"`
	Timestamp  *time.Time             `json:"timestamp,omitempty"`
	ExternalID string                 `json:"externalId,omitempty"`
	Level      Level                  `json:"level,omitempty"`
}

Trace represents a trace in Langfuse

func NewTrace

func NewTrace(name string) Trace

NewTrace creates a new trace with a generated ID

type TraceContext

type TraceContext struct {
	TraceID      string
	SpanID       string // Current observation ID
	ParentSpanID string
}

TraceContext holds trace and observation IDs for context propagation

func GetTraceContext

func GetTraceContext(ctx context.Context) (TraceContext, bool)

GetTraceContext retrieves trace context from a Go context

type TraceContextKey

type TraceContextKey struct{}

TraceContextKey is the context key for storing trace context

type TraceResponse

type TraceResponse struct {
	ID string `json:"id"`
}

TraceResponse represents the response from creating/updating a trace

type TraceUpdate

type TraceUpdate struct {
	Name      *string                `json:"name,omitempty"`
	UserID    *string                `json:"userId,omitempty"`
	SessionID *string                `json:"sessionId,omitempty"`
	Version   *string                `json:"version,omitempty"`
	Release   *string                `json:"release,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"`
	Level     *Level                 `json:"level,omitempty"`
}

TraceUpdate represents an update to a trace

type Usage

type Usage struct {
	Input  int    `json:"input,omitempty"`
	Output int    `json:"output,omitempty"`
	Total  int    `json:"total,omitempty"`
	Unit   string `json:"unit,omitempty"` // TOKENS, CHARACTERS, etc.
}

Usage represents token usage information

Directories

Path Synopsis
examples
advanced command
async_batch command
basic command
error_handling command
getting_started command
logger command
observe_wrapper command

Jump to

Keyboard shortcuts

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