langfuse

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

README

langfuse-go GitHub CI Go Report Card LICENSE GoDoc

Go client & SDK for interacting with Langfuse. Provides comprehensive support for observability tracing, prompt management, model configuration, datasets, sessions, scores, projects, LLM connections, and organization management with efficient batch processing.

Table of Contents

API Reference

Core Observability

Core functionality for tracking and monitoring your AI applications with distributed tracing, session management, and contextual comments.

Tracing
import (
    "context"

    langfuse "github.com/git-hulk/langfuse-go"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()
    trace := langfuse.StartTrace(ctx, "it's a trace")
    span := trace.StartSpan("it's a span")
    span.End()
    trace.End()
    langfuse.Close() // flushes all pending traces
}
Sessions
import (
    "context"
    "time"

    langfuse "github.com/git-hulk/langfuse-go"
    "github.com/git-hulk/langfuse-go/pkg/sessions"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    // Get a session by ID with its traces
    session, err := langfuse.Sessions().Get(ctx, "session-123")

    // List sessions with filters
    sessionsList, err := langfuse.Sessions().List(ctx, sessions.ListParams{
        Page:          1,
        Limit:         10,
        FromTimestamp: time.Now().Add(-24 * time.Hour),
        ToTimestamp:   time.Now(),
        Environment:   []string{"production"},
    })
}
Comments
import (
    "context"

    langfuse "github.com/git-hulk/langfuse-go"
    "github.com/git-hulk/langfuse-go/pkg/comments"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    // Create a comment on a trace
    createdComment, err := langfuse.Comments().Create(ctx, &comments.CreateCommentRequest{
        ObjectType: comments.ObjectTypeTrace,
        ObjectID:   "trace-123",
        Content:    "This trace looks good!",
    })

    // Get a comment by ID
    comment, err := langfuse.Comments().Get(ctx, "comment-id")

    // List comments with filters
    commentsList, err := langfuse.Comments().List(ctx, comments.ListParams{
        ObjectType: comments.ObjectTypeTrace,
        ObjectID:   "trace-123",
        Page:       1,
        Limit:      10,
    })
}

AI/ML Management

Tools for managing prompts, models, evaluation scores, and LLM provider connections for your AI applications.

