Documentation
¶
Overview ¶
Package eval provides tools for evaluating AI model outputs. Evaluations help measure AI application performance (accuracy/quality) and create an effective feedback loop for AI development. They help teams understand if updates improve or regress application quality. Evaluations are a key part of the Braintrust platform.
An evaluation consists of three main components:
- Dataset: A set of test examples with inputs and expected outputs
- TaskFunc: The unit of work we are evaluating, usually one or more calls to an LLM
- Scorer: A function that scores the result of a task against the expected result
Type Parameters ¶
This package uses two generic type parameters throughout its API:
- I: The input type for the task (e.g., string, struct, []byte)
- R: The result/output type from the task (e.g., string, struct, complex types)
All of the input and result types must be JSON-encodable.
For example:
- Case[string, string] is a test case with string input and string output
- TaskFunc[Input, Output] is a task that takes Input and returns Output
- Dataset[string, bool] is an iterator over Cases with string inputs and boolean outputs
See Evaluator.Run for running evaluations.
Example ¶
Example demonstrates how to run a basic evaluation.
package main
import (
"context"
"fmt"
"log"
"go.opentelemetry.io/otel/sdk/trace"
"github.com/braintrustdata/braintrust-sdk-go"
"github.com/braintrustdata/braintrust-sdk-go/eval"
)
func main() {
ctx := context.Background()
// Create tracer provider
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(ctx) }()
// Create Braintrust client (reads BRAINTRUST_API_KEY from environment)
client, err := braintrust.New(tp, braintrust.WithProject("test-project"))
if err != nil {
log.Fatal(err)
}
// Create an evaluator with string input and output types
evaluator := braintrust.NewEvaluator[string, string](client)
// Define a simple task that adds exclamation marks
task := eval.T(func(ctx context.Context, input string) (string, error) {
return input + "!", nil
})
// Create test cases
dataset := eval.NewDataset([]eval.Case[string, string]{
{Input: "hello", Expected: "hello!"},
{Input: "world", Expected: "world!"},
})
// Create a scorer
scorer := eval.NewScorer("exact-match", func(ctx context.Context, result eval.TaskResult[string, string]) (eval.Scores, error) {
if result.Output == result.Expected {
return eval.S(1.0), nil
}
return eval.S(0.0), nil
})
// Run the evaluation
result, err := evaluator.Run(ctx, eval.Opts[string, string]{
Experiment: "example-eval",
Dataset: dataset,
Task: task,
Scorers: []eval.Scorer[string, string]{scorer},
Quiet: true,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Evaluation complete: %s\n", result.Name())
}
Output:
Example (EvalDefinition) ¶
Example_evalDefinition demonstrates how to define a reusable evaluation that can be run locally or registered with a remote eval server.
package main
import (
"context"
"fmt"
"log"
"go.opentelemetry.io/otel/sdk/trace"
"github.com/braintrustdata/braintrust-sdk-go"
"github.com/braintrustdata/braintrust-sdk-go/eval"
)
func main() {
ctx := context.Background()
// Create tracer provider
tp := trace.NewTracerProvider()
defer func() { _ = tp.Shutdown(ctx) }()
// Create Braintrust client
client, err := braintrust.New(tp, braintrust.WithProject("test-project"))
if err != nil {
log.Fatal(err)
}
// Create a runnable eval
e := braintrust.NewEval(client, &eval.Eval[string, string]{
Name: "classify",
Task: eval.T(func(ctx context.Context, input string) (string, error) {
return input + "!", nil
}),
Scorers: []eval.Scorer[string, string]{
eval.NewScorer("exact-match", func(ctx context.Context, result eval.TaskResult[string, string]) (eval.Scores, error) {
if result.Output == result.Expected {
return eval.S(1.0), nil
}
return eval.S(0.0), nil
}),
},
ProjectName: "test-project",
})
// Run it
result, err := e.Run(ctx, eval.RunOpts[string, string]{
Dataset: eval.NewDataset([]eval.Case[string, string]{
{Input: "hello", Expected: "hello!"},
}),
Quiet: true,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Evaluation complete: %s\n", result.Name())
}
Output:
Index ¶
- Constants
- type Case
- type Classification
- type Classifications
- type Classifier
- type ClassifyFunc
- type Dataset
- type DatasetAPI
- type DatasetQueryOpts
- type Eval
- type Evaluator
- type FunctionOpts
- type FunctionsAPI
- type Metadata
- type Opts
- type ParameterDef
- type ParameterSchema
- type Parameters
- func (p Parameters) Bool(name string) bool
- func (p Parameters) Float64(name string) float64
- func (p Parameters) Get(name string) (any, bool)
- func (p Parameters) Has(name string) bool
- func (p Parameters) Int(name string) int
- func (p Parameters) Prompt(name string) (*prompt.Prompt, bool)
- func (p Parameters) String(name string) string
- type Result
- type RunOpts
- type Score
- type ScoreFunc
- type Scorer
- type Scores
- type TaskFunc
- type TaskHooks
- type TaskOutput
- type TaskResult
- type WorkflowBatchItem
- type WorkflowBatchResult
- type WorkflowBatchScorer
- type WorkflowBatchTask
- type WorkflowBatching
- type WorkflowCompletion
- type WorkflowEval
- func (w *WorkflowEval[I, R]) Poll(ctx context.Context, runID string) (*WorkflowResult, error)
- func (w *WorkflowEval[I, R]) ProcessSubmissionResult(ctx context.Context, ref WorkflowSubmissionResult) (*WorkflowResult, error)
- func (w *WorkflowEval[I, R]) Start(ctx context.Context, opts WorkflowStartOpts[I, R]) (*WorkflowResult, error)
- func (w *WorkflowEval[I, R]) Status(ctx context.Context, runID string) (*WorkflowResult, error)
- type WorkflowEvalMemoryStore
- func (s *WorkflowEvalMemoryStore) AddToSet(ctx context.Context, key, member string) error
- func (s *WorkflowEvalMemoryStore) GetOrSet(ctx context.Context, key string, value []byte) ([]byte, bool, error)
- func (s *WorkflowEvalMemoryStore) GetSetSize(ctx context.Context, key string) (int, error)
- func (s *WorkflowEvalMemoryStore) Read(ctx context.Context, key string) ([]byte, error)
- func (s *WorkflowEvalMemoryStore) Write(ctx context.Context, key string, value []byte) error
- type WorkflowEvalRedisStore
- func (s *WorkflowEvalRedisStore) AddToSet(ctx context.Context, key, member string) error
- func (s *WorkflowEvalRedisStore) GetOrSet(ctx context.Context, key string, value []byte) ([]byte, bool, error)
- func (s *WorkflowEvalRedisStore) GetSetSize(ctx context.Context, key string) (int, error)
- func (s *WorkflowEvalRedisStore) Read(ctx context.Context, key string) ([]byte, error)
- func (s *WorkflowEvalRedisStore) Write(ctx context.Context, key string, value []byte) error
- type WorkflowEvalStore
- type WorkflowPollResult
- type WorkflowPollStatus
- type WorkflowRedisCommand
- type WorkflowResult
- type WorkflowRunStatus
- type WorkflowScorer
- type WorkflowScorerDefinition
- type WorkflowScorerItem
- type WorkflowStartOpts
- type WorkflowSubmissionContext
- type WorkflowSubmissionResult
- type WorkflowTask
- type WorkflowTaskDefinition
- type WorkflowTaskItem
- type WorkflowTaskResult
Examples ¶
Constants ¶
const ( // ParameterTypeModel renders a model picker. Its value reaches the task as // a string. ParameterTypeModel = "model" // ParameterTypePrompt renders a prompt picker. ParameterTypePrompt = "prompt" )
Parameter types with a dedicated control in the Braintrust playground. Any other value describes scalar data and is passed through as a JSON Schema type -- "string", "number", "integer", "boolean".
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Case ¶
type Case[I, R any] struct { // Input is the input to the task function. Input I // Expected is the expected output (for scoring). // Optional. Expected R // Tags are labels to attach to this case. // Optional. Tags []string // Metadata is additional metadata for this case. // Optional. Metadata map[string]interface{} // TrialCount overrides Opts.TrialCount for this case. // Optional. Values less than 1 use the evaluation default. TrialCount int // These fields are only set if the Case is part of a Dataset. // They link the eval result back to the source dataset row. ID string // Dataset record ID XactID string // Transaction ID Created string // Creation timestamp }
Case represents a single test case in an evaluation.
type Classification ¶ added in v0.8.0
type Classification struct {
// Name is the grouping key for this classification.
// If empty, it defaults to the name of the Classifier that produced it.
Name string
// ID is the stable identifier for the category (required).
ID string
// Label is an optional human-readable label.
Label string
// Metadata is optional additional metadata for this classification.
Metadata map[string]interface{}
}
Classification represents a single category result returned by a Classifier.
type Classifications ¶ added in v0.8.0
type Classifications = []Classification
Classifications is a collection of Classification results returned by classifiers.
type Classifier ¶ added in v0.8.0
type Classifier[I, R any] interface { // Name returns the name of this classifier. Name() string // Run categorizes the task result. // It returns zero or more Classification results. Run(context.Context, TaskResult[I, R]) (Classifications, error) }
Classifier is an interface for categorizing the output of a task.
Unlike Scorer, which returns numeric scores, a Classifier returns one or more Classification items with structured id/label/metadata.
func NewClassifier ¶ added in v0.8.0
func NewClassifier[I, R any](name string, fn ClassifyFunc[I, R]) Classifier[I, R]
NewClassifier creates a new classifier with the given name and classify function.
type ClassifyFunc ¶ added in v0.8.0
type ClassifyFunc[I, R any] func(ctx context.Context, result TaskResult[I, R]) (Classifications, error)
ClassifyFunc is a function that classifies a task result and returns a list of Classifications.
type Dataset ¶
type Dataset[I, R any] interface { // Next returns the next case, or io.EOF if there are no more cases. Next() (Case[I, R], error) // ID returns the dataset ID if backed by a Braintrust dataset. // Returns empty string for literal in-memory cases. ID() string // Version returns the dataset version if applicable. // Returns empty string for literal cases or unversioned datasets. Version() string }
Dataset is an iterator interface for evaluation datasets. It is commonly an in-memory slice of cases, but can also be a dataset lazily loaded from the Braintrust API.
func NewDataset ¶
NewDataset creates a Dataset iterator from a slice of cases.
type DatasetAPI ¶
type DatasetAPI[I, R any] struct { // contains filtered or unexported fields }
DatasetAPI provides methods for loading datasets with automatic type conversion so they can be easily used in evals.
func (*DatasetAPI[I, R]) Query ¶
func (d *DatasetAPI[I, R]) Query(ctx context.Context, opts DatasetQueryOpts) (Dataset[I, R], error)
Query loads a dataset with advanced query options.
type DatasetQueryOpts ¶
type DatasetQueryOpts struct {
// Name is the dataset name (requires project context)
Name string
// ID is the dataset ID
ID string
// ProjectID scopes a Name lookup to one project. Dataset names are only
// unique within a project, so a Name query without ProjectID or
// ProjectName can match a dataset in an unrelated project.
ProjectID string
// ProjectName scopes a Name lookup to one project, as an alternative to
// ProjectID.
ProjectName string
// Version specifies a specific dataset version
Version string
// Limit specifies the maximum number of records to return (0 = unlimited)
Limit int
}
DatasetQueryOpts contains options for querying datasets.
type Eval ¶ added in v0.12.0
type Eval[I, R any] struct { // Name is the eval name. Used as the default experiment name and as // the registration key when registered with a remote eval server. Name string // Task is the function under evaluation. Task TaskFunc[I, R] // Scorers are the scoring functions applied to each task result. Scorers []Scorer[I, R] // ParameterSchema declares the parameters this eval accepts. Declaring them // makes each one a control in the Braintrust playground; the values a user // configures there reach the task via [TaskHooks.Parameters], merged over // the defaults declared here. // // Optional. Parameters are a property of the eval, so the same definition // carries them whether it is run locally, from the CLI, or from a playground. ParameterSchema ParameterSchema // Dataset is the eval's own set of test cases. Optional: callers that pass // [RunOpts.Dataset] override it, which is what the Braintrust playground // does. It is the only source of data for a standalone run or for // `bt eval <package dir>`, which supply no cases of their own. Dataset Dataset[I, R] // ProjectName is the Braintrust project for this eval. // Optional; falls back to the default project from the client. ProjectName string // contains filtered or unexported fields }
Eval defines an evaluation: the task to run and the scorers to apply. Create one with [braintrust.NewEval], then call Eval.Run to execute it or pass it to a remote eval server.
type Evaluator ¶
type Evaluator[I, R any] struct { // contains filtered or unexported fields }
Evaluator provides a reusable way to run multiple evaluations with the same input and output types. This is useful when you need to run several evaluations in sequence with the same type signature, or use hosted prompts, scorers and datasets with automatic type conversion.
func NewEvaluator
deprecated
func NewEvaluator[I, R any](s *auth.Session, tp *trace.TracerProvider, client *api.API, project string) *Evaluator[I, R]
NewEvaluator creates an evaluator using the legacy API client's transport.
Deprecated: Use NewEvaluatorWithClient with a generated openapi.Client, or braintrust.NewEvaluator for SDK-managed configuration.
func NewEvaluatorWithClient ¶ added in v0.19.0
func NewEvaluatorWithClient[I, R any](s *auth.Session, tp *trace.TracerProvider, api *openapi.Client, project string) *Evaluator[I, R]
NewEvaluatorWithClient creates a new evaluator with explicit dependencies. The type parameters I (input) and R (result/output) must be specified explicitly. Users create Evaluators with braintrust.NewEvaluator.
func (*Evaluator[I, R]) Datasets ¶
func (e *Evaluator[I, R]) Datasets() *DatasetAPI[I, R]
Datasets is used to access Datasets API for loading datasets with this evaluator's type parameters.
func (*Evaluator[I, R]) Functions ¶ added in v0.1.0
func (e *Evaluator[I, R]) Functions() *FunctionsAPI[I, R]
Functions is used to execute hosted Braintrust functions (e.g. hosted tasks and hosted scorers) as part of an eval. As long as I and R are JSON-serializable, FunctionsAPI will automatically convert the input and output to and from JSON.
type FunctionOpts ¶ added in v0.1.0
type FunctionOpts struct {
// Slug is the function slug (required)
Slug string
// Project overrides the default project name (optional)
Project string
// Version pins to a specific function version (optional, e.g., "5878bd218351fb8e")
Version string
// Environment specifies the deployment environment (optional, e.g., "dev", "staging", "production")
Environment string
}
FunctionOpts contains options for loading functions.
type FunctionsAPI ¶ added in v0.1.0
type FunctionsAPI[I, R any] struct { // contains filtered or unexported fields }
FunctionsAPI provides access for executing tasks and scorers hosted at braintrust.dev.
func (*FunctionsAPI[I, R]) Scorer ¶ added in v0.1.0
func (f *FunctionsAPI[I, R]) Scorer(ctx context.Context, opts FunctionOpts) (Scorer[I, R], error)
Scorer loads a server-side scorer and returns a Scorer. The returned scorer, when called, will invoke the Braintrust scorer function remotely.
func (*FunctionsAPI[I, R]) Task ¶ added in v0.1.0
func (f *FunctionsAPI[I, R]) Task(ctx context.Context, opts FunctionOpts) (TaskFunc[I, R], error)
Task loads a server-side task/prompt and returns a TaskFunc. The returned function, when called, will invoke the Braintrust function remotely.
type Opts ¶
type Opts[I, R any] struct { // Required Experiment string Dataset Dataset[I, R] Task TaskFunc[I, R] // At least one of Scorers or Classifiers must be provided. // Scorers return numeric scores; Classifiers return categorical labels. // They run in parallel for each case and are independent of each other. Scorers []Scorer[I, R] Classifiers []Classifier[I, R] // Optional ProjectName string // Project name (uses default from config if not specified) ProjectID string // Project ID; when set, takes precedence over ProjectName and skips project creation Tags []string // Tags to apply to the experiment Metadata Metadata // Metadata to attach to the experiment Update bool // If true, append to existing experiment (default: false) Parallelism int // Number of goroutines (default: 1) TrialCount int // Number of times to run each case (default: 1) Quiet bool // Suppress result output (default: false) // Hooks carries in-flight run callbacks. Its type lives under internal/, so // only this module can populate it: the remote eval runner needs them, and // the shape of eval callbacks is not settled across the Braintrust SDKs // yet. Optional — a nil Hooks fires nothing. Hooks *evalhooks.Hooks // SpanParent overrides the parent attribute set on eval spans. // When zero, the default "experiment_id:<id>" parent is used. // The remote eval server sets this to link spans to a playground context. SpanParent bttrace.Parent // Generation is propagated from the parent context (e.g. a Braintrust playground // invocation) and injected into braintrust.span_attributes on every span. // The Braintrust backend uses it to link eval spans back to the triggering context. Generation any // Parameters holds the already-resolved parameter values surfaced to the task // via [TaskHooks.Parameters]. Callers going through [Eval.Run] get this from // [ParameterSchema.Resolve]; setting it directly bypasses the schema. Parameters Parameters // NoSendLogs runs the eval entirely locally: no experiment is registered // and no eval spans are sent to Braintrust. Cases still run and are scored. // The evaluator's session and API client are not used, so they may be nil. NoSendLogs bool }
Opts defines the options for running an evaluation. I is the input type and R is the result/output type.
Dataset can be in-memory cases created with NewDataset or API-backed datasets loaded with Evaluator.Datasets.
Task can be a TaskFunc, a function wrapped with T, or a hosted task function loaded with [Evaluator.Functions().Task].
Scorers can be local functions created with NewScorer or hosted scorer functions loaded with [Evaluator.Functions().Scorer].
type ParameterDef ¶ added in v0.12.0
type ParameterDef struct {
// Type selects the control the Braintrust playground renders.
//
// "model" renders a model picker whose value arrives as a string. Any other
// value describes scalar data and is passed through as a JSON Schema type --
// "string", "number", "integer", "boolean" -- rendered as a plain input.
Type string
// Default is used when a run supplies no value for this parameter. It is
// also what a local run sees, since nothing overrides it there.
Default any
// Description is shown alongside the control in the playground.
Description string
}
ParameterDef declares a single parameter.
type ParameterSchema ¶ added in v0.12.0
type ParameterSchema map[string]ParameterDef
ParameterSchema declares the parameters an eval accepts, keyed by name.
It is the *declaration*; Parameters is the *resolved values* for one run. Keeping the two names distinct matters, because they are easy to confuse: an eval declares a ParameterSchema once, and every run of it produces its own Parameters.
Declaring a schema makes the parameters configurable from the Braintrust playground, where each entry becomes a control:
ParameterSchema: eval.ParameterSchema{
"model": {Type: "model", Default: "gpt-4o", Description: "Model to use"},
"temperature": {Type: "number", Default: 0.0},
},
func (ParameterSchema) Resolve ¶ added in v0.12.0
func (s ParameterSchema) Resolve(values map[string]any) (Parameters, error)
Resolve merges the supplied values over the schema's declared defaults, producing the Parameters a run surfaces to the task.
Supplied values win. Names absent from the schema pass through, matching the other SDKs -- the playground may send a parameter the code has not declared, and dropping it silently would be worse than surfacing it. Returns nil when there is nothing to surface, so a task can distinguish "no parameters" from "an empty set".
It returns an error so that a parameter type needing conversion or validation can reject a bad value here, before a run starts, rather than failing partway through a task.
Resolve is idempotent: resolving an already-resolved set returns it unchanged. Callers rely on that, because a run may resolve once up front to report a bad value and again when the run is assembled.
type Parameters ¶ added in v0.12.0
Parameters holds the resolved parameter values for a single eval run.
When an eval is driven from the Braintrust playground via the remote eval server, the controls a user configures (a model picker, a numeric threshold, and so on) arrive as a flat map of values. The runner merges them over the defaults declared in ParameterSchema and hands the result to the task on TaskHooks.Parameters. For a local run, whatever is passed in RunOpts.Parameters is what the task sees.
It is a map[string]any, so you can range over it directly, but the typed accessors below are the idiomatic way to read a value: they hide the fact that JSON numbers decode as float64 and never panic on a type mismatch (returning the zero value instead).
model := hooks.Parameters.String("model")
max := hooks.Parameters.Int("max_length")
p, ok := hooks.Parameters.Prompt("summary_prompt")
func (Parameters) Bool ¶ added in v0.12.0
func (p Parameters) Bool(name string) bool
Bool returns the value for name as a bool, or false if it is absent or not a bool.
func (Parameters) Float64 ¶ added in v0.12.0
func (p Parameters) Float64(name string) float64
Float64 returns the value for name as a float64, or 0 if it is absent or not a number.
func (Parameters) Get ¶ added in v0.12.0
func (p Parameters) Get(name string) (any, bool)
Get returns the raw value for name and whether it was present.
func (Parameters) Has ¶ added in v0.12.0
func (p Parameters) Has(name string) bool
Has reports whether a value for name is present.
func (Parameters) Int ¶ added in v0.12.0
func (p Parameters) Int(name string) int
Int returns the value for name as an int, or 0 if it is absent or not a number. JSON numbers decode as float64, so those are converted here; int and json.Number are also accepted.
func (Parameters) Prompt ¶ added in v0.13.0
func (p Parameters) Prompt(name string) (*prompt.Prompt, bool)
Prompt returns the value for name as a prompt.Prompt, and whether it is one. A parameter declared with type "prompt" arrives as a prompt whether its value was chosen in the playground or came from the default declared in Go.
p, ok := hooks.Parameters.Prompt("summary_prompt")
if !ok {
return "", errors.New("summary_prompt is not a prompt")
}
built, err := p.Build(map[string]any{"input": input})
For a local run, prompt data set directly in RunOpts.Parameters -- a prompt.Definition, prompt.Data, or decoded JSON -- is converted here, so the task reads it the same way it would under the playground.
func (Parameters) String ¶ added in v0.12.0
func (p Parameters) String(name string) string
String returns the value for name as a string, or "" if it is absent or not a string.
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result contains the results of an evaluation.
func (*Result) ProjectName ¶ added in v0.12.0
ProjectName returns the project name.
type RunOpts ¶ added in v0.12.0
type RunOpts[I, R any] struct { // Experiment overrides the experiment name. Defaults to [Eval.Name]. Experiment string // ProjectName overrides the project name. Defaults to [Eval.ProjectName]. ProjectName string // ProjectID names the project by ID instead of by name. When set it takes // precedence over ProjectName, and the project is used as-is rather than // created — which is what a caller whose credentials cannot create // projects needs. The Braintrust playground sends this. ProjectID string // Dataset is the test cases to evaluate against. // Defaults to [Eval.Dataset]; required if the eval defines none. Dataset Dataset[I, R] // Tags to apply to the experiment. Tags []string // Metadata to attach to the experiment. Metadata Metadata // Update appends to an existing experiment when true (default: false). Update bool // Parallelism is the number of goroutines (default: 1). Parallelism int // Quiet suppresses result output (default: false). Quiet bool // Hooks carries in-flight run callbacks. Its type lives under internal/, so // only this module can populate it: the remote eval runner needs them, and // the shape of eval callbacks is not settled across the Braintrust SDKs // yet. Optional — a nil Hooks fires nothing. Hooks *evalhooks.Hooks // SpanParent overrides the parent attribute set on eval spans. // When zero, the default "experiment_id:<id>" parent is used. // The remote eval server sets this to link spans to a playground context. SpanParent bttrace.Parent // Generation is propagated from the parent context (e.g. a Braintrust playground // invocation) and injected into braintrust.span_attributes on every span. // The Braintrust backend uses it to link eval spans back to the triggering context. Generation any // Parameters supplies values for this run. They are merged over the defaults // declared in [Eval.ParameterSchema] and surfaced to the task via // [TaskHooks.Parameters]. The remote eval runner sets this from the // playground request; most direct runs leave it empty and get the declared // defaults. Parameters Parameters // NoSendLogs runs the eval entirely locally: no experiment is registered // and no eval spans are sent to Braintrust. Cases still run and are scored. // The result has no experiment ID or permalink. NoSendLogs bool }
RunOpts configures a single evaluation run. These vary per invocation; the Eval definition stays the same.
type Score ¶
type Score struct {
// Name is the name of the score (e.g., "accuracy", "exact_match").
Name string
// Score is the numeric score value.
Score float64
// Metadata is optional additional metadata for this score.
Metadata map[string]interface{}
}
Score represents a single score result.
type Scorer ¶
type Scorer[I, R any] interface { // Name returns the name of this scorer. Name() string // Run evaluates the task result. // It returns one or more Score results. Run(context.Context, TaskResult[I, R]) (Scores, error) }
Scorer is an interface for scoring the output of a task.
type TaskFunc ¶
TaskFunc is the signature for evaluation task functions. It receives the input, hooks for accessing eval context, and returns a TaskOutput.
func T ¶
T is a convenience function for writing short task functions (TaskFunc) that only use the input and output and don't need Hooks or other advanced features.
task := eval.T(func(ctx context.Context, input string) (string, error) {
return input, nil
})
func TaskWithHooks ¶ added in v0.12.0
func TaskWithHooks[I, R any](fn func(ctx context.Context, input I, hooks *TaskHooks) (R, error)) TaskFunc[I, R]
TaskWithHooks is like T but also passes the TaskHooks, for tasks that need to read parameters, metadata, or tags. It handles the TaskOutput wrapping so you can return a plain value.
task := eval.TaskWithHooks(func(ctx context.Context, input string, hooks *eval.TaskHooks) (string, error) {
model := hooks.Parameters.String("model")
return classify(input, model), nil
})
type TaskHooks ¶
type TaskHooks struct {
// The eval and task spans are included, if you want to add custom attributes or events.
TaskSpan oteltrace.Span
EvalSpan oteltrace.Span
// Readonly fields. These aren't necessarily recommended to be included in the task function,
// but are available for advanced use cases.
Expected any // Not usually used in tasks, so this is untyped
Metadata Metadata // Case metadata
Tags []string // Case tags
TrialIndex int // The index of the current trial (0-based)
// Parameters holds the resolved parameter values for this run. When the eval
// is driven from a Braintrust playground via the remote eval server, these
// are the values a user configured for the run (with declared defaults
// merged in). Empty for a local run unless set via [RunOpts.Parameters].
Parameters Parameters
}
TaskHooks provides access to evaluation context within a task. All fields are read-only except for span modification.
type TaskOutput ¶
type TaskOutput[R any] struct { Value R // UserData allows passing custom application context to scorers. // This field is NOT logged and isn't supported outside the context of the Go SDK. // Use this for in-process data like database connections, file handles, or metrics. UserData any }
TaskOutput wraps the output value from a task.
type TaskResult ¶
type TaskResult[I, R any] struct { Input I // The case input Expected R // What we expected Output R // What the task actually returned Metadata Metadata // Case metadata // UserData is custom application context from the task. // This field is NOT logged and isn't supported outside the context of the Go SDK. UserData any }
TaskResult represents the complete result of executing a task on a case. This is passed to scorers for evaluation.
type WorkflowBatchItem ¶ added in v0.18.0
WorkflowBatchItem attaches a provider-safe identifier to a case. Submit must use CustomID as the provider's custom_id, and Collect must return it unchanged.
type WorkflowBatchResult ¶ added in v0.18.0
WorkflowBatchResult contains either a result or a per-item error.
type WorkflowBatchScorer ¶ added in v0.18.0
type WorkflowBatchScorer[I, R any] struct { Name string Batching WorkflowBatching Submit func(context.Context, []WorkflowBatchItem[WorkflowScorerItem[I, R]], WorkflowSubmissionContext) (json.RawMessage, error) Completion WorkflowCompletion Collect func(context.Context, json.RawMessage, WorkflowSubmissionContext, func(WorkflowBatchResult[Scores]) error) error }
WorkflowBatchScorer batches task outputs for asynchronous scoring.
type WorkflowBatchTask ¶ added in v0.18.0
type WorkflowBatchTask[I, R any] struct { Batching WorkflowBatching Submit func(context.Context, []WorkflowBatchItem[WorkflowTaskItem[I, R]], WorkflowSubmissionContext) (json.RawMessage, error) Completion WorkflowCompletion Collect func(context.Context, json.RawMessage, WorkflowSubmissionContext, func(WorkflowBatchResult[WorkflowTaskResult[R]]) error) error }
WorkflowBatchTask submits multiple cases in each provider operation. Collect calls yield for each result and must stop on a yield error. A failed Collect can be retried; already checkpointed items are ignored on replay.
type WorkflowBatching ¶ added in v0.18.0
WorkflowBatching controls provider batch sizes. MaxWait applies only to scorers: it flushes partial batches during advancement, and zero waits until full or no more items can arrive. Task batches are submitted immediately, so a batch task rejects a nonzero MaxWait.
type WorkflowCompletion ¶ added in v0.18.0
type WorkflowCompletion struct {
Poll func(context.Context, json.RawMessage, WorkflowSubmissionContext) (WorkflowPollResult, error)
GetExternalID func(context.Context, json.RawMessage, WorkflowSubmissionContext) (string, error)
}
WorkflowCompletion selects exactly one completion mode. Poll checks the provider; GetExternalID extracts the ID delivered by a verified webhook.
type WorkflowEval ¶ added in v0.18.0
type WorkflowEval[I, R any] struct { Name string Store WorkflowEvalStore Task WorkflowTaskDefinition[I, R] Scorers []Scorer[I, R] WorkflowScorers []WorkflowScorerDefinition[I, R] Classifiers []Classifier[I, R] ParameterSchema ParameterSchema ProjectName string MaxConcurrency int // contains filtered or unexported fields }
WorkflowEval defines a durable evaluation. Keep the definition (including scorer names/order) unchanged while runs are active. Serialize calls advancing the same run, including across processes. Provider callbacks may run concurrently.
func NewWorkflowEval ¶ added in v0.18.0
func NewWorkflowEval[I, R any](evaluator *Evaluator[I, R], definition *WorkflowEval[I, R]) *WorkflowEval[I, R]
NewWorkflowEval attaches the evaluator's API and tracing infrastructure. Applications normally use braintrust.NewWorkflowEval.
func (*WorkflowEval[I, R]) Poll ¶ added in v0.18.0
func (w *WorkflowEval[I, R]) Poll(ctx context.Context, runID string) (*WorkflowResult, error)
Poll checks pending poll-mode submissions once and advances ready stages. It also retries incomplete submissions and collection checkpoints. Submissions reporting WorkflowFailed stay pending and are returned as errors.
func (*WorkflowEval[I, R]) ProcessSubmissionResult ¶ added in v0.18.0
func (w *WorkflowEval[I, R]) ProcessSubmissionResult(ctx context.Context, ref WorkflowSubmissionResult) (*WorkflowResult, error)
ProcessSubmissionResult collects a completed provider operation and advances its run. Repeated completion notifications are harmless after checkpointing.
func (*WorkflowEval[I, R]) Start ¶ added in v0.18.0
func (w *WorkflowEval[I, R]) Start(ctx context.Context, opts WorkflowStartOpts[I, R]) (*WorkflowResult, error)
Start persists the dataset and submits initial task work. Provider polling is explicit: call Poll later, or deliver completion through ProcessSubmissionResult.
func (*WorkflowEval[I, R]) Status ¶ added in v0.18.0
func (w *WorkflowEval[I, R]) Status(ctx context.Context, runID string) (*WorkflowResult, error)
Status reads persisted progress without submitting, polling, or collecting.
type WorkflowEvalMemoryStore ¶ added in v0.18.0
type WorkflowEvalMemoryStore struct {
// contains filtered or unexported fields
}
WorkflowEvalMemoryStore stores workflow state in memory. It is safe for concurrent access, but loses all records when its process exits.
func NewWorkflowEvalMemoryStore ¶ added in v0.18.0
func NewWorkflowEvalMemoryStore() *WorkflowEvalMemoryStore
NewWorkflowEvalMemoryStore creates an empty in-memory workflow store.
func (*WorkflowEvalMemoryStore) AddToSet ¶ added in v0.18.0
func (s *WorkflowEvalMemoryStore) AddToSet(ctx context.Context, key, member string) error
AddToSet atomically adds a unique member.
func (*WorkflowEvalMemoryStore) GetOrSet ¶ added in v0.18.0
func (s *WorkflowEvalMemoryStore) GetOrSet(ctx context.Context, key string, value []byte) ([]byte, bool, error)
GetOrSet atomically creates a record if absent and returns its stored value.
func (*WorkflowEvalMemoryStore) GetSetSize ¶ added in v0.18.0
GetSetSize returns the number of unique members.
type WorkflowEvalRedisStore ¶ added in v0.18.0
type WorkflowEvalRedisStore struct {
// contains filtered or unexported fields
}
WorkflowEvalRedisStore persists records in Redis with atomic Lua operations. Use a dedicated prefix. TTL must exceed the longest run and webhook retry window; it is refreshed on writes, not reads. Expired runs cannot be resumed.
func NewWorkflowEvalRedisStore ¶ added in v0.18.0
func NewWorkflowEvalRedisStore(command WorkflowRedisCommand, prefix string, ttl time.Duration) (*WorkflowEvalRedisStore, error)
NewWorkflowEvalRedisStore creates a Redis store. An empty prefix defaults to braintrust-eval:, and a zero TTL defaults to seven days.
func (*WorkflowEvalRedisStore) AddToSet ¶ added in v0.18.0
func (s *WorkflowEvalRedisStore) AddToSet(ctx context.Context, key, member string) error
AddToSet adds a member and refreshes the set's TTL atomically.
func (*WorkflowEvalRedisStore) GetOrSet ¶ added in v0.18.0
func (s *WorkflowEvalRedisStore) GetOrSet(ctx context.Context, key string, value []byte) ([]byte, bool, error)
GetOrSet atomically creates an absent record and returns the stored value.
func (*WorkflowEvalRedisStore) GetSetSize ¶ added in v0.18.0
GetSetSize returns the number of distinct members.
type WorkflowEvalStore ¶ added in v0.18.0
type WorkflowEvalStore interface {
Read(context.Context, string) ([]byte, error)
Write(context.Context, string, []byte) error
GetOrSet(context.Context, string, []byte) (value []byte, created bool, err error)
AddToSet(context.Context, string, string) error
GetSetSize(context.Context, string) (int, error)
}
WorkflowEvalStore persists workflow records. A missing Read returns nil, nil. GetOrSet and AddToSet must be atomic. Byte records and sets use separate key spaces. Implementations must copy bytes and retain sets as long as records. Callers must serialize advancement of a run across processes; these primitives do not provide a distributed execution lock.
type WorkflowPollResult ¶ added in v0.18.0
type WorkflowPollResult struct {
Status WorkflowPollStatus
Error error
}
WorkflowPollResult reports provider completion or a terminal error.
type WorkflowPollStatus ¶ added in v0.18.0
type WorkflowPollStatus string
WorkflowPollStatus is the provider's completion state.
const ( // WorkflowPending means the provider has not finished. WorkflowPending WorkflowPollStatus = "pending" // WorkflowComplete means results can be collected. WorkflowComplete WorkflowPollStatus = "complete" // WorkflowFailed means the entire provider submission failed. Poll returns // the error and rechecks the submission on every later call, so a permanent // failure blocks completion; start a new run to recover. To finish a run // despite a failed provider batch, report WorkflowComplete and let Collect // omit the results so those items are recorded as failed. WorkflowFailed WorkflowPollStatus = "failed" )
type WorkflowRedisCommand ¶ added in v0.18.0
WorkflowRedisCommand executes a Redis command and returns its decoded result. With go-redis, wrap client.Do(ctx, args...).Result() and translate redis.Nil to nil, nil. Supplying a command adapter avoids adding a Redis client dependency to the SDK. The adapter must support EVAL and return nil, nil for a missing GET.
type WorkflowResult ¶ added in v0.18.0
type WorkflowResult struct {
RunID string
ExperimentID string
Permalink string
Status WorkflowRunStatus
Completed int
Failed int
PendingPoll int
PendingWebhook int
Scores map[string]float64
}
WorkflowResult reports progress. Completed counts terminal cases, including failures. Failed counts cases with any failed task, scorer, or classifier. Scores averages successful values by score name. Permalink links to the experiment and is empty for NoSendLogs runs.
type WorkflowRunStatus ¶ added in v0.18.0
type WorkflowRunStatus string
WorkflowRunStatus is the overall state of a workflow run.
const ( // WorkflowRunWaiting means cases or provider submissions are outstanding. WorkflowRunWaiting WorkflowRunStatus = "waiting" // WorkflowRunCompleted means every case has finished, including failures. WorkflowRunCompleted WorkflowRunStatus = "completed" )
type WorkflowScorer ¶ added in v0.18.0
type WorkflowScorer[I, R any] struct { Name string Submit func(context.Context, WorkflowScorerItem[I, R], WorkflowSubmissionContext) (json.RawMessage, error) Completion WorkflowCompletion Collect func(context.Context, json.RawMessage, WorkflowSubmissionContext) (Scores, error) }
WorkflowScorer submits one asynchronous scoring operation per task output.
type WorkflowScorerDefinition ¶ added in v0.18.0
type WorkflowScorerDefinition[I, R any] interface { // contains filtered or unexported methods }
WorkflowScorerDefinition accepts a WorkflowScorer or WorkflowBatchScorer. Ordinary scorers belong in WorkflowEval.Scorers.
type WorkflowScorerItem ¶ added in v0.18.0
type WorkflowScorerItem[I, R any] struct { TaskResult[I, R] ID string CaseID string Tags []string TrialIndex int }
WorkflowScorerItem is a completed task passed to a deferred scorer. Tags reflect any replacement returned by the task.
type WorkflowStartOpts ¶ added in v0.18.0
type WorkflowStartOpts[I, R any] struct { Dataset Dataset[I, R] Experiment string ProjectID string Tags []string Metadata Metadata TrialCount int Parameters Parameters NoSendLogs bool }
WorkflowStartOpts configures a new run. NoSendLogs supports local execution without a Braintrust client; it does not disable workflow persistence.
type WorkflowSubmissionContext ¶ added in v0.18.0
WorkflowSubmissionContext identifies a provider operation. SubmissionID is stable across retries and should be used as a provider idempotency key.
type WorkflowSubmissionResult ¶ added in v0.18.0
WorkflowSubmissionResult identifies a completed submission. ExternalID alone is sufficient. SubmissionID requires RunID. The application verifies webhooks.
type WorkflowTask ¶ added in v0.18.0
type WorkflowTask[I, R any] struct { Submit func(context.Context, WorkflowTaskItem[I, R], WorkflowSubmissionContext) (json.RawMessage, error) Completion WorkflowCompletion Collect func(context.Context, json.RawMessage, WorkflowSubmissionContext) (WorkflowTaskResult[R], error) }
WorkflowTask submits one asynchronous provider operation per case/trial. Submission handles must contain valid JSON and survive a process restart.
type WorkflowTaskDefinition ¶ added in v0.18.0
type WorkflowTaskDefinition[I, R any] interface { // contains filtered or unexported methods }
WorkflowTaskDefinition accepts a TaskFunc, WorkflowTask, or WorkflowBatchTask.
type WorkflowTaskItem ¶ added in v0.18.0
type WorkflowTaskItem[I, R any] struct { ID string CaseID string Input I Expected R Metadata Metadata Tags []string Parameters Parameters TrialIndex int }
WorkflowTaskItem is a persisted case/trial passed to a workflow task. ID is unique per trial. CaseID is shared by a case's trials: the dataset Case.ID when set, otherwise generated when the run starts.
type WorkflowTaskResult ¶ added in v0.18.0
WorkflowTaskResult is a task output with optional metadata and replacement tags.