Skip to main content

Crate langfuse_ergonomic

Crate langfuse_ergonomic 

Source
Expand description

§langfuse-ergonomic

Ergonomic Rust client for Langfuse, the open-source LLM observability platform.

This crate provides a user-friendly interface to the Langfuse API using builder patterns powered by the bon crate.

§Features

  • Builder Pattern - Intuitive API using the bon builder pattern library
  • Async/Await - Full async support with Tokio
  • Type Safe - Strongly typed with compile-time guarantees
  • Easy Setup - Simple configuration from environment variables
  • Comprehensive - Support for traces, observations, scores, and more
  • Batch Processing - Automatic batching with retry logic and chunking
  • Production Ready - Built-in timeouts, connection pooling, and error handling
  • Self-Hosted Support - Full support for self-hosted Langfuse instances

§Quick Start

use langfuse_ergonomic::{ClientBuilder, LangfuseClient};
use serde_json::json;

// Create client from environment variables
let client = ClientBuilder::from_env()?.build()?;

// Create a trace
let trace = client.trace()
    .name("my-application")
    .input(json!({"query": "Hello, world!"}))
    .output(json!({"response": "Hi there!"}))
    .user_id("user-123")
    .tags(vec!["production".to_string(), "chat".to_string()])
    .call()
    .await?;

println!("Created trace: {}", trace.id);

// List traces with strongly-typed response
let traces = client.list_traces().limit(10).call().await?;
for trace in &traces.data {
    println!("Trace ID: {}, Name: {:?}", trace.id, trace.name);
}

§Type Safety

All API methods return strongly-typed structs instead of JSON values:

// Traces are strongly typed
let traces: Traces = client.list_traces().call().await?;
println!("Found {} traces", traces.data.len());

// Datasets are strongly typed
let dataset: Dataset = client.get_dataset("my-dataset").await?;
println!("Dataset: {}", dataset.name);

// Prompts are strongly typed
let prompt: Prompt = client.get_prompt("my-prompt", None, None).await?;

Note: This crate re-exports types from langfuse-client-base, which are auto-generated from the Langfuse OpenAPI specification. This ensures type accuracy and allows direct access to all fields and their documentation. You can import types from either crate:

// Both imports are equivalent:
use langfuse_ergonomic::Traces;
// or
use langfuse_client_base::models::Traces;

§Configuration

Set these environment variables:

LANGFUSE_PUBLIC_KEY=pk-lf-...
LANGFUSE_SECRET_KEY=sk-lf-...
LANGFUSE_BASE_URL=https://cloud.langfuse.com  # Optional

Or configure explicitly:

let client = ClientBuilder::new()
    .public_key("pk-lf-...")
    .secret_key("sk-lf-...")
    .base_url("https://cloud.langfuse.com".to_string())
    .timeout(Duration::from_secs(30))
    .build()?;

§Batch Processing

The client supports efficient batch processing with automatic chunking and retry logic:

use langfuse_ergonomic::{Batcher, BackpressurePolicy, ClientBuilder};
use std::time::Duration;

let client = ClientBuilder::from_env()?.build()?;

// Create a batcher with custom configuration
let batcher = Batcher::builder()
    .client(client)
    .max_events(50)                            // Events per batch
    .flush_interval(Duration::from_secs(10))   // Auto-flush interval
    .max_retries(3)                            // Retry attempts
    .backpressure_policy(BackpressurePolicy::Block)
    .build()
    .await;

// Events are automatically batched and sent

§Feature Flags

  • compression - Enable gzip, brotli, and deflate compression for requests

§Examples

See the examples/ directory for more usage patterns:

  • basic_trace - Simple trace creation
  • batch_ingestion - Batch processing with automatic chunking
  • trace_with_metadata - Rich metadata and tagging
  • self_hosted - Connecting to self-hosted instances

§License

Licensed under either of:

Re-exports§

pub use batcher::BackpressurePolicy;
pub use batcher::BatchEvent;
pub use batcher::Batcher;
pub use batcher::BatcherBuilderWithClient;
pub use batcher::BatcherConfig;
pub use batcher::BatcherMetrics;
pub use batcher::BatcherMetricsSnapshot;
pub use client::ClientBuilder;
pub use client::LangfuseClient;
pub use error::Error;
pub use error::EventError;
pub use error::IngestionResponse;
pub use error::Result;
pub use traces::IdGenerator;
pub use traces::TraceResponse;

Modules§

batcher
Batch ingestion with automatic chunking, retries, and 207 handling
client
Main client for interacting with the Langfuse API
datasets
Dataset management functionality
error
Error types for the ergonomic Langfuse client
observations
Observation-related functionality (spans, generations, and events)
prompts
Prompt management functionality
scores
Score-related functionality for evaluating traces and observations
traces
Trace-related functionality with builder patterns

Structs§

CreateEventBody
CreateGenerationBody
CreateSpanBody
Dataset
DatasetItem
DatasetRunWithItems
IngestionBatchRequest
ObservationsView
ObservationsViews
PaginatedDatasetItems
PaginatedDatasetRuns
PaginatedDatasets
PromptMetaListResponse
Trace
TraceBody
TraceWithDetails
TraceWithFullDetails
Traces

Enums§

IngestionEvent
ObservationLevel
Prompt
ScoreDataType