Prompts
import (
    "context"

    langfuse "github.com/git-hulk/langfuse-go"
    "github.com/git-hulk/langfuse-go/pkg/prompts"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    createdPrompt, err := langfuse.Prompts().Create(ctx, prompts.PromptEntry{
        Name: "welcome-message",
        Prompt: []prompts.ChatMessageWithPlaceHolder {
            {Role: "system", Content: "You are a helpful assistant."},
            {Role: "user", Content: "Hello!"},
        }
	})

    prompt, err := langfuse.Prompts().Get(ctx, prompts.GetParams{Name: "welcome-message"})

    listResponse, err := langfuse.Prompts().List(ctx, prompts.ListParams{Limit: 20})

    // Compile a text prompt
    textPrompt, err := langfuse.Prompts().Get(ctx, prompts.GetParams{
        Name: "welcome-message-text",
        Label: "latest",
        Version: 1,
    })
    compiledText, err := textPrompt.Compile(map[string]any{
        "name": "Alice",
    })
    renderedText := compiledText.(string)

    // Compile a chat prompt with placeholders
    compiledChat, err := prompt.Compile(map[string]any{
        "user": "Bob",
        "examples": []prompts.ChatMessageWithPlaceHolder{
            {Role: "user", Content: "Hello {{ user }}"},
        },
    })
    chatMessages := compiledChat.([]prompts.ChatMessageWithPlaceHolder)
}
Models
import (
    "context"

    langfuse "github.com/git-hulk/langfuse-go"
    "github.com/git-hulk/langfuse-go/pkg/models"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    // Create a new model
    createdModel, err := langfuse.Models().Create(ctx, &models.ModelEntry{
        ModelName:    "gpt-4",
        MatchPattern: "gpt-4*",
        InputPrice:   0.03,
        OutputPrice:  0.06,
        Unit:         "TOKENS",
    })

    // Get a model by ID
    model, err := langfuse.Models().Get(ctx, "model-id")

    // List models
    listModels, err := langfuse.Models().List(ctx, models.ListParams{
        Page:  1,
        Limit: 20,
    })

    // Delete a model
    err = langfuse.Models().Delete(ctx, "model-id")
}
Scores
import (
    "context"

    langfuse "github.com/git-hulk/langfuse-go"
    "github.com/git-hulk/langfuse-go/pkg/scores"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    // Create a score for a trace
    createdScore, err := langfuse.Scores().Create(ctx, &scores.CreateScoreRequest{
        TraceID:  "trace-123",
        Name:     "accuracy",
        Value:    0.95,
        DataType: scores.ScoreDataTypeNumeric,
        Comment:  "High accuracy score",
    })

    // Get a score by ID
    score, err := langfuse.Scores().Get(ctx, "score-id")

    // List scores with filters
    scoresList, err := langfuse.Scores().List(ctx, scores.ListParams{
        Page:   1,
        Limit:  20,
        Name:   "accuracy",
        Source: scores.ScoreSourceAPI,
    })

    // Delete a score
    err = langfuse.Scores().Delete(ctx, "score-id")
}
LLM Connections
import (
    "context"

    langfuse "github.com/git-hulk/langfuse-go"
    "github.com/git-hulk/langfuse-go/pkg/llmconnections"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    // List LLM connections
    connections, err := langfuse.LLMConnections().List(ctx, llmconnections.ListParams{
        Page:  1,
        Limit: 10,
    })

    // Create or update an LLM connection
    connection, err := langfuse.LLMConnections().Upsert(ctx, &llmconnections.UpsertLLMConnectionRequest{
        Provider:          "OpenAI",
        Adapter:           llmconnections.AdapterOpenAI,
        SecretKey:         "sk-your-openai-key",
        CustomModels:      []string{"gpt-4", "gpt-3.5-turbo"},
        WithDefaultModels: &[]bool{true}[0],
        ExtraHeaders:      map[string]string{"Custom-Header": "value"},
    })
}

Data Management

Manage datasets for training, evaluation, and testing of your AI models.

Datasets
import (
    "context"

    langfuse "github.com/git-hulk/langfuse-go"
    "github.com/git-hulk/langfuse-go/pkg/datasets"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    // Create a new dataset
    createdDataset, err := langfuse.Datasets().Create(ctx, &datasets.CreateDatasetRequest{
        Name:        "evaluation-dataset",
        Description: "Dataset for model evaluation",
        Metadata:    map[string]interface{}{"version": "1.0"},
    })

    // Get a dataset by name
    dataset, err := langfuse.Datasets().Get(ctx, "evaluation-dataset")

    // List datasets
    listDatasets, err := langfuse.Datasets().List(ctx, datasets.ListParams{
        Page:  1,
        Limit: 20,
    })
}

Platform APIs

Utility APIs for media file management and platform health monitoring.

