evals

package
v2.23.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 26 Imported by: 4 modules, 17 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 evals provides the evaluation framework for PromptPack. Eval definitions travel with packs and run both during Arena testing and at runtime in production via the SDK.

An eval is a pure measurement. A handler produces a score and never states pass or fail, and the runner clears any pass/fail a handler sets on a plain eval. Judgment against a threshold belongs to the wrapper that applies it: the "assertion" wrapper for tests and the "guardrail" wrapper for runtime enforcement (see AssertionEvalHandler, GuardrailEvalHandler and ScoreThresholds).

EvalRunner executes EvalDef values against an EvalContext, and EvalTypeRegistry maps eval type names to handlers. The built-in handlers live in the evals/handlers package, which registers them when imported.

Index

Constants

View Source
const (
	// TriggerEveryTurn fires the eval after every assistant turn.
	TriggerEveryTurn = "every_turn"
	// TriggerOnSessionComplete fires the eval when a session ends. A session
	// ends each time the host closes a conversation, including a close that
	// suspends it to be resumed later: a conversation that pauses three times
	// for human approval and then finishes has four sessions, and its
	// on_session_complete evals run four times, each over the transcript as it
	// stood. See EvalRunner.RunSessionEvals.
	TriggerOnSessionComplete = "on_session_complete"
	// TriggerSampleTurns fires the eval on a percentage of turns (hash-based).
	TriggerSampleTurns = "sample_turns"
	// TriggerSampleSessions fires the eval on a percentage of sessions (hash-based).
	TriggerSampleSessions = "sample_sessions"
	// TriggerOnConversationComplete fires the eval once, when the
	// conversation is finished, over the whole transcript. A suspension is not
	// the end of a conversation: in the approval example above, the
	// on_conversation_complete evals run once, after the final session. The
	// runtime cannot tell a finished conversation from a suspended one, so
	// the host says when it is finished (in the SDK, Conversation.Complete
	// rather than Close). See EvalRunner.RunConversationEvals.
	TriggerOnConversationComplete = "on_conversation_complete"
	// TriggerOnWorkflowStep fires the eval after each committed workflow state
	// transition, against the turn that produced it. See
	// EvalRunner.RunWorkflowStepEvals.
	TriggerOnWorkflowStep = "on_workflow_step"
)
View Source
const (
	// GroupFastRunning classifies evals that use simple, deterministic logic
	// (string matching, regex, JSON validation, etc.) and complete quickly.
	GroupFastRunning = "fast-running"

	// GroupLongRunning classifies evals that involve LLM calls, network requests,
	// or compute-intensive operations (cosine similarity, LLM judge, etc.).
	GroupLongRunning = "long-running"

	// GroupExternal classifies evals that call external systems: REST APIs,
	// A2A agents, subprocess exec, or LLM judge providers.
	GroupExternal = "external"
)

Well-known eval groups for automatic classification based on handler type. These are assigned as additional default groups alongside DefaultEvalGroup when an eval has no explicit groups configured.

View Source
const (
	// ContentScopeTranscript examines every assistant message. The zero value,
	// and the behavior evals and assertions rely on.
	ContentScopeTranscript = ""

	// ContentScopeCurrent examines only EvalContext.CurrentOutput, the single
	// message the caller is judging. The guardrail adapter sets it, because the
	// content under test may be a user message (input direction) that a scan of
	// assistant messages would never see.
	ContentScopeCurrent = "current"
)

Content scopes for EvalContext.ContentScope.

View Source
const (
	// SubjectTurnEvals carries turn events; the worker runs RunTurnEvals.
	SubjectTurnEvals = "eval.turn.*"
	// SubjectSessionEvals carries session events, published when a session
	// ends (a conversation closed, possibly to be resumed); the worker runs
	// RunSessionEvals.
	SubjectSessionEvals = "eval.session.*"
	// SubjectConversationEvals carries conversation events, published once
	// when the conversation is finished; the worker runs RunConversationEvals.
	SubjectConversationEvals = "eval.conversation.*"
)

Subjects an EvalWorker subscribes to. Each event payload is JSON with the keys "defs" and "eval_ctx".

View Source
const DefaultEvalGroup = "default"

DefaultEvalGroup is the group assigned to evals that have no explicit groups.

View Source
const DefaultEvalTimeout = 30 * time.Second

DefaultEvalTimeout is the per-eval execution timeout.

View Source
const DefaultExecEvalHookTimeout = 5 * time.Second

DefaultExecEvalHookTimeout bounds how long a single subprocess invocation of an ExecEvalHook may run before it is killed and the result abandoned.

View Source
const DefaultSamplePercentage = 5.0

DefaultSamplePercentage is the default sampling rate when not specified.

View Source
const MetaToolsOffered = types.MetaToolsOffered

MetaToolsOffered is the message-meta key carrying the tool names a turn handed the provider. The provider stage stamps it onto the assistant message it produces, so the set is still readable when evals run later against stored messages.

View Source
const MetricExpressionKey = "jmespath_expression"

MetricExpressionKey is the MetricDef.Extra key naming a JMESPath expression that selects the metric's value out of EvalResult.Value. The name matches the json_path eval handler's parameter.

View Source
const ResultDetailReplacement = "replacement"

ResultDetailReplacement is the EvalResult.Details key under which a check supplies the text that replaces a turn it denies, when the check itself decides what to answer (topic_policy with on_deny set to respond). A guardrail uses it when the validator sets no message of its own.

View Source
const WrapperTypeAssertion = "assertion"

WrapperTypeAssertion is the eval type name for the assertion wrapper handler.

View Source
const WrapperTypeGuardrail = "guardrail"

WrapperTypeGuardrail is the eval type name for the guardrail wrapper handler.

Variables

View Source
var ErrNoBinding = errors.New("no provider binding configured")

ErrNoBinding is returned when no host binding is attached at all. It means the runtime was driven by a caller that never wired one up, which is a wiring error rather than a pack error.

View Source
var ErrUnboundKey = errors.New("no provider bound to this key")

ErrUnboundKey is returned when the pack asked for a logical name the host bound nothing to.

View Source
var ErrWrongKind = errors.New("provider bound to this key cannot do what the check needs")

ErrWrongKind is returned when the host bound something to the key, but what it bound cannot do what the check needs, such as an embedding provider bound to the name a judge-backed check points at. It is a wiring mistake, so callers should surface it at load time rather than on the first turn that needs it.

View Source
var ParamAliases = map[string]map[string]string{
	"content_excludes": {
		// contains filtered or unexported fields
	},

	"max_length": {
		// contains filtered or unexported fields
	},
	"length": {
		// contains filtered or unexported fields
	},
	"min_length": {
		"min_characters": canonicalParamMin,
		"min_chars":      canonicalParamMin,
	},
	"sentence_count": {
		// contains filtered or unexported fields
	},

	"field_presence": {
		// contains filtered or unexported fields
	},
	// contains filtered or unexported fields
}

ParamAliases maps legacy param names to canonical names per eval type. Entries exist for both the canonical type name and any aliases, so that NormalizeParams works regardless of which name is used.

View Source
var ParamDefaults = map[string]map[string]any{

	"topic_policy": {
		"direction":    "input",
		"small_talk":   "allow",
		"on_deny":      "block",
		"on_unknown":   topicPolicyDefaultOnUncertain,
		"on_error":     topicPolicyDefaultOnUncertain,
		"recent_turns": topicPolicyDefaultRecentTurns,
	},
	// contains filtered or unexported fields
}

ParamDefaults provides default param values for aliased eval types. These are applied when the param is not already present.

