eval

package
v0.36.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 25, 2026 License: Apache-2.0 Imports: 20 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package eval is an evaluation harness for GopherAgent agents. It runs an agent against a suite of tasks, checks the tool-call trajectory and the final answer (code graders and an optional LLM-as-judge), and produces pass/fail reports (JSON, JUnit XML, Markdown) that plug into CI.

Terminology

  • Task — one test case; a conversation of one or more Turns.
  • Turn — one user input plus the graders applied to that turn's answer.
  • Trial — one attempt at a Task. Agents are non-deterministic, so a Task may run N trials and report pass@k / pass^k.
  • Transcript — the record of one turn's run: final answer, tool calls, token usage, cost, latency, termination reason.
  • Grader — scores one Transcript. Built-ins (Contains, Regexp, Exact, Trajectory) are deterministic; Judge calls an LLM.
  • Suite — a named collection of Tasks with shared defaults.

Grading philosophy

Grade outcomes first: prefer checking the final answer and the tool results over mandating a rigid step sequence. Trajectory graders offer relaxed modes (in_order, subset) precisely so a creative-but-correct agent path is not penalized. The Judge grader carries an "unknown" escape hatch so a model judge never has to guess.

Zero-cost when unused

Nothing here runs unless a Task references it. Transcript capture allocates only what the event stream produces; the raw event slice is retained only when CaptureOptions.KeepEvents is set. The judge issues LLM calls only for tasks that declare a Judge grader.

Two ways to run

Inside `go test` via RunT — fully deterministic when the Target is backed by llmfake.ScriptedProvider, so it needs no API keys and runs in the library's own CI. Or through the cmd/gopherevals CLI against a real provider, writing reports and exiting non-zero below a pass-rate threshold.

Index

Constants

View Source
const (
	HITLRequired = "required"  // gate reached with no ConfirmHITL wired (out-of-band)
	HITLDenied   = "denied"    // ConfirmHITL returned false
	HITLTimedOut = "timed_out" // ConfirmHITLTimeout expired before a response
)

HITL record kinds — the observable outcomes of a human-in-the-loop gate. The approved path emits no event and so produces no record.

Variables

This section is empty.

Functions

func WriteJSON

func WriteJSON(w io.Writer, rep *SuiteReport) error

WriteJSON writes the report as indented JSON for programmatic consumption.

func WriteJUnit

func WriteJUnit(w io.Writer, rep *SuiteReport) error

WriteJUnit writes the report as JUnit XML: one testcase per task, a <failure> carrying the failing grade reasons, and <skipped> for tasks whose graders were all inconclusive (judge returned unknown).

func WriteMarkdown

func WriteMarkdown(w io.Writer, rep *SuiteReport) error

WriteMarkdown writes a PR-comment-friendly summary: a per-task table plus collapsible failure details.

func WriteTranscripts

func WriteTranscripts(w io.Writer, ts []*Transcript) error

WriteTranscripts writes transcripts as JSONL (one JSON object per line), streaming through a buffered writer so memory stays flat regardless of count. Persist a run's transcripts to re-grade later without re-running the agent (see GradeRecorded).

Types

type ArgMatcher

type ArgMatcher interface {
	MatchArgs(argsJSON string) (bool, string)
}

ArgMatcher validates one tool call's argument JSON. It returns whether the args are acceptable plus a short reason used in failure diffs.

func AnyArgs

func AnyArgs() ArgMatcher

AnyArgs accepts any arguments. It is also the default when ExpectedCall.Args is nil.

func ArgsExact

func ArgsExact(wantJSON string) ArgMatcher

ArgsExact matches when the call args equal wantJSON after canonicalization (parse both, deep-compare) so key order and whitespace do not matter. Falls back to raw string equality when wantJSON is not valid JSON.

func ArgsRegex

func ArgsRegex(key, pattern string) ArgMatcher

ArgsRegex matches when the string value at top-level key matches pattern. It compiles once and panics on a bad pattern (like regexp.MustCompile).