Media
import (
    "context"
    "os"

    langfuse "github.com/git-hulk/langfuse-go"
    "github.com/git-hulk/langfuse-go/pkg/media"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    // Upload a file from filesystem
    uploadResp, err := langfuse.Media().UploadFile(ctx, &media.UploadFileRequest{
        TraceID:     "trace-123",
        Field:       "input",
        FilePath:    "./image.png",
        ContentType: media.ContentTypeImagePNG, // Optional, auto-detected if not provided
    })

    // Upload from byte data
    imageData, _ := os.ReadFile("./image.jpg")
    uploadResp, err = langfuse.Media().UploadFromBytes(ctx, &media.UploadFromBytesRequest{
        TraceID:     "trace-123",
        Field:       "output",
        ContentType: media.ContentTypeImageJPEG,
        Data:        imageData,
    })

    // Get media record
    mediaRecord, err := langfuse.Media().Get(ctx, uploadResp.MediaID)

    // Get presigned upload URL for custom upload flow
    uploadURL, err := langfuse.Media().GetUploadURL(ctx, &media.GetUploadURLRequest{
        TraceID:       "trace-123",
        ContentType:   media.ContentTypeImagePNG,
        ContentLength: len(imageData),
        SHA256Hash:    "base64-encoded-sha256-hash",
        Field:         "metadata",
    })
}
Health
import (
    "context"
    "fmt"

    langfuse "github.com/git-hulk/langfuse-go"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    // Check API health and version
    health, err := langfuse.Health().Check(ctx)
    if err != nil {
        fmt.Printf("Health check failed: %v\n", err)
        return
    }
    
    fmt.Printf("Status: %s, Version: %s\n", health.Status, health.Version)
}

Organization & Projects

Manage projects, API keys, and organization memberships. Most operations require organization-scoped API keys.

Projects
import (
    "context"

    langfuse "github.com/git-hulk/langfuse-go"
    "github.com/git-hulk/langfuse-go/pkg/projects"
)

func main() {
    langfuse := langfuse.NewClient("YOUR_HOST", "YOUR_PUBLIC_KEY", "YOUR_PRIVATE_KEY")

    ctx := context.Background()

    // Get projects associated with your API key
    projects, err := langfuse.Projects().Get(ctx)

    // Create a new project (requires organization-scoped API key)
    createdProject, err := langfuse.Projects().Create(ctx, &projects.CreateProjectRequest{
        Name:      "my-new-project",
        Metadata:  map[string]interface{}{"team": "ai"},
        Retention: 30,
    })

    // Update a project (requires organization-scoped API key)
    updatedProject, err := langfuse.Projects().Update(ctx, "project-id", &projects.UpdateProjectRequest{
        Name:      "updated-project-name",
        Retention: 60,
    })

    // Delete a project (requires organization-scoped API key)
    deleteResponse, err := langfuse.Projects().Delete(ctx, "project-id")

    // Manage API keys for a project (requires organization-scoped API key)
    apiKeys, err := langfuse.Projects().GetAPIKeys(ctx, "project-id")
    
    newAPIKey, err := langfuse.Projects().CreateAPIKey(ctx, "project-id", &projects.CreateAPIKeyRequest{
        Note: &[]string{"API key for production"}[0],
    })
    
    deleteAPIResponse, err := langfuse.Projects().DeleteAPIKey(ctx, "project-id", "api-key-id")
}

Development

Testing
make test                    # Run all tests with race detector (-race -count=1)
go test ./...               # Standard Go test runner  
go test ./pkg/datasets/     # Test specific package
go test -v ./pkg/traces/    # Verbose output for specific package
Code Formatting
make format                 # Format with goimports + gofmt (includes local import ordering)
goimports -w -local github.com/git-hulk/langfuse-go ./...
Build & Linting
go build ./...              # Build all packages
golangci-lint run           # Lint (CI uses v1.64.7)

Contributing

Issues & PRs are welcome. Please include tests for new functionality or bug fixes.

License

MIT License. See LICENSE.

Documentation

Overview

Package langfuse provides a Go client library for interacting with the Langfuse platform.

This package offers comprehensive support for observability tracing, prompt management, model configuration, datasets, sessions, scores, projects, LLM connections, comments, and annotations functionality with efficient batch processing.

Basic usage:

client := langfuse.NewClient("https://cloud.langfuse.com", "your-public-key", "your-secret-key")
defer client.Close()

trace := client.StartTrace("my-application")
span := trace.StartSpan("processing-step")
// ... your application logic
span.End()
trace.End()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ClientOption added in v0.0.4

type ClientOption func(*clientConfig)

