Documentation
¶
Overview ¶
Package langfuse provides observation-centric Langfuse tracing on top of OpenTelemetry.
It exports OTLP/HTTP protobuf traces to Langfuse and can either own an isolated tracer provider or attach a Langfuse processor to an existing OpenTelemetry SDK tracer provider through Config. The package never changes global OpenTelemetry state.
Construct a Client with New, typically from ConfigFromEnv, stamp request-scoped identity with Client.WithTraceAttributes, and record work with Client.Observe:
lf, err := langfuse.New(ctx, langfuse.ConfigFromEnv())
if err != nil {
return err
}
defer lf.Shutdown(shutdownCtx)
err = lf.Observe(ctx, "answer-question", langfuse.TypeGeneration,
langfuse.ObservationAttributes{Input: question},
func(ctx context.Context, o *langfuse.Observation) error {
answer, err := callModel(ctx, question)
o.Update(langfuse.ObservationAttributes{Output: answer})
return err
})
Client.StartObservation is the lower-level pair for lifetimes that span functions; the context it returns carries the parent-child relationship, so observations started from it nest under their parent. Client.RecordScore submits evaluations and user feedback through the Langfuse JSON ingestion endpoint, Client.GetPrompt loads prompt-management prompts with client-side caching and an optional local fallback, Client.UpsertDatasetItem and Client.DatasetItems curate and read datasets, Client.RunExperiment runs and scores an experiment over dataset or local items with each item as its own trace, and Client.Flush and Client.Shutdown control the export lifecycle. Whole traces can be sampled deterministically by trace ID through Config.SampleRate and Client.WithSampleRate, with TraceSampledAt exposing the same decision for correlated application-level sampling. Client.WithContentCapture can override the client's input/output capture default for one local context tree. A nil or disabled Client and the zero Observation are safe no-ops.
Index ¶
- Variables
- func IsDefaultExportSpan(span sdktrace.ReadOnlySpan) bool
- func IsGenAISpan(span sdktrace.ReadOnlySpan) bool
- func IsKnownLLMInstrumentor(span sdktrace.ReadOnlySpan) bool
- func IsLangfuseSpan(span sdktrace.ReadOnlySpan) bool
- func TraceSampledAt(traceID string, fraction float64) (bool, error)
- type AnnotationObjectType
- type AnnotationQueue
- type AnnotationQueueItem
- type AnnotationQueueItemQuery
- type AnnotationQueueItemSpec
- type AnnotationQueueQuery
- type AnnotationQueueSpec
- type AnnotationStatus
- type Client
- func (c *Client) AnnotationQueueItems(ctx context.Context, query AnnotationQueueItemQuery) iter.Seq2[AnnotationQueueItem, error]
- func (c *Client) AnnotationQueues(ctx context.Context, query AnnotationQueueQuery) iter.Seq2[AnnotationQueue, error]
- func (c *Client) AssignAnnotationQueue(ctx context.Context, queueID, userID string) error
- func (c *Client) Comments(ctx context.Context, query CommentQuery) iter.Seq2[Comment, error]
- func (c *Client) CreateAnnotationQueue(ctx context.Context, spec AnnotationQueueSpec) (AnnotationQueue, error)
- func (c *Client) CreateAnnotationQueueItem(ctx context.Context, spec AnnotationQueueItemSpec) (AnnotationQueueItem, error)
- func (c *Client) CreateComment(ctx context.Context, spec CommentSpec) (string, error)
- func (c *Client) CreateScore(ctx context.Context, score Score) (string, error)
- func (c *Client) CreateScoreConfig(ctx context.Context, spec ScoreConfigSpec) (ScoreConfig, error)
- func (c *Client) DatasetItems(ctx context.Context, query DatasetItemQuery) iter.Seq2[DatasetItem, error]
- func (c *Client) Datasets(ctx context.Context, query DatasetQuery) iter.Seq2[Dataset, error]
- func (c *Client) DeleteAnnotationQueueItem(ctx context.Context, queueID, itemID string) error
- func (c *Client) DeleteDatasetItem(ctx context.Context, id string) error
- func (c *Client) Event(ctx context.Context, name string, values ObservationAttributes)
- func (c *Client) ExperimentItems(ctx context.Context, query ExperimentItemQuery) iter.Seq2[StoredExperimentItem, error]
- func (c *Client) Experiments(ctx context.Context, query ExperimentQuery) iter.Seq2[StoredExperiment, error]
- func (c *Client) Flush(ctx context.Context) error
- func (c *Client) GetAnnotationQueue(ctx context.Context, id string) (AnnotationQueue, error)
- func (c *Client) GetAnnotationQueueItem(ctx context.Context, queueID, itemID string) (AnnotationQueueItem, error)
- func (c *Client) GetComment(ctx context.Context, id string) (Comment, error)
- func (c *Client) GetDataset(ctx context.Context, name string) (Dataset, error)
- func (c *Client) GetDatasetItem(ctx context.Context, id string) (DatasetItem, error)
- func (c *Client) GetPrompt(ctx context.Context, name string, query PromptQuery) (Prompt, error)
- func (c *Client) GetScoreConfig(ctx context.Context, id string) (ScoreConfig, error)
- func (c *Client) Observe(ctx context.Context, name string, observationType ObservationType, ...) error
- func (c *Client) RecordScore(ctx context.Context, score Score) error
- func (c *Client) RunExperiment(ctx context.Context, run ExperimentRun) (ExperimentResult, error)
- func (c *Client) ScoreConfigs(ctx context.Context, query ScoreConfigQuery) iter.Seq2[ScoreConfig, error]
- func (c *Client) Scores(ctx context.Context, query ScoreQuery) iter.Seq2[StoredScore, error]
- func (c *Client) Shutdown(ctx context.Context) error
- func (c *Client) StartExperimentItem(ctx context.Context, experiment Experiment, item ExperimentItem, name string, ...) (context.Context, *Observation, error)
- func (c *Client) StartObservation(ctx context.Context, name string, observationType ObservationType, ...) (context.Context, *Observation)
- func (c *Client) UnassignAnnotationQueue(ctx context.Context, queueID, userID string) error
- func (c *Client) UpdateAnnotationQueueItem(ctx context.Context, queueID, itemID string, status AnnotationStatus) (AnnotationQueueItem, error)
- func (c *Client) UpdateScoreConfig(ctx context.Context, id string, update ScoreConfigUpdate) (ScoreConfig, error)
- func (c *Client) UpsertDataset(ctx context.Context, spec DatasetSpec) (Dataset, error)
- func (c *Client) UpsertDatasetItem(ctx context.Context, spec DatasetItemSpec) (DatasetItem, error)
- func (c *Client) WithBaggagePropagation(ctx context.Context) context.Context
- func (c *Client) WithContentCapture(ctx context.Context, enabled bool) context.Context
- func (c *Client) WithParent(ctx context.Context, parent *Observation) context.Context
- func (c *Client) WithSampleRate(ctx context.Context, fraction float64) context.Context
- func (c *Client) WithTraceAttributes(ctx context.Context, values TraceAttributes) context.Context
- func (c *Client) WithTraceAttributesFromBaggage(ctx context.Context) context.Context
- type Comment
- type CommentObjectType
- type CommentQuery
- type CommentSpec
- type Config
- type Dataset
- type DatasetItem
- type DatasetItemQuery
- type DatasetItemSpec
- type DatasetItemStatus
- type DatasetQuery
- type DatasetSpec
- type Evaluation
- type Evaluator
- type EvaluatorInput
- type Experiment
- type ExperimentItem
- type ExperimentItemQuery
- type ExperimentItemResult
- type ExperimentQuery
- type ExperimentResult
- type ExperimentRun
- type ExperimentTask
- type Level
- type MaskField
- type Observation
- type ObservationAttributes
- type ObservationType
- type Prompt
- type PromptFallback
- type PromptMessage
- type PromptQuery
- type PromptRef
- type PromptSource
- type PromptType
- type RunEvaluator
- type Score
- type ScoreCategory
- type ScoreConfig
- type ScoreConfigQuery
- type ScoreConfigSpec
- type ScoreConfigUpdate
- type ScoreDataType
- type ScoreQuery
- type ScoreSource
- type StoredExperiment
- type StoredExperimentItem
- type StoredScore
- type TraceAttributes
- type Usage
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrAnnotationQueueItemNotFound = errors.New("langfuse: annotation queue item not found")
ErrAnnotationQueueItemNotFound reports that the annotation queue item, or its queue, does not exist.
var ErrAnnotationQueueNotFound = errors.New("langfuse: annotation queue not found")
ErrAnnotationQueueNotFound reports that the annotation queue does not exist.
var ErrCommentNotFound = errors.New("langfuse: comment not found")
ErrCommentNotFound reports that the comment does not exist.
var ErrCommentObjectNotFound = errors.New("langfuse: comment object not found")
ErrCommentObjectNotFound reports that the object a new comment refers to does not exist, or is not yet visible after ingestion.
var ErrDatasetItemNotFound = errors.New("langfuse: dataset item not found")
ErrDatasetItemNotFound reports that the dataset item, or its dataset, does not exist.
var ErrDatasetNotFound = errors.New("langfuse: dataset not found")
ErrDatasetNotFound reports that the dataset does not exist.
var ErrExperimentItemNotExported = errors.New("langfuse: experiment item root is not exported")
ErrExperimentItemNotExported reports that a borrowed provider's sampler dropped an experiment item root.
var ErrInvalidExperiment = errors.New("langfuse: invalid experiment")
ErrInvalidExperiment reports an experiment, run, or item that Client.StartExperimentItem or Client.RunExperiment rejected.
var ErrPromptNotFound = errors.New("langfuse: prompt not found")
ErrPromptNotFound reports that the requested prompt name, version, or label does not exist in the Langfuse project. Test with errors.Is.
var ErrPromptTypeMismatch = errors.New("langfuse: prompt type mismatch")
ErrPromptTypeMismatch reports that a resolved prompt did not have the type requested by PromptQuery.Type. Test with errors.Is.
var ErrScoreConfigNotFound = errors.New("langfuse: score config not found")
ErrScoreConfigNotFound reports that the score config does not exist.
var ErrScoreQueueFull = errors.New("langfuse: score queue is full")
ErrScoreQueueFull reports that a non-blocking client did not accept a score because its bounded delivery queue was full.
var ErrShutdownInProgress = errors.New("langfuse: shutdown is in progress")
ErrShutdownInProgress reports that another call is currently shutting down the client. It prevents re-entrant shutdown callbacks from waiting on themselves. Call Shutdown again after the owning call completes to receive its stored result.
var ErrTracerProviderInUse = errors.New("langfuse: tracer provider already has a Langfuse client")
ErrTracerProviderInUse reports that another Langfuse client already owns the Langfuse processor attachment for a borrowed tracer provider.
var ErrWriteOutcomeUnknown = errors.New("langfuse: write outcome unknown")
ErrWriteOutcomeUnknown reports a REST write, such as a dataset or score config write or Client.CreateScore, that failed after it was sent and may have been applied. The SDK never repeats such a write.
Functions ¶
func IsDefaultExportSpan ¶ added in v0.7.0
func IsDefaultExportSpan(span sdktrace.ReadOnlySpan) bool
IsDefaultExportSpan applies the default Langfuse LLM-focused span filter. It accepts SDK observations, spans with OpenTelemetry GenAI semantic convention attributes under gen_ai.*, and spans from known LLM instrumentation scopes.
func IsGenAISpan ¶ added in v0.7.0
func IsGenAISpan(span sdktrace.ReadOnlySpan) bool
IsGenAISpan reports whether span has an OpenTelemetry GenAI semantic convention attribute under gen_ai.*.
func IsKnownLLMInstrumentor ¶ added in v0.7.0
func IsKnownLLMInstrumentor(span sdktrace.ReadOnlySpan) bool
IsKnownLLMInstrumentor reports whether span comes from a known LLM instrumentation scope.
func IsLangfuseSpan ¶ added in v0.7.0
func IsLangfuseSpan(span sdktrace.ReadOnlySpan) bool
IsLangfuseSpan reports whether span was created by this SDK's tracer.
func TraceSampledAt ¶ added in v0.4.0
TraceSampledAt reports whether the trace identified by the 32-character lowercase hex traceID falls inside fraction under the SDK's deterministic threshold scheme, the same scheme the isolated-mode sampler uses, shared with OpenTelemetry's TraceIDRatioBased. A trace selected at a smaller fraction is always selected at any larger one, so work gated at a small fraction (an expensive evaluation on 2% of traces) runs only on traces that a larger export fraction also kept. It returns an error for a malformed trace ID or a fraction that is not finite or not within [0, 1]; it never guesses. It is a pure predicate on the trace ID and does not know what rate the trace was actually sampled at: when gating work on an existing observation, gate on Observation.Sampled and on the returned decision together, after checking the error.
Example ¶
package main
import (
"fmt"
"log"
"github.com/fgn/go-langfuse"
)
func main() {
// TraceSampledAt is deterministic: every caller agrees on the same trace,
// and a trace selected at a smaller fraction is always selected at a
// larger one. Gating an expensive evaluation at 2% therefore evaluates
// only traces that an export fraction of at least 2% also kept.
traceID := "0af7651916cd43dd8448eb211c80319c"
quarter, err := langfuse.TraceSampledAt(traceID, 0.25)
if err != nil {
log.Fatal(err)
}
majority, err := langfuse.TraceSampledAt(traceID, 0.6)
if err != nil {
log.Fatal(err)
}
fmt.Println(quarter, majority)
}
Output: false true
Types ¶
type AnnotationObjectType ¶ added in v0.13.0
type AnnotationObjectType string
AnnotationObjectType is the kind of object an annotation queue item reviews.
const ( AnnotationObjectTrace AnnotationObjectType = "TRACE" AnnotationObjectObservation AnnotationObjectType = "OBSERVATION" AnnotationObjectSession AnnotationObjectType = "SESSION" )
type AnnotationQueue ¶ added in v0.13.0
type AnnotationQueue struct {
ID string
Name string
Description string
ScoreConfigIDs []string
CreatedAt time.Time
UpdatedAt time.Time
}
AnnotationQueue is an annotation queue as stored by Langfuse.
type AnnotationQueueItem ¶ added in v0.13.0
type AnnotationQueueItem struct {
ID string
QueueID string
ObjectID string
ObjectType AnnotationObjectType
Status AnnotationStatus
// CompletedAt is when the item was last completed, zero when Langfuse
// has no time; returning an item to PENDING keeps it, so Status tells
// whether the item is complete.
CompletedAt time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
AnnotationQueueItem is one object in an annotation queue.
type AnnotationQueueItemQuery ¶ added in v0.13.0
type AnnotationQueueItemQuery struct {
// QueueID is required.
QueueID string
// Status, when set, selects only items in that state.
Status AnnotationStatus
// PageSize is the number of items per request; 0 selects 50 and Langfuse
// accepts at most 100.
PageSize int
}
AnnotationQueueItemQuery selects the items of one queue for Client.AnnotationQueueItems.
type AnnotationQueueItemSpec ¶ added in v0.13.0
type AnnotationQueueItemSpec struct {
// QueueID, ObjectID, and ObjectType are required.
QueueID string
ObjectID string
ObjectType AnnotationObjectType
// Status is empty (PENDING) or an AnnotationStatus.
Status AnnotationStatus
}
AnnotationQueueItemSpec adds an object to an annotation queue.
type AnnotationQueueQuery ¶ added in v0.13.0
type AnnotationQueueQuery struct {
// PageSize is the number of queues per request; 0 selects 50 and
// Langfuse accepts at most 100.
PageSize int
}
AnnotationQueueQuery configures Client.AnnotationQueues.
type AnnotationQueueSpec ¶ added in v0.13.0
type AnnotationQueueSpec struct {
// Name is required.
Name string
// Description is shown to reviewers. It is not masked.
Description string
// ScoreConfigIDs are the score configs reviewers fill in, in display
// order.
ScoreConfigIDs []string
}
AnnotationQueueSpec creates an annotation queue.
type AnnotationStatus ¶ added in v0.13.0
type AnnotationStatus string
AnnotationStatus is the review state of an annotation queue item.
const ( AnnotationPending AnnotationStatus = "PENDING" AnnotationCompleted AnnotationStatus = "COMPLETED" )
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client owns all Langfuse exporter, processor, and lifecycle state. Its zero value is a safe no-op.
func New ¶
New constructs a client and validates configuration without performing network I/O. A disabled configuration bypasses all other validation.
Example ¶
package main
import (
"context"
"log"
"time"
"github.com/fgn/go-langfuse"
)
func main() {
ctx := context.Background()
lf, err := langfuse.New(ctx, langfuse.Config{
BaseURL: "https://cloud.langfuse.com",
PublicKey: "pk-lf-...",
SecretKey: "sk-lf-...",
Environment: "production",
})
if err != nil {
log.Fatal(err)
}
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = lf.Shutdown(shutdownCtx)
}()
_, observation := lf.StartObservation(ctx, "nightly-import", langfuse.TypeSpan,
langfuse.ObservationAttributes{Input: "42 records"})
observation.End()
}
Output:
func (*Client) AnnotationQueueItems ¶ added in v0.13.0
func (c *Client) AnnotationQueueItems( ctx context.Context, query AnnotationQueueItemQuery, ) iter.Seq2[AnnotationQueueItem, error]
AnnotationQueueItems lazily iterates over the items of one queue, newest first, with the paging and failure rules of Client.DatasetItems. A missing queue wraps ErrAnnotationQueueNotFound.
func (*Client) AnnotationQueues ¶ added in v0.13.0
func (c *Client) AnnotationQueues(ctx context.Context, query AnnotationQueueQuery) iter.Seq2[AnnotationQueue, error]
AnnotationQueues lazily iterates over the project's annotation queues, newest first, with the paging and failure rules of Client.DatasetItems.
func (*Client) AssignAnnotationQueue ¶ added in v0.13.0
AssignAnnotationQueue assigns a queue to a Langfuse user, who must be a member of the project; assigning twice is harmless. A missing queue or a user outside the project fails with status 404, and a failure after sending wraps ErrWriteOutcomeUnknown.
func (*Client) Comments ¶ added in v0.13.0
Comments lazily iterates over the project's comments with the paging and failure rules of Client.DatasetItems. Langfuse returns comments in no defined order, so sort them, for example by CreatedAt, after collecting them; pages can repeat or skip comments added during the loop.
func (*Client) CreateAnnotationQueue ¶ added in v0.13.0
func (c *Client) CreateAnnotationQueue(ctx context.Context, spec AnnotationQueueSpec) (AnnotationQueue, error)
CreateAnnotationQueue creates an annotation queue. A name already in use or an unknown score config fails with status 400. The write is sent once; a failure after sending wraps ErrWriteOutcomeUnknown.
func (*Client) CreateAnnotationQueueItem ¶ added in v0.13.0
func (c *Client) CreateAnnotationQueueItem( ctx context.Context, spec AnnotationQueueItemSpec, ) (AnnotationQueueItem, error)
CreateAnnotationQueueItem adds an object to a queue and returns the stored item. Langfuse neither checks that the object exists nor deduplicates items, so adding an object twice queues it twice; list the queue first when that matters. A missing queue wraps ErrAnnotationQueueNotFound. The write is sent once; a failure after sending wraps ErrWriteOutcomeUnknown.
func (*Client) CreateComment ¶ added in v0.13.0
CreateComment adds a comment and returns its ID. A missing object wraps ErrCommentObjectNotFound; Langfuse looks traces, observations, and sessions up in its analytics store, so a trace exported moments ago can be missing. The write is sent once; a failure after sending wraps ErrWriteOutcomeUnknown, and repeating it can add a second comment.
func (*Client) CreateScore ¶ added in v0.13.0
CreateScore sends one score to the Langfuse score REST endpoint and waits for the server to accept it, so a rejected request returns an error; Client.RecordScore queues scores for background delivery instead. It is the call for a score whose Source is ScoreSourceAnnotation, such as a value prefilled for an annotation queue. Langfuse checks the request shape before accepting the score but processes it asynchronously: a score whose value does not fit its ConfigID, or whose config is archived, is dropped later without an error, and the score appears in Client.Scores after a few seconds. With ConfigID, the score takes the config's name.
The score is validated as RecordScore validates it and uses the same environment and Metadata masking, but is never suppressed by sampling. Timestamp must be zero because the server stamps the time.
CreateScore returns the score ID, Score.ID or a generated one, with success and with every error once the request is built, including ErrWriteOutcomeUnknown; invalid scores and unavailable clients return "". The write is sent once, and repeating it with the returned ID updates the same score. Writing an existing ID merges into it: an omitted Comment, ConfigID, ObservationID, SessionID, or DatasetRunID keeps its stored value, an omitted QueueID or Source does not, metadata keys accumulate, and the trace ID, environment, and timestamp of the first write remain.
func (*Client) CreateScoreConfig ¶ added in v0.13.0
func (c *Client) CreateScoreConfig(ctx context.Context, spec ScoreConfigSpec) (ScoreConfig, error)
CreateScoreConfig creates a score config. The write is sent once; a failure after sending wraps ErrWriteOutcomeUnknown, and repeating it can create a second config with the same name.
func (*Client) DatasetItems ¶ added in v0.12.0
func (c *Client) DatasetItems(ctx context.Context, query DatasetItemQuery) iter.Seq2[DatasetItem, error]
DatasetItems lazily iterates over the ACTIVE items of one dataset, one request per page, each within a 30-second budget. Without AsOf, items written during iteration can be skipped or repeated. A failure, wrapping ErrDatasetNotFound for a missing dataset, is yielded once with a zero DatasetItem and ends the loop.
func (*Client) Datasets ¶ added in v0.12.0
Datasets lazily iterates over the datasets of the project, newest first, with the paging and failure rules of Client.DatasetItems; datasets created during the loop can make a page repeat earlier ones.
func (*Client) DeleteAnnotationQueueItem ¶ added in v0.13.0
DeleteAnnotationQueueItem removes one item from its queue; scores already recorded for the object remain. A missing item or queue wraps ErrAnnotationQueueItemNotFound, and a failure after sending wraps ErrWriteOutcomeUnknown.
func (*Client) DeleteDatasetItem ¶ added in v0.12.0
DeleteDatasetItem deletes one dataset item; on a versioned server earlier versions remain. A missing item wraps ErrDatasetItemNotFound, and a failure after sending wraps ErrWriteOutcomeUnknown.
func (*Client) Event ¶
func (c *Client) Event(ctx context.Context, name string, values ObservationAttributes)
Event records an instantaneous event observation.
func (*Client) ExperimentItems ¶ added in v0.12.0
func (c *Client) ExperimentItems( ctx context.Context, query ExperimentItemQuery, ) iter.Seq2[StoredExperimentItem, error]
ExperimentItems lazily iterates over stored experiment items, newest first, with the rules of Client.Experiments.
func (*Client) Experiments ¶ added in v0.12.0
func (c *Client) Experiments(ctx context.Context, query ExperimentQuery) iter.Seq2[StoredExperiment, error]
Experiments lazily iterates over stored experiments, most recently active first, one request per page with the budget and failure rules of Client.DatasetItems. Langfuse builds them from exported item traces, so a run appears only after its traces are ingested.
func (*Client) Flush ¶
Flush exports all ended observations and delivers every score accepted before the call; scores recorded after Flush begins do not extend the wait. A score mid-retry holds Flush until it is delivered or dropped, bounded by ctx.
Example ¶
package main
import (
"context"
"log"
"time"
"github.com/fgn/go-langfuse"
)
func main() {
ctx := context.Background()
lf, err := langfuse.New(ctx, langfuse.ConfigFromEnv())
if err != nil {
log.Fatal(err)
}
lf.Event(ctx, "job-completed", langfuse.ObservationAttributes{
Metadata: map[string]any{"records": 42},
})
// Short-lived jobs and serverless handlers flush before returning so
// batched observations are exported while the client stays usable.
flushCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := lf.Flush(flushCtx); err != nil {
log.Printf("flush: %v", err)
}
}
Output:
func (*Client) GetAnnotationQueue ¶ added in v0.13.0
GetAnnotationQueue reads one annotation queue by ID. A missing queue wraps ErrAnnotationQueueNotFound.
func (*Client) GetAnnotationQueueItem ¶ added in v0.13.0
func (c *Client) GetAnnotationQueueItem(ctx context.Context, queueID, itemID string) (AnnotationQueueItem, error)
GetAnnotationQueueItem reads one queue item. A missing item or queue wraps ErrAnnotationQueueItemNotFound.
func (*Client) GetComment ¶ added in v0.13.0
GetComment reads one comment by ID. A missing comment wraps ErrCommentNotFound.
func (*Client) GetDataset ¶ added in v0.12.0
GetDataset reads one dataset by name. A missing dataset wraps ErrDatasetNotFound.
func (*Client) GetDatasetItem ¶ added in v0.12.0
GetDatasetItem reads one dataset item by ID. A missing item or dataset wraps ErrDatasetItemNotFound.
func (*Client) GetPrompt ¶ added in v0.3.0
GetPrompt is safe to call on a nil, disabled, or shut-down client; with a Fallback set it returns that fallback, so callers need no nil guard.
GetPrompt fetches one prompt version from the Langfuse prompts API, serving it from the client-side cache when fresh. An expired entry is returned immediately while one background refresh per prompt runs; a cache miss fetches synchronously, bounded by ctx and a 10-second fetch budget. If the fetch fails for any reason other than ctx ending, query.Fallback is returned when set; otherwise the error carries at most the prompt name and HTTP status, and wraps ErrPromptNotFound for 404. A result whose type does not match query.Type likewise resolves to the fallback or wraps ErrPromptTypeMismatch. A nil ctx or invalid query is always an error.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/fgn/go-langfuse"
)
func main() {
// Client setup may be optional in an application. GetPrompt remains safe
// when the client is nil, so the call site needs no separate nil branch.
var lf *langfuse.Client
prompt, err := lf.GetPrompt(context.Background(), "response-template", langfuse.PromptQuery{
Type: langfuse.PromptTypeText,
Fallback: &langfuse.PromptFallback{Text: "Process {{input}}."},
})
if err != nil {
log.Fatal(err)
}
fmt.Println(prompt.Text)
fmt.Println(prompt.Source)
}
Output: Process {{input}}. fallback
func (*Client) GetScoreConfig ¶ added in v0.13.0
GetScoreConfig reads one score config by ID. A missing config wraps ErrScoreConfigNotFound.
func (*Client) Observe ¶
func (c *Client) Observe( ctx context.Context, name string, observationType ObservationType, values ObservationAttributes, fn func(ctx context.Context, observation *Observation) error, ) error
Observe starts an observation, runs fn with the child context and the observation handle, and always ends the observation, including when fn panics. A non-nil error returned by fn is recorded through Observation.RecordError and returned unchanged, so fn does not need to record it itself. When fn panics, the observation is marked failed with the payload-free status "panic", the panic value is never captured, and the panic propagates. On a nil, disabled, or stopped client fn still runs, receiving ctx unchanged and a no-op handle. A nil fn is a validation error and starts no observation.
Example ¶
package main
import (
"context"
"log"
"github.com/fgn/go-langfuse"
)
func main() {
ctx := context.Background()
lf, err := langfuse.New(ctx, langfuse.ConfigFromEnv())
if err != nil {
log.Fatal(err)
}
err = lf.Observe(ctx, "retrieve-documents", langfuse.TypeRetriever,
langfuse.ObservationAttributes{Input: "safe api design"},
func(ctx context.Context, observation *langfuse.Observation) error {
// Child observations started from ctx nest under this one. The
// observation always ends, a returned error is recorded on it,
// and a panic is marked as a failure before it propagates.
documents, err := retrieve(ctx, "safe api design")
if err != nil {
return err
}
observation.Update(langfuse.ObservationAttributes{Output: documents})
return nil
})
if err != nil {
log.Printf("retrieve: %v", err)
}
}
func retrieve(ctx context.Context, query string) ([]string, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
return []string{"doc-" + query}, nil
}
Output:
func (*Client) RecordScore ¶
RecordScore submits one score through the Langfuse JSON ingestion endpoint using the client's credentials and environment; a score for the experiment item trace that ctx belongs to uses the item's "sdk-experiment" environment instead. The score is validated synchronously, so every returned error marks a score that was not accepted, and then queued for asynchronous delivery with bounded retry (network errors, HTTP 408, 429, and 5xx responses, and per-item ingestion errors with those statuses, using the same backoff defaults as observation export), so transport failures never reach the caller: after the retry budget they are reported as payload-free OpenTelemetry diagnostics and the score is dropped. Client.Flush and Client.Shutdown drain accepted scores. When the queue is full, the call returns ErrScoreQueueFull unless Config.BlockOnQueueFull waits for space, bounded by ctx. A disabled client returns nil without sending, and a shut-down client returns an error. The complete serialized score event is limited to 128 KiB.
Example ¶
package main
import (
"context"
"log"
"github.com/fgn/go-langfuse"
)
func main() {
ctx := context.Background()
lf, err := langfuse.New(ctx, langfuse.ConfigFromEnv())
if err != nil {
log.Fatal(err)
}
rating := 4.0
err = lf.RecordScore(ctx, langfuse.Score{
ID: "feedback-42", // idempotent upsert key
Name: "user-feedback",
SessionID: "conversation-456",
NumericValue: &rating,
Comment: "clear and concise answer",
})
if err != nil {
log.Printf("record score: %v", err)
}
}
Output:
func (*Client) RunExperiment ¶ added in v0.12.0
func (c *Client) RunExperiment(ctx context.Context, run ExperimentRun) (ExperimentResult, error)
RunExperiment runs Task on every item, scores each output with the evaluators, scores the run with the run evaluators, and flushes.
Each item runs as Client.StartExperimentItem would, in a root observation named "experiment-item-run" that ends when the task returns. A dataset item is first linked to the dataset run named RunName, and that run's ID becomes the item's experiment ID; Langfuse derives it from the dataset and run name. A failed link fails the item. Each evaluator runs in its own evaluator observation, and its evaluations become scores on the item root. Run evaluations become scores on the dataset run, so local runs keep them only in the result. Task and evaluator errors are recorded like Observation.RecordError, and panics are recovered as errors.
It returns an error, without running anything, for an invalid run, and otherwise reports failures per item in the result. Canceling ctx stops starting items and running run evaluators, skips their scores and the flush, and returns the context error with the partial result; a flush failure is returned with the complete result. A nil or disabled client runs the tasks and evaluators without exporting anything.
func (*Client) ScoreConfigs ¶ added in v0.13.0
func (c *Client) ScoreConfigs(ctx context.Context, query ScoreConfigQuery) iter.Seq2[ScoreConfig, error]
ScoreConfigs lazily iterates over the project's score configs, newest first and including archived ones, with the paging and failure rules of Client.DatasetItems.
func (*Client) Scores ¶ added in v0.13.0
func (c *Client) Scores(ctx context.Context, query ScoreQuery) iter.Seq2[StoredScore, error]
Scores lazily iterates over the project's scores, one request per page, with the budget and failure rules of Client.DatasetItems. It reads the Langfuse v3 score API, the score listing available on servers in events-only mode, and returns every field group.
func (*Client) Shutdown ¶
Shutdown permanently stops this Client after draining queued observations and scores, bounded by ctx. In borrowed mode it shuts down the Langfuse processor using ctx before unregistering it; the provider and all unrelated processors remain owned by the application. A concurrent or re-entrant call returns ErrShutdownInProgress. After shutdown completes, later calls return the first call's stored result.
func (*Client) StartExperimentItem ¶ added in v0.12.0
func (c *Client) StartExperimentItem( ctx context.Context, experiment Experiment, item ExperimentItem, name string, values ObservationAttributes, ) (context.Context, *Observation, error)
StartExperimentItem starts the root observation of one experiment item in a new trace and returns a context that carries the item's identity.
End the observation when the task finishes; Langfuse measures item latency on it. Spans started from the returned context in the item trace on this client's provider, including evaluators after End, get the item identity and langfuse.environment "sdk-experiment" at start. Isolated mode always samples the item trace; a borrowed provider's sampler that drops the root yields ErrExperimentItemNotExported. On error the observation is a no-op and the context carries neither the item identity nor an ambient span. A nil or disabled client only validates the input.
func (*Client) StartObservation ¶
func (c *Client) StartObservation( ctx context.Context, name string, observationType ObservationType, values ObservationAttributes, ) (context.Context, *Observation)
StartObservation starts an observation. Child work must use the returned context to preserve the parent-child relationship.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/fgn/go-langfuse"
)
func main() {
ctx := context.Background()
lf, err := langfuse.New(ctx, langfuse.ConfigFromEnv())
if err != nil {
log.Fatal(err)
}
// StartObservation suits lifetimes that span functions, such as ending a
// generation only after a stream is fully consumed.
generationCtx, generation := lf.StartObservation(ctx, "generate-answer",
langfuse.TypeGeneration, langfuse.ObservationAttributes{
Model: "gemini-3.6-flash",
Input: "What is context in Go?",
})
defer generation.End()
answer, usage, err := callModel(generationCtx, "What is context in Go?")
if err != nil {
generation.RecordError(err)
return
}
generation.Update(langfuse.ObservationAttributes{Output: answer, Usage: &usage})
}
func callModel(ctx context.Context, question string) (string, langfuse.Usage, error) {
if err := ctx.Err(); err != nil {
return "", langfuse.Usage{}, err
}
return fmt.Sprintf("answer to %q", question), langfuse.Usage{
InputTokens: 6,
OutputTokens: 8,
}, nil
}
Output:
func (*Client) UnassignAnnotationQueue ¶ added in v0.13.0
UnassignAnnotationQueue removes a user's queue assignment; removing a missing assignment is harmless. Errors follow Client.AssignAnnotationQueue.
func (*Client) UpdateAnnotationQueueItem ¶ added in v0.13.0
func (c *Client) UpdateAnnotationQueueItem( ctx context.Context, queueID, itemID string, status AnnotationStatus, ) (AnnotationQueueItem, error)
UpdateAnnotationQueueItem sets the status of one queue item and returns the stored item; completing it stamps CompletedAt. A missing item or queue wraps ErrAnnotationQueueItemNotFound, and a failure after sending wraps ErrWriteOutcomeUnknown.
func (*Client) UpdateScoreConfig ¶ added in v0.13.0
func (c *Client) UpdateScoreConfig(ctx context.Context, id string, update ScoreConfigUpdate) (ScoreConfig, error)
UpdateScoreConfig changes one score config and returns the stored config. A missing config wraps ErrScoreConfigNotFound, and a failure after sending wraps ErrWriteOutcomeUnknown.
func (*Client) UpsertDataset ¶ added in v0.12.0
UpsertDataset creates or updates the named dataset. A nil or panicking Mask result for Metadata fails before any request. The write is sent once; a failure after sending wraps ErrWriteOutcomeUnknown.
func (*Client) UpsertDatasetItem ¶ added in v0.12.0
func (c *Client) UpsertDatasetItem(ctx context.Context, spec DatasetItemSpec) (DatasetItem, error)
UpsertDatasetItem creates or updates one dataset item and returns the stored item; every accepted write adds a version and earlier versions remain. A nil, panicking, oversized, or unserializable Mask result fails before any request. The write is sent once; a failure after sending wraps ErrWriteOutcomeUnknown, and repeating it can add a version or, without an ID, a duplicate item. A missing dataset wraps ErrDatasetNotFound.
func (*Client) WithBaggagePropagation ¶ added in v0.6.0
WithBaggagePropagation marks the returned context so this Client's trace attributes travel as W3C baggage to every downstream service. From the returned context on, WithTraceAttributes, WithTraceAttributesFromBaggage, and StartObservation each return a context whose langfuse_* baggage members are rebuilt from the state visible at that point; callers must propagate the latest returned context, because earlier contexts and aliases keep their old members.
Propagated members are the Langfuse trace attributes (user ID, session ID, trace name, version, request-scoped environment, and string metadata values) plus an application-root marker for the current trace. Values must be printable ASCII without spaces or '+' and at most 200 bytes; values outside that domain stay on the local trace but are dropped from baggage with a diagnostic. Tags never propagate cross-process.
Baggage is delivered by whatever propagator the application has installed, so these values are sent to EVERY destination the context reaches — third-party APIs included — not only to services that use Langfuse. Enable it only on paths where that disclosure is intended.
The trace claim carried in baggage is bound to the trace that was current at the last synchronizing call; a root started directly on the application's tracer cannot refresh it. Start roots through StartObservation on propagation-enabled paths when application-root continuity matters downstream.
func (*Client) WithContentCapture ¶ added in v0.10.0
WithContentCapture returns a context that overrides Config.DisableContentCapture for SDK observations subsequently started on this context path. The decision is client-scoped, inherited by child contexts, and fixed on each observation when it starts so later Observation.Update calls use the same policy. It controls only ObservationAttributes.Input, ObservationAttributes.Output, and Observation.RecordError text; metadata, status messages, scores, and third-party OpenTelemetry data keep their documented policies.
func (*Client) WithParent ¶ added in v0.11.0
WithParent returns a context on which SDK observations of this client start as children of parent, in parent's trace, while ctx's active OpenTelemetry span stays unchanged for every other tracer. Use it when the observation's parent lives on another context path, such as a call made under an application span that exports to a different backend; making parent's context active instead would re-parent that backend's spans under a span it never receives.
The binding applies to every observation started directly on the returned context. Each started observation returns its own ordinary context, with itself as the active span, so its children nest normally. Started observations inherit parent's root claim and, with the SDK-owned provider, parent's sampling decision; a borrowed provider's sampler stays authoritative. Score-suppression authority that ctx's path already lost in parent's trace is not restored. Content capture, cancellation, deadline, values, trace attributes, and baggage opt-in all come from ctx, so ctx should carry the same user, session, and metadata as parent's path. Experiment identity is not copied from parent. A nil parent or one from another client is ignored with a diagnostic.
func (*Client) WithSampleRate ¶ added in v0.4.0
WithSampleRate returns a context that overrides the configured sample rate for the sampling decision made by the first SDK observation subsequently started on this context path. The fraction must be finite and within [0, 1]; 0 exports nothing, 1 exports everything. The decision is inherited by every SDK observation started from that observation's returned context (and inside its Client.Observe callback), so a rate set later on that path has no effect on the already-decided trace. Sibling observations started independently from a context that carries no decision yet re-decide deterministically from the trace ID and their own effective rate: with equal rates they always agree; setting different rates inside one trace makes trace membership subtree-scoped. Set the rate once per request, before the first observation, unless subtree-scoped rates are intended. An invalid fraction is ignored with a diagnostic, as is any call on a borrowed-provider client, where the application's sampler remains authoritative.
Example ¶
package main
import (
"context"
"log"
"github.com/fgn/go-langfuse"
)
func main() {
ctx := context.Background()
lf, err := langfuse.New(ctx, langfuse.ConfigFromEnv())
if err != nil {
log.Fatal(err)
}
// Set the rate once per request, before the first observation. The whole
// trace is then kept or dropped together, so a high-volume path can run
// at 2% while other request types keep the configured default.
ctx = lf.WithSampleRate(ctx, 0.02)
observationCtx, observation := lf.StartObservation(ctx, "classify-request",
langfuse.TypeGeneration, langfuse.ObservationAttributes{})
defer observation.End()
if observation.Sampled() {
// Attach expensive payloads only when the trace is kept for export.
observation.Update(langfuse.ObservationAttributes{Input: "large payload"})
}
_ = observationCtx
}
Output:
func (*Client) WithTraceAttributes ¶
WithTraceAttributes returns a context that propagates request-scoped trace fields to observations subsequently started from it. If an SDK observation belonging to this Client is active, it is updated immediately as well.
Example ¶
package main
import (
"context"
"log"
"github.com/fgn/go-langfuse"
)
func main() {
ctx := context.Background()
lf, err := langfuse.New(ctx, langfuse.ConfigFromEnv())
if err != nil {
log.Fatal(err)
}
// Stamp request-scoped identity once; observations started from the
// returned context share the same trace name, user, session, and tags.
ctx = lf.WithTraceAttributes(ctx, langfuse.TraceAttributes{
Name: "chat-turn",
UserID: "user-123",
SessionID: "conversation-456",
Tags: []string{"chat"},
})
observationCtx, observation := lf.StartObservation(ctx, "chat-turn",
langfuse.TypeAgent, langfuse.ObservationAttributes{})
defer observation.End()
_ = observationCtx
}
Output:
func (*Client) WithTraceAttributesFromBaggage ¶ added in v0.6.0
WithTraceAttributesFromBaggage applies Langfuse trace attributes received as W3C baggage to the returned context. Receipt is explicit and never automatic: call it only after the application has authenticated the request, because inbound baggage is caller- controlled and would otherwise set tenant attribution.
Only the protocol v1 members are applied, each validated against the wire domain: user ID, session ID, trace name, version, environment, and string metadata values land in propagated trace state with local WithTraceAttributes values taking precedence per field; an accepted environment also updates the current recording span. The application-root marker is honored only when it names the ambient span context's trace ID. Inbound metadata passes through the configured Mask exactly once.
The returned context's baggage always has the entire langfuse_* namespace removed — accepted, invalid, excluded, and unknown members alike — so a standard inject forwards nothing of Langfuse's unless WithBaggagePropagation re-enables export from the accepted state. Foreign baggage members are preserved untouched.
type Comment ¶ added in v0.13.0
type Comment struct {
ID string
ObjectType CommentObjectType
ObjectID string
Content string
AuthorUserID string
CreatedAt time.Time
UpdatedAt time.Time
}
Comment is a comment as stored by Langfuse.
type CommentObjectType ¶ added in v0.13.0
type CommentObjectType string
CommentObjectType is the kind of object a comment is attached to.
const ( CommentObjectTrace CommentObjectType = "TRACE" CommentObjectObservation CommentObjectType = "OBSERVATION" CommentObjectSession CommentObjectType = "SESSION" CommentObjectPrompt CommentObjectType = "PROMPT" )
type CommentQuery ¶ added in v0.13.0
type CommentQuery struct {
// ObjectType, when set, selects comments on that kind of object; ObjectID
// requires it.
ObjectType CommentObjectType
ObjectID string
AuthorUserID string
// PageSize is the number of comments per request; 0 selects 50 and
// Langfuse accepts at most 100.
PageSize int
}
CommentQuery selects comments for Client.Comments.
type CommentSpec ¶ added in v0.13.0
type CommentSpec struct {
// ObjectType and ObjectID are required and must name an existing object;
// a prompt is named by its version's ID.
ObjectType CommentObjectType
ObjectID string
// Content is required Markdown of at most 5000 UTF-16 code units after
// Langfuse trims surrounding whitespace. It is explicit caller content
// and is not masked.
Content string
// AuthorUserID, when set, must name a member of the project's
// organization.
AuthorUserID string
// ObjectStartTime, when set, is the start time of the commented
// observation; it only speeds up Langfuse's lookup of the object.
ObjectStartTime time.Time
}
CommentSpec creates a comment.
type Config ¶
type Config struct {
// BaseURL is the Langfuse host or OTLP traces endpoint. It defaults to
// https://cloud.langfuse.com.
BaseURL string
// PublicKey identifies the Langfuse project.
PublicKey string
// SecretKey authenticates writes to the Langfuse project.
SecretKey string
// Environment and Release are stamped on every span observed by the
// Langfuse processor.
Environment string
Release string
// SampleRate selects the fraction of traces exported in isolated mode,
// decided once per trace by a deterministic threshold on the trace ID and
// inherited by every SDK observation started on the deciding context
// path. nil selects the default of 1.0 (export everything); a non-nil
// value must be finite and within [0, 1], where 0 exports no traces while
// scores and prompts keep working. [Client.StartExperimentItem] item
// traces are always sampled. Other values are a validation error in
// [New]. It is ignored with a diagnostic when TracerProvider is set,
// where the application's sampler remains authoritative.
// [Client.WithSampleRate] overrides it per context path.
SampleRate *float64
// ServiceName overrides service.name on an SDK-owned provider. When empty,
// the standard OpenTelemetry resource.Default value is retained, including
// OTEL_SERVICE_NAME. It is ignored when TracerProvider is set.
ServiceName string
// TracerProvider attaches the Langfuse processor to a caller-owned provider. The client
// never replaces the global provider or shuts this provider down.
TracerProvider *sdktrace.TracerProvider
// ShouldExportSpan controls which recorded spans are exported to Langfuse.
// nil uses [IsDefaultExportSpan]. A non-nil filter is a full override of
// the default content filter; sampling, lifecycle, and SDK project-key
// isolation remain mandatory internal gates. The filter can run at span
// start, for application-root classification, and at end, for export. The
// start call sees creation-time attributes plus Langfuse configuration and
// propagated trace attributes, but not attributes added later. The callback
// must be concurrency-safe, side-effect-free, and non-blocking, and must not
// retain the span. A panic omits root classification at start and rejects
// export at end.
ShouldExportSpan func(sdktrace.ReadOnlySpan) bool
// MaxQueueSize bounds how many ended export-eligible spans the client
// buffers in memory while waiting for batch export. Zero selects the
// default of 2048. Values outside [0, 65536] are a validation error in
// [New].
MaxQueueSize int
// BlockOnQueueFull makes ending an exported observation, and recording a
// score, wait for buffer space instead of dropping when the
// corresponding queue is full. A sustained export outage can then stall
// goroutines that end observations or record scores, so it defaults to
// false. On a full span queue, new spans are dropped with a diagnostic,
// matching OpenTelemetry defaults. On a full score queue,
// [Client.RecordScore] returns [ErrScoreQueueFull].
BlockOnQueueFull bool
// Disabled makes the complete client a safe no-op.
Disabled bool
// DisableContentCapture removes Input and Output supplied through
// ObservationAttributes, and [Observation.RecordError] text, by default.
// [Client.WithContentCapture] can override this setting for observations
// started on one client-scoped context path.
// It does not remove content emitted by third-party OpenTelemetry
// instrumentation. Identifiers, metadata, model data, and usage are still
// recorded.
DisableContentCapture bool
// Mask redacts content before it leaves the process. It receives each value
// exactly as the caller supplied it, including json.RawMessage, and returns
// a replacement that is serialized the same way. Trace, observation, and
// score metadata arrive and must stay a map[string]any, error text a
// string, and experiment metadata a JSON object; dataset metadata may be
// any JSON value. A nil return or a panic omits the value from telemetry,
// where error text becomes the payload-free "error"; a panic also fails an
// experiment start. Dataset writes fail on either, because an omitted
// dataset field keeps its stored value. Mask covers observation input and
// output, [Observation.RecordError] text, all metadata, dataset item
// content, and experiment expected output; it never sees identifiers,
// names, descriptions, schemas, model fields, StatusMessage, or
// third-party spans. Calls are synchronous and concurrent, so Mask must be
// fast and concurrency-safe.
Mask func(field MaskField, value any) any
// contains filtered or unexported fields
}
Config configures a Langfuse client.
func ConfigFromEnv ¶
func ConfigFromEnv() Config
ConfigFromEnv returns configuration from the eight documented LANGFUSE_* variables. It intentionally does not read the deprecated LANGFUSE_HOST.
Example ¶
package main
import (
"context"
"log"
"time"
"github.com/fgn/go-langfuse"
)
func main() {
// ConfigFromEnv reads LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY,
// LANGFUSE_BASE_URL, LANGFUSE_TRACING_ENVIRONMENT, LANGFUSE_RELEASE,
// LANGFUSE_SAMPLE_RATE, LANGFUSE_TRACING_ENABLED, and
// LANGFUSE_CONTENT_CAPTURE_ENABLED.
lf, err := langfuse.New(context.Background(), langfuse.ConfigFromEnv())
if err != nil {
log.Fatal(err)
}
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = lf.Shutdown(shutdownCtx)
}()
}
Output:
type Dataset ¶ added in v0.12.0
type Dataset struct {
ID string
Name string
Description string
// Metadata and the schemas are the server's JSON; nil when absent or null.
Metadata json.RawMessage
InputSchema json.RawMessage
ExpectedOutputSchema json.RawMessage
CreatedAt time.Time
UpdatedAt time.Time
}
Dataset is a dataset as stored by Langfuse.
type DatasetItem ¶ added in v0.12.0
type DatasetItem struct {
ID string
DatasetID string
DatasetName string
Status DatasetItemStatus
Input json.RawMessage
ExpectedOutput json.RawMessage
Metadata json.RawMessage
SourceTraceID string
SourceObservationID string
CreatedAt time.Time
UpdatedAt time.Time
// Version is the DatasetItemQuery.AsOf the item was read at; zero when
// read without one.
Version time.Time
}
DatasetItem is a dataset item as stored by Langfuse. Content fields hold the server's JSON, nil when absent or null; media references are not decoded.
func (DatasetItem) ExperimentItem ¶ added in v0.12.0
func (i DatasetItem) ExperimentItem() ExperimentItem
ExperimentItem returns the item for Client.RunExperiment and Client.StartExperimentItem, linked to its dataset and pinned to its Version; an item read without AsOf runs unpinned. Input, ExpectedOutput, and Metadata are the stored json.RawMessage values, or nil.
type DatasetItemQuery ¶ added in v0.12.0
type DatasetItemQuery struct {
// DatasetName is required.
DatasetName string
// AsOf, when non-zero, reads the item versions valid at that instant, at
// millisecond precision; pass the same value as ExperimentItem.Version.
// Servers without Langfuse's default versioned datasets ignore it.
AsOf time.Time
SourceTraceID string
SourceObservationID string
// PageSize is the number of items per request; 0 selects 20 and Langfuse
// accepts at most 100. A page response is limited to 16 MiB.
PageSize int
}
DatasetItemQuery selects the items of one dataset for Client.DatasetItems.
type DatasetItemSpec ¶ added in v0.12.0
type DatasetItemSpec struct {
// DatasetName is required.
DatasetName string
// ID selects the item to update; when empty, every request creates a new
// item. IDs are unique per project, so an ID already used in another
// dataset fails with status 409, as does a concurrent edit of the item.
ID string
// Input, ExpectedOutput, and Metadata are any JSON values, masked as
// MaskDatasetItemInput, MaskDatasetItemExpectedOutput, and
// MaskDatasetItemMetadata, and are limited to 1 MiB each. json.RawMessage
// values are sent verbatim.
Input any
ExpectedOutput any
Metadata any
SourceTraceID string
SourceObservationID string
// Status is empty (ACTIVE for a new item) or a DatasetItemStatus.
Status DatasetItemStatus
}
DatasetItemSpec creates or updates one dataset item. Nil content fields, including typed nils, keep the stored value (null for a new item), so a Mask result of nil is an error.
type DatasetItemStatus ¶ added in v0.12.0
type DatasetItemStatus string
DatasetItemStatus is the lifecycle state of a dataset item.
const ( DatasetItemActive DatasetItemStatus = "ACTIVE" DatasetItemArchived DatasetItemStatus = "ARCHIVED" )
type DatasetQuery ¶ added in v0.12.0
type DatasetQuery struct {
// PageSize is the number of datasets per request; 0 selects 20 and
// Langfuse accepts at most 100.
PageSize int
}
DatasetQuery configures Client.Datasets.
type DatasetSpec ¶ added in v0.12.0
type DatasetSpec struct {
// Name may contain "/" folder separators. Required.
Name string
// Description is not masked; a pointer to "" clears it.
Description *string
// Metadata is any JSON value, masked as MaskDatasetMetadata. Langfuse
// cannot clear it, so an empty map stores {}.
Metadata any
// InputSchema and ExpectedOutputSchema are JSON Schemas for item
// content; JSON null removes one. They are not masked.
InputSchema json.RawMessage
ExpectedOutputSchema json.RawMessage
}
DatasetSpec creates or updates a dataset by name; nil fields keep the stored values.
type Evaluation ¶ added in v0.12.0
type Evaluation struct {
Name string
NumericValue *float64
StringValue *string
DataType ScoreDataType
ConfigID string
Comment string
Metadata map[string]any
}
Evaluation is one score produced by an evaluator. The value and type rules are those of Score.
type Evaluator ¶ added in v0.12.0
type Evaluator func(ctx context.Context, input EvaluatorInput) ([]Evaluation, error)
Evaluator scores the output of one item. ctx carries the evaluator's own observation in the item trace.
type EvaluatorInput ¶ added in v0.12.0
type EvaluatorInput struct {
Input any
Output any
ExpectedOutput any
Metadata any
// Evaluations holds the item's evaluations so far; it is set only for
// ExperimentRun.CompositeEvaluator.
Evaluations []Evaluation
}
EvaluatorInput is what an Evaluator judges.
type Experiment ¶ added in v0.12.0
type Experiment struct {
// ID identifies the run and is shared by all its items; use a new ID for
// every run. Required: at most 255 bytes of valid UTF-8 without control
// characters.
ID string
// Name labels the run in Langfuse and may repeat across runs. Required;
// same rules as ID.
Name string
// Description is optional, at most 16 KiB, and not masked.
Description string
// Metadata is masked as MaskExperimentMetadata and exported as a JSON
// object of at most 16 KiB on every span of the item trace.
Metadata map[string]any
}
Experiment identifies one experiment run.
type ExperimentItem ¶ added in v0.12.0
type ExperimentItem struct {
// ID identifies the item across runs, such as [DatasetItem.ID].
// Required; same rules as Experiment.ID.
ID string
// DatasetID links the item to its Langfuse dataset; empty for local data.
// Same rules as Experiment.ID.
DatasetID string
// Version is the DatasetItemQuery.AsOf the item was read at; zero omits it.
Version time.Time
// Input is the task input. It is exported as the root observation's
// Input, like ObservationAttributes.Input, unless the start values set
// one.
Input any
// ExpectedOutput is masked as MaskExperimentItemExpectedOutput, at most
// 256 KiB, and omitted when content capture is off. Strings are sent
// verbatim, a json.RawMessage JSON string as that string, and other
// values as JSON.
ExpectedOutput any
// Metadata is passed to the task and evaluators as supplied. When it is
// a JSON object, such as a map[string]any or an object json.RawMessage,
// it is masked as MaskExperimentItemMetadata and exported with the rules
// of Experiment.Metadata; Langfuse stores no other shape, so other
// values are not exported.
Metadata any
}
ExperimentItem is one item of an experiment run.
type ExperimentItemQuery ¶ added in v0.12.0
type ExperimentItemQuery struct {
// From is required: only items started at or after it are read.
From time.Time
// To, when non-zero, excludes items started at or after it.
To time.Time
// ExperimentIDs, ExperimentNames, ItemIDs, and DatasetIDs, when set, each
// restrict the result to items matching one of their values; values must
// not contain commas or surrounding whitespace.
ExperimentIDs, ExperimentNames, ItemIDs, DatasetIDs []string
// PageSize is the number of items per request; 0 selects 50 and Langfuse
// accepts at most 100.
PageSize int
}
ExperimentItemQuery selects stored experiment items for Client.ExperimentItems.
type ExperimentItemResult ¶ added in v0.12.0
type ExperimentItemResult struct {
Item ExperimentItem
Output any
// Evaluations holds the evaluations returned by the evaluators, including
// any whose score was rejected.
Evaluations []Evaluation
// TraceID and ObservationID identify the item root; empty when the item
// did not start or the client is disabled.
TraceID string
ObservationID string
// DatasetRunID is the dataset run the item was linked to, if any.
DatasetRunID string
// Err reports why the item has no output: its start, dataset run link,
// or task failed, or the run was canceled before it started.
Err error
// EvaluationErr joins evaluator failures and rejected scores.
EvaluationErr error
}
ExperimentItemResult is the outcome of one item.
type ExperimentQuery ¶ added in v0.12.0
type ExperimentQuery struct {
// From is required: only experiments started at or after it are read.
From time.Time
// To, when non-zero, excludes experiments started at or after it.
To time.Time
// IDs, Names, and DatasetIDs, when set, each restrict the result to
// experiments matching one of their values; values must not contain
// commas or surrounding whitespace.
IDs, Names, DatasetIDs []string
// PageSize is the number of experiments per request; 0 selects 50 and
// Langfuse accepts at most 100.
PageSize int
}
ExperimentQuery selects stored experiments for Client.Experiments.
type ExperimentResult ¶ added in v0.12.0
type ExperimentResult struct {
// ExperimentID is the first dataset run ID among the items, or a random
// ID shared by the run's local items.
ExperimentID string
Name string
RunName string
Description string
// DatasetRunID is the first item's dataset run ID; empty for local data.
DatasetRunID string
// ItemResults are in the order of ExperimentRun.Items.
ItemResults []ExperimentItemResult
RunEvaluations []Evaluation
// RunEvaluationErr joins run evaluator failures and rejected scores.
RunEvaluationErr error
}
ExperimentResult is the outcome of Client.RunExperiment.
func (ExperimentResult) Summary ¶ added in v0.12.0
func (r ExperimentResult) Summary(includeItems bool) string
Summary renders the result for a terminal or log: the run, its task and evaluation failure counts, each evaluation's mean over numeric values, the run evaluations and their errors, and, when includeItems is set, every item with its input, output, evaluations, and errors.
type ExperimentRun ¶ added in v0.12.0
type ExperimentRun struct {
// Name labels the experiment and may repeat across runs. Required; same
// rules as Experiment.ID.
Name string
// RunName names this run and is exported as the experiment name; for
// dataset items it names the dataset run, so reusing it adds items to
// that run. Empty selects Name followed by the start time.
RunName string
// Description and Metadata follow the rules of [Experiment]; Metadata is
// also sent with each dataset run link.
Description string
Metadata map[string]any
// Items are the data; each needs an ID, and an item without Input fails.
// Items from [DatasetItem.ExperimentItem] also link the run to their
// dataset.
Items []ExperimentItem
// Task is required.
Task ExperimentTask
// Evaluators run in order after a successful task.
Evaluators []Evaluator
// CompositeEvaluator runs after Evaluators when they produced at least one
// evaluation, with those evaluations in its input.
CompositeEvaluator Evaluator
// RunEvaluators run in order once every item has finished.
RunEvaluators []RunEvaluator
// MaxConcurrency bounds how many items run at once; 0 selects 50.
MaxConcurrency int
}
ExperimentRun configures Client.RunExperiment.
type ExperimentTask ¶ added in v0.12.0
type ExperimentTask func(ctx context.Context, item ExperimentItem) (output any, err error)
ExperimentTask produces the output of one item. ctx carries the item's root observation, so observations started from it join the item trace.
type MaskField ¶ added in v0.9.0
type MaskField string
MaskField identifies the SDK field passed to Config.Mask.
const ( MaskObservationInput MaskField = "observation input" MaskObservationOutput MaskField = "observation output" MaskTraceMetadata MaskField = "trace metadata" MaskObservationMetadata MaskField = "observation metadata" MaskScoreMetadata MaskField = "score metadata" MaskErrorMessage MaskField = "error message" MaskDatasetMetadata MaskField = "dataset metadata" MaskDatasetItemInput MaskField = "dataset item input" MaskDatasetItemExpectedOutput MaskField = "dataset item expected output" MaskDatasetItemMetadata MaskField = "dataset item metadata" MaskExperimentMetadata MaskField = "experiment metadata" MaskExperimentItemMetadata MaskField = "experiment item metadata" MaskExperimentItemExpectedOutput MaskField = "experiment item expected output" )
type Observation ¶
type Observation struct {
// contains filtered or unexported fields
}
Observation is a concurrency-safe handle around one OpenTelemetry span. Its zero value is a safe no-op.
func (*Observation) End ¶
func (o *Observation) End()
End ends the observation exactly once at the current time.
func (*Observation) EndAt ¶ added in v0.3.0
func (o *Observation) EndAt(at time.Time)
EndAt ends the observation exactly once at the provided time. It exists for instrumentation that records work after the fact: pair it with ObservationAttributes.StartTime and CompletionStartTime to reproduce the observed timeline. A zero time falls back to the current time with a diagnostic, and an end time before an explicitly supplied StartTime is replaced by that start time with a diagnostic. Only the first End or EndAt call takes effect; later calls are ignored.
func (*Observation) ID ¶
func (o *Observation) ID() string
ID returns the lowercase 16-character OpenTelemetry span ID, or an empty string for a no-op observation.
func (*Observation) RecordError ¶
func (o *Observation) RecordError(err error)
RecordError records an exception and marks the observation as failed. It does not end the observation. At most eight exception events are retained; later calls are omitted with one diagnostic. Error text is content: it is exported only when content capture is enabled for the observation, and then passes through Config.Mask as MaskErrorMessage. Otherwise, and when the text is invalid UTF-8, over 64 KiB, or masked to anything but a string, the status and exception message are the payload-free string "error". The exception type is always recorded. For a payload-free failure category, set Level and StatusMessage through Observation.Update instead.
func (*Observation) Sampled ¶ added in v0.4.0
func (o *Observation) Sampled() bool
Sampled reports whether this observation's trace was selected for export by sampling. It reports false on a no-op observation. It is a sampling decision, not a delivery guarantee: exporting still requires End, a live client, and export success. Use it to skip work whose only purpose is enriching an observation that will never be exported, together with TraceSampledAt when gating on a smaller correlated fraction.
func (*Observation) TraceID ¶
func (o *Observation) TraceID() string
TraceID returns the lowercase 32-character OpenTelemetry trace ID, or an empty string for a no-op observation.
func (*Observation) Update ¶
func (o *Observation) Update(values ObservationAttributes)
Update merges non-zero fields into an active observation. Structured model, usage, and cost maps replace their complete serialized attributes when set; metadata merges by top-level key. StartTime cannot be changed after start and is ignored with a diagnostic.
type ObservationAttributes ¶
type ObservationAttributes struct {
// Input and Output are explicit content. They are never inferred by the
// SDK, are subject to Config.DisableContentCapture and
// Client.WithContentCapture, and pass through Mask.
Input any
Output any
// Metadata merges by top-level key across Update calls and passes through
// Mask. Empty maps are ignored and cannot clear earlier metadata. At most 32
// distinct keys are retained over an observation's lifetime; keys are
// limited to 200 bytes.
Metadata map[string]any
Level Level
// StatusMessage is explicit telemetry content, is limited to 16 KiB, and
// does not pass through Mask. Sanitize it before calling the SDK.
StatusMessage string
// Version overrides a propagated TraceAttributes.Version on this
// observation only.
Version string
// The remaining fields are honored only by generation and embedding
// observations, except Prompt, which Langfuse links only on generations.
Model string
ModelParameters map[string]any
Usage *Usage
CostDetails map[string]float64
Prompt *PromptRef
CompletionStartTime time.Time
// StartTime is honored only by StartObservation; Event and Update ignore
// it with a diagnostic.
StartTime time.Time
}
ObservationAttributes contains fields that can be set when an observation starts or in a later Update. Zero values are ignored and updates never clear an already recorded value. Each serialized structured value is limited to 1 MiB and the observation-level payload attributes are limited to 2 MiB in aggregate over the observation's current values. Separately bounded trace/client propagation and exception events sit outside that aggregate. Oversized fields are omitted with a payload-free OpenTelemetry diagnostic.
type ObservationType ¶
type ObservationType string
ObservationType identifies how Langfuse presents an observation.
const ( TypeSpan ObservationType = "span" TypeGeneration ObservationType = "generation" TypeEvent ObservationType = "event" TypeEmbedding ObservationType = "embedding" TypeAgent ObservationType = "agent" TypeTool ObservationType = "tool" TypeChain ObservationType = "chain" TypeRetriever ObservationType = "retriever" TypeEvaluator ObservationType = "evaluator" TypeGuardrail ObservationType = "guardrail" )
type Prompt ¶ added in v0.3.0
type Prompt struct {
Name string
Version int
Type PromptType
Text string
Messages []PromptMessage
Config json.RawMessage
Labels []string
Tags []string
CommitMessage string
// Source reports whether this value was fetched, served from fresh or
// stale cache, or produced from PromptQuery.Fallback.
Source PromptSource
}
Prompt is one fetched prompt version. GetPrompt returns an independent deep copy (the SDK's cached master is never exposed), so callers may retain or modify the value freely.
func (Prompt) Compile ¶ added in v0.3.0
Compile substitutes {{variable}} occurrences in the prompt content and returns the compiled copy; the receiver is unchanged. String values substitute verbatim; any other value is JSON-encoded, and a conversion that fails or panics leaves that occurrence unresolved; Compile never fails and never panics. For chat prompts, a variable whose value is []PromptMessage fills the placeholder of that name: an empty slice removes the placeholder, and a slice containing any invalid message leaves the placeholder unchanged (never a partial splice). Unresolved variables and unfilled placeholders stay verbatim, matching the Python SDK; non-string values use JSON rather than Python's str().
Example ¶
package main
import (
"fmt"
"github.com/fgn/go-langfuse"
)
func main() {
prompt := langfuse.Prompt{
Type: langfuse.PromptTypeText,
Text: "Summarize {{topic}} in one line.",
}
compiled := prompt.Compile(map[string]any{"topic": "Go context"})
fmt.Println(compiled.Text)
}
Output: Summarize Go context in one line.
func (Prompt) CompileStrict ¶ added in v0.3.0
CompileStrict compiles the same copy as Compile and also reports missing content variables, values that cannot be stringified, and unfilled chat placeholders. The returned prompt contains every successful substitution even when the error is non-nil.
func (Prompt) DecodeConfig ¶ added in v0.3.0
DecodeConfig decodes Config into v. An absent config is a no-op, allowing callers to set defaults on v before decoding prompt-owned overrides.
The prompt config is server-controlled, so a decode failure is reported through payload-free categories that name only the caller-owned target type: the underlying encoding/json error is never wrapped or surfaced, because its text can echo config values or offending bytes into an error callers routinely log.
func (Prompt) Ref ¶ added in v0.3.0
Ref returns the reference that links observations to this prompt version, for ObservationAttributes.Prompt. It returns nil, safely skipping linking, for a fallback prompt and for any value that cannot form a valid reference (empty Name or Version <= 0, such as a zero Prompt).
type PromptFallback ¶ added in v0.3.0
type PromptFallback struct {
// Type declares the prompt shape. Empty infers chat when Messages is
// non-nil (an empty non-nil slice is a deliberate empty chat prompt) and
// text otherwise. Explicit text requires Messages == nil; explicit chat
// requires Text == "".
Type PromptType
// Text is the text prompt body.
Text string
// Messages is the chat prompt body.
Messages []PromptMessage
// Config is surfaced through Prompt.Config; when non-empty it must be
// valid JSON.
Config json.RawMessage
}
PromptFallback is a locally supplied prompt body used when a fetch cannot resolve a compatible prompt.
type PromptMessage ¶ added in v0.3.0
type PromptMessage struct {
Role string
Content string
// PlaceholderName marks this message as a named placeholder slot; when
// set, Role, Content, and Extra must be empty.
PlaceholderName string
// Extra preserves additional message fields beyond role and content (for
// example tool_calls) verbatim, as one JSON object. Compile never
// substitutes inside Extra.
Extra json.RawMessage
}
PromptMessage is one chat prompt message. A regular message sets Role (required) and Content (optional; tool-call messages may have empty content); a placeholder message sets only PlaceholderName, a named slot filled at Compile time.
type PromptQuery ¶ added in v0.3.0
type PromptQuery struct {
// Version selects an exact prompt version. Zero means "use Label";
// negative values are rejected.
Version int
// Label selects the deployment label; empty means "production".
// Version and Label are mutually exclusive.
Label string
// Type requires the resolved prompt to have this shape. Empty accepts
// either text or chat. A mismatch is resolved through Fallback when set
// and otherwise returns ErrPromptTypeMismatch. Type filters per call: it
// is not part of the cache key and does not suppress the shared entry's
// background refresh, so a differently typed caller still keeps the entry
// fresh.
Type PromptType
// CacheTTL overrides the 60-second default freshness window for this
// call. Zero means the default; negative values are rejected. Freshness
// is judged against the age of the cached entry at call time, so callers
// with different TTLs share one entry (a deliberate divergence from the
// official SDKs, which stamp an expiry when the entry is inserted).
CacheTTL time.Duration
// DisableCache bypasses the cache entirely for this call (no read, no
// write, no shared in-flight fetch), forcing a fresh fetch.
DisableCache bool
// Fallback is returned when a fetch fails without a cached value or the
// resolved prompt does not match Type, so a local prompt can guarantee
// availability. A fallback result is never cached and Ref on it returns
// nil, so it is not linked to observations. Fallback never overrides the
// caller's own context cancellation on a blocking fetch path.
Fallback *PromptFallback
}
PromptQuery selects a prompt version and controls caching. The zero value requests the "production"-labeled version with the default 60-second TTL.
type PromptSource ¶ added in v0.3.0
type PromptSource string
PromptSource reports how GetPrompt resolved a prompt.
const ( PromptSourceServer PromptSource = "server" PromptSourceCache PromptSource = "cache" PromptSourceStale PromptSource = "stale" PromptSourceFallback PromptSource = "fallback" )
type PromptType ¶ added in v0.3.0
type PromptType string
PromptType discriminates text and chat prompts.
const ( PromptTypeText PromptType = "text" PromptTypeChat PromptType = "chat" )
type RunEvaluator ¶ added in v0.12.0
type RunEvaluator func(ctx context.Context, results []ExperimentItemResult) ([]Evaluation, error)
RunEvaluator scores a whole run from its item results, including failed items.
type Score ¶
type Score struct {
// ID makes submissions idempotent: Langfuse upserts scores by ID.
// Optional; the SDK generates a random ID when empty so retried
// deliveries cannot create duplicates.
ID string
// Name identifies the score series, for example "user-feedback".
// Required; at most 200 characters.
Name string
// TraceID, SessionID, DatasetRunID, and ObservationID select the score
// target. Exactly one of TraceID, SessionID, or DatasetRunID is required,
// and ObservationID additionally requires TraceID. DatasetRunID is an
// experiment ID returned by [Client.RunExperiment] for dataset items.
// Correction scores require a trace target.
TraceID string
SessionID string
DatasetRunID string
ObservationID string
// Exactly one of NumericValue or StringValue must be set. NUMERIC and
// BOOLEAN use NumericValue, while CATEGORICAL, CORRECTION, and TEXT use
// StringValue. Boolean scores use NumericValue 0 or 1.
NumericValue *float64
StringValue *string
// DataType is optional; when empty, Langfuse infers NUMERIC or
// CATEGORICAL from the value type. TEXT values must contain 1 to 500
// UTF-16 code units.
DataType ScoreDataType
// ConfigID references a Langfuse score config by its identifier.
// Optional; at most 200 characters. Langfuse checks the score against the
// config only after accepting it and drops a violating score without
// reporting it to the client, for RecordScore and CreateScore alike.
// Correction scores cannot use ConfigID.
ConfigID string
// Comment is explicit content supplied by the caller. It is not
// processed by Config.Mask; sanitize it before calling the SDK.
Comment string
// Metadata is passed to Config.Mask as one complete value and must remain a
// map[string]any to be retained. The resulting map is serialized as one JSON
// value.
Metadata map[string]any
// Timestamp records when the scored interaction happened, for example
// when feedback is computed by a batch job hours after the trace. The
// zero value stamps the score with the time RecordScore accepted it. The
// UTC year must stay within the four-digit RFC 3339 range.
// [Client.CreateScore] cannot set it.
Timestamp time.Time
// Source is empty or ScoreSourceAPI for RecordScore. CreateScore also
// accepts ScoreSourceAnnotation, which requires ConfigID unless the
// score is CORRECTION, so the value can prefill an annotation queue.
Source ScoreSource
// QueueID names the annotation queue the score belongs to. Optional.
QueueID string
}
Score is one evaluation or feedback value attached to a trace, a session, an observation, or a dataset run. Scores are submitted through the Langfuse JSON ingestion API rather than the OpenTelemetry trace pipeline.
type ScoreCategory ¶ added in v0.13.0
ScoreCategory is one category of a categorical or boolean score config. Scores use the label as their value.
type ScoreConfig ¶ added in v0.13.0
type ScoreConfig struct {
ID string
Name string
DataType ScoreDataType
Archived bool
Categories []ScoreCategory
MinValue *float64
MaxValue *float64
Description string
CreatedAt time.Time
UpdatedAt time.Time
}
ScoreConfig is a score config as stored by Langfuse.
type ScoreConfigQuery ¶ added in v0.13.0
type ScoreConfigQuery struct {
// PageSize is the number of configs per request; 0 selects 50 and
// Langfuse accepts at most 100.
PageSize int
}
ScoreConfigQuery configures Client.ScoreConfigs.
type ScoreConfigSpec ¶ added in v0.13.0
type ScoreConfigSpec struct {
// Name is required: at most 35 UTF-16 code units of letters, digits,
// underscores, spaces, periods, parentheses, and hyphens. Scores that use
// the config are stored under its name.
Name string
// DataType is ScoreTypeNumeric, ScoreTypeBoolean, ScoreTypeCategorical,
// or ScoreTypeText.
DataType ScoreDataType
// Categories are required for a CATEGORICAL config, which needs at least
// one, and not allowed for any other; labels and values must be unique.
// BOOLEAN configs get "True" (1) and "False" (0).
Categories []ScoreCategory
// MinValue and MaxValue bound a NUMERIC config inclusively; nil is
// unbounded, and MaxValue must exceed MinValue.
MinValue *float64
MaxValue *float64
// Description is shown in the Langfuse UI. It is not masked.
Description string
}
ScoreConfigSpec creates a score config. Langfuse does not key configs by name, so creating the same spec twice stores two configs.
type ScoreConfigUpdate ¶ added in v0.13.0
type ScoreConfigUpdate struct {
// Archived hides a config from new annotations; Langfuse then drops new
// scores that reference it.
Archived *bool
Name *string
// Description, set to "", empties the description.
Description *string
// Categories replace the stored ones; they fit a CATEGORICAL config, or
// a BOOLEAN one as exactly "True" (1) then "False" (0). The SDK rejects
// an empty non-nil slice.
Categories []ScoreCategory
MinValue *float64
MaxValue *float64
}
ScoreConfigUpdate changes a stored score config; nil fields keep their stored values, and at least one must be set. Langfuse cannot change the data type or remove MinValue or MaxValue, and validates the result as a whole.
type ScoreDataType ¶
type ScoreDataType string
ScoreDataType identifies how Langfuse stores and aggregates a score value.
const ( ScoreTypeBoolean ScoreDataType = "BOOLEAN" ScoreTypeCategorical ScoreDataType = "CATEGORICAL" ScoreTypeCorrection ScoreDataType = "CORRECTION" ScoreTypeNumeric ScoreDataType = "NUMERIC" ScoreTypeText ScoreDataType = "TEXT" )
type ScoreQuery ¶ added in v0.13.0
type ScoreQuery struct {
IDs []string
Names []string
Sources []ScoreSource
DataTypes []ScoreDataType
Environments []string
ConfigIDs []string
QueueIDs []string
AuthorUserIDs []string
// TraceIDs, SessionIDs, and DatasetRunIDs select the scored object and
// exclude each other; TraceIDs also match the scores of the traces'
// observations. ObservationIDs requires TraceIDs.
TraceIDs []string
ObservationIDs []string
SessionIDs []string
DatasetRunIDs []string
// Values matches exact values and requires exactly one of the NUMERIC
// (finite numbers in JavaScript syntax), BOOLEAN ("true" or "false"), or
// CATEGORICAL (labels) data types.
Values []string
// MinValue and MaxValue bound the value inclusively and require
// DataTypes to be exactly NUMERIC.
MinValue *float64
MaxValue *float64
// From and To, when non-zero, bound the score timestamp to [From, To).
// Updating a score keeps its timestamp, so they cannot find recent
// changes to older scores.
From time.Time
To time.Time
// PageSize is the number of scores per request; 0 selects 50 and Langfuse
// accepts at most 100.
PageSize int
}
ScoreQuery selects scores for Client.Scores. Each non-empty filter restricts the result to scores matching one of its values; values must not contain commas or surrounding whitespace.
type ScoreSource ¶ added in v0.13.0
type ScoreSource string
ScoreSource records how a score was produced.
const ( // ScoreSourceAPI is the default for scores written through the SDK. ScoreSourceAPI ScoreSource = "API" // ScoreSourceAnnotation marks a human annotation, or a prefilled value // for a reviewer to confirm in an annotation queue. ScoreSourceAnnotation ScoreSource = "ANNOTATION" // ScoreSourceEval marks a score from a Langfuse-managed evaluator; the // SDK reads it but cannot write it. ScoreSourceEval ScoreSource = "EVAL" )
type StoredExperiment ¶ added in v0.12.0
type StoredExperiment struct {
ID string
Name string
Description string
DatasetID string
StartTime time.Time
EndTime time.Time
ItemCount int
// Metadata is the server's JSON object; nil when absent.
Metadata json.RawMessage
// Scores holds up to 50 scores on the experiment itself, such as run
// evaluations, without the fields that [StoredScore] lists as missing
// from experiment reads.
Scores []StoredScore
}
StoredExperiment is an experiment as Langfuse reports it. Its ID is the experiment ID of its items, which is also the dataset run ID for runs over dataset items.
type StoredExperimentItem ¶ added in v0.12.0
type StoredExperimentItem struct {
// ObservationID and TraceID identify the item root.
ObservationID string
TraceID string
StartTime time.Time
// EndTime is zero while the root is open.
EndTime time.Time
Level Level
Environment string
ExperimentID string
ExperimentName string
ExperimentDescription string
ItemID string
DatasetID string
// ItemVersion is zero for an unpinned item.
ItemVersion time.Time
// Content fields hold the server's JSON, nil when absent.
Input json.RawMessage
Output json.RawMessage
ExpectedOutput json.RawMessage
Metadata json.RawMessage
ItemMetadata json.RawMessage
ExperimentMetadata json.RawMessage
// Scores holds up to 50 scores on the item's trace and observations,
// without the fields that [StoredScore] lists as missing from experiment
// reads.
Scores []StoredScore
}
StoredExperimentItem is one experiment item as Langfuse reports it: the item's root observation and its experiment identity.
type StoredScore ¶ added in v0.13.0
type StoredScore struct {
Score
Environment string
// AuthorUserID is the Langfuse user who annotated the score, if any.
AuthorUserID string
CreatedAt time.Time
UpdatedAt time.Time
}
StoredScore is a score as stored by Langfuse. Score holds the fields a write sets; a BOOLEAN value is NumericValue 0 or 1, as Score writes it, and a CATEGORICAL value is its label in StringValue. Client.Scores fills every field; the scores of experiment reads lack Comment, ConfigID, Metadata, QueueID, and AuthorUserID, which Langfuse omits there.
type TraceAttributes ¶
type TraceAttributes struct {
Name string
UserID string
SessionID string
// Tags merge in caller order, de-duplicate, and retain at most 64 values
// and 16 KiB of UTF-8 data over one trace context.
Tags []string
// Metadata merges by top-level key and retains at most 32 distinct keys in
// one trace context so required observation fields remain within default
// OpenTelemetry span limits. Keys are limited to 200 bytes.
Metadata map[string]any
Version string
// Environment is a request-scoped override of Config.Environment for
// spans exported on this context path, validated with the same rule. It
// is also the only source of the langfuse_environment baggage member
// under [Client.WithBaggagePropagation]; the client-wide default is
// never propagated cross-process.
Environment string
}
TraceAttributes are request-scoped fields copied to an active SDK observation and to spans subsequently started from the returned context.
type Usage ¶
type Usage struct {
InputTokens int64
OutputTokens int64
CacheReadInputTokens int64
CacheCreationInputTokens int64
ReasoningOutputTokens int64
// Details contains additional provider-specific subsets. Keys prefixed
// input_ or output_ are subtracted from the corresponding base bucket.
// Such buckets must be mutually exclusive, must not overlap the typed
// cache/reasoning fields, and must be subsets of their inclusive total. The
// canonical input, output, total, cache, and reasoning keys are reserved.
// At most 64 provider-specific detail buckets are retained, with keys
// limited to 200 bytes.
Details map[string]int64
}
Usage records inclusive provider token counts. InputTokens includes cache tokens, and OutputTokens includes reasoning tokens. The SDK normalizes these values to Langfuse's exclusive usage_details representation while total remains the checked sum of the inclusive input and output totals.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
contrib
|
|
|
googlegenai
module
|
|
|
openai
module
|
|
|
examples
|
|
|
annotation
command
|
|
|
existingotel
command
|
|
|
experiments
command
|
|
|
prompts
command
|
|
|
quickstart
command
|
|
|
sampling
command
|
|
|
scores
command
|
|
|
shortlived
command
|
|
|
streaming
command
|
|
|
internal
|
|
|
attributes
Package attributes owns Langfuse's OpenTelemetry attribute contract.
|
Package attributes owns Langfuse's OpenTelemetry attribute contract. |
|
diagnostic
Package diagnostic reports payload-free SDK diagnostics through OpenTelemetry.
|
Package diagnostic reports payload-free SDK diagnostics through OpenTelemetry. |
|
otlpreceiver
Package otlpreceiver provides a local OTLP/HTTP protobuf receiver for tests.
|
Package otlpreceiver provides a local OTLP/HTTP protobuf receiver for tests. |
|
processor
Package processor contains the Langfuse OpenTelemetry span processor.
|
Package processor contains the Langfuse OpenTelemetry span processor. |