func ArgsSubset

func ArgsSubset(want map[string]any) ArgMatcher

ArgsSubset matches when every key in want is present in the call args with an equal value; extra keys in the call are ignored.

type CaptureOptions

type CaptureOptions struct {
	// KeepEvents retains the raw StreamEvent slice on Transcript.Events. Off
	// by default — most graders read the derived fields, not the raw trace.
	KeepEvents bool
	// IncludeSubagents records tool calls forwarded from sub-agents
	// (Source != ""). Off by default: forwarded events are observational, and
	// the framework itself treats them as non-authoritative for the answer.
	IncludeSubagents bool
}

CaptureOptions tunes what Capture records.

type ExpectedCall

type ExpectedCall struct {
	Name string
	Args ArgMatcher
}

ExpectedCall is one entry in an expected trajectory. Args nil means AnyArgs.

type Grade

type Grade struct {
	Grader string  `json:"grader"`
	Pass   bool    `json:"pass"`
	Score  float64 `json:"score"`            // 0..1; code graders emit 0 or 1
	Reason string  `json:"reason,omitempty"` // human-readable why (esp. on failure)
	// Unknown marks a verdict the grader could not determine (a judge escape
	// hatch). Unknown grades are excluded from a trial's pass/fail decision.
	Unknown bool `json:"unknown,omitempty"`
	// Err is a grader infrastructure failure (LLM call failed, panic) — not a
	// task failure. Reported distinctly; excluded from pass/fail like Unknown.
	Err error `json:"-"`
}

Grade is one grader's verdict on one Transcript.

type Grader

type Grader interface {
	Name() string
	Grade(ctx context.Context, tr *Transcript) Grade
}

Grader scores one Transcript. Implementations must be safe for concurrent use: the runner may grade trials in parallel.

func All

func All(gs ...Grader) Grader

All passes only when every sub-grader passes; Score is the minimum.

func Any

func Any(gs ...Grader) Grader

Any passes when at least one sub-grader passes; Score is the maximum.

func Contains

func Contains(substrs ...string) Grader

Contains passes when FinalAnswer contains every substring (case-sensitive).

func ContainsFold

func ContainsFold(substrs ...string) Grader

ContainsFold is Contains with case-insensitive matching.

func Exact

func Exact(want string) Grader

Exact passes when FinalAnswer equals want after trimming surrounding space.

func GraderFunc

func GraderFunc(name string, fn func(ctx context.Context, tr *Transcript) Grade) Grader

GraderFunc adapts a closure into a Grader. name labels the grade in reports.

func HITLTriggered

func HITLTriggered(tools ...string) Grader

HITLTriggered passes when a human-in-the-loop approval gate fired during the turn — for any of the named tools, or any tool when none are named.

Only the non-approval outcomes are observable: an unconfigured gate (ConfirmHITL nil → "required"), a denial, or a timeout. The approved path runs the tool silently with no HITL event. So to assert that a dangerous tool MUST be gated, run the agent-under-eval with ConfirmHITL denying (or left nil) — the resulting record proves the gate fired.

func NoError

func NoError() Grader

NoError passes when the run finished cleanly (no error, terminated "done").

func NoHITL

func NoHITL() Grader

NoHITL passes when no approval gate fired. Use it to guard against over-triggering — a safe request must not trip a confirmation gate.

func Regexp

func Regexp(pattern string) Grader

Regexp passes when FinalAnswer matches pattern. It compiles once at construction and panics on a bad pattern (like regexp.MustCompile), so misconfiguration fails loudly at wiring time, not mid-suite.

func Trajectory

func Trajectory(mode MatchMode, calls []ExpectedCall, opts ...TrajectoryOptions) Grader

Trajectory returns a code-based grader over Transcript.ToolCalls using the given match mode. Score carries partial credit for subsequence/subset modes; Reason carries a positional or set diff on failure.

type HITLRecord