ValidMetricTypes is the set of valid metric type values.

ValidTriggers is the set of valid trigger values.

Functions

func ApplyDefaults

func ApplyDefaults(evalType string, params map[string]any) map[string]any

ApplyDefaults merges default params for the given eval type. User-provided params take precedence over defaults.

func DefaultAliases

func DefaultAliases() [][2]string

DefaultAliases returns a copy of the pairs registered with RegisterDefaultAlias, as alias and target, sorted by alias.

func DefaultGroupsForType

func DefaultGroupsForType(evalType string) []string

DefaultGroupsForType returns the groups for a given eval type. The result always starts with DefaultEvalGroup, followed by, in order of precedence: the groups registered with RegisterTypeGroups for that type; the groups its handler declares through GroupDeclarer; or the built-in classification (GroupFastRunning, GroupLongRunning or GroupExternal). An alias registered with RegisterDefaultAlias or EvalTypeRegistry.RegisterAlias is classified as its target.

func DescribeUnresolved added in v2.5.0

func DescribeUnresolved(key string, err error) string

DescribeUnresolved renders why a logical name could not be resolved, in terms the person who has to fix it can act on: which name the pack used, and whether the fix is in the pack or in the host's wiring.

func EncodeEvalWhen

func EncodeEvalWhen(when *EvalWhen) map[string]any

EncodeEvalWhen is the inverse of DecodeEvalWhen: it renders promptkit's when-conditions into the spec's open `when` object, for building an eval programmatically. A nil or empty EvalWhen yields nil.

func ExtractToolsOffered added in v2.4.0

func ExtractToolsOffered(messages []types.Message) []string

ExtractToolsOffered returns the union of the tool sets recorded under MetaToolsOffered on the messages, sorted and deduplicated, or nil when there are none.

A turn can hand the provider a different set on each tool round, so the union is what the turn offered. Per-round detail is in the per-message meta.

func ExtractValue

func ExtractValue(result EvalResult, metric *MetricDef) (float64, bool)

ExtractValue returns the number to record for this metric, and whether there is one at all.

The bool separates "no value" from a measured zero. An eval that produces no scalar, such as a judge answering with a rubric, returns ok false, and callers should skip the sample.

Precedence:

  1. A JMESPath expression declared on the metric (see MetricExpressionKey), evaluated against result.Value. When present it is the only source.
  2. result.MetricValue, the gauge number.
  3. result.Score, the normalized 0 to 1 score.

An expression that does not resolve, or resolves to something non-numeric, yields no sample.

func ExtractWorkflowExtras

func ExtractWorkflowExtras(messages []types.Message) map[string]any

ExtractWorkflowExtras pulls workflow metadata from message Meta fields. Returns nil if no workflow metadata is found.

func FlakinessScore

func FlakinessScore(results []bool) float64

FlakinessScore returns a value from 0.0 (deterministic) to 1.0 (maximally flaky, i.e. 50/50 split). The formula is:

1 - |2*passRate - 1|

Returns 0 for an empty slice.

func Groups

func Groups(e *EvalDef) []string

Groups returns the groups an eval belongs to. When no explicit groups are configured, returns DefaultGroupsForType(e.Type), which includes DefaultEvalGroup plus well-known classification groups (fast-running, long-running, external) based on the eval type. An "assertion" or "guardrail" wrapper is classified by the eval it wraps (its eval_type param), since that is the work it does. When explicit groups are set, returns them as-is (overriding defaults).

func IsEnabled

func IsEnabled(e *EvalDef) bool

IsEnabled returns whether an eval is enabled. Defaults to true when Enabled is nil, because absent means enabled.

func MetricLabels

func MetricLabels(m *MetricDef) map[string]string

MetricLabels returns the Prometheus labels a metric declares, or nil.

Labels live in the "labels" key of MetricDef.Extra. A labels value of the wrong shape, or one with a non-string label value, yields nil rather than a partial map; ValidateEvals does not report it.

func NormalizeParams

func NormalizeParams(evalType string, params map[string]any) map[string]any

NormalizeParams rewrites legacy param names to canonical names. Unknown params pass through unchanged.

func PassAtK

func PassAtK(results []bool, k int) float64

PassAtK computes the pass@k metric from the Codex paper:

pass@k = 1 - C(n-c, k) / C(n, k)

where n is the total number of samples, c is the number of correct (passing) samples, and k is the number of samples drawn. It returns 1.0 when k <= 0, 0.0 when results is empty, 1.0 when every sample passes, and 0.0 when k > n.

func PassRate

func PassRate(results []bool) float64

PassRate returns the fraction of true values in results (0.0 to 1.0), such as the repeated assertion outcomes of one test. It returns 0 for an empty slice.

func RegisterDefault

func RegisterDefault(h EvalTypeHandler)

RegisterDefault adds a handler to the default set used by NewEvalTypeRegistry. It affects only registries created afterward. It is safe to call concurrently, though it is usually called from an init function.

func RegisterDefaultAlias

func RegisterDefaultAlias(aliasType, targetType string)

RegisterDefaultAlias registers an alias mapping applied by NewEvalTypeRegistry. The target must be registered with RegisterDefault before the registry is created; an alias whose target is missing is skipped. It is safe to call concurrently.

func RegisterTypeGroups

func RegisterTypeGroups(evalType string, groups []string)

RegisterTypeGroups registers the classification groups DefaultGroupsForType returns for a dynamic eval type, such as an exec handler that classifies itself as long-running or external. It takes precedence over groups a handler declares through GroupDeclarer. It keeps a copy of groups, and is safe to call concurrently with DefaultGroupsForType.

func ResultReplacement added in v2.17.0

func ResultReplacement(result *EvalResult) string

ResultReplacement returns the replacement text a result supplies under ResultDetailReplacement, or "" when it supplies none.

func SamplePercentage

func SamplePercentage(e *EvalDef) float64

SamplePercentage returns the sampling percentage, defaulting to DefaultSamplePercentage when unset.

func SeedBudgetMetadata

func SeedBudgetMetadata(
	metadata map[string]any, messages []types.Message, latencyMs *int64,
) map[string]any

SeedBudgetMetadata fills in the spend, token and latency values the budget eval handlers read, deriving them from data the caller already holds.

It returns a copy of metadata with total_cost, input_tokens, output_tokens and cached_tokens summed from the CostInfo of every message, and latency_ms (as a float64) when latencyMs is non-nil. The cost_budget handler reads the cost and token keys and latency_budget reads latency_ms. Pass latencyMs as nil where no call has completed yet, such as for an input-direction guardrail.

Values already present in metadata win over the derived ones. The input map is never mutated.

func SetMetricLabels

func SetMetricLabels(m *MetricDef, labels map[string]string)

SetMetricLabels records Prometheus labels on a metric.

It is the inverse of MetricLabels and stores the labels under the "labels" key of MetricDef.Extra. Passing an empty map removes the key. A nil metric is ignored.

func ShouldRun

func ShouldRun(
	trigger EvalTrigger, samplePct float64, ctx *TriggerContext,
) bool

ShouldRun determines whether an eval should fire given its trigger, sampling percentage, and current context. Sampling is deterministic: the same sessionID+turnIndex always produces the same decision.

func ShouldRunWhen

func ShouldRunWhen(raw map[string]any, toolCalls []ToolCallRecord) (shouldRun bool, reason string)

ShouldRunWhen evaluates `when` preconditions against the tool call records of the current eval context. It returns whether the eval should run and, when it should not, the reason. An empty `when` always runs. A nil or empty toolCalls fails any condition that needs a tool call.