ClientOption is a function that configures a Langfuse client.

func WithHTTPClient added in v0.0.4

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client for the Langfuse client.

This allows you to customize timeout settings, transport configuration, and other HTTP client behavior. If not provided, resty will use its default HTTP client.

Example:

httpClient := &http.Client{
	Timeout: 30 * time.Second,
	Transport: &http.Transport{
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 10,
	},
}
client := langfuse.NewClient("https://cloud.langfuse.com", "public-key", "secret-key", langfuse.WithHTTPClient(httpClient))

type Langfuse added in v0.0.3

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

Langfuse is the main client for interacting with the Langfuse platform.

It provides access to all Langfuse functionality including tracing, prompts, models, datasets, sessions, scores, projects, LLM connections, comments, and annotations through dedicated client instances.

The client manages HTTP connections and provides efficient batch processing for trace ingestion with automatic flushing and graceful shutdown capabilities.

func NewClient

func NewClient(host string, publicKey string, secretKey string, options ...ClientOption) *Langfuse

NewClient creates a new Langfuse client instance with the specified host and credentials.

The host should be the base URL of your Langfuse instance (e.g., "https://cloud.langfuse.com"). The publicKey and secretKey are obtained from your Langfuse project settings. Optional configuration can be provided using ClientOption functions.

The client automatically configures HTTP basic authentication and sets the API base URL. Remember to call Close() when done to ensure all pending traces are flushed.

Example with custom HTTP client:

httpClient := &http.Client{Timeout: 30 * time.Second}
client := langfuse.NewClient("https://cloud.langfuse.com", "public-key", "secret-key", langfuse.WithHTTPClient(httpClient))

func (*Langfuse) Close added in v0.0.3

func (c *Langfuse) Close() error

Close gracefully shuts down the client and flushes all pending traces.

This method ensures that all batched traces are sent to Langfuse before the client is closed. It should be called when you're done using the client, typically in a defer statement.

Returns an error if the shutdown process fails or times out.

func (*Langfuse) Comments added in v0.0.3

func (c *Langfuse) Comments() *comments.Client

Comments returns a client for managing comments on traces, observations, and sessions.

Use this client to add contextual comments to your traces and observations for collaboration and debugging purposes.

func (*Langfuse) Datasets added in v0.0.3

func (c *Langfuse) Datasets() *datasets.Client

Datasets returns a client for managing datasets and dataset items.

Use this client to create and manage datasets for training, evaluation, and testing of your AI models, including dataset items and runs.

func (*Langfuse) Flush added in v0.0.3

func (c *Langfuse) Flush()

func (*Langfuse) Health added in v0.0.3

func (c *Langfuse) Health() *health.Client

Health returns a client for checking API health status and version.

Use this client to verify connectivity and server status.

func (*Langfuse) LLMConnections added in v0.0.3

func (c *Langfuse) LLMConnections() *llmconnections.Client

LLMConnections returns a client for managing LLM provider connections.

Use this client to configure connections to various LLM providers like OpenAI, Anthropic, Azure OpenAI, AWS Bedrock, and Google Vertex AI.

func (*Langfuse) Media added in v0.0.3

func (c *Langfuse) Media() *media.Client

Media returns a client for managing media files associated with traces and observations.

Use this client to upload, retrieve, and manage media files including images, audio, video, and documents. Media files are associated with traces and observations through their input, output, or metadata fields.

func (*Langfuse) Models added in v0.0.3

func (c *Langfuse) Models() *models.Client

Models returns a client for managing model configurations and pricing.

Use this client to define model pricing, match patterns, and manage model metadata for cost tracking and analytics.

func (*Langfuse) Organizations added in v0.0.3

func (c *Langfuse) Organizations() *organizations.Client

Organizations returns a client for managing organization and project memberships.

Use this client to manage user roles and permissions within organizations and projects. Most operations require organization-scoped API keys.