type HITLRecord struct {
	Tool   string `json:"tool"`
	Args   string `json:"args,omitempty"`
	Kind   string `json:"kind"`             // required | denied | timed_out
	Source string `json:"source,omitempty"` // "" = top-level; "subagent:<name>" = forwarded
}

HITLRecord is one human-in-the-loop approval gate observed during a turn.

type HistoryReader

type HistoryReader interface {
	History(ctx context.Context, sessionKey string) ([]history.Message, error)
}

HistoryReader is an optional Target extension. Targets that implement it get tool results joined into the Transcript after each turn — tool results are not stream events, they live in session history as Role="tool" messages. Targets without it still capture tool calls, just with empty ToolCallRecord.Result.

type Judge

type Judge struct {
	// Provider is any agent.LLMProvider — a real vendor for CI or a fake in
	// tests. Required.
	Provider agent.LLMProvider
	// Rubric describes what a passing answer looks like. Required unless
	// Rubrics is set.
	Rubric string
	// Rubrics, when non-empty, lists individual criteria; the judge scores the
	// fraction satisfied and passes only when all are met. Combined with Rubric
	// if both are set.
	Rubrics []string
	// Samples is the number of independent judge calls (default 3). Ties and
	// all-unknown outcomes resolve conservatively (see Grade).
	Samples int
	// IncludeTrajectory appends the tool-call sequence (names, args, truncated
	// results) to the prompt and switches on evidence discipline: only tool
	// results count as trusted evidence, never the agent's own claims.
	IncludeTrajectory bool
	// MaxTranscriptBytes bounds the trajectory section of the prompt
	// (default 16 KiB, middle-truncated).
	MaxTranscriptBytes int
	// GraderName labels the grade in reports (default "judge").
	GraderName string
}

Judge grades a transcript with an LLM against a natural-language rubric. It issues Samples independent calls and takes a majority vote, dropping unparseable samples — model judges are noisy, so a single call is unreliable. A "unknown" verdict is an escape hatch: it is excluded from the trial's pass/fail decision rather than counted as a failure.

func (*Judge) Grade

func (j *Judge) Grade(ctx context.Context, tr *Transcript) Grade

Grade implements Grader: sample the judge, majority-vote, and build a Grade.

func (*Judge) Name

func (j *Judge) Name() string

Name implements Grader.

type MatchMode

type MatchMode int

MatchMode selects how a tool-call trajectory is compared to expectations.

const (
	// MatchStrict requires the same calls in the same order with matching
	// args; any extra or missing call fails. All-or-nothing (score 0 or 1).
	MatchStrict MatchMode = iota
	// MatchInOrder requires the expected calls to appear as an ordered
	// subsequence of the actual calls; extra calls in between are allowed.
	// The relaxed default for CI gating (per Anthropic: don't mandate rigid
	// step sequences).
	MatchInOrder
	// MatchUnordered requires the same multiset of calls in any order, with
	// no extra calls.
	MatchUnordered
	// MatchSubset requires every expected call to appear somewhere, order
	// irrelevant, extra calls allowed.
	MatchSubset
	// MatchSuperset requires every actual call to match some expected entry —
	// the agent called nothing outside the expected set (but may call fewer).
	MatchSuperset
)

func (MatchMode) String

func (m MatchMode) String() string

String renders a MatchMode for reports and diagnostics.

type PassPolicy

type PassPolicy struct {
	// MinScore: a trial passes when the mean of its non-excluded grade scores
	// is >= MinScore. When 0 (the default), a trial passes only if every
	// non-Unknown, non-error grade has Pass=true.
	MinScore float64
	// AllTrials selects pass^k: the task passes only if every trial passes.
	// Default (false) is pass@k: at least one passing trial passes the task.
	AllTrials bool
}

PassPolicy decides how grades and trials combine into pass/fail.

type Runner

