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
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 ¶
func NewEvaluator[I, R any](s *auth.Session, tp *trace.TracerProvider, api *api.API, project string) *Evaluator[I, R]
NewEvaluator 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.