Skip to main content

langfuse_ergonomic/
lib.rs

1//! # langfuse-ergonomic
2//!
3//! Ergonomic Rust client for [Langfuse](https://langfuse.com), the open-source LLM observability platform.
4//!
5//! This crate provides a user-friendly interface to the Langfuse API using builder patterns
6//! powered by the [`bon`](https://bon-rs.com) crate.
7//!
8//! ## Features
9//!
10//! - **Builder Pattern** - Intuitive API using the bon builder pattern library
11//! - **Async/Await** - Full async support with Tokio
12//! - **Type Safe** - Strongly typed with compile-time guarantees
13//! - **Easy Setup** - Simple configuration from environment variables
14//! - **Comprehensive** - Support for traces, observations, scores, and more
15//! - **Batch Processing** - Automatic batching with retry logic and chunking
16//! - **Production Ready** - Built-in timeouts, connection pooling, and error handling
17//! - **Self-Hosted Support** - Full support for self-hosted Langfuse instances
18//!
19//! ## Quick Start
20//!
21//! ```no_run
22//! use langfuse_ergonomic::{ClientBuilder, LangfuseClient};
23//! use serde_json::json;
24//!
25//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
26//! // Create client from environment variables
27//! let client = ClientBuilder::from_env()?.build()?;
28//!
29//! // Create a trace
30//! let trace = client.trace()
31//!     .name("my-application")
32//!     .input(json!({"query": "Hello, world!"}))
33//!     .output(json!({"response": "Hi there!"}))
34//!     .user_id("user-123")
35//!     .tags(vec!["production".to_string(), "chat".to_string()])
36//!     .call()
37//!     .await?;
38//!
39//! println!("Created trace: {}", trace.id);
40//!
41//! // List traces with strongly-typed response
42//! let traces = client.list_traces().limit(10).call().await?;
43//! for trace in &traces.data {
44//!     println!("Trace ID: {}, Name: {:?}", trace.id, trace.name);
45//! }
46//! # Ok(())
47//! # }
48//! ```
49//!
50//! ## Type Safety
51//!
52//! All API methods return strongly-typed structs instead of JSON values:
53//!
54//! ```no_run
55//! # use langfuse_ergonomic::{ClientBuilder, Traces, Dataset, Prompt};
56//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
57//! # let client = ClientBuilder::from_env()?.build()?;
58//! // Traces are strongly typed
59//! let traces: Traces = client.list_traces().call().await?;
60//! println!("Found {} traces", traces.data.len());
61//!
62//! // Datasets are strongly typed
63//! let dataset: Dataset = client.get_dataset("my-dataset").await?;
64//! println!("Dataset: {}", dataset.name);
65//!
66//! // Prompts are strongly typed
67//! let prompt: Prompt = client.get_prompt("my-prompt", None, None).await?;
68//! # Ok(())
69//! # }
70//! ```
71//!
72//! **Note:** This crate re-exports types from `langfuse-client-base`, which are auto-generated
73//! from the Langfuse OpenAPI specification. This ensures type accuracy and allows direct access
74//! to all fields and their documentation. You can import types from either crate:
75//!
76//! ```rust,ignore
77//! // Both imports are equivalent:
78//! use langfuse_ergonomic::Traces;
79//! // or
80//! use langfuse_client_base::models::Traces;
81//! ```
82//!
83//! ## Configuration
84//!
85//! Set these environment variables:
86//!
87//! ```bash
88//! LANGFUSE_PUBLIC_KEY=pk-lf-...
89//! LANGFUSE_SECRET_KEY=sk-lf-...
90//! LANGFUSE_BASE_URL=https://cloud.langfuse.com  # Optional
91//! ```
92//!
93//! Or configure explicitly:
94//!
95//! ```no_run
96//! # use langfuse_ergonomic::ClientBuilder;
97//! # use std::time::Duration;
98//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
99//! let client = ClientBuilder::new()
100//!     .public_key("pk-lf-...")
101//!     .secret_key("sk-lf-...")
102//!     .base_url("https://cloud.langfuse.com".to_string())
103//!     .timeout(Duration::from_secs(30))
104//!     .build()?;
105//! # Ok(())
106//! # }
107//! ```
108//!
109//! ## Batch Processing
110//!
111//! The client supports efficient batch processing with automatic chunking and retry logic:
112//!
113//! ```no_run
114//! use langfuse_ergonomic::{Batcher, BackpressurePolicy, ClientBuilder};
115//! use std::time::Duration;
116//!
117//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
118//! let client = ClientBuilder::from_env()?.build()?;
119//!
120//! // Create a batcher with custom configuration
121//! let batcher = Batcher::builder()
122//!     .client(client)
123//!     .max_events(50)                            // Events per batch
124//!     .flush_interval(Duration::from_secs(10))   // Auto-flush interval
125//!     .max_retries(3)                            // Retry attempts
126//!     .backpressure_policy(BackpressurePolicy::Block)
127//!     .build()
128//!     .await;
129//!
130//! // Events are automatically batched and sent
131//! # Ok(())
132//! # }
133//! ```
134//!
135//! ## Feature Flags
136//!
137//! - `compression` - Enable gzip, brotli, and deflate compression for requests
138//!
139//! ## Examples
140//!
141//! See the `examples/` directory for more usage patterns:
142//! - `basic_trace` - Simple trace creation
143//! - `batch_ingestion` - Batch processing with automatic chunking
144//! - `trace_with_metadata` - Rich metadata and tagging
145//! - `self_hosted` - Connecting to self-hosted instances
146//!
147//! ## License
148//!
149//! Licensed under either of:
150//! - Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))
151//! - MIT license ([LICENSE-MIT](LICENSE-MIT))
152
153#![warn(rustdoc::broken_intra_doc_links)]
154#![cfg_attr(docsrs, feature(doc_cfg))]
155
156pub mod batcher;
157pub mod client;
158pub mod datasets;
159pub mod error;
160pub mod observations;
161pub mod prompts;
162pub mod scores;
163pub mod traces;
164
165// Re-export commonly used types at the crate root for convenience
166pub use batcher::{
167    BackpressurePolicy, BatchEvent, Batcher, BatcherBuilderWithClient, BatcherConfig,
168    BatcherMetrics, BatcherMetricsSnapshot,
169};
170pub use client::{ClientBuilder, LangfuseClient};
171pub use error::{Error, EventError, IngestionResponse, Result};
172pub use traces::{IdGenerator, TraceResponse};
173
174// Re-export types from langfuse-client-base for convenience
175//
176// These types are auto-generated from the Langfuse OpenAPI specification and provide
177// strongly-typed access to all API responses. Re-exporting them here allows users to
178// import everything they need from a single crate without depending directly on
179// langfuse-client-base.
180//
181// Users can import from either crate:
182//   use langfuse_ergonomic::Traces;
183//   use langfuse_client_base::models::Traces;  // equivalent
184//
185// Type categories:
186// - Trace types: Trace, TraceBody, TraceWithDetails, TraceWithFullDetails, Traces
187// - Observation types: ObservationsView, ObservationsViews, ObservationLevel
188// - Dataset types: Dataset, DatasetItem, DatasetRunWithItems, PaginatedDatasets,
189//                  PaginatedDatasetItems, PaginatedDatasetRuns
190// - Prompt types: Prompt, PromptMetaListResponse
191// - Event/Ingestion types: CreateEventBody, CreateGenerationBody, CreateSpanBody,
192//                          IngestionEvent, IngestionBatchRequest
193// - Utility types: ScoreDataType
194pub use langfuse_client_base::models::{
195    CreateEventBody, CreateGenerationBody, CreateSpanBody, Dataset, DatasetItem,
196    DatasetRunWithItems, IngestionBatchRequest, IngestionEvent, ObservationLevel, ObservationsView,
197    ObservationsViews, PaginatedDatasetItems, PaginatedDatasetRuns, PaginatedDatasets, Prompt,
198    PromptMetaListResponse, ScoreDataType, Trace, TraceBody, TraceWithDetails,
199    TraceWithFullDetails, Traces,
200};