type Runner struct {
	// NewTarget builds a fresh Target per (task, trial). Required.
	NewTarget TargetFactory
	// Concurrency overrides Suite.Concurrency when > 0.
	Concurrency int
	// Capture tunes transcript capture (KeepEvents, IncludeSubagents).
	Capture CaptureOptions
	// OnTrial, when non-nil, observes each finished trial (progress logging).
	// It is called from worker goroutines and must be concurrency-safe.
	OnTrial func(TrialReport)
	// OnTranscript, when non-nil, receives each turn's raw Transcript as it is
	// captured, before grading. Called from worker goroutines and must be
	// concurrency-safe. Use it to persist transcripts for later re-grading
	// (see WriteTranscripts / GradeRecorded).
	OnTranscript func(*Transcript)
}

Runner executes a Suite against targets built by NewTarget.

func (*Runner) RunSuite

func (r *Runner) RunSuite(ctx context.Context, s Suite) (*SuiteReport, error)

RunSuite executes every (task, trial) pair with bounded concurrency and returns the aggregated report. The returned error covers harness failures only (nil factory, empty suite); task and grader failures live in the report. Grader panics are recovered into Grade.Err. A cancelled ctx leaves later trials marked ctx-terminated but still emits a partial report.

type Suite

type Suite struct {
	Name  string
	Tasks []Task
	// Trials is the default per-task trial count (min 1 applied at run time).
	Trials int
	// Timeout is the default per-trial timeout (0 = none).
	Timeout time.Duration
	// Concurrency caps parallel trials across the whole suite (min 1).
	Concurrency int
	// PassRateThreshold in [0,1]: RunSuite marks Summary.BelowThreshold when
	// the task pass rate falls under it. 0 disables the check.
	PassRateThreshold float64
}

Suite is a named collection of tasks with shared defaults.

func LoadSuite

func LoadSuite(path string, judge agent.LLMProvider) (Suite, error)

LoadSuite reads and compiles an eval suite YAML file. The judge provider is injected here (never named in YAML, so files carry no keys or endpoints); pass nil when no task uses a judge block.

func ParseSuiteBytes

func ParseSuiteBytes(path string, data []byte, judge agent.LLMProvider) (Suite, error)

ParseSuiteBytes compiles suite YAML from bytes. Validation aggregates all issues into a single SuiteValidationError.

type SuiteConfig

type SuiteConfig struct {
	Suite struct {
		Name              string       `yaml:"name"`
		Trials            int          `yaml:"trials"`
		Concurrency       int          `yaml:"concurrency"`
		Timeout           string       `yaml:"timeout"`
		PassRateThreshold float64      `yaml:"pass_rate_threshold"`
		Tasks             []taskConfig `yaml:"tasks"`
	} `yaml:"suite"`
}

SuiteConfig is the YAML schema for an eval suite. See examples/agent_eval for a worked file.

type SuiteReport

type SuiteReport struct {
	Suite     string       `json:"suite"`
	StartedAt time.Time    `json:"started_at"`
	Tasks     []TaskReport `json:"tasks"`
	Summary   Summary      `json:"summary"`
}

SuiteReport is the full result of RunSuite.

func GradeRecorded

func GradeRecorded(ctx context.Context, s Suite, ts []*Transcript) (*SuiteReport, error)

GradeRecorded re-runs a suite's graders against already-captured transcripts without invoking the agent — cheap iteration on a revised judge rubric or a tightened trajectory. Transcripts are matched to tasks by TaskID and to turns by TurnIndex; a transcript for a task not in the suite is ignored.

func RunT

func RunT(t *testing.T, r *Runner, s Suite) *SuiteReport

RunT runs a suite as Go subtests — one t.Run per task. A failing task reports its failing grades (and any harness/grader errors) via t.Errorf, so `go test` output points straight at what broke. It returns the full report so a test can additionally assert on usage, cost, or pass rate.

With a Target backed by llmfake.ScriptedProvider this is fully deterministic and needs no API keys — the shape the library's own CI uses.