A `when` that ValidateEvalWhen rejects does not run, and the validation error is the reason. Callers that can report an error rather than a skip, as the eval runner does, should call ValidateEvalWhen first.

It takes the raw map because EvalDef.When is a map[string]any; EvalWhen is the runtime's reading of it.

func StripScoreThresholds

func StripScoreThresholds(params map[string]any) map[string]any

StripScoreThresholds returns params without min_score and max_score, so the keys never reach an inner eval handler. Handlers reject those keys with an error result that scores 0, which a guardrail reads as a block. The input map is never mutated.

func ValidateEvalTypes

func ValidateEvalTypes(defs []EvalDef, registry *EvalTypeRegistry) []string

ValidateEvalTypes checks that every EvalDef's Type has a registered handler in the given registry, AND (when the handler implements ParamValidator) that its params are usable by the handler, AND (when it implements ParamNamer) that every param is one the handler reads. Returns a list of human-readable error strings for any type-lookup or param-validation failures. See ValidateHandlerParams.

Params are normalized (ApplyDefaults + NormalizeParams) before calling ValidateParams, so handlers only need to check canonical key names.

It also reports a Threshold an assertion or guardrail wrapper cannot apply (an unknown operator, a missing value, or one declared alongside min_score or max_score), and an unusable `when`. The SDK exposes it as a preflight check, and its eval middleware skips defs that fail it, with a warning.

func ValidateEvalWhen

func ValidateEvalWhen(raw map[string]any) error

ValidateEvalWhen reports an authoring fault in a `when` object: a condition promptkit does not implement, or a recognized condition carrying a value of the wrong type.

The supported conditions are the fields of EvalWhen. The PromptPack spec leaves `when` open, so a pack can carry a condition this runtime does not implement; it is reported as an error here rather than ignored or treated as a failed gate. A nil or empty map is valid.

func ValidateEvals

func ValidateEvals(defs []EvalDef, scope string) []string

ValidateEvals validates a slice of EvalDef for correctness and returns each finding's Message. See ValidateEvalsDetailed, which returns the same findings with the def they name, a code and a severity. The scope parameter is used in error messages (e.g. "pack", "prompt:foo"). prompt.Pack.Validate reports its findings, and the SDK's Open skips each def it rejects, with a warning. It checks:

  • IDs are non-empty and unique within the slice
  • Type is non-empty
  • Trigger is a valid value
  • sample_percentage (if set) is in [0, 100]
  • Metric name matches Prometheus naming regex
  • Metric type is one of gauge/counter/histogram/boolean
  • Metric label names match the Prometheus label regex and do not start with "__"
  • when contains only supported conditions of the right type

func ValidateHandlerParams added in v2.18.0

func ValidateHandlerParams(
	evalType string, handler EvalTypeHandler, params map[string]any, allowed ...string,
) error

ValidateHandlerParams runs the load-time param checks for one declared check: the handler's own ValidateParams when it implements ParamValidator, then, when it implements ParamNamer, a check that every key is one it reads. evalType is the name the check was declared under (it may be an alias) and is used in the error. Params must already be normalized (ApplyDefaults and NormalizeParams).

allowed names keys the caller consumes itself and the handler need not list, such as a guardrail's direction and message. min_score and max_score are always allowed: they are the wrappers' thresholds, and the handlers that must not see them reject them with their own message.

func WithProviderBinding added in v2.5.0

func WithProviderBinding(ctx context.Context, b ProviderBinding) context.Context

WithProviderBinding attaches a host's binding to ctx. Mirrors inference.WithRegistry: the pipeline attaches it once and every stage and handler below reads it from the context it was given.

Types

type AssertionEvalHandler

type AssertionEvalHandler struct {
	// contains filtered or unexported fields
}

AssertionEvalHandler is a registered eval type ("assertion") that wraps an inner eval and applies pass/fail judgment based on score thresholds.

The result is the inner eval's result with Kind set to EvalKindAssertion and Passed set. Passed is false when the inner result carries an Error, true when it carries no score, and otherwise true when the score satisfies min_score and max_score. With neither set, min_score defaults to 1.0.

When EvalRunner runs a def with a Threshold, the threshold sets the pass line instead (see ScoreThresholdsFromSpec). A def that sets both a Threshold and min_score or max_score is an error result.

Params structure:

{
  "eval_type":  "llm_judge",           // inner eval type (required)
  "eval_params": { "criteria": "..." }, // params for inner eval
  "min_score":  0.8,                    // minimum passing score (optional)
  "max_score":  1.0                     // maximum passing score (optional)
}

func (*AssertionEvalHandler) Eval

func (h *AssertionEvalHandler) Eval(
	ctx context.Context, evalCtx *EvalContext, params map[string]any,
) (*EvalResult, error)

Eval resolves the inner handler from the registry, executes it, and applies threshold-based pass/fail judgment.

func (*AssertionEvalHandler) EvalTimeout added in v2.15.0

func (h *AssertionEvalHandler) EvalTimeout(params map[string]any) time.Duration

EvalTimeout delegates to the wrapped eval.

func (*AssertionEvalHandler) ParamNames added in v2.18.0

func (h *AssertionEvalHandler) ParamNames() []string

ParamNames lists the assertion wrapper's own params. min_score and max_score are always accepted (see ValidateHandlerParams).

func (*AssertionEvalHandler) Type

func (h *AssertionEvalHandler) Type() string

Type returns the registered eval type name.

func (*AssertionEvalHandler) ValidateParams added in v2.2.0

func (h *AssertionEvalHandler) ValidateParams(params map[string]any) error

ValidateParams lets a wrapped eval's own param validation run at load time, the same as a directly declared one. The guardrail factory and sdk.ValidatePack both look for this interface, so implementing it here is what makes `type: guardrail` wrapping a check with a typo'd param fail to load rather than load unprotected.

The inner params are also checked for keys the inner check does not read (see ValidateHandlerParams). That check runs here, at load, and not on Eval.

type EvalContext

type EvalContext struct {
	Messages []types.Message `json:"messages"`
	// TurnIndex is the 0-based turn being evaluated: 0 for the conversation's
	// first turn. A session or conversation eval gets its last turn's index.
	TurnIndex     int              `json:"turn_index"`
	CurrentOutput string           `json:"current_output"`
	ToolCalls     []ToolCallRecord `json:"tool_calls,omitempty"`

	// ToolsOffered holds the tool names this turn handed the provider: the
	// descriptor set that reaches ToolSupport.BuildTooling, after the prompt's
	// allowed_tools, the implicit capability tools, exclusions and skill tool
	// grants have all been applied. Sorted and deduplicated.
	//
	// This is what the model could see, as opposed to ToolCalls, which is what
	// it chose to do. Only the former shows that a skill's allowed-tools grant
	// took effect, because a grant that works and one that does nothing produce
	// identical ToolCalls whenever the model does not call the granted tool.
	//
	// Hosts populate it; it is empty when the host does not.
	ToolsOffered []string       `json:"tools_offered,omitempty"`
	SessionID    string         `json:"session_id"`
	PromptID     string         `json:"prompt_id"`
	Variables    map[string]any `json:"variables,omitempty"`
	Metadata     map[string]any `json:"metadata,omitempty"`
	Extras       map[string]any `json:"extras,omitempty"`

	// PriorResults holds results from evals that have already run in this
	// batch. This allows evals like guardrail_triggered to inspect the
	// outcomes of earlier evals without coupling to pipeline internals.
	PriorResults []EvalResult `json:"prior_results,omitempty"`

	// ContentScope tells content-matching handlers how much of the
	// conversation to examine. Empty (the default) means the whole
	// transcript, which is what evals and assertions want: "was this ever
	// said". ContentScopeCurrent means CurrentOutput only, which is what a
	// guardrail wants: it judges one specific message.
	//
	// The scope is explicit because BuildEvalContext always populates
	// CurrentOutput, so its presence cannot indicate scope.
	ContentScope string `json:"content_scope,omitempty"`

	// Caller is who the conversation acts for, as the host set it with
	// sdk.WithCaller. The zero value means none was set. The tool_exec
	// handler puts it on the tool call it runs, so the host's executor sees
	// it, an exec eval handler receives it on stdin (context.caller), and a
	// host's own handler can read it. It is not otherwise serialized:
	// PromptKit never persists, logs or emits it.
	Caller types.Caller `json:"-"`

	// Partial marks CurrentOutput as a reply still being written: a
	// stream_hold: segment guardrail judging the reply so far, before the
	// model has finished it (PartialJudge). A handler judges only what it
	// says, not what it has yet to say; an LLM judge is told so.
	Partial bool `json:"partial,omitempty"`
}

EvalContext provides data to eval handlers. For turn-level evals: Messages contains history up to the current turn. For session-level evals: Messages contains the full conversation.

func BuildEvalContext

func BuildEvalContext(
	messages []types.Message,
	turnIndex int,
	sessionID string,
	promptID string,
	metadata map[string]any,
) *EvalContext

BuildEvalContext constructs an EvalContext from a message history snapshot. It extracts the last assistant message as CurrentOutput, builds ToolCallRecords from assistant tool calls matched with their tool-role results, and pulls workflow metadata from message Meta fields.

This is the canonical way to build an EvalContext outside of a live conversation. The SDK's Evaluate uses it, as does PromptArena.

func BuildGuardrailEvalContext

func BuildGuardrailEvalContext(
	messages []types.Message, currentOutput string, metadata map[string]any,
) *EvalContext

BuildGuardrailEvalContext constructs an EvalContext for a guardrail, which judges one specific message rather than scanning a transcript.

It differs from BuildEvalContext in two ways. CurrentOutput is the caller-supplied currentOutput rather than the last assistant message, because an input guardrail judges the user's message, and ContentScope is set to ContentScopeCurrent. ToolCalls, ToolsOffered, Extras, Metadata and PriorResults are derived from the message history exactly as BuildEvalContext derives them, so a handler sees the same data either way.

TurnIndex, SessionID, PromptID and Variables are left unset because they cannot be derived from the message history. Handlers that depend on them are unsuitable as guardrails.

type EvalDef

type EvalDef = packspec.Eval

EvalDef defines a single evaluation within a PromptPack. Evals are defined at pack level and/or prompt level. Prompt-level evals override pack-level evals by ID (see ResolveEvals).

EvalDef is an alias for packspec.Eval, which is generated from the PromptPack schema. A type alias cannot carry methods, so the accessors IsEnabled, SamplePercentage and Groups are free functions.

Threshold is applied by the wrapper that states a verdict: on a def of type "assertion" or "guardrail", EvalRunner hands it to the wrapper as its pass line in place of min_score and max_score (see ScoreThresholdsFromSpec). On any other def it is carried, not applied: an eval never states pass or fail, and a consumer with its own assertion layer may read it.

func FilterByGroups

func FilterByGroups(defs []EvalDef, groups []string) []EvalDef

FilterByGroups returns only the defs that belong to at least one of the requested groups. If groups is nil or empty, all defs are returned unchanged. Each def's effective groups are determined by Groups, which includes DefaultEvalGroup when none are set. A requested group that matches no def is logged as a warning.

func ResolveEvals

func ResolveEvals(packEvals, promptEvals []EvalDef) []EvalDef

ResolveEvals merges pack-level and prompt-level eval definitions. Prompt-level evals override pack-level evals when they share the same ID. The returned slice preserves pack ordering first, followed by any prompt-only evals (those with no pack counterpart) in their original order.

func Values

func Values(in []*EvalDef) []EvalDef

Values dereferences a slice of eval pointers into values.

The generated Prompt holds []*Eval because the schema implies pointers for optional object arrays, while the eval APIs take values. This converts at that boundary rather than pointerizing every signature behind it. A nil entry is skipped rather than dereferenced.

type EvalFinding added in v2.18.0

type EvalFinding struct {
	// Index is the def's position in the slice that was validated.
	Index int
	// ID is the def's id, empty when it has none.
	ID string
	// Code says what the finding is about.
	Code EvalFindingCode
	// Severity is EvalFindingWarning for EvalFindingUnknownTrigger and
	// EvalFindingError for every other code.
	Severity EvalFindingSeverity
	// Reason is the finding without the scope and index prefix.
	Reason string
	// Message is the finding as ValidateEvals words it:
	// "<scope> evals[<i>] (id=<quoted id>): <reason>", or
	// "<scope> evals[<i>]: <reason>" for a def without an id.
	Message string
}

EvalFinding is one problem ValidateEvalsDetailed found with a def.

func ValidateEvalsDetailed added in v2.18.0

func ValidateEvalsDetailed(defs []EvalDef, scope string) []EvalFinding

ValidateEvalsDetailed runs the checks ValidateEvals runs and returns each finding with the index and id of the def it names, a code and a severity, in def order. Classify a finding by its Code or Severity, never by its text.

type EvalFindingCode added in v2.18.0

type EvalFindingCode string

EvalFindingCode identifies what a ValidateEvalsDetailed finding is about.

const (
	EvalFindingIDRequired          EvalFindingCode = "id_required"
	EvalFindingDuplicateID         EvalFindingCode = "duplicate_id"
	EvalFindingTypeRequired        EvalFindingCode = "type_required"
	EvalFindingTriggerRequired     EvalFindingCode = "trigger_required"
	EvalFindingUnknownTrigger      EvalFindingCode = "unknown_trigger"
	EvalFindingSamplePercentage    EvalFindingCode = "sample_percentage_out_of_range"
	EvalFindingMetricNameRequired  EvalFindingCode = "metric_name_required"
	EvalFindingMetricNameInvalid   EvalFindingCode = "metric_name_invalid"
	EvalFindingMetricTypeRequired  EvalFindingCode = "metric_type_required"
	EvalFindingMetricTypeInvalid   EvalFindingCode = "metric_type_invalid"
	EvalFindingMetricRangeInverted EvalFindingCode = "metric_range_inverted"
	EvalFindingMetricLabelInvalid  EvalFindingCode = "metric_label_invalid"
	EvalFindingMetricLabelReserved EvalFindingCode = "metric_label_reserved"
	EvalFindingWhenUnusable        EvalFindingCode = "when_unusable"
)

The codes ValidateEvalsDetailed reports.

type EvalFindingSeverity added in v2.18.0

type EvalFindingSeverity string

EvalFindingSeverity is how serious a ValidateEvalsDetailed finding is.

const (
	// EvalFindingError marks a def that is wrong.
	EvalFindingError EvalFindingSeverity = "error"
	// EvalFindingWarning marks a def that is valid but cannot run in this
	// runtime: a trigger it does not know. The PromptPack schema lists trigger
	// values as examples, not an enum, so such a pack is spec-valid.
	EvalFindingWarning EvalFindingSeverity = "warning"
)

type EvalHook

type EvalHook interface {
	// Name returns a stable identifier for the hook (used in logs).
	Name() string
	// OnEvalResult is called once per eval result, after the handler runs.
	// The hook may mutate result in place.
	OnEvalResult(ctx context.Context, def *EvalDef, evalCtx *EvalContext, result *EvalResult)
}

EvalHook observes eval results as they are produced by the runner.

Unlike ProviderHook or ToolHook, EvalHook is purely observational: evals compute scores and do not gate execution, so there is no allow/deny semantics. Hooks are invoked once per executed eval, after the handler runs (or after a skip/error result is synthesized), and before the result is emitted as an event.

Hooks may mutate the result in place (e.g. to redact sensitive content from Explanation, annotate Details, or attach tracing metadata). The mutated result is what the runner returns to its caller and emits on the event bus.

Typical uses:

  • Push results to external systems (metrics, tracing, logs)
  • Redact or enrich result fields
  • Shell out to a subprocess for custom scoring pipelines

type EvalResult

type EvalResult struct {
	EvalID string `json:"eval_id"`
	Type   string `json:"type"`

	// Kind is the role this result was produced in, stated by whatever produced
	// it. The zero value is EvalKindEval: an eval nothing wrapped is a
	// measurement.
	Kind events.EvalKind `json:"kind,omitempty"`

	// Passed is set only by a role that coerces a score to a boolean: an
	// assertion or a guardrail. For a guardrail it is the inverse of
	// Details["triggered"]. An eval measures and does not pass or fail, so for
	// EvalKindEval it is always nil.
	//
	// EvalRunner enforces this: it clears Passed on any handler result whose Kind
	// is not assertion or guardrail. Passed is never derived from Score.
	Passed *bool `json:"passed,omitempty"`

	Score *float64 `json:"score,omitempty"`

	// Value is what the eval measured: the handler's own output, in whatever
	// shape that handler produces, such as a rubric's per-criterion map, a
	// classifier's label, or a reasoning service's JSON. The assertion and
	// guardrail wrappers leave it unchanged.
	Value       any      `json:"value,omitempty"`
	MetricValue *float64 `json:"metric_value,omitempty"`

	// Metrics are named sub-scores the eval produced alongside its score, such as
	// a rubric's clarity and accuracy from one judge call, or an exec program's
	// functional_score and security_score.
	//
	// The names come from the handler's output rather than from the pack, which
	// declares one metric per eval, so they are not trusted: a judge model can
	// return a new key on any call. Reports and events carry them as they are.
	// Prometheus export is opt-in on the host's collector and bounded there
	// (metrics.CollectorOpts.EvalDimensionLimit). Put a large per-test breakdown
	// in Details instead.
	Metrics map[string]float64 `json:"metrics,omitempty"`

	Explanation string `json:"explanation,omitempty"`
	DurationMs  int64  `json:"duration_ms"`
	Error       string `json:"error,omitempty"`

	// Message is the author-configured message for this eval, as distinct from
	// Explanation, which is what the handler computed. The runtime never sets
	// it. A consumer such as PromptArena fills it from its own assertion
	// configuration, so that a result serialized by the runtime and one populated
	// by a consumer have the same shape.
	Message    string          `json:"message,omitempty"`
	Details    map[string]any  `json:"details,omitempty"`
	Violations []EvalViolation `json:"violations,omitempty"`
	Skipped    bool            `json:"skipped,omitempty"`
	SkipReason string          `json:"skip_reason,omitempty"`
	SessionID  string          `json:"session_id,omitempty"`
	// TurnIndex is the 0-based turn the result belongs to. Always serialized:
	// 0 is the conversation's first turn, not an absent value.
	TurnIndex int `json:"turn_index"`
}

EvalResult captures the outcome of a single eval execution. Handlers produce scores only (0.0 to 1.0); there is no pass/fail on a plain eval. The assertion and guardrail wrappers state a verdict in Passed.

type EvalRunner

type EvalRunner struct {
	// contains filtered or unexported fields
}

EvalRunner executes evals in-process. It is the leaf execution unit used by all dispatch modes (in-proc, event-driven, worker).

func NewEvalRunner

func NewEvalRunner(
	registry *EvalTypeRegistry, opts ...RunnerOption,
) *EvalRunner

NewEvalRunner creates an EvalRunner with the given registry and options.

func (*EvalRunner) AddHook

func (r *EvalRunner) AddHook(h EvalHook)

AddHook appends an EvalHook to the runner. Call it during setup, before evals start running; there is no locking. Nil hooks are ignored.

func (*EvalRunner) Clone

func (r *EvalRunner) Clone() *EvalRunner

Clone creates a copy of the runner with the same registry, timeout, and hooks but a nil emitter. Use this when you need a per-caller runner that can be mutated (SetEmitter, AddHook) without affecting a shared base.

Hooks are copied into a new slice so appending to the clone does not mutate the source. The emitter is dropped; wire a fresh one with SetEmitter.

func (*EvalRunner) Registry added in v2.19.0

func (r *EvalRunner) Registry() *EvalTypeRegistry

Registry returns the eval type registry the runner resolves handlers from, so a caller holding only the runner can check defs against the handlers that will run them (ValidateEvalTypes).

func (*EvalRunner) RunConversationEvals

func (r *EvalRunner) RunConversationEvals(
	ctx context.Context,
	defs []EvalDef,
	evalCtx *EvalContext,
) []EvalResult

RunConversationEvals runs conversation-level evals (on_conversation_complete trigger). Call this once, when the conversation is finished (the end of an Arena self-play run, or a host's last session of a conversation), and not when it is suspended to be resumed, such as while a held tool call waits for a human's approval. Call RunSessionEvals for the final session as well.

func (*EvalRunner) RunSessionEvals

func (r *EvalRunner) RunSessionEvals(
	ctx context.Context,
	defs []EvalDef,
	evalCtx *EvalContext,
) []EvalResult

RunSessionEvals runs session-level evals (on_session_complete and sample_sessions triggers). Call this when a session ends: each time the conversation is closed, whether it is finished or suspended to be resumed.

func (*EvalRunner) RunTurnEvals

func (r *EvalRunner) RunTurnEvals(
	ctx context.Context,
	defs []EvalDef,
	evalCtx *EvalContext,
) []EvalResult

RunTurnEvals runs turn-level evals (every_turn and sample_turns triggers). It skips defs that are disabled, have another trigger, are excluded by sampling, or fail their when-conditions, and executes the rest in order. Each eval sees the earlier results of the batch in EvalContext.PriorResults.

func (*EvalRunner) RunWorkflowStepEvals added in v2.17.0

func (r *EvalRunner) RunWorkflowStepEvals(
	ctx context.Context,
	defs []EvalDef,
	evalCtx *EvalContext,
) []EvalResult

RunWorkflowStepEvals runs workflow-step evals (on_workflow_step trigger). Call this once for each committed workflow state transition, with an EvalContext built from the turn that produced the transition.

func (*EvalRunner) SetEmitter

func (r *EvalRunner) SetEmitter(e *events.Emitter)

SetEmitter sets (or clears) the event emitter. Must be called before running evals.

type EvalTrigger

type EvalTrigger string

EvalTrigger names when an eval fires.

The Trigger* constants are untyped, so each assigns to both EvalTrigger and the plain string EvalDef.Trigger. EvalTrigger does not validate: a Go named string type accepts any literal, so `var t EvalTrigger = "nonsense"` compiles. ValidTriggers is the check.

type EvalTypeHandler

type EvalTypeHandler interface {
	// Type returns the eval type identifier (e.g. "contains", "regex").
	Type() string

	// Eval executes the evaluation and returns a result.
	// The EvalContext carries messages, tool calls, and metadata.
	// Params come from the EvalDef.Params map.
	Eval(ctx context.Context, evalCtx *EvalContext, params map[string]any) (*EvalResult, error)
}

EvalTypeHandler defines the interface for eval type implementations. Each handler covers a single eval type (e.g. "contains", "llm_judge"). Handlers are stateless; params are passed per invocation.

type EvalTypeRegistry

type EvalTypeRegistry struct {
	// contains filtered or unexported fields
}

EvalTypeRegistry provides thread-safe registration and lookup of EvalTypeHandler implementations by type name.

func NewEmptyEvalTypeRegistry

func NewEmptyEvalTypeRegistry() *EvalTypeRegistry

NewEmptyEvalTypeRegistry creates a registry with no handlers registered. Use this in tests to control exactly which handlers are available.

func NewEvalTypeRegistry

func NewEvalTypeRegistry() *EvalTypeRegistry

NewEvalTypeRegistry creates a registry pre-populated with the handlers and aliases added through RegisterDefault and RegisterDefaultAlias, plus the "assertion" and "guardrail" wrappers. The evals/handlers package registers the built-in handlers in its init function, so import it for its side effects:

import _ "github.com/AltairaLabs/PromptKit/runtime/v2/evals/handlers"

func (*EvalTypeRegistry) Get

func (r *EvalTypeRegistry) Get(evalType string) (EvalTypeHandler, error)

Get returns the handler for the given type, or an error if not found.

func (*EvalTypeRegistry) Has

func (r *EvalTypeRegistry) Has(evalType string) bool

Has returns true if a handler is registered for the given type.

func (*EvalTypeRegistry) ParamNames added in v2.18.0

func (r *EvalTypeRegistry) ParamNames(evalType string) ([]string, bool)

ParamNames returns the params the handler registered for evalType (or an alias of it) reads, sorted, and true. It returns nil and false when the type is not registered or its handler does not implement ParamNamer, which means its params are not known, not that it takes none.

func (*EvalTypeRegistry) Register

func (r *EvalTypeRegistry) Register(handler EvalTypeHandler)

Register adds a handler to the registry. If a handler with the same type is already registered, it is replaced. A handler that implements GroupDeclarer has its groups recorded for DefaultGroupsForType.

func (*EvalTypeRegistry) RegisterAlias

func (r *EvalTypeRegistry) RegisterAlias(aliasType, targetType string) error

RegisterAlias maps an alias name to an existing handler type. Lookups for aliasType will resolve to the handler registered for targetType. Returns an error if targetType has no registered handler.

func (*EvalTypeRegistry) Types

func (r *EvalTypeRegistry) Types() []string

Types returns a sorted list of all registered eval type names.

type EvalViolation

type EvalViolation struct {
	TurnIndex   int            `json:"turn_index"`
	Description string         `json:"description"`
	Evidence    map[string]any `json:"evidence,omitempty"`
}

EvalViolation represents a single eval violation within a conversation or session.

type EvalWhen

type EvalWhen struct {
	ToolCalled        string `json:"tool_called,omitempty" yaml:"tool_called,omitempty"`
	ToolCalledPattern string `json:"tool_called_pattern,omitempty" yaml:"tool_called_pattern,omitempty"`
	AnyToolCalled     bool   `json:"any_tool_called,omitempty" yaml:"any_tool_called,omitempty"`
	MinToolCalls      int    `json:"min_tool_calls,omitempty" yaml:"min_tool_calls,omitempty"`
}

EvalWhen specifies preconditions that must be met for an eval to run.

func DecodeEvalWhen

func DecodeEvalWhen(raw map[string]any) *EvalWhen

DecodeEvalWhen reads promptkit's when-conditions out of the spec's open `when` object. A map that decodes to no conditions yields nil, meaning no gate. An unrecognized or wrongly typed `when` also yields nil, so callers should reject it with ValidateEvalWhen first.

type EvalWorker

type EvalWorker struct {
	// contains filtered or unexported fields
}

EvalWorker is a reusable worker loop for event-driven eval execution. It subscribes to eval events via EventSubscriber, deserializes payloads, calls EvalRunner, and writes results via ResultWriter. Platforms wire this with their own EventSubscriber and ResultWriter implementations.

func NewEvalWorker

func NewEvalWorker(
	runner *EvalRunner,
	subscriber EventSubscriber,
	resultWriter ResultWriter,
	opts ...WorkerOption,
) *EvalWorker

NewEvalWorker creates a worker that processes eval events.

func (*EvalWorker) Start

func (w *EvalWorker) Start(ctx context.Context) error

Start subscribes to SubjectTurnEvals, SubjectSessionEvals and SubjectConversationEvals and processes the events: turn events run RunTurnEvals, session events RunSessionEvals and conversation events RunConversationEvals. Start blocks until the context is canceled or a subscription returns an error, and it cancels the other subscriptions in either case.

type EventSubscriber

type EventSubscriber interface {
	Subscribe(
		ctx context.Context,
		subject string,
		handler func(event []byte) error,
	) error
}

EventSubscriber subscribes to eval events from an event bus. PromptKit ships only the interface; a platform supplies an implementation backed by a message system such as Redis Streams, NATS or Kafka.

type ExecEvalHook

type ExecEvalHook struct {
	// contains filtered or unexported fields
}

ExecEvalHook is an EvalHook that spawns an external process per eval result and writes the JSON-encoded EvalResult to its stdin. It is strictly fire-and-forget: stdout is discarded, non-zero exits and invocation errors are logged but never propagated, and the hook never modifies the result.

This mirrors the observe-mode behavior of hooks.ExecProviderHook. Evals have no allow/deny semantics.

func NewExecEvalHook

func NewExecEvalHook(cfg *ExecEvalHookConfig) *ExecEvalHook

NewExecEvalHook constructs an ExecEvalHook from the given config. When cfg.Sandbox is nil the hook runs the command directly on the host.

func (*ExecEvalHook) Name

func (h *ExecEvalHook) Name() string

Name returns the hook name.

func (*ExecEvalHook) OnEvalResult

func (h *ExecEvalHook) OnEvalResult(
	ctx context.Context, _ *EvalDef, _ *EvalContext, result *EvalResult,
)

OnEvalResult marshals the result to JSON and pipes it to the configured subprocess on stdin. Errors (marshal failures, subprocess failures, timeouts) are logged and discarded; the eval pipeline continues regardless.

type ExecEvalHookConfig

type ExecEvalHookConfig struct {
	// Name is a stable identifier used in logs.
	Name string
	// Command is the absolute path (or PATH-resolvable name) of the
	// executable to spawn for each eval result.
	Command string
	// Args are additional arguments passed to the command.
	Args []string
	// Env is a list of environment variable names whose values are
	// forwarded from the host process to the subprocess.
	Env []string
	// TimeoutMs is the per-invocation timeout in milliseconds. Zero
	// means use DefaultExecEvalHookTimeout.
	TimeoutMs int
	// Sandbox, when non-nil, overrides the default direct-exec sandbox.
	// Use this to run eval hooks in a container, a sidecar, or a custom
	// backend; see runtime/hooks/sandbox for the interface.
	Sandbox sandbox.Sandbox
}

ExecEvalHookConfig configures an ExecEvalHook. It is the eval-side analog of hooks.ExecHookConfig: a command to spawn, its arguments and environment, a per-call timeout, and an optional Sandbox that controls how the subprocess is actually launched.

type GroupDeclarer added in v2.18.0

type GroupDeclarer interface {
	// EvalGroups returns the handler's classification groups, without
	// DefaultEvalGroup.
	EvalGroups() []string
}

GroupDeclarer is an optional interface an EvalTypeHandler implements to declare the classification groups its eval type belongs to, such as GroupLongRunning and GroupExternal for a handler that calls a judge model. DefaultGroupsForType returns DefaultEvalGroup followed by these groups.

The declaration is recorded when the handler is passed to RegisterDefault or EvalTypeRegistry.Register, under the handler's Type and under any alias registered for it. Like RegisterTypeGroups, the record is process-wide, not per registry: the latest handler registered for a type sets its groups. A handler that does not implement GroupDeclarer is classified by the built-in table, which defaults to GroupFastRunning.

type GuardrailEvalHandler

type GuardrailEvalHandler struct {
	// contains filtered or unexported fields
}

GuardrailEvalHandler is a registered eval type ("guardrail") that wraps an inner eval and determines whether the guardrail was triggered.

The result is the inner eval's result with Kind set to EvalKindGuardrail, Passed set to the inverse of triggered, and Details["triggered"] and Details["action"] set. A guardrail is triggered under ScoreThresholds.Triggered: the score is below min_score or above max_score (min_score defaults to 1.0 when neither is set), or the inner result has no score.

When EvalRunner runs a def with a Threshold, the threshold sets the line instead, as for AssertionEvalHandler.

Params structure:

{
  "eval_type":   "content_excludes",     // inner eval type (required)
  "eval_params": { "patterns": ["..."] }, // params for inner eval
  "action":      "block",                 // recorded in Details["action"] (optional, default: "block")
  "min_score":   0.8,                     // triggers below this score (optional)
  "max_score":   1.0                      // triggers above this score (optional)
}

func (*GuardrailEvalHandler) Eval

func (h *GuardrailEvalHandler) Eval(
	ctx context.Context, evalCtx *EvalContext, params map[string]any,
) (*EvalResult, error)

Eval resolves the inner handler from the registry, executes it, and determines whether the guardrail was triggered.

func (*GuardrailEvalHandler) EvalTimeout added in v2.15.0

func (h *GuardrailEvalHandler) EvalTimeout(params map[string]any) time.Duration

EvalTimeout delegates to the wrapped eval.

func (*GuardrailEvalHandler) ParamNames added in v2.18.0

func (h *GuardrailEvalHandler) ParamNames() []string

ParamNames lists the guardrail wrapper's own params.

func (*GuardrailEvalHandler) Type

func (h *GuardrailEvalHandler) Type() string

Type returns the registered eval type name.

func (*GuardrailEvalHandler) ValidateParams added in v2.2.0

func (h *GuardrailEvalHandler) ValidateParams(params map[string]any) error

ValidateParams mirrors AssertionEvalHandler.ValidateParams.

type HandlerTimeout added in v2.15.0

type HandlerTimeout interface {
	// EvalTimeout returns the time this handler allows itself for params,
	// or zero when it sets no bound of its own.
	EvalTimeout(params map[string]any) time.Duration
}

HandlerTimeout is implemented by handlers that bound their own work (a subprocess, a tool call) and can legitimately need longer than the runner's per-eval timeout. Without it the runner's timeout (30s by default) silently caps a configured `timeout_ms: 300000` at 30 seconds.

type Logger

type Logger interface {
	Printf(format string, v ...any)
}

Logger is a minimal logging interface for EvalWorker.

type MetricDef

type MetricDef = packspec.MetricDef

MetricDef defines a Prometheus-style metric associated with an eval. It is an alias for packspec.MetricDef.

The spec leaves MetricDef open to runtime extension, so keys the spec does not name, including labels, are carried in the Extra field. Read labels with MetricLabels and write them with SetMetricLabels.

type MetricRecorder

type MetricRecorder interface {
	Record(result EvalResult, metric *MetricDef) error
}

MetricRecorder records eval results as metrics. This interface is implemented by metrics.MetricContext and injected into MetricResultWriter to avoid circular dependencies.

type MetricResultWriter

type MetricResultWriter struct {
	// contains filtered or unexported fields
}

MetricResultWriter feeds eval results to a MetricRecorder for Prometheus exposition. Every eval result is recorded: if the EvalDef includes an explicit Metric definition it is used; otherwise a default gauge metric named after the eval ID is created automatically.

func NewMetricResultWriter

func NewMetricResultWriter(
	recorder MetricRecorder, defs []EvalDef,
) *MetricResultWriter

NewMetricResultWriter creates a writer that records metrics. The defs slice provides the metric definitions keyed by eval ID.

func (*MetricResultWriter) WriteResults

func (w *MetricResultWriter) WriteResults(
	_ context.Context, results []EvalResult,
) error

WriteResults records each eval result as a Prometheus metric. If the EvalDef has an explicit Metric definition, that is used. Otherwise a default gauge metric named after the eval ID is generated so that every eval produces a metric without requiring pack authors to define one explicitly.

type MetricType

type MetricType = string

MetricType defines the Prometheus metric type for eval results.

const (
	// MetricGauge represents a gauge metric (set to a value).
	MetricGauge MetricType = "gauge"
	// MetricCounter represents a counter metric (increment only).
	MetricCounter MetricType = "counter"
	// MetricHistogram represents a histogram metric (observe values).
	MetricHistogram MetricType = "histogram"
	// MetricBoolean represents a boolean metric (0 or 1).
	MetricBoolean MetricType = "boolean"
)

type ParamNamer added in v2.18.0

type ParamNamer interface {
	ParamNames() []string
}

ParamNamer is an optional interface for EvalTypeHandler implementations that list the params they read. A handler that implements it has its params checked for unknown keys wherever ParamValidator runs (ValidateEvalTypes, the guardrail factory, and the assertion and guardrail wrappers' ValidateParams), so a misspelled key fails at load instead of being silently ignored. Every built-in handler implements it; a custom handler that does not is not checked.

ParamNames returns the canonical names, after ApplyDefaults and NormalizeParams: a legacy name NormalizeParams rewrites need not be listed. The threshold keys min_score and max_score belong to the wrappers and are never reported as unknown, so they are not listed either.

type ParamValidator

type ParamValidator interface {
	// ValidateParams returns nil if params are usable by this handler,
	// or an error describing what is missing or wrong. The error message
	// should be self-contained: it is logged or surfaced in a
	// ValidateEvalTypes result without a wrapping prefix.
	ValidateParams(params map[string]any) error
}

ParamValidator is an optional interface for EvalTypeHandler implementations that have required or strictly-typed params. Handlers without required params need not implement it.

ValidateParams is called at two points:

  1. When a guardrail hook is constructed, so a pack validator with unusable params is surfaced at SDK load time instead of failing every turn.
  2. By ValidateEvalTypes, so build-time checks and the SDK's eval middleware see param errors the same way.

Params passed to ValidateParams have already been normalized via ApplyDefaults and NormalizeParams, so implementations should check for canonical key names only.

type PartialEvalRequest added in v2.22.0

type PartialEvalRequest struct {
	// Content is the partial content accumulated so far.
	Content string
	// Params are the eval's params, as EvalPartial receives them.
	Params map[string]any
	// Caller is who the conversation acts for (EvalContext.Caller).
	Caller types.Caller
}

PartialEvalRequest is the partial content a StreamableRequestEvalHandler judges, with who the conversation acts for.

type PartialHolder added in v2.22.0

type PartialHolder interface {
	// PartialHold returns how many bytes at the end of content, the partial
	// content accumulated so far, could be the start of content the handler
	// would flag once more of it arrives. Zero when none could be.
	PartialHold(content string, params map[string]any) int
}

PartialHolder is an optional extension of a streamable handler whose match can span chunks, such as a banned word a provider splits across two of them. A guardrail whose handler implements it keeps the tail PartialHold names from the caller until a later chunk shows whether it completes a match, so no fragment of blocked content is delivered before the match is seen.

type PartialJudge added in v2.22.0

type PartialJudge interface {
	// SegmentHoldByDefault reports whether the handler's output guardrails
	// hold a streamed reply per segment unless the guardrail says otherwise
	// (true), or hold the whole turn (false): a free-form judge whose
	// criteria may need the complete reply.
	SegmentHoldByDefault() bool
}

PartialJudge is an optional interface for a handler that can soundly judge a reply still being written (EvalContext.Partial): its verdict on what a prefix says does not depend on what follows. A guardrail on such a handler may hold a streamed reply per segment (stream_hold: segment), judging each segment before it reaches the caller. A handler whose criteria a prefix fails by being incomplete ("answers the question") must not implement it.

type ProviderBinding added in v2.5.0

type ProviderBinding interface {
	// LLM returns the provider that can run completions for the logical key,
	// which is what a judge-backed check needs. It returns ErrWrongKind when
	// the host bound something that is not one.
	LLM(key string) (providers.Provider, error)

	// Classifier returns the inference provider bound to the logical key, which
	// is what a classifier-backed check needs. It returns ErrWrongKind when the
	// host bound something that is not one. The return type is any; callers
	// assert inference.Provider.
	Classifier(key string) (any, error)
}

ProviderBinding resolves a pack's logical provider names against what the host bound to them.

Implementations live with the host (the SDK, Arena), because only the host knows what it has. Each method answers for one KIND of use, so a mismatch is reported as a mismatch ("you bound an embedder to the name a judge check uses") rather than as an absence, which makes the failure legible.

func BindingFromContext added in v2.5.0

func BindingFromContext(ctx context.Context) ProviderBinding

BindingFromContext returns the binding attached to ctx, or nil when none is.

type Range

type Range = packspec.MetricDefRange

Range defines the valid range for a metric value. It is an alias for packspec.MetricDefRange.

type ResultWriter

type ResultWriter interface {
	WriteResults(ctx context.Context, results []EvalResult) error
}

ResultWriter controls WHERE eval results go. Implementations may write to Prometheus metrics, message metadata, telemetry spans, databases, or external APIs. Platform-specific writers are implemented outside PromptKit.

type RunnerOption

type RunnerOption func(*EvalRunner)

RunnerOption configures an EvalRunner.

func WithEmitter

func WithEmitter(e *events.Emitter) RunnerOption

WithEmitter configures the runner to emit eval.completed/eval.failed events.

func WithEvalHook

func WithEvalHook(h EvalHook) RunnerOption

WithEvalHook registers an EvalHook that observes every eval result the runner produces. Multiple hooks may be registered; they are invoked in registration order, before the result is emitted on the event bus.

func WithRejectedDefs added in v2.19.0

func WithRejectedDefs(reasons map[string]string) RunnerOption

WithRejectedDefs names defs, by id, that the runner must not run, each with the reason (for example a ValidateEvalTypes finding). Such a def still goes through the runner's trigger, sampling and when filtering, hooks and event emission, but its result is an error carrying the reason and its handler is never called. A caller that checked defs at load and cannot drop them uses it to report them where results are read.

func WithTimeout

func WithTimeout(d time.Duration) RunnerOption

WithTimeout sets the per-eval execution timeout.

type ScoreThresholds

type ScoreThresholds struct {
	// Min triggers on a score below it. Max triggers on a score above it. Both
	// are optional; with neither set, Triggered requires a score of 1.0.
	Min *float64
	Max *float64

	// MinExclusive makes Min strict: a score equal to Min falls outside it
	// (a guardrail triggers, an assertion fails). MaxExclusive does the same
	// for Max. Both are false for min_score and
	// max_score, which are inclusive; ScoreThresholdsFromSpec sets them for the
	// spec's gt and lt operators.
	MinExclusive bool
	MaxExclusive bool
}

ScoreThresholds turns an eval score into a verdict. It is the shared implementation used by the "guardrail" eval type here and by the pipeline's guardrail hook adapter; evals themselves never apply it.

func ExtractScoreThresholds

func ExtractScoreThresholds(params map[string]any) ScoreThresholds

ExtractScoreThresholds reads min_score and max_score from wrapper params. A value that is missing or not a number is left unset.

func ScoreThresholdsFromSpec added in v2.18.0

func ScoreThresholdsFromSpec(t *Threshold) (ScoreThresholds, error)

ScoreThresholdsFromSpec converts an eval's spec-shaped threshold ({operator, value}) into ScoreThresholds. The operators are gte (>=), gt (>), lte (<=), lt (<) and eq (==); gt and lt are strict. A nil threshold yields the zero ScoreThresholds. An unknown operator or a missing value is an error.

func (ScoreThresholds) Triggered

func (t ScoreThresholds) Triggered(result *EvalResult) bool

Triggered reports whether a result trips a guardrail under these thresholds.

A nil result or nil score means the handler could not judge, and Triggered returns true: a guardrail fails closed, as the pipeline's guardrail hook does. The assertion wrapper makes the opposite choice for a nil score and passes it.

type StreamableEvalHandler

type StreamableEvalHandler interface {
	EvalTypeHandler

	// EvalPartial evaluates partial content accumulated so far.
	// Called on each streaming chunk. Implementations should be efficient
	// and avoid expensive operations on every call.
	EvalPartial(ctx context.Context, content string, params map[string]any) (*EvalResult, error)
}

StreamableEvalHandler is an opt-in extension for EvalTypeHandler. Handlers implementing this interface support incremental evaluation on partial (streaming) content, enabling early abort in guardrails.

type StreamableRequestEvalHandler added in v2.22.0

type StreamableRequestEvalHandler interface {
	EvalTypeHandler

	// EvalPartialRequest evaluates partial content accumulated so far.
	EvalPartialRequest(ctx context.Context, req PartialEvalRequest) (*EvalResult, error)
}

StreamableRequestEvalHandler is StreamableEvalHandler with the caller: a guardrail whose handler implements it calls EvalPartialRequest on each streaming chunk in place of EvalPartial.

type Threshold

type Threshold = packspec.EvalThreshold

Threshold is the {operator, value} threshold shape the PromptPack spec defines for an eval. The assertion and guardrail wrappers apply it; on a plain eval it is carried but not applied. ScoreThresholdsFromSpec lists the operators.

type ToolCallRecord

type ToolCallRecord = types.ToolCallRecord

ToolCallRecord is an alias for types.ToolCallRecord.

func ExtractToolCalls

func ExtractToolCalls(messages []types.Message) []ToolCallRecord

ExtractToolCalls builds ToolCallRecords from a message history by matching assistant tool calls with their corresponding tool-role result messages. Each record's TurnIndex is the index of the assistant message in messages.

type TriggerContext

type TriggerContext struct {
	// SessionID identifies the current session (used for sampling).
	SessionID string

	// TurnIndex is the current turn's 0-based index (used for sampling).
	TurnIndex int

	// IsSessionComplete indicates whether the session has ended.
	IsSessionComplete bool
}

TriggerContext provides context for trigger evaluation decisions.

type WorkerOption

type WorkerOption func(*EvalWorker)

WorkerOption configures an EvalWorker.

func WithLogger

func WithLogger(l Logger) WorkerOption

WithLogger sets a custom logger for the worker. The default logs at warn level through the runtime logger.

Directories

Path Synopsis
Package handlers provides eval type handler implementations.
Package handlers provides eval type handler implementations.

Jump to

Keyboard shortcuts

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