func (*Langfuse) Projects added in v0.0.3

func (c *Langfuse) Projects() *projects.Client

Projects returns a client for managing projects and API keys.

Use this client to create, update, and manage projects, as well as manage API keys within projects. Most operations require organization-scoped API keys.

func (*Langfuse) Prompts added in v0.0.3

func (c *Langfuse) Prompts() *prompts.Client

Prompts returns a client for managing prompt templates and versions.

Use this client to create, retrieve, list, and manage prompt templates for your AI applications.

func (*Langfuse) Scores added in v0.0.3

func (c *Langfuse) Scores() *scores.Client

Scores returns a client for managing evaluation scores and score configurations.

Use this client to create, retrieve, and manage scores for your traces and observations, including score configurations for different data types.

func (*Langfuse) Sessions added in v0.0.3

func (c *Langfuse) Sessions() *sessions.Client

Sessions returns a client for managing user sessions and their associated traces.

Use this client to retrieve and analyze user sessions, including filtering by time ranges and environments.

func (*Langfuse) StartTrace added in v0.0.3

func (c *Langfuse) StartTrace(ctx context.Context, name string) *traces.Trace

StartTrace creates a new trace with the given name.

A trace represents a single execution flow in your application and can contain multiple observations (spans). Traces are automatically batched and sent to Langfuse for efficient ingestion.

Returns a Trace instance that you can use to add observations and metadata.

Directories

Path Synopsis
pkg
annotations
Package annotations provides functionality for managing annotation queues and items in Langfuse.
Package annotations provides functionality for managing annotation queues and items in Langfuse.
batch
Package batch provides a generic, type-safe batch processor for efficient API ingestion.
Package batch provides a generic, type-safe batch processor for efficient API ingestion.
comments
Package comments provides functionality for managing comments on traces, observations, and sessions in Langfuse.
Package comments provides functionality for managing comments on traces, observations, and sessions in Langfuse.
common
Package common provides shared types and utilities for HTTP operations across all Langfuse clients.
Package common provides shared types and utilities for HTTP operations across all Langfuse clients.
datasets
Package datasets provides functionality for managing datasets and dataset items in Langfuse.
Package datasets provides functionality for managing datasets and dataset items in Langfuse.
health
Package health provides functionality to check the Langfuse API health.
Package health provides functionality to check the Langfuse API health.
llmconnections
Package llmconnections provides functionality for managing LLM provider connections in Langfuse.
Package llmconnections provides functionality for managing LLM provider connections in Langfuse.
logger
Package logger provides a global zap logger instance for JSON formatted logging across the entire langfuse-go project.
Package logger provides a global zap logger instance for JSON formatted logging across the entire langfuse-go project.
media
Package media provides functionality for managing media records in Langfuse.
Package media provides functionality for managing media records in Langfuse.
models
Package models provides functionality for managing model configurations and pricing in Langfuse.
Package models provides functionality for managing model configurations and pricing in Langfuse.
organizations
Package organizations provides functionality for managing organization and project memberships in Langfuse.
Package organizations provides functionality for managing organization and project memberships in Langfuse.
projects
Package projects provides functionality for managing projects and API keys in Langfuse.
Package projects provides functionality for managing projects and API keys in Langfuse.
prompts
Package prompts provides functionality for managing prompt templates and versions in Langfuse.
Package prompts provides functionality for managing prompt templates and versions in Langfuse.
scores
Package scores provides functionality for managing evaluation scores and score configurations in Langfuse.
Package scores provides functionality for managing evaluation scores and score configurations in Langfuse.
sessions
Package sessions provides functionality for managing user sessions and their associated traces in Langfuse.
Package sessions provides functionality for managing user sessions and their associated traces in Langfuse.
traces
Package traces provides functionality for distributed tracing in Langfuse.
Package traces provides functionality for distributed tracing in Langfuse.

Jump to

Keyboard shortcuts

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