type SuiteValidationError

type SuiteValidationError struct {
	Path   string
	Issues []string
}

SuiteValidationError aggregates every problem found in a suite file so they can be fixed in one pass (mirrors builder.YAMLValidationError).

func (*SuiteValidationError) Error

func (e *SuiteValidationError) Error() string

type Summary

type Summary struct {
	Tasks          int              `json:"tasks"`
	Passed         int              `json:"passed"`
	Failed         int              `json:"failed"`
	PassRate       float64          `json:"pass_rate"`
	TotalUsage     agent.TokenUsage `json:"total_usage"`
	TotalCostUSD   float64          `json:"total_cost_usd,omitempty"`
	Duration       time.Duration    `json:"duration"`
	BelowThreshold bool             `json:"below_threshold"`
}

Summary rolls up a suite run.

type Target

type Target interface {
	// Run streams the agent's events for one turn. The eval harness ranges
	// the iterator to completion to build a Transcript.
	Run(ctx context.Context, sessionKey string, msg history.Message) iter.Seq[agent.StreamEvent]
}

Target is what a trial runs against. *agent.AgentLoop already satisfies the Run signature; use WrapLoop to adapt one. The interface is defined consumer-side (here) so eval never has to import a concrete loop type.

func WrapLoop

func WrapLoop(loop *agent.AgentLoop) Target

WrapLoop adapts an AgentLoop into a Target that also implements HistoryReader (via loop.Sessions.History), so captured transcripts carry tool results. This is the one-liner most adopters want inside a TargetFactory.

type TargetFactory

type TargetFactory func(ctx context.Context, taskID string, trial int) (Target, error)

TargetFactory builds a fresh, isolated Target for one trial. It is called once per (task, trial); implementations must not share mutable state (scripted providers, in-memory sessions) across calls unless that state is safe to reuse — otherwise trials leak history and scripted turns into each other. taskID and trial are passed so a factory can, e.g., pick a scripted provider per task.

type Task

type Task struct {
	// ID must be unique within a Suite; it names the JUnit testcase.
	ID string
	// Turns is the conversation; at least one is required.
	Turns []Turn
	// Trials overrides Suite.Trials for this task (0 = inherit).
	Trials int
	// Timeout bounds one whole trial (all turns). 0 = inherit Suite.Timeout.
	Timeout time.Duration
	// Policy decides pass/fail across graders and trials.
	Policy PassPolicy
}

Task is one test case — a conversation of one or more turns.

func SingleTurn

func SingleTurn(id, input string, graders ...Grader) Task

SingleTurn builds a one-turn Task from a plain-text input — the common case.

func TaskFromHistory

func TaskFromHistory(id string, msgs []history.Message) Task

TaskFromHistory builds a golden Task from a recorded session: each user message opens a turn, the assistant tool calls become an in-order trajectory expectation, and the final assistant text becomes a Contains grader. The result is a starting scaffold — tighten or relax the generated graders by hand. This is the cheapest way to seed a suite from a real conversation.

type TaskReport

type TaskReport struct {
	TaskID   string        `json:"task_id"`
	Trials   []TrialReport `json:"trials"`
	Pass     bool          `json:"pass"`
	PassAtK  bool          `json:"pass_at_k"`
	PassAllK bool          `json:"pass_all_k"`
}

TaskReport aggregates a task's trials. PassAtK (≥1 trial passed) and PassAllK (every trial passed) are always computed; Pass reflects the task's PassPolicy.

type ToolCallRecord

type ToolCallRecord struct {
	ID       string `json:"id"`
	Name     string `json:"name"`
	ArgsJSON string `json:"args,omitempty"`
	Reused   bool   `json:"reused,omitempty"` // wave executor reused a speculative result
	Source   string `json:"source,omitempty"` // "" = top-level; "subagent:<name>" = forwarded
	// Result is the tool's output, joined from history by correlation ID.
	// Empty when the Target does not implement HistoryReader or the loop did
	// not correlate the row (pre-correlation sessions).
	Result string `json:"result,omitempty"`
}

ToolCallRecord is one tool invocation observed on the event stream, enriched after the run with its result from session history when the Target implements HistoryReader.

type TrajectoryOptions

type TrajectoryOptions struct {
	IncludeSubagents bool // match against Source != "" calls too
	IgnoreReused     bool // skip cache-hit (Reused) calls
}

TrajectoryOptions tunes which recorded calls participate in matching.

type Transcript

type Transcript struct {
	TaskID     string          `json:"task_id"`
	Trial      int             `json:"trial"`
	TurnIndex  int             `json:"turn_index"`
	SessionKey string          `json:"session_key"`
	Input      history.Message `json:"input"`
	// FinalAnswer is the accumulated top-level (Source=="") assistant text.
	// A top-level ReflectedEvent discards the buffer and replaces it, matching
	// AgentLoop.RunIteration's canonical-answer semantics.
	FinalAnswer  string              `json:"final_answer"`
	ToolCalls    []ToolCallRecord    `json:"tool_calls,omitempty"`
	HITL         []HITLRecord        `json:"hitl,omitempty"` // approval gates that fired
	Events       []agent.StreamEvent `json:"-"`              // retained only when KeepEvents
	Usage        agent.TokenUsage    `json:"usage"`
	CostUSD      float64             `json:"cost_usd,omitempty"`
	Model        string              `json:"model,omitempty"`
	Latency      time.Duration       `json:"latency"`
	Err          error               `json:"-"`
	ErrMessage   string              `json:"error,omitempty"` // Err.Error() for serialization
	TerminatedBy string              `json:"terminated_by"`   // done|error|max_iters|limit_exhausted|ctx
}

Transcript is the record of one turn's run. It is JSON-serializable so it can be persisted (see record.go) and re-graded without re-running the agent. Bounded by construction: the tool-call and event counts are capped by the target's MaxIters configuration; Events is retained only when CaptureOptions.KeepEvents is set.

func Capture

func Capture(ctx context.Context, target Target, sessionKey string, msg history.Message, opts CaptureOptions) *Transcript

Capture ranges the target's event stream for one turn and builds a Transcript. It never returns an error: agent failures surface as Transcript.Err / TerminatedBy so a whole suite keeps running. When target implements HistoryReader, tool results are joined afterward.

func ReadTranscripts

func ReadTranscripts(r io.Reader) ([]*Transcript, error)

ReadTranscripts reads JSONL transcripts written by WriteTranscripts. It reconstructs Transcript.Err from the serialized ErrMessage so replay graders (NoError, Judge) behave exactly as they did live.

type TrialReport

type TrialReport struct {
	TaskID       string           `json:"task_id"`
	Trial        int              `json:"trial"`
	Pass         bool             `json:"pass"`
	Turns        []TurnReport     `json:"turns"`
	Usage        agent.TokenUsage `json:"usage"`
	CostUSD      float64          `json:"cost_usd,omitempty"`
	Latency      time.Duration    `json:"latency"`
	TerminatedBy string           `json:"terminated_by"`
	Error        string           `json:"error,omitempty"` // harness/factory error for this trial
}

TrialReport is the result of one attempt at a task (all turns).

type Turn

type Turn struct {
	Input   history.Message
	Graders []Grader
}

Turn is one exchange in a Task's conversation: a user input and the graders applied to that turn's Transcript. Multi-turn tasks share one session within a trial, so later turns can test memory and anaphora.

type TurnReport

type TurnReport struct {
	TurnIndex   int              `json:"turn_index"`
	Input       string           `json:"input"`
	FinalAnswer string           `json:"final_answer"`
	ToolCalls   []ToolCallRecord `json:"tool_calls,omitempty"`
	Grades      []Grade          `json:"grades"`
	Pass        bool             `json:"pass"`
}

TurnReport is the graded result of one turn within a trial.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL