eval

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: BSD-2-Clause Imports: 75 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 a behavioral eval harness for jargo bots. It drives a real bot over RTVI, plays scripted conversation turns, and asserts on the semantic events the bot emits. That is a level above unit tests, which check one processor at a time.

A scenario describes one conversation to hold with a bot and how to judge it. A YAML file holds one or more under `scenarios:`, each with a `name:`, and a scenario's keys say which kind it is:

turns:     a scripted scenario: the user's turns are written out, each
           with the events expected back from the bot
persona:   a simulated scenario, a simulation for short: an LLM plays a
           caller with a goal, and a judge reads the whole conversation
success:   with neither of the above, a rubric: what a simulation is
           judged on, without the caller, to judge a conversation the
           harness didn't drive; it has nothing to run

The same scenario runs from a Go test (the bot hosted in-process, see Run) or from the command line against a running bot. In text modality each user turn is delivered as RTVI send-text, so the audio processors sit idle; in audio modality it is synthesized and streamed as microphone audio, so the bot's own VAD, turn detection and STT run for real.

Scenario files

Any key a scenario can have may also sit at the top of the file, where it is the default for every scenario in it. A scenario that sets the same key replaces the whole value; nothing is merged, so a `context:` is written out in full, never added to. A scenario is named `<file name>/<scenario name>`:

name: turn_completion
judge: !include ../judge_text.yaml
scenarios:
  - name: short_answer
    turns:
      - user: "Japan."
        expect:
          - event: response

A file holding a scenario's own keys at its top level and no `scenarios:` is deprecated; it still loads, as that one scenario under the file's `name:`, with a warning.

Any value can come from a separate file with !include, resolved against the directory of the file that names it, so scenarios can share a block they all need, the user: and judge: blocks above all:

user: !include user_audio.yaml
judge: !include judge_audio.yaml

Integers are plain decimal only, so a DTMF `012` keeps its digits rather than being read as octal.

Expectation fields

event: <name>            required: the event to match
within_ms: <int>         latency budget, measured from the turn's user input
text_contains: <str>     substring check on the event's text, whatever the spacing
text_excludes: <str>     the reverse of text_contains: the text must not hold it
text_matches: <regex> | [<regex>, ...]
                         regular expressions (RE2, as Go's regexp reads them)
                         the text must each match; the failure names the first
                         pattern that did not match
eval: <str>              criterion an LLM judge checks the bot's reply against
                         (response, llm_response, tts_response, and the
                         expression its TTS performed), or, on function_call,
                         the call itself by name and args
allow_continue: false    with eval: judge the reply yes or no, never
                         continue (see below)
marker: <str>            for llm_marker: what the marker meant, one of
                         complete, short, long, incomplete for either of
                         those two, or silent
marker_first: <bool>     for llm_marker: the marker came before any text
markers: <int>           for llm_marker: how many markers the response holds
text_after: <bool>       for llm_marker: text follows the first marker
metric: <str>            for metrics: the kind of metric the report must hold
                         (ttfb, processing, tokens, ...)
processor: <str>         for metrics: text the name of the processor that
                         measured it must contain
name: <str>              for function_call: the tool the call must be to
args: <mapping>          for function_call: an argument subset the call must carry
calls: <list>            for function_call: several calls, in any order
check_from: <str>        previous (default) or turn_start (see below)
absent: true             assert the event does NOT arrive

Turn fields

user: <str> | <list>     what the user says, sent as text or synthesized
dtmf: <str>              keypad keys the user presses; quote it, # is a comment
audio: <path>            in audio modality, a recording played instead of
                         synthesizing user, which still says what it says
image: <path>            an image served when the bot requests one
expect: <list>           the events to match, in order
send_after: <mapping>    when to send this turn's input (see below)

user and dtmf are mutually exclusive, and both are optional: a turn with neither only waits and asserts, which is what a bot-first scenario needs to check an opening greeting. expect is optional too, for a turn that only sends. audio and image paths resolve against the scenario file.

In audio modality a spoken turn may pause, as a person does mid-thought: user is then a list of text and pause_ms silences, played to the bot as one stretch of audio. The judge and text_contains see the text alone. A turn's pauses can total at most MaxTurnPauseMS:

turns:
  - user:
      - "So last week I went to"
      - pause_ms: 2000
      - "Spain with my family."

Scenario fields

name: <str>              required: the scenario's name
turns: <list>            the turns, played in order
context: <list>          messages the bot's context starts from
stop_on_failure: <bool>  whether the first failed turn ends the scenario
                         (default true); false drives every turn, for a
                         scenario whose turns are scored independently
user: <mapping>          how user turns are delivered
judge: <mapping>         what the judge evaluates, and what decides the verdicts

The user: block:

user:
  modality: audio          # audio | text (default text)
  speech:                  # needed unless every spoken turn has audio:
    service: kokoro        # the TTS that synthesizes the user turns
    voice: af_heart        # voices are language-specific
    language: en           # optional; must match the voice
    speed: 1.0             # optional
    sample_rate: 16000     # optional

The judge: block:

judge:
  modality: audio          # audio | text (default text)
  eval:                    # what judges (default ollama)
    service: ollama
    model: gemma4:12b
  transcription:           # required when modality is audio
    service: moonshine     # STT for the bot's audio
    language: en           # optional; the language the bot speaks

audio makes the bot speak and judges the transcription of its actual audio; text (the default) skips TTS and judges the LLM text, which is faster and silent. A factory: key in any service block names a registered builder that makes the service from the block instead.

Asserting on the bot's reply

Three events carry the bot's own words:

response       the transcription of the bot's actual synthesized audio in
               audio modality, or the LLM text in text modality: the real
               end-to-end check, to prefer
llm_response   the text the model produced (bot-llm-text), in both modalities
tts_response   the text the TTS reports speaking (bot-tts-text), audio
               modality only: a text modality scenario asserting on it is
               refused when it is loaded

In an expressive conversation (alpha), expression is the expression the bot's TTS performed, from bot-output, in the tags the LLM writes: <<excited>> where the delivery of its spoken text changes (<<neutral>> back to the baseline), [[laughter]] for a sound, [[pause 600]] for a pause. A tag the TTS can't perform is never reported. A content check on it accumulates the expression performed in the turn.

A turn often answers in more than one response: an interim filler ("Let me check on that.") and then the answer. So a content check on a reply aggregates. It accumulates the text of successive segments and re-checks on each, until the check passes, the judge rejects, or within_ms expires. A missing substring is not a failure on its own, because more text may follow, which is why an assertion on text the bot never produces waits out its whole budget. Set within_ms on one to keep that short.

A judge grades the conversation rather than one reply on its own: it is given each user turn and each segment of the bot's reply, so a terse answer is read against the question it answers. It may also answer "continue", meaning the reply so far is only filler and the criterion should be judged again once more arrives.

allow_continue: false, with eval:, judges the reply yes or no, never continue. The judge answers continue for a reply on the way to its answer, a "let me check" before the result, and the harness then waits for more of the reply. Setting allow_continue: false forces the judge to consider the reply as final, the thing to be judged, rather than skipping it: a wait reassurance ("still working on it...") is judged that way:

expect:
  - event: response
    eval: "says it is still working on the task, reporting no result"
    allow_continue: false

Asserting on the markers the model emits

A model reading the turn-completion protocol begins each response with a marker saying whether the user's turn was finished. The markers are a diagnostic and never reach a client, so a scenario asserting on one asks the bot to report them:

turns:
  - user: "Let me think about it, hmmm"
    expect:
      - event: llm_marker
        marker: incomplete        # the bot held the turn open
  - user: "I think I'd go to Japan."
    expect:
      - event: llm_marker
        marker: complete          # ... and answered this one

The event carries the response as the model produced it, before anything was held back, so a scenario can check the model against the protocol it was given: marker_first that nothing came before the marker, markers how many the response holds, and text_after whether anything follows the first one, which a complete turn should have and an incomplete one should not.

marker: silent is a reply the LLM answered with its silent mark, which the bot dropped unspoken.

Asserting on the bot's metrics and its own messages

metrics is a report of what the bot's processors measured, such as a service's TTFB, its processing time or its usage. A bot sends them when its pipeline has metrics on, grouped by kind (ttfb, processing, tokens, ...). metric: names the kind the report must hold and processor: text the measuring processor's name must contain; a bare metrics takes any report. The zero a pipeline reports for every processor as it starts is not a measurement and never matches. A report that arrived while an expectation above was waiting for its own event is behind this one, so look back for it:

turns:
  - user: "What is the capital of Germany?"
    expect:
      - event: user_transcription
      - event: metrics
        metric: ttfb
        processor: STT
        check_from: turn_start

Every report of a run is kept with its result (ScriptResult.BotMetrics and SimulationResult.BotMetrics, and bot_metrics in a suite's results.jsonl, for passed and failed runs alike), expected or not, so an expectation is only needed to hold a turn open until one arrives.

server_message is a message of the bot's own making: whatever data it pushed in an RTVI server message frame. It is how a bot built for an eval reports what only it can know, such as a result it computed or that it has finished its work on a turn. The event's text is the data as JSON (or the data itself when it is a string), with a space after each comma and colon, so the content checks read it and a matched expectation records it in the run's result:

turns:
  - user: "What is the capital of Germany?"
    expect:
      - event: server_message
        text_contains: '"done": true'

flow_node is the bot's conversation flow, built with the flows package, entering a node. The event's text is the node's name, so text_matches pins the node a turn leads to; a node of a subflow is named "<parent>.<node>":

turns:
  - user: "I'd like to book an appointment."
    expect:
      - event: flow_node
        text_matches: ['^verify_to_book[.]']

Asserting on function calls

A function_call expectation holds the set of calls the turn should make. They are matched by name in any order and the expectation passes only when every one is found. Write a single call with the name/args shorthand:

expect:
  - event: function_call
    name: get_weather
    args: {city: Paris}

and several under calls:, where an entry is a bare tool name or a mapping:

expect:
  - event: function_call
    calls:
      - get_weather
      - {name: get_restaurants, args: {city: Paris}}

args is a subset check: every argument listed must be present with that value, and any further argument the model passed is ignored. A bare function_call, with neither name nor calls, matches whatever the bot calls. Asserting on a call's name or its arguments requires the bot to report them, which the harness arranges for itself (see Handler).

function_call_stopped takes the same calls: shape, and its args say how the call ended, which is how a scenario tells work that was stopped from work that finished on its own. A stopped call carries no arguments to judge, so it takes no eval:.

Absent events

absent: true inverts an expectation. It passes only when no event of that type arrives before the within_ms budget expires, and fails as soon as one does, which is how "must not answer twice" is written:

expect:
  - event: response
    eval: "answers the question"
  - event: response
    absent: true
    within_ms: 5000

It matches on event type alone, so no content, call, marker or metric check may accompany it, and it waits out its whole budget: set within_ms explicitly to keep the quiet window short.

Where an expectation looks

Expectations are met in order: each is looked for only once the one above it has been met, and an event of another type that arrives in the meantime is passed over. check_from: turn_start lets an expectation run against events since the beginning of the turn that were not used by the expectations above it. Use it for an event whose timing the bot does not control, such as a call a backend makes at its own pace, or a reply some models give before the tool call that others give after.

Scheduling a turn

A turn's input goes out once the bot has finished speaking, unless the turn carries send_after. That waits for an event to have been seen, then waits delay_ms longer, which is how an interruption is written:

turns:
  - user: "tell me about Paris"
    expect:
      - event: llm_started
  - user: "actually, tell me about Tokyo"
    send_after: {event: llm_started, delay_ms: 500}
    expect:
      - event: bot_interrupted

An event seen earlier in the run anchors the delay at that earlier sighting, so the turn may fire at once. The wait for the event is bounded at 30s, and a turn whose schedule never fires reports the schedule rather than any of its expectations.

event is optional. On its own, delay_ms is a pure time delay measured from the previous turn's send, for pacing turns where there is no event to anchor on.

Diagnosing a run

A result carries more than its failures: how long the run took, every event the bot emitted whether or not the scenario asserted on it, and a timestamped trace of what the harness itself decided. Together they are what makes a scenario that failed once and passed the next time readable. Options.OnProgress reports the same as it happens, for a caller watching a long run.

Experimental: this package may still change in a minor release.

Index

Constants

View Source
const (

	// ConversationRoleUser is a user turn.
	ConversationRoleUser = "user"
	// ConversationRoleAssistant is a bot turn.
	ConversationRoleAssistant = "assistant"
	// ConversationRoleToolCall is a function the bot called.
	ConversationRoleToolCall = "tool_call"
)

The roles and keys of a conversation file's messages.

View Source
const (
	// EventBotStartedSpeaking fires when the bot reports it started speaking.
	EventBotStartedSpeaking = "bot_started_speaking"
	// EventBotStoppedSpeaking fires when the bot reports it stopped speaking.
	EventBotStoppedSpeaking = "bot_stopped_speaking"
	// EventBotBackchannel is a short acknowledgment the bot spoke to the end
	// while the user talked, such as "Mm-hmm".
	EventBotBackchannel = "bot_backchannel"
	// EventUserBackchannel is a short acknowledgment the user said while the
	// bot talked, which neither interrupted it nor reached its LLM.
	EventUserBackchannel = "user_backchannel"
	// EventBotEnded is appended when the bot ends the call by closing the
	// connection.
	EventBotEnded = "bot_ended"
	// EventHarnessError is appended when the harness's own pipeline reported
	// an error: a service in it failed, not the bot.
	EventHarnessError = "harness_error"
)

The event types the stream adds beyond the ones a scenario names in script.go.

View Source
const (
	// VerdictYes means the reply satisfies the criterion.
	VerdictYes = "yes"
	// VerdictNo means the reply gives a substantive answer that fails it.
	VerdictNo = "no"
	// VerdictContinue means the bot is still working toward its answer, and the
	// criterion should be judged again once more text arrives.
	VerdictContinue = "continue"
	// VerdictNone means the judge's question failed, so nothing was decided.
	VerdictNone = "none"
)

The verdicts a judge can return.

View Source
const (
	// FailureTimeout means no event of the expected type arrived within the
	// budget.
	FailureTimeout = "timeout"
	// FailureJudgeNo means the judge rejected the reply, or a function call's
	// criterion.
	FailureJudgeNo = "judge_no"
	// FailureJudgeContinue means the judge never accepted the reply before the
	// budget ran out.
	FailureJudgeContinue = "judge_continue"
	// FailureNoJudge means the scenario uses `eval:` but no judge could be
	// built.
	FailureNoJudge = "no_judge"
	// FailureNoContent means the matched event carried no text to judge.
	FailureNoContent = "no_content"
	// FailureTextMismatch means text_contains was not in the event's text.
	FailureTextMismatch = "text_mismatch"
	// FailureTextPresent means text_excludes was found in the event's text.
	FailureTextPresent = "text_present"
	// FailureTextUnmatched means a text_matches pattern did not match the
	// event's text.
	FailureTextUnmatched = "text_unmatched"
	// FailureMarkerMismatch means the marker meant something other than the
	// expectation asked for.
	FailureMarkerMismatch = "marker_mismatch"
	// FailureMarkerFormat means the response did not follow the marker protocol
	// the expectation checks.
	FailureMarkerFormat = "marker_format"
	// FailureMissingFunctionCall means an expected function call never arrived.
	FailureMissingFunctionCall = "missing_function_call"
	// FailureFunctionArgsMismatch means the call arrived with other arguments.
	FailureFunctionArgsMismatch = "function_args_mismatch"
	// FailureUnexpectedEvent means an absent expectation saw the event it
	// forbade.
	FailureUnexpectedEvent = "unexpected_event"
	// FailureSendAfterTimeout means a turn's send_after event never fired.
	FailureSendAfterTimeout = "send_after_timeout"
	// FailureBotEnded means the bot ended the call before a turn's send_after
	// or expectation was met.
	FailureBotEnded = "bot_ended"
	// FailureConnectFailed means the harness never connected to the bot.
	FailureConnectFailed = "connect_failed"
	// FailureClosedBeforeReady means the bot closed the connection before
	// bot-ready.
	FailureClosedBeforeReady = "closed_before_ready"
	// FailureHandshakeTimeout means the bot connected but never sent bot-ready.
	FailureHandshakeTimeout = "handshake_timeout"
	// FailureAudioUnsupported means bot-ready said the transport is off for
	// audio the run uses.
	FailureAudioUnsupported = "audio_unsupported"
	// FailureJudgeNoVerdict means a judge call failed, so it decided nothing.
	FailureJudgeNoVerdict = "judge_no_verdict"
	// FailureError means the harness itself failed (a sub-pipeline, the judge,
	// sending to the bot), not the bot.
	FailureError = "error"
)

The kinds a failure can be, the stable key for grouping failures across runs. Each says how an assertion failed, so a repeated suite can report "10x timeout on turn 3" without parsing free-text reasons.

View Source
const (
	// RunEventConnect is a run that never connected to the bot.
	RunEventConnect = "<connect>"
	// RunEventBotReady is a run whose bot never became ready.
	RunEventBotReady = "<bot-ready>"
	// RunEventHarness is a run the harness's own pipeline failed: a service in
	// it, not the bot.
	RunEventHarness = "<harness>"
	// RunEventError is a run an unexpected error in the harness ended, with
	// its stack in the trace.
	RunEventError = "<error>"
)

The event names a failure of the run itself carries, rather than one of an expectation.

View Source
const (
	// TurnPassed means every expectation of the turn was met.
	TurnPassed = "passed"
	// TurnFailed means at least one was not.
	TurnFailed = "failed"
	// TurnNotRun means the run ended before reaching the turn. It is distinct
	// from a pass: a run that stops at its first failure leaves its later turns
	// undriven, and counting those as passes would inflate any rate computed
	// from the result.
	TurnNotRun = "not_run"
)

The statuses a turn resolves to.

View Source
const (
	// SimulationEndedByEndCall means the persona called its end_call tool.
	SimulationEndedByEndCall = "end_call"
	// SimulationEndedByBot means the bot ended the call (it closed the
	// connection).
	SimulationEndedByBot = "bot"
	// SimulationEndedByMaxTurns means the persona's turn cap was reached.
	SimulationEndedByMaxTurns = "max_turns"
	// SimulationEndedByMaxDuration means the run's wall-clock cap was reached.
	SimulationEndedByMaxDuration = "max_duration"
	// SimulationEndedBySilence means neither side did anything for
	// max_silence_s.
	SimulationEndedBySilence = "silence"
	// SimulationEndedByError means the run did not complete (see
	// SimulationResult.Error).
	SimulationEndedByError = "error"
)

How a simulation run came to an end, for SimulationResult.EndedBy.

View Source
const (
	// StatusTurn heads a turn, carrying its input as the event.
	StatusTurn = "turn"
	// StatusMatched means the expectation was met.
	StatusMatched = "matched"
	// StatusFailed means the event arrived but did not satisfy the expectation.
	StatusFailed = "failed"
	// StatusTimeout means nothing of the expectation's kind arrived at all
	// before its budget expired.
	StatusTimeout = "timeout"
)

The statuses of a ScriptTurnProgress.

View Source
const (
	ModalityText  = "text"
	ModalityAudio = "audio"
)

The modalities a user: or judge: block may name.

View Source
const (
	// EventUserStartedSpeaking fires when the bot's VAD detects the user's speech
	// beginning (audio mode only).
	EventUserStartedSpeaking = "user_started_speaking"
	// EventUserStoppedSpeaking fires when the user's turn ends (audio mode only).
	EventUserStoppedSpeaking = "user_stopped_speaking"
	// EventUserTranscription carries the bot's STT transcription of the user's
	// speech (audio mode only).
	EventUserTranscription = "user_transcription"
	// EventLLMStarted fires when the bot begins generating a response.
	EventLLMStarted = "llm_started"
	// EventResponse is the bot's reply whatever the modality: the transcription
	// of its actual synthesized audio in audio modality, the LLM text in text
	// modality, where a scenario's response expectations are read as
	// llm_response when it is loaded.
	EventResponse = "response"
	// EventLLMResponse carries the bot's LLM text, joined across the response.
	EventLLMResponse = "llm_response"
	// EventTTSResponse carries the text the bot's TTS reports speaking, one
	// segment as each arrives (audio modality only: in text modality the bot
	// skips TTS, so no segment is ever produced).
	EventTTSResponse = "tts_response"
	// EventFunctionCall fires when the bot invokes a tool.
	EventFunctionCall = "function_call"
	// EventFunctionCallStopped fires when a tool call ends, its args saying
	// how it ended: stopped, or run to completion.
	EventFunctionCallStopped = "function_call_stopped"
	// EventImage is an image the bot output, such as a generated one. The bot
	// reports images only to a scenario that expects one.
	EventImage = "image"
	// EventBotInterrupted fires when the bot's in-flight output is cut off, by a
	// barge-in or by a turn sent with send_after. It is the event a barge-in
	// scenario asserts on.
	EventBotInterrupted = "bot_interrupted"
	// EventVADUserStartedSpeaking is the raw VAD signal, ungated by turn
	// detection (audio mode only). Useful as a timing anchor when a turn strategy
	// gates or defers the turn-level user_stopped_speaking.
	EventVADUserStartedSpeaking = "vad_user_started_speaking"
	// EventVADUserStoppedSpeaking is the raw VAD signal for the end of speech
	// (audio mode only).
	EventVADUserStoppedSpeaking = "vad_user_stopped_speaking"
	// EventLLMMarker carries the sideband marker the bot's model emitted in a
	// response, such as a turn-completion marker or the silent mark of a reply
	// dropped unspoken. It arrives when the response ends, and carries the
	// response's raw text with it. Markers never reach a client by default; a
	// scenario asserting on one asks the bot to report them.
	EventLLMMarker = "llm_marker"
	// EventExpression is the expression the bot's TTS performed in an
	// expressive conversation (alpha), from bot-output, in the tags the LLM
	// writes: <<excited>> where the delivery of its spoken text changes
	// (<<neutral>> back to the baseline), [[laughter]] for a sound,
	// [[pause 600]] for a pause. A tag the TTS can't perform is never reported.
	EventExpression = "expression"
	// EventMetrics is a report of what the bot's processors measured, such as
	// a service's TTFB, its processing time or its usage, as the bot sent it in
	// an RTVI metrics message, grouped by kind under "data". A bot sends them
	// when its pipeline has metrics on. They are kept out of the events seen,
	// and every one is kept with the run's result (see ScriptResult.BotMetrics).
	EventMetrics = "metrics"
	// EventServerMessage is a message of the bot's own making: whatever data
	// it pushed in an RTVI server message frame, under "data". Its text is
	// that data as JSON, or the data itself when it is a string, so the content
	// checks read it and a matched expectation records it.
	EventServerMessage = "server_message"
	// EventFlowNode is the bot's conversation flow, built with the flows
	// package, entering a node: the flow-node-entered message's data, under
	// "data". Its text is the node's name, so the content checks read it; a
	// node of a subflow is named "<parent>.<node>".
	EventFlowNode = "flow_node"
)

Event names a scenario can assert on. These are the friendly names scenarios use; the harness maps the bot's RTVI server messages onto them.

View Source
const (
	// MarkerComplete means the user's turn was finished and the bot answers.
	MarkerComplete = "complete"
	// MarkerShort means the user was cut off and the bot waits.
	MarkerShort = "short"
	// MarkerLong means the user asked for time and the bot waits longer.
	MarkerLong = "long"
	// MarkerIncomplete matches either of the two above, for a scenario that
	// cares that the bot held the turn open rather than which reason it read.
	MarkerIncomplete = "incomplete"
	// MarkerSilent means the LLM answered with its silent mark and the bot
	// dropped the reply unspoken. It is the kind the LLM service stamps on
	// such a reply's marker (frames.LLMMarkerKindSilent).
	MarkerSilent = "silent"
)

The meanings a marker expectation can name, which are the emitter's own vocabulary rather than the marker text, since that is configurable.

View Source
const (
	// CheckFromPrevious looks only from where the expectation above it was
	// met. It is the default.
	CheckFromPrevious = "previous"
	// CheckFromTurnStart looks at the events since the beginning of the turn
	// that the expectations above it did not use.
	CheckFromTurnStart = "turn_start"
)

Where an expectation checks for its event from.

View Source
const (
	// SendAfterMaxWait is how long a turn waits for the event its send_after
	// names before giving up. It is not the expectation budget: nothing is
	// being asserted yet, only waited for.
	SendAfterMaxWait = 30 * time.Second
	// BotQuietMaxWait is how long a turn waits for the bot to finish speaking
	// before it is sent. A reply is still spoken after its first sentence
	// satisfied the previous turn; a turn sent over it would have that tail
	// transcribed as its own reply, or discarded together with the answer that
	// followed it in the same breath.
	BotQuietMaxWait = 30 * time.Second
	// SendAfterPoll is how often the send_after wait checks whether its event
	// has been seen.
	SendAfterPoll = 10 * time.Millisecond
)
View Source
const (
	// DefaultOllamaJudgeModel is the model the judge classifies with when the
	// block names none.
	DefaultOllamaJudgeModel = "gemma4:12b"
	// DefaultOpenAIModel is the model the deprecated `service: openai` builds
	// with when the block names none.
	DefaultOpenAIModel = "gpt-4o"
	// DefaultOllamaEndpoint is where the Ollama service is reached when the
	// block names no endpoint.
	DefaultOllamaEndpoint = "http://localhost:11434/v1"
)

Default models and endpoint of the built-in LLM services.

View Source
const (
	// DefaultEventTimeoutMS is the latency budget for an expectation that sets
	// no within_ms. It is generous so an expectation without one waits long
	// enough for a slow LLM or TTS response, and a function-call round trip,
	// rather than failing on latency. Set within_ms to assert on timing.
	DefaultEventTimeoutMS = 60_000
	// DefaultBotReadyTimeout is how long the bot has, once connected, to answer
	// the handshake with bot-ready. A bot builds its pipeline when the harness
	// connects, so the wait covers its startup: connecting its services and
	// loading any local models.
	DefaultBotReadyTimeout = 60 * time.Second
	// DefaultConnectTimeout is how long the harness waits for the bot to accept
	// connections at all.
	DefaultConnectTimeout = 5 * time.Second
)
View Source
const (
	// AudioSupportCheckOff runs every bot unchecked.
	AudioSupportCheckOff = "off"
	// AudioSupportCheckWhenAdvertised refuses a bot whose bot-ready reports its
	// transport off for audio the run uses.
	AudioSupportCheckWhenAdvertised = "when_advertised"
)

The values SessionParams.AudioSupportCheck takes.

View Source
const (
	DefaultMaxTurns     = 20
	DefaultMaxDurationS = 300.0
	DefaultMaxSilenceS  = 30.0
)

A simulation's defaults: the caps on the persona's turns, on the run's wall clock, and on a lull in which neither side does anything.

View Source
const (
	// MeasureTurns is the persona's turns.
	MeasureTurns = "turns"
	// MeasureDuration is the conversation's seconds, from its first line to the
	// hang-up.
	MeasureDuration = "duration"
	// MeasureWords is the longest bot reply in words, each Chinese or Japanese
	// character counting as one.
	MeasureWords = "words"
	// MeasureLatency is the slowest reply, in seconds.
	MeasureLatency = "latency"
	// MeasureFunctionCalls compares the calls the bot made with a list of the
	// calls it should make.
	MeasureFunctionCalls = "function_calls"
)

The measures a measured metric can name, computed by the harness from the run.

View Source
const (
	// EventEndCall is the event that reports the persona's end_call, once the
	// reply that made the call has gone out to the bot.
	EventEndCall = "end_call"
	// ClosingReplyWait is how long the run waits, after the persona hangs up on
	// its own last line, for the bot's reply to it. The wait runs only while
	// neither side is speaking, by the bot's reports, and starts over when one
	// stops: the persona's last line plays out after the call is made, and the
	// bot's reply can be long. A flow makes its final tool calls in that turn,
	// and a caller who hangs up mid-sentence is not what the simulation tests.
	ClosingReplyWait = 15 * time.Second
	// BotEndedWait is how long the run waits, after the bot hangs up, for what
	// it said last to close into a turn. The harness hears the bot stop only in
	// the silence that follows, and the turn model may wait out its 3 s silence
	// fallback.
	BotEndedWait = 5 * time.Second
)
View Source
const (
	// MetricOutOfRange is a measure outside its bounds.
	MetricOutOfRange = "out_of_range"
	// MetricFunctionCalls is a function_calls measure whose calls did not
	// match the list.
	MetricFunctionCalls = "function_calls"
)

The failure kinds of a measured metric.

View Source
const (
	// DefaultBasePort is the first port a suite assigns to its runs.
	DefaultBasePort = 7900
	// DefaultConcurrency is how many runs a suite executes at once when its
	// manifest says nothing.
	DefaultConcurrency = 4
	// BotConnectTimeout is how long to wait for a freshly spawned bot to start
	// listening. The harness retries the connect, so this doubles as readiness
	// waiting.
	BotConnectTimeout = 60 * time.Second
	// BotStopTimeout is how long to wait for a bot to exit after it is asked to
	// terminate before killing it.
	BotStopTimeout = 10 * time.Second
	// WorkerSafetyTimeout is the safety net for a hung harness. The harness's
	// own per-expectation timeouts bound a healthy run far below this; the cap
	// only catches a run that wedges, so it cannot hold a concurrency slot
	// forever.
	WorkerSafetyTimeout = 600 * time.Second
	// DefaultSpawn is the default spawn template; {bot} and {port} are
	// substituted per run.
	DefaultSpawn = "{bot} --port {port}"
	// EventUpdate fires with a *SuiteRun whenever that run changes status:
	//
	//	event.On(&suite.Registry, eval.EventUpdate, func(ctx context.Context, run *eval.SuiteRun) { … })
	//
	// Runs are mutated in place, so handlers run synchronously, on the
	// goroutine running that run, and must return promptly; they see the run
	// as the change left it. Several runs go at once, so a handler may be
	// called from several goroutines at the same time.
	EventUpdate = "on_update"
)
View Source
const (
	// RunPending is a run not started yet.
	RunPending = "pending"
	// RunRunning is a run in progress.
	RunRunning = "running"
	// RunDone is a run that finished, with a result or an error.
	RunDone = "done"
)

The statuses of a SuiteRun.

View Source
const (
	// PipelineSpeech is the user's speech.
	PipelineSpeech = "speech"
	// PipelineTranscription is the transcription of the bot's speech.
	PipelineTranscription = "transcription"
	// PipelineJudge is the judge.
	PipelineJudge = "judge"
	// PipelinePersona is a simulation's persona LLM.
	PipelinePersona = "persona"
	// PipelineHarness is everything else.
	PipelineHarness = "harness"
)

The harness's log categories: each tags the logs of one of the harness's own pipelines, independent of which service it uses. Anything untagged (RTVI, connection, harness internals) falls through to PipelineHarness.

View Source
const (
	// DefaultSampleRate is the rate the user's audio is streamed at when the
	// block names none.
	DefaultSampleRate = 16000
	// CacheSampleRate is the rate the cache stores audio at, and the built-in
	// services synthesize at, so one cached utterance serves every pipeline
	// rate.
	CacheSampleRate = 24000
)
View Source
const EndCallFunction = "end_call"

EndCallFunction is the tool the persona hangs up with.

View Source
const EventConversationEnded = "on_conversation_ended"

EventConversationEnded fires once the pipeline a ConversationObserver watches is done, with a ConversationEndedMessage holding the conversation:

event.On(&observer.Registry, eval.EventConversationEnded,
	func(ctx context.Context, m eval.ConversationEndedMessage) { … })
View Source
const EventPersonaTurn = "persona_turn"

EventPersonaTurn is the event the relay appends for each response the persona completes.

View Source
const EventProgress = "on_progress"

EventProgress fires with a progress record as the conversation advances: a scripted scenario's turns and expectations as they resolve (a ScriptTurnProgress), a simulation's lines as they are spoken (a SimulationProgress). Records are delivered in order, and Run waits for every handler before it returns:

event.On(&session.Registry, eval.EventProgress, func(ctx context.Context, p eval.Progress) { … })
View Source
const FrameDuration = 40 * time.Millisecond

FrameDuration is one audio frame per tick, on both edges. 40 ms matches the bot's output chunking (AudioOut10msChunks defaults to 4), so the receive side re-emits the bot's chunks one for one rather than splitting them, and it is still fine-grained enough for the VAD and turn models (well under their start and stop windows).

View Source
const FromNow = -1

FromNow is the since of a NextEvent that looks only at what arrives from now on, not back into the turn's log.

View Source
const JudgeNoGrace = 2 * time.Second

JudgeNoGrace is how long a judge's "no" waits for more of the reply once the bot has stopped speaking: the transcription of its last sentence lands after the stop.

View Source
const MaxTurnPauseMS = 60_000

MaxTurnPauseMS is the most a turn's pauses can add up to, in milliseconds. A caller silent for longer has stopped taking part, and the turn's audio, silence included, is built in memory.

View Source
const RunEventJudge = "<judge>"

RunEventJudge is where a judge that gave no verdict on the goal is reported.

View Source
const SuiteClassifierTimeout = 2500 * time.Millisecond

SuiteClassifierTimeout is how long a suite classifier has to answer a question. Jev, and Google's and Zoom's Decisions APIs answer in a few hundred milliseconds, so a question still waiting this long is one to ask again.

Variables

View Source
var (
	// ErrTimeout is a wait whose deadline passed before its event arrived.
	ErrTimeout = errors.New("eval: timed out")
	// ErrBotEnded is a wait for an event that will never arrive: the bot ended
	// the call first.
	ErrBotEnded = errors.New("eval: the bot ended the call")
)

The ways a wait on the stream ends without its event.

View Source
var (
	// ErrUnknownService reports a `service:` name that is not built in.
	ErrUnknownService = errors.New("eval: unknown service")
	// ErrServiceUnavailable reports a built-in service name with no builder
	// registered yet.
	ErrServiceUnavailable = errors.New("eval: service not available")
	// ErrFactory reports a `factory:` that is not a registered dotted name, or
	// that returned something the block cannot use.
	ErrFactory = errors.New("eval: bad factory")
)

Errors the service constructors report.

Functions

func CallLines added in v0.7.0

func CallLines(message map[string]any) []string

CallLines is a tool_call message as the judge reads it: the call, and a line more when it was canceled.

func CapturePipelineLogs added in v0.7.0

func CapturePipelineLogs(ctx context.Context, logsDir, prefix, name string, enabled bool) (context.Context, func())

CapturePipelineLogs captures the harness's logs for one run into a single <prefix>.debug.log under logsDir.

The logs are buffered in memory and written by the returned func, one section per pipeline, headed with name. The returned context tags the run with prefix, and the capture takes only the records logged with a context carrying that tag, so concurrent runs never mix. It writes nothing unless enabled. Records reach it through the default logger once QuietLogs has installed its handler.

func CheckFrom added in v0.7.0

func CheckFrom() []string

CheckFrom returns the values check_from: may take.

func ClassifierFromConfig added in v0.7.0

func ClassifierFromConfig(cfg *LLMServiceConfig, where string) (classifier.Classifier, error)

ClassifierFromConfig builds the classifier a `judge.eval:` block names.

A factory builds it, and may return a classifier.Classifier or an LLM service (an llm.Inferencer), which a classifier/llmclassifier classifier then asks. Otherwise the block names an LLM, as LLMServiceFromConfig reads it, and a classifier/llmclassifier classifier asks that. where is the block's name in the file, for the errors; a nil cfg uses all the defaults.

func DefaultCacheDir added in v0.7.0

func DefaultCacheDir() (string, error)

DefaultCacheDir is where cached user audio is stored when no directory is given: jargo/eval/tts under the user's cache directory.

func DefaultOllamaJudgeExtra added in v0.7.0

func DefaultOllamaJudgeExtra() map[string]any

DefaultOllamaJudgeExtra is the request parameters the default judge model is sent. It is thinking-capable, and only its JSON verdict is ever read, so reasoning buys nothing while costing latency and eating into the token budget the verdict needs.

func DescribeConfig added in v0.7.0

func DescribeConfig(c *Configured, color bool) string

DescribeConfig is a two-line summary of a scenario's user and judge config, for pre-run logs. Each line is a set of `key: value` segments separated by `|`:

user  -> modality: audio | speech: kokoro/af_heart
judge -> modality: audio | transcription: moonshine/small-streaming | eval: ollama/gemma4:12b

With color, each segment's keyword is ANSI-colored by category (modality, service, judge LLM) so they are easy to tell apart.

func DescribeSimulation added in v0.7.0

func DescribeSimulation(s *SimulationScenario, color bool) string

DescribeSimulation is a three-line summary of a simulation's user config, judge config, and goal, for pre-run logs: the lines of DescribeConfig, the user line also naming the persona LLM that plays the user and the run's caps, then the caller's goal:

user  -> modality: text | persona: ollama/gemma4:12b | max_turns: 8 | max_duration_s: 120 | max_silence_s: 30
judge -> modality: text | eval: ollama/gemma4:12b
goal  -> Book a table for two at 6 PM, then end the call.

With color, the keywords are ANSI-colored as DescribeConfig colors them.

func FailureKinds added in v0.7.0

func FailureKinds() []string

FailureKinds returns the categories of AssertionFailure.Kind.

func FunctionCallEvents added in v0.7.0

func FunctionCallEvents() []string

FunctionCallEvents returns the events carrying a function call.

func GoogleClassifier added in v0.7.0

func GoogleClassifier(config map[string]any) (any, error)

GoogleClassifier is Google's Decisions API, a classifier that answers in a few hundred milliseconds. It is the factory registered as "evals.judges.google_classifier".

config is the `judge.eval:` block, with an optional `model`; the client's default otherwise. This is harness code, the factory the release suite names, so the API key comes from GOOGLE_API_KEY, and its absence is an error.

func Handler

func Handler(buildBot Bot) http.Handler

Handler serves buildBot over RTVI on a plain WebSocket: it accepts one client per connection, wires the eval transport into the bot's pipeline, and runs it until the client disconnects. Mount it in a bot's own HTTP server to expose an eval endpoint that `jargo eval run`, or any RTVI WebSocket client, can drive. The in-process Host uses it too.

The endpoint speaks RTVI through the eval serializer, which additionally understands the harness's own control messages. Serving the bot's production RTVI endpoint to the harness instead works, but a scenario asserting on tool arguments will not see them: raising the report level is deliberately something only this serializer allows.

The harness sets each connection's flags on its URL (see evalws.SkipTTSQueryParam and the parameters beside it), and they apply to that connection alone. A bot run under the development runner needs none of this: the harness connects to the runner's /ws, and runner.CreateTransport builds the same transport from its eval-connect message.

func IsScenarioFile added in v0.7.0

func IsScenarioFile(path string) bool

IsScenarioFile reports whether a YAML file is a scenario of any kind rather than a fragment one includes.

Every scenario file has a `name:`; a fragment a scenario includes with !include (a block of turns, a judge: block) has none. A file that does not parse counts as a scenario, so loading it reports the error instead of a directory run skipping it silently.

func JudgeableEvents added in v0.7.0

func JudgeableEvents() []string

JudgeableEvents returns the events whose payloads carry bot-generated text a judge can evaluate.

func LLMServiceFromConfig added in v0.7.0

func LLMServiceFromConfig(cfg *LLMServiceConfig, where string) (llm.Inferencer, error)

LLMServiceFromConfig builds an LLM service from a block naming one: the judge's, its explainer's, or a persona's.

A factory builds it; otherwise the service name picks a provider, "ollama" by default. where is the block's name in the file ("judge.eval", "simulator"), for the errors; a nil cfg uses all the defaults.

`service: openai` still builds an OpenAI service, with a warning, keyed from OPENAI_API_KEY.

func LoadUserAudio added in v0.7.0

func LoadUserAudio(path string) (pcm []byte, sampleRate int, err error)

LoadUserAudio reads an audio file as the PCM a user turn is sent as: 16-bit little-endian mono PCM, and its sample rate.

The file keeps its own sample rate; the bot resamples on its way in. A file of several channels is downmixed to their mean. It fails with an error naming the path when the file cannot be read as audio, or holds none.

func MarkerKinds added in v0.7.0

func MarkerKinds() []string

MarkerKinds returns what a marker: may name on an llm_marker expectation.

func MatchingMetrics added in v0.7.0

func MatchingMetrics(event map[string]any, metric, processor string) map[string][]any

MatchingMetrics is the measurements of a metrics event that an expectation's filters take, by kind: metric is the kind to keep, or empty for every kind, and processor text the measuring processor's name must contain, or empty for any processor. It is empty when none is kept.

The zero a pipeline reports for every processor as it starts is a placeholder, not a measurement, and is left out.

func OllamaService added in v0.7.0

func OllamaService(cfg *LLMServiceConfig) *ollama.LLMService

OllamaService builds a local Ollama LLM service from a block.

An `extra:` mapping goes to the model as request parameters, which is how `reasoning_effort: none` reaches a thinking model. The default model comes with the extras it needs (DefaultOllamaJudgeExtra); a named model gets only the extras asked for.

func PipelineLogCategories added in v0.7.0

func PipelineLogCategories() []string

PipelineLogCategories returns the log categories, in the order a run's debug log lists them.

func PipelineLogLabels added in v0.7.0

func PipelineLogLabels() map[string]string

PipelineLogLabels returns the heading of each category's section in a run's debug log.

func QuietLogs added in v0.7.0

func QuietLogs() (restore func())

QuietLogs makes the default logger write nothing but the per-run captures (see CapturePipelineLogs), keeping the output clean for a caller's display, until the returned func restores the default logger and the log package's output as they were.

func RegisterFactory added in v0.7.0

func RegisterFactory(name string, f Factory)

RegisterFactory registers a factory under name, the dotted name a block's `factory:` gives, replacing any registered before. The names the release suite uses come registered, so its scenarios load unchanged: "evals.judges.typesafe_classifier" is TypesafeClassifier, "evals.judges.google_classifier" is GoogleClassifier and "evals.judges.zoom_classifier" is ZoomClassifier.

func RegisterSTTService added in v0.7.0

func RegisterSTTService(name string, build STTServiceBuilder)

RegisterSTTService registers the builder of a built-in transcription service, such as "moonshine" or "whisper", replacing any registered before.

func RegisterTTSService added in v0.7.0

func RegisterTTSService(name string, build TTSServiceBuilder)

RegisterTTSService registers the builder of a built-in user TTS, such as "kokoro", replacing any registered before.

func Run

func Run(t *testing.T, path string, buildBot Bot)

Run plays the scenario at path against buildBot, hosted in-process over a loopback WebSocket, and reports every unmet expectation through t. Text mode: each user turn is injected as RTVI send-text, so audio processors sit idle. For an LLM judge or audio mode, use RunWith.

func RunWith

func RunWith(t *testing.T, path string, buildBot Bot, opts Options)

RunWith is Run with explicit Options (a judge, audio mode, or both).

func RunWithJudge

func RunWithJudge(t *testing.T, path string, buildBot Bot, judge Judge)

RunWithJudge is Run with a judge for the scenario's `judge:` assertions (see NewClassifierJudge). Pass nil when no scenario uses `judge:`.

func ScenarioSuffixes added in v0.7.0

func ScenarioSuffixes() []string

ScenarioSuffixes returns the file name suffixes a scenario file is looked for under.

func SimulationEndings added in v0.7.0

func SimulationEndings() []string

SimulationEndings returns the values SimulationResult.EndedBy takes.

func SimulationMeasures added in v0.7.0

func SimulationMeasures() []string

SimulationMeasures returns what a measured metric can measure.

func TTSCacheKey added in v0.7.0

func TTSCacheKey(cfg *SpeechConfig) string

TTSCacheKey is a stable identity for a `user.speech:` block: its service, voice, model, language and speed, not its sample rate.

func TTSSampleRate added in v0.7.0

func TTSSampleRate(cfg *SpeechConfig) int

TTSSampleRate is the sample rate a `user.speech:` block asks for (default 16 kHz).

func TurnStatuses added in v0.7.0

func TurnStatuses() []string

TurnStatuses returns the values ScriptTurnResult.Status takes.

func TypesafeClassifier added in v0.7.0

func TypesafeClassifier(config map[string]any) (any, error)

TypesafeClassifier is TypeSafe's Jev, a hosted classifier that answers in a few hundred milliseconds. It is the factory registered as "evals.judges.typesafe_classifier".

config is the `judge.eval:` block, with an optional `model` and `endpoint`; the client's defaults otherwise. This is harness code, the factory the release suite names, so the API key comes from TYPESAFE_API_KEY, and its absence is an error.

func ZoomClassifier added in v1.0.0

func ZoomClassifier(config map[string]any) (any, error)

ZoomClassifier is Zoom's Decisions API, a classifier that answers in a few hundred milliseconds. It is the factory registered as "evals.judges.zoom_classifier".

config is the `judge.eval:` block, with an optional `model` ("zoom-decisions" or "zoom-decisions-pro"); the client's default otherwise. This is harness code, the factory the release suite names, so the API key comes from ZOOM_AI_API_KEY, and its absence is an error.

Types

type AssertionFailure added in v0.7.0

type AssertionFailure struct {
	// TurnIndex is the index of the turn that failed, from 0, or -1 for a
	// failure of the run before any turn.
	TurnIndex int
	// ExpectationIndex is the index of the expectation within the turn, from
	// 0, or -1 for a turn-level failure (a send_after that never fired) or a
	// failure of the run itself.
	ExpectationIndex int
	// EventName is the expectation's event name, or one of the RunEvent names
	// for a failure of the run itself.
	EventName string
	// Reason explains what went wrong. It is free text and differs on every
	// run, often the judge's prose.
	Reason string
	// Kind is how the assertion failed, one of FailureKinds. It says which
	// assertion gave way, not what that means about the bot, and is what
	// failures are grouped by across many runs.
	Kind string
}

AssertionFailure is a single failed assertion within an eval, or a failure of the run itself.

func (AssertionFailure) String added in v0.7.0

func (f AssertionFailure) String() string

String renders a failure as a single line.

type Bot

type Bot func(in, out processor.Processor) *pipeline.Worker

Bot builds the bot's pipeline task around the harness-provided transport endpoints. The pipeline must include an rtvi.Processor so the harness can drive it (send-text) and observe its events. The builder is transport- agnostic: the harness supplies a WebSocket transport's input and output.

type BotMetricsReport added in v0.7.0

type BotMetricsReport struct {
	// At is when it arrived, in seconds since the run's stream began.
	At float64 `json:"at"`
	// Data is the report as the bot sent it, its measurements grouped by kind
	// (ttfb, processing, tokens, and so on).
	Data map[string]any `json:"data"`
}

BotMetricsReport is one metrics report the bot sent during a run.

type BotUnavailableError added in v0.7.0

type BotUnavailableError struct {
	// Kind is the failure kind the run records: FailureConnectFailed when the
	// bot refused the connection, FailureClosedBeforeReady when it closed the
	// connection before bot-ready, FailureAudioUnsupported when its bot-ready
	// reported its transport off for audio the run uses, and FailureError when
	// the harness's own pipeline failed first.
	Kind string
	// Reason is what happened, with the close code and reason when there was
	// one.
	Reason string
}

BotUnavailableError is a bot that refused the connection, closed it before bot-ready, or cannot carry the run's audio.

func (*BotUnavailableError) Error added in v0.7.0

func (e *BotUnavailableError) Error() string

type CachingTTSConfig added in v0.7.0

type CachingTTSConfig struct {
	// CacheKey is a stable identity for the inner service's config (see
	// TTSCacheKey); combined with the text, it keys the cache.
	CacheKey string
	// CacheDir is where cached audio is stored; empty uses DefaultCacheDir.
	CacheDir string
	// UseCache is whether cached audio is read and new audio written; nil
	// uses the cache.
	UseCache *bool
	// SampleRate is the rate the service's audio is played at; zero uses
	// DefaultSampleRate.
	SampleRate int
}

CachingTTSConfig configures a CachingTTSService.

type CachingTTSService added in v0.7.0

type CachingTTSService struct {
	*tts.Base
	// contains filtered or unexported fields
}

CachingTTSService is a pipeline TTS that wraps a real service and caches its audio on disk.

For each utterance it emits the cached audio when present, otherwise it runs the wrapped service, caches the audio, and forwards it. The cache stores audio at CacheSampleRate, and the audio is resampled to the service's rate as it plays. The inner service's start and close are forwarded so it works inside the pipeline. Only local and HTTP inner services are supported.

func NewCachingTTSService added in v0.7.0

func NewCachingTTSService(inner tts.Synthesizer, cfg CachingTTSConfig) (*CachingTTSService, error)

NewCachingTTSService wraps inner, the local or HTTP synthesizer that does the synthesis, in a cache. A WebSocket-streaming synthesizer, or one that appends its audio to the service's contexts rather than yielding it, is refused: its RunTTS yields no audio to cache.

func TTSServiceFromConfig added in v0.7.0

func TTSServiceFromConfig(cfg *SpeechConfig, cacheDir string, useCache bool) (*CachingTTSService, error)

TTSServiceFromConfig builds the user-audio TTS, wrapped in a cache, from a `user.speech:` block.

A factory builds the inner service; otherwise the service name picks one, "kokoro". The wrapper synthesizes each user utterance once and reuses it across runs, from cacheDir (empty uses DefaultCacheDir), and useCache false forces fresh synthesis. The wrapper streams at the block's sample rate (see TTSSampleRate).

`service: cartesia` still builds a Cartesia HTTP TTS, with a warning.

func (*CachingTTSService) Inner added in v0.7.0

func (s *CachingTTSService) Inner() tts.Synthesizer

Inner is the synthesizer the service wraps.

func (*CachingTTSService) RunTTS added in v0.7.0

func (s *CachingTTSService) RunTTS(
	ctx context.Context, text, contextID string, yield func(f frames.Frame) error,
) error

RunTTS emits the audio for text from the cache, or by driving the inner service: TTSStartedFrame, TTSAudioRawFrame and TTSStoppedFrame on a cache hit, the inner service's own frames on a miss.

func (*CachingTTSService) SampleRate added in v0.7.0

func (s *CachingTTSService) SampleRate() int

SampleRate is the rate the service's audio is played at.

func (*CachingTTSService) Synthesize added in v0.7.0

func (s *CachingTTSService) Synthesize(ctx context.Context, text string) ([]byte, error)

Synthesize is the audio for text, from the cache or by driving the inner service, as 16-bit mono PCM at the service's sample rate.

type ClassifierJudge added in v1.0.0

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

ClassifierJudge judges a conversation with a classifier, and asks an LLM for the reasons.

Every question goes to the classifier, which answers with an option and a probability for each of the options it was offered. A reply is judged yes, no or continue, with the conversation before it and the reply itself sent apart, so the classifier knows which part to judge. A tool call is judged yes or no by its name and arguments. Each verdict carries the classifier's confidence, and its reason starts out as the probabilities it gave (P(yes)=0.97). Each question's verdict is cached by its criterion and state; a failed question is not, since it decided nothing.

A whole simulation run is judged by EvaluateRun: the goal is one yes or no question over the whole conversation, and each bot turn is asked about on its own, once per criterion, with only the conversation before it as context. All of a run's questions go out at once.

A classifier gives no reasons, so the judge asks an LLM of its own, the explainer, for them: for every no, and for every yes less sure than ExplainBelow, but never for a continue. The explainer is told the verdict and asked only what in the conversation supports it, so it never changes a verdict; the reason it gives takes the place of the probabilities, which the verdict still carries.

A question that fails is asked once more; a second failure gives a none (no verdict), with the reason "judge call failed: " and the error, its credentials masked.

func NewClassifierJudge added in v1.0.0

func NewClassifierJudge(cfg ClassifierJudgeConfig) (*ClassifierJudge, error)

NewClassifierJudge builds a judge.

func NewClassifierJudgeFromConfig added in v1.0.0

func NewClassifierJudgeFromConfig(cfg *JudgeEvalConfig) (*ClassifierJudge, error)

NewClassifierJudgeFromConfig builds a judge from a scenario's `judge.eval:` block.

The block names an LLM, Ollama by default, and the judge classifies and explains with it. A factory builds the classifier instead, or an LLM service to classify with; the explainer is then the `explainer:` block's LLM, or the default LLM when the block names none. `explainer: false` gives no explainer. A nil cfg uses all the defaults. For a fully custom judge, build one with NewClassifierJudge.

It fails when the block names an unknown service, or its factory is not registered or returned neither a classifier nor an LLM service.

func (*ClassifierJudge) AddAssistantMessage added in v1.0.0

func (j *ClassifierJudge) AddAssistantMessage(text string)

AddAssistantMessage adds a segment of the bot's current reply to the conversation the judge sees. Consecutive segments are one reply.

func (*ClassifierJudge) AddToolCall added in v1.0.0

func (j *ClassifierJudge) AddToolCall(text string)

AddToolCall records a tool call the bot made, on one line, e.g. book({"time": "6pm"}). A reply and a call are judged on the spoken conversation only, so it is kept but not shown to them.

func (*ClassifierJudge) AddUserMessage added in v1.0.0

func (j *ClassifierJudge) AddUserMessage(text string)

AddUserMessage records a user turn, so a later reply is judged in context (a terse "that's four" answering "what is two plus two?", say).

func (*ClassifierJudge) Classifier added in v1.0.0

func (j *ClassifierJudge) Classifier() classifier.Classifier

Classifier is the classifier that decides the verdicts.

func (*ClassifierJudge) Close added in v1.0.0

func (j *ClassifierJudge) Close(ctx context.Context) error

Close releases what the judge holds open; the session calls it when the run ends.

func (*ClassifierJudge) Evaluate added in v1.0.0

func (j *ClassifierJudge) Evaluate(ctx context.Context, criterion string, allowContinue *bool) JudgeVerdict

Evaluate judges whether the bot's latest reply satisfies criterion, in the conversation so far. allowContinue is whether this reply may be judged continue; nil leaves it to the judge's own setting. It gives a yes, a no, or, when continue is allowed, a continue when the bot is still working toward its answer, cached by criterion, conversation and the answers it was allowed. A final verdict that needs a reason is explained, and a failed question is a none with the failure as its reason, not cached.

func (*ClassifierJudge) EvaluateCall added in v1.0.0

func (j *ClassifierJudge) EvaluateCall(
	ctx context.Context, name string, args map[string]any, criterion string,
) JudgeVerdict

EvaluateCall judges whether a tool call the bot made satisfies criterion, in the conversation so far. It gives a yes or a no, cached by call, criterion and conversation, and explained when it needs a reason. A failed question is a none, not cached.

func (*ClassifierJudge) EvaluateRun added in v1.0.0

func (j *ClassifierJudge) EvaluateRun(ctx context.Context, criteria []Criterion, success string) RunVerdicts

EvaluateRun judges the whole conversation: every bot turn on every criterion, and the goal.

The goal is asked over the whole conversation, tool calls included. Each bot turn is its own question, judged in the light of the conversation before it, with the turn itself as latest_bot_reply, and its verdict is a no only when the criterion applies to the turn and the turn fails it. The questions run concurrently. When any verdict needs a reason, the explainer is asked about the run once and its reasons go with the classifier's verdicts.

It gives the goal's verdict and, per criterion name, a verdict per bot turn in order. A failed question is a none for each verdict it asked for, and a run with a failed question is not cached.

type ClassifierJudgeConfig added in v1.0.0

type ClassifierJudgeConfig struct {
	// Classifier decides the verdicts. The judge sets it up before its first
	// question and cleans it up when it is closed. Required.
	Classifier classifier.Classifier
	// Explainer is the LLM asked for the reason behind a no or an unsure
	// verdict; nil reports the probabilities alone.
	Explainer llm.Inferencer
	// ExplainBelow is the confidence under which a yes is explained too; nil
	// uses 0.75. Zero limits the explainer to the no verdicts, and a value above
	// 1 sends it every verdict.
	ExplainBelow *float64
	// AllowContinue is whether a reply may be judged continue: the bot is still
	// working toward its answer, so the harness waits for more of it. Nil allows
	// it. A suite whose judged replies are all final answers turns it off, and a
	// reply is then yes or no; a reply that is still arriving is still judged
	// again as more of it comes. An expectation can set allow_continue: false
	// on itself alone, which forces the judge to consider its reply as final,
	// the thing to be judged, rather than skipping it: a wait reassurance
	// ("still working on it...") is judged that way.
	AllowContinue *bool
	// MaxTokens caps the explainer's answer for one reason; zero uses 200,
	// enough for a short sentence.
	MaxTokens int
}

ClassifierJudgeConfig configures an ClassifierJudge.

type Client added in v0.7.0

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

Client is the eval pipeline that talks to the bot, and the user's sends into it.

Built once per run: WaitForBot, Start, Handshake, the turns (SendText, Say, Play, SendDTMF, SendImage), then Stop. The pipeline is

input -> [STT -> speech gate -> bot-turn aggregator] -> sink -> [persona LLM]
      -> [user TTS] -> [persona relay] -> output -> [assistant aggregator]

The bracketed stages exist in audio mode (the STT that transcribes the bot's speech, the gate that drops transcripts of audio from before a send that talked over the bot, the aggregator that cuts the transcripts into the bot's turns, the user TTS) or in a simulation (the persona LLM, its relay, and the assistant aggregator that keeps the persona's own replies in its context). The bot's output comes in through the input and stops at the sink, as events; the user's turns start at the sink and leave through the output. In a simulation the persona answers the bot on its own from the sink. A session builds it, with the params its scenario asks for.

func NewClient added in v0.7.0

func NewClient(
	botURL string, params ClientParams, sessionParams SessionParams,
	stream *EventStream, trace *Trace, userTTS *CachingTTSService, botSTT SegmentedSTT, persona *Persona,
) *Client

NewClient builds the client for the bot at botURL. stream is where the bot's output is appended as events; userTTS speaks the user's text turns, or is nil for text turns; botSTT transcribes the bot's audio into the response event, or is nil when unused; persona is a simulation's simulated caller, whose LLM rides in the pipeline and answers the bot, or nil.

The bot's speech is transcribed by a segmented STT or not at all: only a segmented STT's transcripts can be traced to when their audio began, which is how the client tells the speech a send talked over from the bot's reply.

func (*Client) Handshake added in v0.7.0

func (c *Client) Handshake(ctx context.Context) error

Handshake waits for bot-ready, then sends what the scenario asks of the bot and its context.

A bot that never says ready is not a usable eval target, so this fails instead of sending turns to a half-started bot: with a *BotUnavailableError when the bot refuses the connection, closes it before bot-ready, or reports its transport off for audio the run uses, and with an error naming the timeout when bot-ready never comes.

func (*Client) HangUp added in v0.7.0

func (c *Client) HangUp()

HangUp ends the persona's part of the conversation: it answers nothing more.

func (*Client) HasUserTTS added in v0.7.0

func (c *Client) HasUserTTS() bool

HasUserTTS reports whether text user turns are spoken to the bot rather than sent as text.

func (*Client) Play added in v0.7.0

func (c *Client) Play(ctx context.Context, path string) error

Play plays a recording to the bot as the user's turn, instead of synthesizing one.

It goes out like a spoken turn: resampled to the user audio rate, paced to the bot, and recorded.

func (*Client) ReportEndCall added in v0.7.0

func (c *Client) ReportEndCall(event map[string]any)

ReportEndCall appends the persona's end_call event once the reply that made the call has gone out.

func (*Client) Say added in v0.7.0

func (c *Client) Say(ctx context.Context, text string) error

Say speaks text as the user. The user TTS synthesizes it (cached) and the output paces it to the bot as live audio.

func (*Client) SayWithPauses added in v0.7.0

func (c *Client) SayWithPauses(ctx context.Context, parts []TurnPart) error

SayWithPauses speaks the user's text with real silence between its parts.

Each text is synthesized by the user TTS (cached), and the turn goes out like a recording: one stretch of audio, paced to the bot and recorded.

func (*Client) Send added in v0.7.0

func (c *Client) Send(message rtvi.Message)

Send sends an RTVI client message to the bot through the transport pipeline.

func (*Client) SendDTMF added in v0.7.0

func (c *Client) SendDTMF(keys string)

SendDTMF sends a DTMF keypress turn as one RTVI dtmf message. The bot handles the keys the way it handles a phone keypad.

func (*Client) SendImage added in v0.7.0

func (c *Client) SendImage(imagePath string) error

SendImage registers an image for the current turn. The bot's eval transport serves it back when the bot asks for a user image. The file is sent as is.

func (*Client) SendText added in v0.7.0

func (c *Client) SendText(text string)

SendText sends a text user turn as an RTVI send-text message.

func (*Client) SendsUserAudio added in v0.7.0

func (c *Client) SendsUserAudio() bool

SendsUserAudio reports whether the user's side streams audio to the bot.

func (*Client) Start added in v0.7.0

func (c *Client) Start(ctx context.Context) error

Start builds the eval pipeline and starts running it, which connects to the bot. It fails when a stage of the pipeline cannot be built: the VAD the bot's speech is heard with.

func (*Client) Stop added in v0.7.0

func (c *Client) Stop(ctx context.Context)

Stop saves the recording, ends the bot's session, and ends the pipeline.

func (*Client) WaitForBot added in v0.7.0

func (c *Client) WaitForBot(ctx context.Context) error

WaitForBot waits until the bot accepts connections.

It retries a plain TCP connect until the bot is listening, and stops short of the WebSocket handshake on purpose: a full connection would make the bot greet, and that connection would then be thrown away. It returns the last connect error when the bot never accepted within the connect timeout.

type ClientInputTransport added in v0.7.0

type ClientInputTransport struct {
	*wsclient.RTVIInputTransport
	// contains filtered or unexported fields
}

ClientInputTransport feeds the bot's audio to the harness's VAD and STT as a continuous stream.

The bot sends audio only while its TTS produces it, with gaps at its pauses. A gap reads as silence to a VAD, which would end the bot's turn mid-sentence, so the audio is buffered and re-emitted one 40 ms frame per tick, silence filling the gaps.

func (*ClientInputTransport) Cleanup added in v0.7.0

func (i *ClientInputTransport) Cleanup(ctx context.Context) error

Cleanup stops the gap-fill stream, then cleans the transport up.

func (*ClientInputTransport) ProcessFrame added in v0.7.0

ProcessFrame passes a frame on. When audio is enabled the start begins the gap-fill stream, and an end or a cancel stops it before the transport.

func (*ClientInputTransport) PushAudioFrame added in v0.7.0

func (i *ClientInputTransport) PushAudioFrame(_ context.Context, f frames.InputAudioFrame)

PushAudioFrame buffers the bot's audio for the fill task.

func (*ClientInputTransport) PushFrame added in v0.7.0

PushFrame pushes a frame on. When the bot reports an interruption, the audio it sent but a client would never play is dropped, and the recorder drops the same bytes.

type ClientOutputTransport added in v0.7.0

type ClientOutputTransport struct {
	*wsclient.OutputTransport
	// contains filtered or unexported fields
}

ClientOutputTransport streams the user's audio to the bot as a continuous real-time stream.

A real-time task sends one 40 ms frame per tick: queued TTS audio when there is some, silence otherwise, so the bot's VAD and turn detection see the silence they need to end a turn. It runs only when audio output is on.

func (*ClientOutputTransport) Cleanup added in v0.7.0

func (o *ClientOutputTransport) Cleanup(ctx context.Context) error

Cleanup stops the send stream, then cleans the transport up.

func (*ClientOutputTransport) ProcessFrame added in v0.7.0

ProcessFrame passes a frame on. In audio mode the start begins the real-time send stream, and an end or a cancel stops it before the transport. An interruption drops the user audio not yet sent, and the recorder drops the same bytes.

func (*ClientOutputTransport) WriteAudio added in v0.7.0

WriteAudio queues the user audio for the send task.

It reports the audio as not sent, so the output does not push this unpaced frame downstream; the send task pushes the paced frames instead.

type ClientParams added in v0.7.0

type ClientParams struct {
	// BotAudio is whether the bot speaks; in text mode it is asked to skip TTS
	// at connect.
	BotAudio bool
	// UserAudio is whether the user's turns reach the bot as audio.
	UserAudio bool
	// UserSpeech is the TTS config the user's turns are synthesized with, or
	// nil; it sets the user audio rate.
	UserSpeech *SpeechConfig
	// CaptureBotAudio is whether the bot forwards its synthesized audio, for
	// the response transcription.
	CaptureBotAudio bool
	// CaptureBotImages is whether the bot reports the images it outputs.
	CaptureBotImages bool
	// ReportLevel is the function-call report level to ask of the bot, or ""
	// for its default.
	ReportLevel rtvi.FunctionCallReportLevel
	// VADEvents is whether to ask the bot for its raw VAD events.
	VADEvents bool
	// MarkerEvents is whether to ask the bot for the sideband markers its LLM
	// emits.
	MarkerEvents bool
	// Context is the messages the bot's context starts from, sent right after
	// the handshake; empty sends nothing.
	Context []map[string]any
}

ClientParams is what the scenario asks of the bot; the session derives it from its scenario.

type ClientRecorder added in v0.7.0

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

ClientRecorder builds the conversation recording from the raw audio, not the paced streams.

The pacing tick cannot be held precisely, and a recording of the paced streams stutters. So each side is recorded as it was produced or received, laid out on its own timeline with silence only where a real pause was, and mixed to mono by Write. Audio the bot sent past an interruption is dropped, as a real client would drop it.

func NewClientRecorder added in v0.7.0

func NewClientRecorder(sampleRate int) *ClientRecorder

NewClientRecorder builds a recorder that writes at sampleRate; both sides are resampled to it on write.

func (*ClientRecorder) AddBot added in v0.7.0

func (r *ClientRecorder) AddBot(pcm []byte, inRate int)

AddBot records a chunk of the bot's audio (raw, before the gap-fill loop), 16-bit mono PCM at inRate.

func (*ClientRecorder) AddUser added in v0.7.0

func (r *ClientRecorder) AddUser(pcm []byte, inRate int)

AddUser records a chunk of the user's TTS audio (raw, before pacing to the bot), 16-bit mono PCM at inRate.

func (*ClientRecorder) DropBotTail added in v0.7.0

func (r *ClientRecorder) DropBotTail(numBytes int)

DropBotTail drops the last numBytes of the bot's audio: sent, but never played.

func (*ClientRecorder) DropUserTail added in v0.7.0

func (r *ClientRecorder) DropUserTail(numBytes int)

DropUserTail drops the last numBytes of the user's audio: synthesized, but never sent.

func (*ClientRecorder) HasAudio added in v0.7.0

func (r *ClientRecorder) HasAudio() bool

HasAudio reports whether any audio has been recorded on either side.

func (*ClientRecorder) Write added in v0.7.0

func (r *ClientRecorder) Write(path string) (bool, error)

Write resamples both sides to a common rate, aligns them, mixes them to mono and writes a WAV file at path, creating its directory. It reports whether a file was written, which it is not when nothing was recorded.

type ClientSerializer added in v0.7.0

type ClientSerializer struct {
	*rtviclient.Serializer
	// contains filtered or unexported fields
}

ClientSerializer is the harness's serializer: RTVI client messages, plus the bot's audio.

eval-bot-audio becomes an InputAudioRawFrame, so the harness's STT can transcribe what the bot actually said. Every other message from the bot stays a raw message, as rtviclient.Serializer keeps it, and the event stream maps the ones a scenario reads to its events. Its reports about the harness (its VAD, speaking and transcription of the harness's speech) cannot be mistaken for what the harness computes from the bot's audio that way, nor its reports about itself for the harness's own output.

One ClientSerializer serves one connection.

func NewClientSerializer added in v0.7.0

func NewClientSerializer() *ClientSerializer

NewClientSerializer builds the harness's serializer.

func (*ClientSerializer) Deserialize added in v0.7.0

func (s *ClientSerializer) Deserialize(data []byte) (frames.Frame, error)

Deserialize turns an RTVI server message into a frame: the bot's audio as audio, any other as the raw message it is. It returns (nil, nil) for a message that is not an RTVI message.

type ClientTransport added in v0.7.0

type ClientTransport struct {
	*wsclient.RTVITransport
	// contains filtered or unexported fields
}

ClientTransport is the harness's RTVI client transport, with audio edges that behave like a live transport.

The input fills the gaps in the bot's audio and the output paces the user's; both feed the recorder the raw audio when one is given. On connect it sends the connection's flags in an eval-connect message, ahead of the RTVI handshake, which is how a bot hosted by the development runner recognizes the harness and learns what the connection asks of it.

func NewClientTransport added in v0.7.0

func NewClientTransport(
	uri string, params wsclient.Params, flags evalws.ConnectionFlags, recorder *ClientRecorder,
) *ClientTransport

NewClientTransport builds the harness's transport to the bot at uri, sending flags first on every connection. recorder is fed the raw audio on both edges, or is nil not to record. The serializer defaults to a ClientSerializer when params does not set one.

func (*ClientTransport) Flags added in v0.7.0

Flags are the connection's flags, as sent in eval-connect.

type Configured added in v0.7.0

type Configured struct {
	// UserAudio is whether the user's turns reach the bot as speech
	// (user.modality: audio) rather than as text.
	UserAudio bool
	// UserSpeech is the user.speech: block, or nil in text modality, or in
	// audio modality when every spoken turn plays a recording.
	UserSpeech *SpeechConfig
	// BotAudio is whether the bot speaks (judge.modality: audio). In text
	// modality, the default, the bot skips TTS and the judge reads its LLM
	// text.
	BotAudio bool
	// Transcriber is the judge.transcription: block, or nil in text modality.
	Transcriber *TranscriptionConfig
	// Judge is the judge.eval: block, DefaultJudgeEvalConfig when it is
	// omitted.
	Judge JudgeEvalConfig
}

Configured is the modality and service config a scripted scenario and a simulation share, read from their user: and judge: blocks.

type Conversation added in v0.7.0

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

Conversation builds a conversation's messages as the conversation happens, in the format a conversation file holds (see ConversationRoleUser).

The user's turns and the bot's calls are added as they come. What the bot says gathers into its current turn, which the next user turn, or EndBotTurn, closes. A Conversation is safe for concurrent use.

func NewConversation added in v0.7.0

func NewConversation() *Conversation

NewConversation is an empty conversation.

func (*Conversation) AddAssistantMessage added in v0.7.0

func (c *Conversation) AddAssistantMessage(text string)

AddAssistantMessage adds a segment of what the bot said to its current turn.

func (*Conversation) AddToolCall added in v0.7.0

func (c *Conversation) AddToolCall(name string, arguments map[string]any)

AddToolCall adds a function the bot called.

func (*Conversation) AddUserMessage added in v0.7.0

func (c *Conversation) AddUserMessage(text string)

AddUserMessage adds a user turn, which ends the bot's turn; empty text only ends the bot's turn.

func (*Conversation) CancelToolCall added in v0.7.0

func (c *Conversation) CancelToolCall(name string)

CancelToolCall marks the bot's latest call to name that is not canceled yet as canceled.

func (*Conversation) EndBotTurn added in v0.7.0

func (c *Conversation) EndBotTurn()

EndBotTurn ends the bot's turn: what it said since the user last spoke becomes one message.

func (*Conversation) Messages added in v0.7.0

func (c *Conversation) Messages() []map[string]any

Messages are the messages so far, without the bot's turn in progress.

func (*Conversation) UserSpokeLast added in v0.7.0

func (c *Conversation) UserSpokeLast() bool

UserSpokeLast reports whether a user turn is the last thing said, with nothing from the bot since.

type ConversationEndedMessage added in v0.7.0

type ConversationEndedMessage struct {
	// Conversation is the conversation's messages, as a conversation file
	// holds them (see Conversation).
	Conversation []map[string]any
}

ConversationEndedMessage is the message accompanying EventConversationEnded.

type ConversationObserver added in v0.7.0

type ConversationObserver struct {
	event.Registry
	// contains filtered or unexported fields
}

ConversationObserver records a bot's conversation, and reports it once the pipeline is done.

Each side's turn is what the context aggregators write to the LLM context, so the user's turns are what the bot heard and the bot's turns are what it said, cut where the user interrupted it. Text a client sends with RTVI's send-text is a user turn too, since it goes to the context as is. Each turn is recorded as it is written, so summarizing the context later doesn't lose it, and the context's other messages, such as a flow's tool changes, stay out.

It records what passes through the worker it is attached to: in a bot with several workers, that is the one holding the conversation's context, and calls made in other workers are not in it.

observer := eval.NewConversationObserver()
event.On(&observer.Registry, eval.EventConversationEnded,
	func(_ context.Context, m eval.ConversationEndedMessage) {
		data, _ := json.MarshalIndent(m.Conversation, "", "  ")
		_ = os.WriteFile("call.conversation.json", data, 0o600)
	})
worker := pipeline.NewWorker(p, pipeline.WorkerConfig{Observers: []processor.Observer{observer}})

func NewConversationObserver added in v0.7.0

func NewConversationObserver() *ConversationObserver

NewConversationObserver builds the observer.

func (*ConversationObserver) Cleanup added in v0.7.0

func (o *ConversationObserver) Cleanup(ctx context.Context) error

Cleanup reports the conversation: the pipeline is done, and so is the bot's last turn.

func (*ConversationObserver) ObserveEveryPush added in v0.7.0

func (*ConversationObserver) ObserveEveryPush() bool

ObserveEveryPush reports that the observer sees only a frame's first push.

func (*ConversationObserver) OnPushFrame added in v0.7.0

func (o *ConversationObserver) OnPushFrame(data processor.FramePushed)

OnPushFrame adds what a frame says about the conversation to it.

type Criterion added in v0.7.0

type Criterion struct {
	// Name is the criterion's name, which the run's verdicts are keyed by.
	Name string
	// Criterion is the natural-language criterion.
	Criterion string
}

Criterion is one per-turn criterion of a judged run: its name and what it asks of every bot reply.

type EventStream added in v0.7.0

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

EventStream is the bot's output as events: a queue the drivers read, fed by the pipeline.

The sink hands it the bot's RTVI messages, each mapped to its event (see RTVIMessageToEvent), and the harness appends events of its own; the drivers pop events as they wait for them. One rule runs through it: what the bot produced before the user's latest send is not the reply to it. An LLM response still streaming at the send, or cut by an interruption, is dropped until the bot's next llm-started, and a spoken turn that began before the send is dropped when it ends.

It is safe for concurrent use: the pipeline feeds it and the driver reads it.

func NewEventStream added in v0.7.0

func NewEventStream(botAudio bool, trace *Trace) *EventStream

NewEventStream builds the stream of a run. botAudio says whether the scenario runs in audio mode, where tts_response is emitted; trace is where each event is logged as it arrives.

func (*EventStream) Append added in v0.7.0

func (s *EventStream) Append(event map[string]any)

Append queues an event for the drivers. It stamps its arrival time as "at" (seconds since the stream began) unless it has one, records it, and logs it. A metrics event is recorded in Metrics rather than EventsSeen.

func (*EventStream) BeginTurn added in v0.7.0

func (s *EventStream) BeginTurn()

BeginTurn forgets the events popped during the previous turn.

func (*EventStream) BotEnded added in v0.7.0

func (s *EventStream) BotEnded()

BotEnded notes that the bot closed the connection: it sends nothing more, and is no longer speaking.

func (*EventStream) BotHasEnded added in v0.7.0

func (s *EventStream) BotHasEnded() bool

BotHasEnded reports whether the bot ended the call (see BotEnded).

func (*EventStream) BotSegmentEnded added in v0.7.0

func (s *EventStream) BotSegmentEnded()

BotSegmentEnded notes that a segment of the bot's speech ended and awaits transcription.

func (*EventStream) BotSegmentStarted added in v0.7.0

func (s *EventStream) BotSegmentStarted()

BotSegmentStarted notes that the VAD hears a segment of the bot's speech.

func (*EventStream) BotSegmentTranscribed added in v0.7.0

func (s *EventStream) BotSegmentTranscribed()

BotSegmentTranscribed notes that a segment of the bot's speech was transcribed, whether or not it yielded text.

func (*EventStream) BotSpeaking added in v0.7.0

func (s *EventStream) BotSpeaking() bool

BotSpeaking reports whether the bot reports itself speaking right now.

func (*EventStream) BotSpeechOutstanding added in v0.7.0

func (s *EventStream) BotSpeechOutstanding() string

BotSpeechOutstanding is what of the bot's speech is not yet accounted for, for the trace.

func (*EventStream) BotTranscribed added in v0.7.0

func (s *EventStream) BotTranscribed() bool

BotTranscribed reports whether everything the bot has said is transcribed and closed into a turn.

func (*EventStream) BotTurnStarted added in v0.7.0

func (s *EventStream) BotTurnStarted()

BotTurnStarted notes that the bot began a spoken turn.

func (*EventStream) BotTurnStopped added in v0.7.0

func (s *EventStream) BotTurnStopped(text string)

BotTurnStopped appends the bot's finished spoken turn as a response, unless it is stale.

Speech the bot was saying when a send talked over it never reaches a turn (the client drops it by its audio's time). A turn is still stale while the bot's LLM has not restarted since the send: the bot going on with what it was saying, which must not pass for the reply. Nothing is appended for an empty text.

func (*EventStream) DropPendingBotOutput added in v0.7.0

func (s *EventStream) DropPendingBotOutput(why string)

DropPendingBotOutput drops the bot's queued output, so a later turn cannot match it.

A queued user_transcription stays: a DTMF keypress reports its transcription just before the turn starts, and that is the turn's input, not stale bot output. The events seen and the latest event times are left as they are. why says what prompted the drop, for the trace.

func (*EventStream) Elapsed added in v0.7.0

func (s *EventStream) Elapsed() float64

Elapsed is the seconds since the stream began, the clock the events' "at" is on, to the millisecond.

func (*EventStream) EventsSeen added in v0.7.0

func (s *EventStream) EventsSeen() []map[string]any

EventsSeen is every event in arrival order, for the result's diagnostics.

func (*EventStream) HarnessError added in v0.7.0

func (s *EventStream) HarnessError() (string, bool)

HarnessError is the harness's first pipeline error, and whether there was one (see HarnessFailed).

func (*EventStream) HarnessFailed added in v0.7.0

func (s *EventStream) HarnessFailed(err string)

HarnessFailed notes that a service in the harness's own pipeline failed; the first error is kept.

func (*EventStream) InputSent added in v0.7.0

func (s *EventStream) InputSent()

InputSent marks the user's input as sent: the bot's reply is what it says from now on.

func (*EventStream) InputSentAt added in v0.7.0

func (s *EventStream) InputSentAt() time.Time

InputSentAt is when the user's latest input was sent; the bot's speech from before it is not the reply.

func (*EventStream) LastActivity added in v0.7.0

func (s *EventStream) LastActivity() time.Time

LastActivity is when either side last did anything: an event, or a frame that only buffers toward one.

func (*EventStream) LatestEventTime added in v0.7.0

func (s *EventStream) LatestEventTime(eventType string) (time.Time, bool)

LatestEventTime is when an event of eventType last arrived, and whether one has at all.

func (*EventStream) Metrics added in v0.7.0

func (s *EventStream) Metrics() []map[string]any

Metrics is every metrics event the bot sent, in arrival order.

func (*EventStream) NextAny added in v0.7.0

func (s *EventStream) NextAny(ctx context.Context, deadline time.Time) (map[string]any, error)

NextAny pops the next queued event, whatever its type, waiting for one until deadline. It returns ErrTimeout when none arrives in time.

func (*EventStream) NextEvent added in v0.7.0

func (s *EventStream) NextEvent(
	ctx context.Context, eventType string, deadline time.Time, since int, accept func(map[string]any) bool,
) (map[string]any, error)

NextEvent is the next unclaimed event of eventType that accept takes, looking from since.

The turn's log is searched first, from since on (FromNow looks only at what arrives from now on), then the queue is popped until such an event arrives. Events popped on the way stay in the log, unclaimed: a scenario need not list every event the bot emits, and an expectation that looks back from an earlier point can still claim them. accept, when not nil, is a further check on an event of the type, such as a call's name; one it turns down is left for another expectation.

It returns ErrTimeout when none arrives before deadline, ErrBotEnded when the bot ended the call and none is left to arrive (the harness's transcription of what the bot said last, in audio mode, is waited for first, since it can land after the bot is gone), and a *HarnessError when the harness's own pipeline failed.

func (*EventStream) ObservingBoundary added in v0.7.0

func (s *EventStream) ObservingBoundary()

ObservingBoundary starts a turn that sends nothing: what the bot says next belongs to it.

What the bot says until it starts speaking again, however late its transcription lands, is the previous turn's and is discarded. What it says from then on is the turn's, even when its LLM did not produce it.

func (*EventStream) RTVIMessageToEvent added in v1.0.0

func (s *EventStream) RTVIMessageToEvent(message []byte) map[string]any

RTVIMessageToEvent translates one of the bot's RTVI messages, as the client received it, into the event it maps to, or nil; many map to none.

The LLM text is buffered and emitted as one llm_response when the response ends; a marker is its own llm_marker as soon as it arrives; tts_response is emitted only in audio mode; the bot's reports, about its own speaking and interruptions and about the harness (its VAD and transcription messages), become their events. The audio-mode response is not made here: the turn aggregator appends it when the bot's spoken turn ends.

func (*EventStream) TalkedOverUntil added in v0.7.0

func (s *EventStream) TalkedOverUntil() (until time.Time, ok bool)

TalkedOverUntil is when the bot started speaking again after the latest turn began. The bot's speech that began before then belongs to the turn before: what it was saying when a send talked over it, or the reply an observing turn waited out. It is far in the future until the bot starts speaking again, and ok is false when the latest send did not talk over it.

func (*EventStream) Touch added in v0.7.0

func (s *EventStream) Touch()

Touch notes activity that makes no event, so a lull is measured from it.

func (*EventStream) TurnBoundary added in v0.7.0

func (s *EventStream) TurnBoundary()

TurnBoundary starts a new turn: only what the bot says from now on belongs to it.

When the bot is speaking at this point, the turn talks over it, and what the bot says until it starts speaking again, however late its transcription lands, is the previous turn's and is discarded.

func (*EventStream) TurnPosition added in v0.7.0

func (s *EventStream) TurnPosition() int

TurnPosition is how many events the turn has popped so far: where an expectation beginning now looks from.

func (*EventStream) UnclaimedSince added in v0.7.0

func (s *EventStream) UnclaimedSince(since int) []map[string]any

UnclaimedSince is the events popped from position since on that no expectation has claimed.

func (*EventStream) WaitBotQuiet added in v0.7.0

func (s *EventStream) WaitBotQuiet(ctx context.Context, timeout time.Duration) bool

WaitBotQuiet waits up to timeout for the bot to stop speaking, and reports whether it is quiet.

func (*EventStream) WaitBotTranscribed added in v0.7.0

func (s *EventStream) WaitBotTranscribed(ctx context.Context, timeout time.Duration) bool

WaitBotTranscribed waits up to timeout for everything the bot has said to be transcribed and closed into a turn, and reports whether it was.

func (*EventStream) WaitBotTurnClosed added in v1.0.0

func (s *EventStream) WaitBotTurnClosed(ctx context.Context, timeout time.Duration) bool

WaitBotTurnClosed waits up to timeout for no turn of the bot's to be open, and reports whether none was.

The bot-turn aggregator reports a turn's start and stop on a goroutine of its own, after it has handed the turn on, so whatever answers the turn can be ready before the stop is in the stream. A caller about to record an answer waits here first, so the bot's turn always comes before the answer to it.

type Expectation

type Expectation struct {
	// Event is the friendly event name to match (see the Event constants).
	Event string
	// WithinMS is the latency budget, measured from the turn's user send: all
	// of a turn's expectations share that one anchor, so a stalled turn fails
	// within a single budget rather than one per expectation. Zero uses the
	// harness default.
	WithinMS int
	// TextContains, when set, requires the event's text to contain this
	// substring, whatever the spacing.
	TextContains string
	// TextExcludes is the mirror of TextContains: the event's text must not hold
	// this substring. With TextContains or Eval, which accumulate a reply, it is
	// checked on the reply accumulated up to the match.
	TextExcludes string
	// TextMatches are regular expressions the event's text must each match,
	// checked on the same text as TextExcludes.
	TextMatches Patterns
	// Calls is the set of calls expected in the turn, for a function call
	// event. They are matched by name in any order and the expectation passes
	// only when all of them are found. Built from calls:, or from the single
	// name:/args: shorthand; nil for any other event.
	Calls []FunctionCall
	// Eval, when set, is a natural-language criterion an LLM judge checks the
	// event's text against. Meaningful on the bot-generated text events
	// (response, llm_response, tts_response, and the expression its TTS
	// performed) and on function_call, where it is about each matched call's
	// name and arguments rather than text.
	Eval string
	// Marker, on an llm_marker, is the meaning the marker must have: one of
	// MarkerKinds, where incomplete accepts short or long.
	Marker string
	// MarkerFirst, on an llm_marker, is whether the first marker in the
	// response's raw text must come before any text.
	MarkerFirst *bool
	// Markers, on an llm_marker, is how many markers the response's raw text
	// must hold.
	Markers *int
	// TextAfter, on an llm_marker, is whether text must (true) or must not
	// (false) follow the first marker in the raw text.
	TextAfter *bool
	// Metric, on a metrics event, is the kind of metric the report must hold,
	// as the bot names it: ttfb, processing, tokens, and so on. Empty takes any
	// kind.
	Metric string
	// Processor, on a metrics event, is text the name of the processor that
	// measured the metric must contain. Empty takes any processor.
	Processor string
	// CheckFrom is where the expectation checks for its event from: previous
	// (the default, also when empty), where the expectation above it was met;
	// or turn_start, the beginning of the turn, at events the expectations
	// above it did not use.
	CheckFrom string
	// AllowContinue, with Eval, is whether the judge may answer continue and
	// have the harness wait for more of the reply; nil leaves it to the judge's
	// own setting. False forces the judge to consider the reply as final, the
	// thing to be judged, rather than skipping it.
	AllowContinue *bool
	// Absent inverts the expectation: it passes only when no event of this type
	// arrives before the WithinMS budget expires, and fails as soon as one does.
	// It matches on event type only, so no content, call, marker or metric check may
	// accompany it.
	Absent bool
}

Expectation is a single expected event in a scenario turn.

func (*Expectation) Aggregates added in v0.7.0

func (e *Expectation) Aggregates() bool

Aggregates reports whether the check accumulates text across events rather than matching one. A reply with a content check accumulates the bot's segments, and an expression check the expression performed in the turn; a user_transcription with TextContains accumulates an STT's pieces.

type ExpectationMatcher added in v0.7.0

type ExpectationMatcher struct {

	// LastMatchText is the text content of the most recently matched event
	// (the bot's response, or a user transcript), surfaced to verbose progress.
	// Empty for events with no text (llm_started, speaking events).
	LastMatchText string
	// contains filtered or unexported fields
}

ExpectationMatcher matches one expectation at a time against the event stream.

Expected events must appear in order, with unmatched events allowed in between. A reply with a content check aggregates its segments and re-checks on each, so an interim "Let me check" is rolled past rather than taken for the answer. A turn's function calls match by name in any order.

func NewExpectationMatcher added in v0.7.0

func NewExpectationMatcher(stream *EventStream, judge Judge, trace *Trace) *ExpectationMatcher

NewExpectationMatcher builds a matcher over stream. judge answers eval: assertions, or is nil when the scenario has none.

func (*ExpectationMatcher) Match added in v0.7.0

func (m *ExpectationMatcher) Match(
	ctx context.Context, exp *Expectation, anchor time.Time, budgetMS, turnIdx, expIdx int,
) (*AssertionFailure, error)

Match waits for the expected event and verifies it. Its budget is budgetMS measured from anchor; turnIdx and expIdx are where the failure is recorded.

Stale bot output is not filtered here: the stream drops it on an interruption and the driver before each send.

It returns the failure, or nil when the expectation is satisfied. The error is ErrTimeout when no matching event arrives at all (so the caller can report that none arrived; a response that arrives but never satisfies the content check is a failure instead), ErrBotEnded when the bot ends the call before the expectation is met (an absent: expectation is met instead, since the event can no longer arrive), a *HarnessError, or ctx's error.

func (*ExpectationMatcher) ResetTurn added in v0.7.0

func (m *ExpectationMatcher) ResetTurn()

ResetTurn forgets the previous turn's events.

type ExpectationResult added in v0.3.0

type ExpectationResult struct {
	// ExpectationIndex is the index of the expectation within the turn, from 0.
	ExpectationIndex int
	// EventName is the expectation's event name.
	EventName string
	// Passed reports whether the expectation was satisfied.
	Passed bool
	// Matched is what it matched, in short, when it passed: the marker of an
	// llm_marker, a function call's signature, the text of a reply or a
	// transcript. It is empty for an event carrying no text, and on a failure,
	// whose reason is in the turn's failures.
	Matched string
}

ExpectationResult is what one expectation of a turn resolved to, pass or fail.

type ExplainerConfig added in v0.7.0

type ExplainerConfig struct {
	// Disabled is set by `explainer: false`.
	Disabled bool
	// LLM is the explainer's LLM block; nil when none was given.
	LLM *LLMServiceConfig
}

ExplainerConfig is a `judge.eval.explainer:` value: an LLM block, or false for no explainer. Absent, the judging LLM explains, or the default LLM when a factory built the classifier.

func (*ExplainerConfig) UnmarshalYAML added in v0.7.0

func (c *ExplainerConfig) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML reads false or an LLM block.

type Factory added in v0.7.0

type Factory func(config map[string]any) (any, error)

Factory builds a service from the config block that names it. It is given the whole block as written, and returns the service: a classifier or an LLM, a TTS, or an STT, by the block it is named in.

type FunctionCall

type FunctionCall struct {
	// Name is the tool name to match. An empty name matches any call, which is
	// what a bare function_call expectation asserts.
	Name string
	// Args, when set, is a subset check on the call's arguments: every listed
	// key must be present with the listed value, and any further argument the
	// model passed is ignored.
	Args map[string]any
}

FunctionCall is one expected tool call within a function call expectation.

func (FunctionCall) Signature added in v0.7.0

func (c FunctionCall) Signature() string

Signature is a short label for the call: name(arg=value, ...).

type HarnessError added in v0.7.0

type HarnessError struct {
	// Reason is the pipeline's error.
	Reason string
}

HarnessError is a wait abandoned because a service in the harness's own pipeline failed, so what the bot does next is no evidence.

func (*HarnessError) Error added in v0.7.0

func (e *HarnessError) Error() string

type Judge

type Judge interface {
	// AddUserMessage records a user turn in the conversation.
	AddUserMessage(text string)
	// AddAssistantMessage appends a segment of the bot's current reply.
	AddAssistantMessage(text string)
	// Evaluate judges the conversation so far against criterion. allowContinue
	// is whether this reply may be judged VerdictContinue; nil leaves it to the
	// judge's own setting. A judge that cannot answer reports VerdictNone with
	// the reason, rather than failing: an unavailable judge leaves the
	// assertion undecided, not the run broken.
	Evaluate(ctx context.Context, criterion string, allowContinue *bool) JudgeVerdict
	// EvaluateCall judges a tool call the bot made against criterion, by the
	// call's name and arguments, with the conversation so far as context. It is
	// how a scenario checks what an argument subset cannot match verbatim.
	//
	// A call is not a partial reply, so there is nothing to wait for and the
	// verdict is yes or no; a judge answering VerdictContinue is read as a no.
	EvaluateCall(ctx context.Context, name string, args map[string]any, criterion string) JudgeVerdict
}

Judge decides whether the bot's most recent reply satisfies a natural-language criterion, which is what a scenario's `judge:` assertion asks. It is fed the conversation as the scenario plays: the harness records each user turn and each segment of the bot's reply, and Evaluate judges the most recent reply in that context. That is what lets a terse or ambiguous reply be resolved, one that would not make sense on its own.

A judge is per-scenario, because the conversation it holds is. The harness treats it as optional, so a scenario with no `judge:` assertion needs none. A judge that also has a Close(context.Context) error method is closed when the run ends, however it ends.

type JudgeConfig added in v0.7.0

type JudgeConfig struct {
	// Modality is "text" (the default) or "audio".
	Modality string `yaml:"modality,omitempty"`
	// Transcription is the STT that transcribes the bot's audio, required in
	// audio modality.
	Transcription *TranscriptionConfig `yaml:"transcription,omitempty"`
	// Eval is the judge that decides the verdicts; nil uses the default.
	Eval *JudgeEvalConfig `yaml:"eval,omitempty"`
}

JudgeConfig is a scenario's `judge:` block: how the bot's reply is judged, from its LLM text or from a transcription of its speech, and by which judge.

type JudgeEvalConfig added in v0.7.0

type JudgeEvalConfig struct {
	// LLMServiceConfig names the LLM that classifies, or the factory that
	// builds the classifier. Its Raw is the whole `judge.eval:` block.
	LLMServiceConfig `yaml:",inline"`
	// Explainer is the LLM that gives the reasons.
	Explainer ExplainerConfig `yaml:"explainer,omitempty"`
	// ExplainBelow is the confidence under which a yes is explained too; nil
	// uses 0.75.
	ExplainBelow *float64 `yaml:"explain_below,omitempty"`
	// AllowContinue is whether a reply may be judged continue; nil allows it.
	AllowContinue *bool `yaml:"allow_continue,omitempty"`
}

JudgeEvalConfig is a scenario's `judge.eval:` block: the classifier that decides the verdicts, the LLM that explains them, and how.

judge:
  eval:
    service: ollama          # the LLM that classifies (the default), or
    model: gemma4:12b        #   factory: a registered factory that takes
                             #   this block and returns a classifier
    explainer:               # optional; the LLM that gives reasons
      service: ollama        #   (the judging LLM if omitted, the default
      model: gemma4:12b      #   LLM for a factory's classifier; none if
                             #   set to false)
    explain_below: 0.75      # optional
    allow_continue: true     # optional; false judges a reply yes or no only

func DefaultJudgeEvalConfig added in v0.7.0

func DefaultJudgeEvalConfig() JudgeEvalConfig

DefaultJudgeEvalConfig is the judge a scenario uses when its judge.eval: block is omitted: the default local Ollama model.

func (*JudgeEvalConfig) UnmarshalYAML added in v0.7.0

func (c *JudgeEvalConfig) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML reads the block and keeps it as written in Raw.

type JudgeVerdict

type JudgeVerdict struct {
	// Verdict is VerdictYes, VerdictNo, VerdictContinue, or VerdictNone when
	// the judge's question failed and nothing was decided.
	Verdict string
	// Reason is the explainer's one-sentence reason for the verdict, or the
	// classifier's probabilities when nothing explained it.
	Reason string
	// RawResponse is the judge's raw answer, for diagnostics.
	RawResponse string
	// Confidence is how sure the judge is of the verdict, from 0 to 1; nil when
	// it did not say.
	Confidence *float64
	// Probabilities is the probability of each outcome the classifier was
	// offered; empty when the question failed.
	Probabilities map[string]float64
}

JudgeVerdict is the outcome of a single judge call.

func (JudgeVerdict) Passed

func (v JudgeVerdict) Passed() bool

Passed reports whether the verdict is a definite yes.

type JudgedScenario added in v0.7.0

type JudgedScenario interface {
	LoadedScenario
	// contains filtered or unexported methods
}

JudgedScenario is what a conversation is judged against: a *SimulationScenario or a *Rubric.

type Kind added in v0.7.0

type Kind string

Kind is the kind of scenario, as a run, a session and a results record name it.

const (
	// KindScript is a scripted scenario.
	KindScript Kind = "script"
	// KindSimulation is a simulation.
	KindSimulation Kind = "simulation"
)

The kinds of scenario that run.

type LLMServiceConfig added in v0.7.0

type LLMServiceConfig struct {
	// Factory is the name a factory was registered under (see RegisterFactory);
	// it is given the whole block and returns the service.
	Factory string `yaml:"factory,omitempty"`
	// Service is the built-in provider, "ollama" by default.
	Service string `yaml:"service,omitempty"`
	// Model is the model; empty uses the provider's default.
	Model string `yaml:"model,omitempty"`
	// Endpoint is the provider's base URL; empty uses its default.
	Endpoint string `yaml:"endpoint,omitempty"`
	// Extra is forwarded to the model as top-level request parameters. Nil,
	// with no Model either, gives the default model the extras it needs; an
	// empty map sends none.
	Extra map[string]any `yaml:"extra,omitempty"`
	// Raw is the block as written, every key included, which is what a factory
	// is given. Filled when the block is read from YAML; for a block built in
	// code, the fields above are used.
	Raw map[string]any `yaml:"-"`
}

LLMServiceConfig is a block naming an LLM: the judge's (inside `judge.eval:`), its explainer's, or a simulation's.

A Factory builds the service; otherwise Service names a built-in provider, "ollama" by default.

func (*LLMServiceConfig) UnmarshalYAML added in v0.7.0

func (c *LLMServiceConfig) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML reads the block and keeps it as written in Raw.

type LoadedScenario added in v0.7.0

type LoadedScenario interface {
	// ScenarioName is the scenario's name, `<file name>/<scenario name>` for
	// one in a file's scenarios: list.
	ScenarioName() string
	// contains filtered or unexported methods
}

LoadedScenario is one scenario a file holds, of whichever kind: *ScriptScenario, *SimulationScenario or *Rubric.

type Manifest

type Manifest struct {
	// Runs are the (bot, scenario) and (bot, simulation) runs to execute.
	Runs []*SuiteRun
	// Spawn is the spawn command template ({bot} and {port} substituted).
	Spawn string
	// Concurrency is how many runs execute at once.
	Concurrency int
	// Repeat is how many times to run each (bot, scenario) pair. Attempts run
	// attempt-major rather than grouped per bot, so every bot meets the same
	// machine conditions in the same stretch of the sweep and a transient
	// slowdown shows up as a band across all of them instead of a regression in
	// whichever bot happened to be running.
	Repeat int
	// BasePort is the first port to assign; each run gets BasePort + index, so
	// the reserved range widens with Repeat (bots x scenarios x repeat ports
	// from BasePort up).
	BasePort int
	// RunsDir is the base for run output (a <name>/ subdir is added), or "".
	RunsDir string
	// Record is whether to record conversation audio.
	Record bool
	// CacheDir is the directory for cached synthesized user audio, or "".
	CacheDir string
}

Manifest is a parsed eval-suite manifest.

func LoadManifest

func LoadManifest(path string, overrides ManifestOverrides) (*Manifest, error)

LoadManifest parses a manifest YAML into a Manifest.

A set override wins over the manifest's value, so the command line wins. Manifest paths resolve against the manifest's directory, overrides against the working directory.

type ManifestOverrides added in v0.7.0

type ManifestOverrides struct {
	// BotsDir is the directory bot paths are relative to.
	BotsDir string
	// ScenariosDir is the directory bare scenario names resolve under.
	ScenariosDir string
	// RunsDir is the base for run output.
	RunsDir string
	// Spawn is the spawn command template.
	Spawn string
	// Concurrency is how many runs execute at once.
	Concurrency *int
	// Repeat is how many times each (bot, scenario) pair runs. Set here or in
	// the manifest, it also replaces each simulation's own runs, a repeat of
	// one included.
	Repeat *int
	// BasePort is the first port assigned.
	BasePort *int
	// Record is whether to record conversation audio.
	Record *bool
	// CacheDir is the synthesized-audio cache directory.
	CacheDir string
}

ManifestOverrides are the values the command line sets over a manifest's own. A zero field (an empty string, a nil pointer) leaves the manifest's value; paths resolve against the working directory rather than the manifest's.

type Options

type Options struct {
	// Judge grades `eval:` assertions. Nil builds one from the scenario's
	// judge: block when it has any. It holds the conversation it grades
	// against, so give each scenario its own rather than reusing one across
	// scenarios.
	Judge Judge
	// UserTTS speaks the user's turns. When set, each user turn is synthesized
	// with this TTS service's synthesizer and streamed to the bot as audio (so
	// the bot's real VAD, turn detection and STT run), instead of the text-mode
	// send-text. Nil builds one from the scenario's user: block's speech, if
	// any. A local or HTTP service works, e.g. a Kokoro or an OpenAI TTS; a
	// WebSocket-streaming one does not.
	UserTTS TTSService
	// BotSTT transcribes the bot's audio for a scenario asserting response in
	// audio mode. Nil builds one from the scenario's judge: block's
	// transcription.
	BotSTT SegmentedSTT
	// OnProgress, when set, is called as each turn and expectation resolves, in
	// order, for a caller reporting a long run as it happens rather than at the
	// end (see EventProgress). Keep it quick: the records queue behind it.
	OnProgress func(ScriptTurnProgress)
	// Params is how the run behaves: its timeouts, its cache, its audio
	// support check.
	Params SessionParams
	// BotReadyTimeout is how long the bot has, once connected, to answer the
	// RTVI handshake with bot-ready, which covers the bot's startup; zero uses
	// Params. A bot that closes the connection first fails the run at once.
	BotReadyTimeout time.Duration
	// ConnectTimeout is how long the bot has to accept connections at all
	// before the run fails to connect; zero uses Params.
	ConnectTimeout time.Duration
}

Options configures a scenario run: the services a ScriptSession is given, and its SessionParams.

type Patterns added in v0.3.0

type Patterns []string

Patterns are regular expressions an event's text must each match. The patterns are RE2, as Go's regexp reads them, so a lookaround or a backreference is rejected when the scenario is loaded.

type Persona added in v0.7.0

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

Persona is the simulated caller: its instruction, its LLM, and the context it runs on. It is safe for concurrent use.

func NewPersona added in v0.7.0

func NewPersona(description, goal string, service PersonaLLM) *Persona

NewPersona builds the persona: description is who the caller is, as free text, goal what the caller wants from the call, and service the LLM that plays the caller, run inside the eval pipeline.

func (*Persona) Context added in v0.7.0

func (p *Persona) Context() *frames.LLMContext

Context is the context the persona runs on, with the end_call tool; empty until the call starts.

func (*Persona) HangUp added in v0.7.0

func (p *Persona) HangUp()

HangUp ends the persona's part of the call: it answers nothing more.

func (*Persona) Hear added in v0.7.0

func (p *Persona) Hear(event map[string]any) *frames.LLMContextFrame

Hear takes in one of the bot's events, and returns the frame that has the persona answer once the bot's turn is done, or nil.

A response the bot gives while one of its function calls is still running is held and joined with the response after the call, so the persona answers the bot's whole turn rather than its "let me check". In audio mode the aggregator does this instead.

func (*Persona) HungUp added in v0.7.0

func (p *Persona) HungUp() bool

HungUp reports whether the persona has ended its part of the call.

func (*Persona) Instruction added in v0.7.0

func (p *Persona) Instruction() string

Instruction is the system instruction the persona LLM runs under.

func (*Persona) LLM added in v0.7.0

func (p *Persona) LLM() PersonaLLM

LLM is the LLM service that plays the caller, a processor in the eval pipeline.

func (*Persona) OnEndCall added in v0.7.0

func (p *Persona) OnEndCall(handler llm.FunctionCallHandler)

OnEndCall registers what happens when the persona calls end_call: handler is run with the call's params, whose success and reason arguments are the persona's own claim.

type PersonaLLM added in v0.7.0

type PersonaLLM interface {
	processor.Processor
	RegisterFunction(name string, h llm.FunctionCallHandler, opts ...llm.RegisterOption)
}

PersonaLLM is the LLM service that plays the caller: a processor in the eval pipeline, on which the end_call tool is registered. Every jargo LLM service built on llm.Base is one.

func PersonaLLMFromConfig added in v0.7.0

func PersonaLLMFromConfig(cfg *LLMServiceConfig) (PersonaLLM, error)

PersonaLLMFromConfig builds the persona LLM a simulator: block names: an LLM service the eval pipeline runs.

A factory builds it; otherwise the block names an LLM, as LLMServiceFromConfig reads it, Ollama by default. It fails when the block names an unknown service, or its factory is not registered or builds something a pipeline cannot run as an LLM service.

type Rubric added in v0.7.0

type Rubric struct {
	// Name is the rubric's name.
	Name string
	// Success is what counts as the bot having done its job, judged over the
	// whole conversation.
	Success string
	// Metrics are the criteria every reply is judged on.
	Metrics []SimulationMetric
	// Judge is the judge.eval: block, as a simulation's.
	Judge JudgeEvalConfig
}

Rubric is what a conversation is judged on, without the caller a simulation plays. It judges a conversation the harness didn't drive, such as a production call. In a scenario file, an entry with a success: and neither persona: nor turns: is a rubric. Its metrics are judged ones: a measured metric needs a live run.

func NewRubric added in v0.7.0

func NewRubric(name, success string, metrics []SimulationMetric) (*Rubric, error)

NewRubric builds a rubric over the default judge, refusing a measured metric.

func RubricFromMap added in v0.7.0

func RubricFromMap(data map[string]any, source string) (*Rubric, error)

RubricFromMap builds a rubric from a mapping with a rubric entry's keys: name, success, and the optional metrics and judge block, each as a scenario file writes it; other keys are ignored. source is where the mapping came from, for error messages; empty is "rubric".

func (*Rubric) ScenarioName added in v0.7.0

func (r *Rubric) ScenarioName() string

ScenarioName is the rubric's name.

type RunJudge added in v0.7.0

type RunJudge interface {
	// AddUserMessage records a user turn in the conversation.
	AddUserMessage(text string)
	// AddAssistantMessage appends a segment of the bot's current reply.
	AddAssistantMessage(text string)
	// AddToolCall records a tool call the bot made, on one line.
	AddToolCall(text string)
	// EvaluateRun judges the whole conversation: the goal, and every bot turn
	// on every criterion.
	EvaluateRun(ctx context.Context, criteria []Criterion, success string) RunVerdicts
}

RunJudge is the judge a whole conversation is put to: told the conversation, it decides the goal and every bot turn on every criterion. ClassifierJudge is one. A run judge that also has a Close(context.Context) error method is closed by whoever built it.

type RunVerdicts added in v0.7.0

type RunVerdicts struct {
	// Goal is the verdict on the goal, over the whole conversation.
	Goal JudgeVerdict
	// Turns is, per criterion name, a verdict per bot turn, in order.
	Turns map[string][]JudgeVerdict
}

RunVerdicts is a whole simulation run's verdicts.

type STTServiceBuilder added in v0.7.0

type STTServiceBuilder func(cfg *TranscriptionConfig) (SegmentedSTT, error)

STTServiceBuilder builds the STT a built-in `judge.transcription.service:` name stands for.

type ScenarioError added in v0.7.0

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

ScenarioError is a scenario file that is malformed, or a scenario in it that is invalid for its kind. Its message names the file and, where there is one, the turn and expectation at fault, both counted from 0.

func (*ScenarioError) Error added in v0.7.0

func (e *ScenarioError) Error() string

Error returns the message.

type ScenarioFile added in v0.3.0

type ScenarioFile struct {
	// Name is the file's own `name:`.
	Name string
	// Path is the file it was read from.
	Path string
	// Scenarios are the scenarios it holds, in file order.
	Scenarios []LoadedScenario
}

ScenarioFile is a scenario file: what it is called, where it is, and the scenarios it holds.

Manifests and the command line load files through LoadFile, so every kind of scenario mixes in one list.

func LoadFile added in v0.3.0

func LoadFile(path string) (*ScenarioFile, error)

LoadFile reads a scenario file, parsing each scenario as whichever kind it is.

A file in the deprecated shape, a scenario's own keys at the top level and no scenarios:, loads as that one scenario under the file's name: and warns.

The error is a *ScenarioError when the file is malformed, or a scenario is of no kind, claims to be two, or is invalid for its kind.

func (*ScenarioFile) Scenario added in v0.7.0

func (f *ScenarioFile) Scenario(name string) (LoadedScenario, error)

Scenario is the scenario called name, or a *ScenarioError naming the ones the file holds.

type ScenarioSession added in v0.7.0

type ScenarioSession interface {
	// Trace is the run's trace.
	Trace() *Trace
	// contains filtered or unexported methods
}

ScenarioSession is a session of either kind, as SessionFromScenario builds it: a *ScriptSession or a *SimulationSession. Switch on its type to run it.

func SessionFromScenario added in v0.7.0

func SessionFromScenario(
	scenario LoadedScenario, botURL string, params SessionParams, services SessionServices,
) (ScenarioSession, error)

SessionFromScenario builds a ready-to-run session for a scenario of either kind: a *ScriptSession for a *ScriptScenario, a *SimulationSession for a *SimulationScenario, each constructing the services it needs that services does not give. Then run it:

url := "ws://localhost:7860/ws"
session, err := eval.SessionFromScenario(scenario, url, eval.SessionParams{}, eval.SessionServices{})
if err != nil { … }
switch s := session.(type) {
case *eval.ScriptSession:
	result, err := s.Run(ctx)
	…
case *eval.SimulationSession:
	result, err := s.Run(ctx)
	…
}

It fails when a persona LLM is given for a scripted scenario, which has no persona, when a simulation's judge cannot judge a whole run, when scenario is neither kind (a rubric has nothing to run), or when a service the scenario names cannot be built.

type ScriptDriver added in v0.7.0

type ScriptDriver struct {

	// Turns is one record per turn, filled in as the driver runs. They start as
	// not run and stay that way on every path that ends the run early, so the
	// result always says which turns were actually scored.
	Turns []ScriptTurnResult
	// contains filtered or unexported fields
}

ScriptDriver plays a scenario's turns in order and matches each turn's expectations.

A failed turn ends the scenario by default, since the conversation is in an unknown state from there on; stop_on_failure: false drives every turn regardless.

type ScriptResult added in v0.7.0

type ScriptResult struct {
	// ScenarioName is the name of the scenario that was run.
	ScenarioName string
	// Failures are the assertions that failed, in order. It is the turns'
	// failures flattened, plus any that belong to no turn, such as a run that
	// never connected.
	Failures []AssertionFailure
	// Turns is one record per scenario turn, in order: what a per-turn pass
	// rate is computed from, without needing the scenario file for a
	// denominator.
	Turns []ScriptTurnResult
	// DurationMS is the wall-clock time the run took, in milliseconds.
	DurationMS int
	// EventsSeen is every event observed, for diagnostics, whether or not the
	// scenario asserted on it: what a failure is read against.
	EventsSeen []map[string]any
	// DebugLog is a timestamped trace of the harness's own decisions (events
	// received, audio transcribed, matcher progress), for diagnosing a flaky
	// run.
	DebugLog []string
	// Skipped, when set, means the scenario was not run, and says why. Such a
	// result is neither passed nor failed.
	Skipped string
	// BotMetrics is every metrics report the bot sent during the run, in
	// order. Empty for a bot that runs without metrics.
	BotMetrics []BotMetricsReport
}

ScriptResult is the outcome of running a scripted scenario.

func Host

func Host(ctx context.Context, scenario *ScriptScenario, buildBot Bot, opts Options) (ScriptResult, error)

Host stands up buildBot on an in-process loopback WebSocket and plays scenario against it, returning the result. Run wraps this for the go-test path; callers that want the Result directly (custom reporting, benchmarks) can use it.

What goes wrong with the run itself, a bot that never becomes ready or a harness that fails mid-run, is a failure in the Result, and the error is what RunURL returns.

func RunURL

func RunURL(ctx context.Context, scenario *ScriptScenario, botURL string, opts Options) (ScriptResult, error)

RunURL plays scenario against a bot already listening at botURL (a ws:// or wss:// RTVI endpoint). It backs the command-line runner.

A bot that never accepts the connection, refuses it, or never becomes ready is a failure of the Result (a <connect> or <bot-ready> one), and so is the harness failing mid-run (an <error> or <harness> one), with every turn not reached left TurnNotRun. The error is ctx ending, or a service the scenario names that cannot be built.

func (ScriptResult) Passed added in v0.7.0

func (r ScriptResult) Passed() bool

Passed reports whether every assertion passed and the scenario was run.

func (ScriptResult) String added in v0.7.0

func (r ScriptResult) String() string

String renders a human-readable summary of the run.

type ScriptScenario added in v0.7.0

type ScriptScenario struct {
	// Name identifies the scenario in reports.
	Name string
	// Turns are played in order.
	Turns []ScriptTurn
	// Context is the conversation the bot's context should start from: LLM
	// messages in the universal shape, each a role and its content, such as
	// {"role": "system", "content": "Be terse."}. When set, the harness sends
	// them once the bot is ready, replacing whatever context the bot built for
	// itself. Leave it out to test the bot's own opening state.
	Context []map[string]any
	// Configured is the scenario's user: and judge: blocks.
	Configured
	// StopOnFailure is whether the first failed turn ends the scenario; nil is
	// true. A failed turn leaves the conversation in an unknown state, so the
	// remaining turns usually just burn a budget each. Set it false for a
	// scenario whose turns are scored independently; give those turns an
	// explicit within_ms, since with the 60s default a silent bot costs one full
	// budget per turn.
	StopOnFailure *bool
	// SourcePath is the file the scenario was loaded from.
	SourcePath string
}

ScriptScenario is a scripted scenario: a conversation and the events it should produce.

func (*ScriptScenario) NeedsBotImages added in v0.7.0

func (s *ScriptScenario) NeedsBotImages() bool

NeedsBotImages reports whether the scenario asserts on the images the bot outputs, which it reports only on request.

func (*ScriptScenario) NeedsMarkerEvents added in v0.7.0

func (s *ScriptScenario) NeedsMarkerEvents() bool

NeedsMarkerEvents reports whether the scenario asserts on the model's markers, which the bot emits only on request.

func (*ScriptScenario) NeedsVADEvents added in v0.7.0

func (s *ScriptScenario) NeedsVADEvents() bool

NeedsVADEvents reports whether the scenario uses the raw VAD speaking events, which the bot emits only on request.

func (*ScriptScenario) RequiredReportLevel added in v0.7.0

func (s *ScriptScenario) RequiredReportLevel() rtvi.FunctionCallReportLevel

RequiredReportLevel is the function-call report level the scenario's assertions need: full for arguments, name for names, or "" when they need nothing beyond the default. A call with an eval: needs full too, since the judge is asked about the call's arguments.

func (*ScriptScenario) ScenarioName added in v0.7.0

func (s *ScriptScenario) ScenarioName() string

ScenarioName is the scenario's name.

func (*ScriptScenario) WantsResponse added in v0.7.0

func (s *ScriptScenario) WantsResponse() bool

WantsResponse reports whether any expectation asserts on the transcription of the bot's audio.

type ScriptSession added in v0.7.0

type ScriptSession struct {
	*Session[ScriptResult]
	// contains filtered or unexported fields
}

ScriptSession runs one ScriptScenario against a bot.

Build one with ScriptSessionFromScenario, which constructs the judge, the user TTS and the bot STT the scenario needs, then call Run:

url := "ws://localhost:7860/ws"
session, err := eval.ScriptSessionFromScenario(scenario, url, eval.SessionParams{}, nil, nil, nil)
if err != nil { … }
result, err := session.Run(ctx)

Per-turn outcomes are in result.Turns, for a scenario scored a turn at a time.

func NewScriptSession added in v0.7.0

func NewScriptSession(
	scenario *ScriptScenario, botURL string, params SessionParams, judge Judge,
	userTTS *CachingTTSService, botSTT SegmentedSTT,
) (*ScriptSession, error)

NewScriptSession builds the session of scenario against the bot at botURL.

The services come pre-built, or nil where the scenario has no use for them; ScriptSessionFromScenario constructs the ones a scenario needs. judge answers eval: assertions, or is nil when the scenario has none; userTTS speaks the user's turns, or is nil for text turns; botSTT transcribes the bot's audio for the response event, or is nil when the scenario has none.

func ScriptSessionFromScenario added in v0.7.0

func ScriptSessionFromScenario(
	scenario *ScriptScenario, botURL string, params SessionParams, judge Judge,
	userTTS *CachingTTSService, botSTT SegmentedSTT,
) (*ScriptSession, error)

ScriptSessionFromScenario builds a ready-to-run session from scenario, constructing the services it needs. Pass judge, userTTS or botSTT to use your own: otherwise the judge is built from the scenario's judge: block when it has eval: assertions, the user TTS from its user: block's speech in audio mode, and the bot STT from its judge: block's transcription when it asserts response in audio mode.

It fails when a service the scenario's blocks name cannot be built, a transcription factory returning anything but a SegmentedSTT included.

func (*ScriptSession) Driver added in v0.7.0

func (s *ScriptSession) Driver() *ScriptDriver

Driver is the session's script driver, whose turn records fill in as it runs.

type ScriptTurn added in v0.7.0

type ScriptTurn struct {
	// User is the text the harness sends as the user's turn: an RTVI send-text
	// in text modality, or synthesized speech in audio modality. Empty for a
	// turn that only waits and asserts.
	User string
	// Expect are the expected events, in the order they should arrive.
	// Optional: a turn may just send input, with the assertion on a later turn.
	Expect []Expectation
	// Parts are the turn's text and pauses, in order, when it pauses; User then
	// holds the text alone. Requires user.modality: audio, and the pauses can
	// total at most MaxTurnPauseMS.
	Parts []TurnPart
	// Audio is the path of an audio file, resolved against the scenario file,
	// played as this turn instead of synthesizing User. User is required
	// alongside it and is what the recording says: the judge reads it as the
	// turn's input and text_contains matches against it. Requires
	// user.modality: audio, and is mutually exclusive with DTMF.
	Audio string
	// DTMF is a keypad sequence the user presses, one frame per key. Quote it
	// in YAML: an unquoted # starts a comment.
	DTMF string
	// SendAfter, when set, schedules when the turn's input is sent rather than
	// sending it once the bot has finished speaking.
	SendAfter *SendAfter
	// Image is the path of an image, resolved against the scenario file,
	// registered for this turn: when the bot requests a user image during the
	// turn, it is served this one. It stays registered until a later turn
	// provides a different image.
	Image string
}

ScriptTurn is one turn in a scripted scenario.

A turn drives the bot one of three ways: the harness sends a user utterance (the person speaks), it sends a dtmf keypress sequence (the person presses keys), or it is observation-only (neither, which is what a bot-first scenario needs to check an opening greeting). User and DTMF are mutually exclusive.

type ScriptTurnProgress added in v0.7.0

type ScriptTurnProgress struct {
	// TurnIndex is the turn being run, from 0.
	TurnIndex int
	// ExpectationIndex is the index of the expectation, from 0, or -1 for a
	// turn-level record (the turn header, or a send_after that never fired).
	ExpectationIndex int
	// EventName is the expectation's event, or the turn's input for a turn
	// header.
	EventName string
	// Status is StatusTurn, StatusMatched, StatusFailed or StatusTimeout.
	Status string
	// Detail is optional extra text: the failure reason, the user utterance.
	Detail string
}

ScriptTurnProgress is a progress record emitted while a turn runs, for a caller reporting progress live.

type ScriptTurnResult added in v0.7.0

type ScriptTurnResult struct {
	// TurnIndex is the index of the turn in the scenario, from 0.
	TurnIndex int
	// Status is one of TurnStatuses. TurnNotRun means the run ended before
	// reaching this turn (see ScriptScenario.StopOnFailure).
	Status string
	// Failures are the turn's failed assertions, in order; empty unless Status
	// is TurnFailed.
	Failures []AssertionFailure
	// Expectations are what each expectation resolved to, in order, up to the
	// one that timed out; what a passed run matched is only recorded here.
	Expectations []ExpectationResult
	// DurationMS is the wall-clock time the turn took, in milliseconds; 0 when
	// the turn was not run.
	DurationMS int
}

ScriptTurnResult is the outcome of one turn within a scenario run.

A turn's expectations share one deadline and stop at the first to time out, so the turn is the unit a run is scored by.

type SegmentedSTT added in v1.0.0

type SegmentedSTT interface {
	processor.Processor
	RunSTT() stt.RunSTTFunc
	SetRunSTT(run stt.RunSTTFunc)
}

SegmentedSTT is a speech-to-text service that transcribes whole speech segments, which is what the harness transcribes the bot's audio with: it wraps the run to record when each segment's audio began. Every segmented provider service satisfies it, as does a *stt.SegmentService.

func STTServiceFromConfig added in v0.7.0

func STTServiceFromConfig(cfg *TranscriptionConfig) (SegmentedSTT, error)

STTServiceFromConfig builds the STT that transcribes the bot's audio, from a `judge.transcription:` block.

A factory builds it; otherwise the service name picks one, "moonshine" by default. A factory must return a SegmentedSTT, as the built-in ones do. A nil cfg uses the Moonshine default.

type SendAfter

type SendAfter struct {
	// Event is the event to schedule from, or empty for a pure delay.
	Event string
	// DelayMS is how long to wait after the event was seen, or, with no event,
	// after the previous turn's send.
	DelayMS int
}

SendAfter schedules when a turn's input (user or dtmf) is sent. The harness waits for Event to have been seen, either earlier in the run or arriving now, then waits DelayMS longer before sending. That is how a barge-in is written: `send_after: {event: llm_started, delay_ms: 500}` interrupts 500ms after the bot started responding.

Event is optional. On its own, DelayMS is a pure time delay measured from the previous turn's send, with no event to anchor on.

type Session added in v0.7.0

type Session[R any] struct {
	event.Registry
	// contains filtered or unexported fields
}

Session is one conversation with a bot, driven to a result R.

Connect, run the handshake, let the driver converse, tear down, and turn what happened, a failed connect or a harness error included, into the driver's result. ScriptSession and SimulationSession build the client and the driver for their kind of scenario; SessionFromScenario builds whichever kind a scenario is. It raises EventProgress.

func (*Session[R]) Run added in v0.7.0

func (s *Session[R]) Run(ctx context.Context) (R, error)

Run connects, drives the conversation, and returns the result.

What goes wrong with the run itself is a failure of the result rather than an error: a bot that never accepts the connection is a <connect> failure, one that never becomes ready a <bot-ready> failure, and a harness that fails mid-run an <error> or <harness> one, scored against the turn it interrupted. Only ctx ending is returned as an error.

func (*Session[R]) Trace added in v0.7.0

func (s *Session[R]) Trace() *Trace

Trace is the run's trace.

type SessionParams added in v0.7.0

type SessionParams struct {
	// ConnectTimeout is how long to wait for the bot to accept the connection
	// before giving up; zero uses DefaultConnectTimeout.
	ConnectTimeout time.Duration
	// BotReadyTimeout is how long to wait, once connected, for the bot to
	// answer the RTVI handshake with bot-ready; zero uses
	// DefaultBotReadyTimeout.
	BotReadyTimeout time.Duration
	// DefaultTimeoutMS is, for scripted scenarios, the latency budget of
	// expectations without their own within_ms (a turn's expectations share one
	// deadline anchored at the send); zero uses DefaultEventTimeoutMS.
	DefaultTimeoutMS int
	// RecordPath is where to save the conversation audio, or "". Only an audio
	// run records.
	RecordPath string
	// CacheDir is the directory for cached synthesized user audio, or "" for
	// the default (see DefaultCacheDir).
	CacheDir string
	// UseCache, when false, ignores cached user audio and forces fresh
	// synthesis, with no cache reads or writes; nil is true.
	UseCache *bool
	// AudioSupportCheck is whether an audio run checks that the bot's transport
	// carries the audio it uses, as the bot reports in bot-ready. With
	// AudioSupportCheckWhenAdvertised, a bot that reports a direction the run
	// uses as off is refused before the conversation (failure kind
	// audio_unsupported); a bot that reports nothing runs unchecked. "" is
	// AudioSupportCheckOff.
	AudioSupportCheck string
}

SessionParams is how a run behaves, whichever kind of scenario it is: timeouts, recording, caching, teardown.

It is plain configuration, so one value serves many runs; the services a run uses are passed to the session separately. The zero value uses the defaults.

type SessionServices added in v0.7.0

type SessionServices struct {
	// PersonaLLM plays a simulation's caller; it applies to simulations only.
	PersonaLLM PersonaLLM
	// Judge decides the scenario's eval: assertions, or a simulation's goal and
	// criteria, which takes a judge that is also a RunJudge (ClassifierJudge is
	// both).
	Judge Judge
	// UserTTS speaks the user's turns in audio mode.
	UserTTS *CachingTTSService
	// BotSTT transcribes the bot's audio when the run transcribes it.
	BotSTT SegmentedSTT
}

SessionServices are the services a session can be given rather than build from its scenario. A nil field is built from the scenario when the run needs it.

type SimulationDriver added in v0.7.0

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

SimulationDriver lets the persona LLM hold the conversation, then judges the whole of it.

The persona answers the bot on its own inside the client's pipeline. The driver reports each line as progress and watches for the end: the persona's end_call, the bot hanging up, the turn cap, the time cap, a lull neither side breaks, or a failure of the harness's own pipeline. Then one judge call over the whole transcript scores every bot turn on every criterion and decides the goal.

func (*SimulationDriver) Conversation added in v0.7.0

func (d *SimulationDriver) Conversation() []map[string]any

Conversation is the conversation with the persona as user and the bot as assistant, without the tool calls.

func (*SimulationDriver) Timeline added in v0.7.0

func (d *SimulationDriver) Timeline() []map[string]any

Timeline is the conversation as the events told it, each line with the tool calls made by then (under "evidence").

A bot turn is everything the bot said between two persona turns, however turn detection or a function call split it; a turn in which the bot said nothing is not a turn.

func (*SimulationDriver) ToolCalls added in v0.7.0

func (d *SimulationDriver) ToolCalls() []string

ToolCalls are the bot's function calls in order, one line each; a canceled call is listed as canceled.

type SimulationJudge added in v0.7.0

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

SimulationJudge judges conversations against a simulation or a rubric.

Each conversation is judged by a judge built from the simulation's judge: block, closed once the conversation is judged. A judge passed in is used instead and left open for its owner to close; it keeps the conversation it is told, so it judges one conversation.

file, _ := eval.LoadFile("book_table.yaml")
scenario, _ := file.Scenario("book_table/available")
var messages []map[string]any
data, _ := os.ReadFile("run.conversation.json")
_ = json.Unmarshal(data, &messages)
judgement, err := eval.NewSimulationJudge(scenario.(eval.JudgedScenario), nil, nil, nil).Judge(ctx, messages)

A production call, recorded by ConversationObserver, is judged against a rubric the same way, with the observer's conversation as the messages.

func NewSimulationJudge added in v0.7.0

func NewSimulationJudge(
	simulation JudgedScenario, judge RunJudge, explainBelow *float64, trace *Trace,
) *SimulationJudge

NewSimulationJudge builds the judge of simulation, a *SimulationScenario or a *Rubric.

judge is the judge to ask, which should not have seen any conversation yet; nil builds one for each conversation. explainBelow is, for the judges it builds, the confidence under which a yes is explained too (above 1, every verdict is); nil keeps the simulation's judge: block. trace is the run's trace, to log each verdict in, or nil.

func (*SimulationJudge) Judge added in v0.7.0

func (j *SimulationJudge) Judge(ctx context.Context, messages []map[string]any) (SimulationJudgement, error)

Judge judges a conversation, its messages as a conversation file holds them (see Conversation), and gives the verdict on the goal and the criterion metrics' outcomes.

It fails only when the judge it builds cannot be built.

type SimulationJudgement added in v0.7.0

type SimulationJudgement struct {
	// Goal is the verdict on the success: yes, no, or none when the judge gave
	// none.
	Goal JudgeVerdict
	// Metrics are the criterion metrics' outcomes, in the simulation's order.
	Metrics []SimulationMetricScore
}

SimulationJudgement is what the judge decided about one conversation.

type SimulationMetric added in v0.7.0

type SimulationMetric struct {
	// Name is the metric's name in the results.
	Name string
	// Criterion is what the judge decides on each bot turn; empty for a
	// measured metric.
	Criterion string
	// MinScore is the share of the bot's turns the judge must answer yes for,
	// in 0..1, below which a judged metric fails the run; nil reports the score
	// without gating.
	MinScore *float64
	// Measure is one of SimulationMeasures; empty for a judged metric.
	Measure string
	// MinValue is the measured value's lower bound, inclusive, or nil.
	MinValue *float64
	// MaxValue is the measured value's upper bound, inclusive, or nil.
	MaxValue *float64
	// Calls, for function_calls, is the calls the bot should make: each a name,
	// or a name with Args as a subset of the call's arguments; an empty, non-nil
	// list means none. Nil for every other metric.
	Calls []FunctionCall
}

SimulationMetric is a quality metric: a judged criterion, or a measure with a range or a call list.

type SimulationMetricScore added in v0.7.0

type SimulationMetricScore struct {
	// Name is the metric's name, from the simulation file.
	Name string
	// Score is the share of the bot's turns the judge answered yes for, in
	// 0..1; nil when there was no turn to judge.
	Score *float64
	// Passed reports whether the metric let the run pass: its score reached its
	// MinScore, or it has none.
	Passed bool
	// Reason is what the score rests on: the turns that fell short and why, or
	// that every turn passed.
	Reason string
	// MinScore is the score the metric needed, or nil when it only reports.
	MinScore *float64
	// Verdicts are the judge's verdict on each bot turn, in order; empty for a
	// measured metric.
	Verdicts []SimulationTurnVerdict
	// Value is what a measured metric measured, in its unit; nil for a judged
	// one, or when there was nothing to measure.
	Value *float64
	// FailureKind is how the metric failed, for grouping across runs: judge_no
	// when the judge rejected a turn, judge_no_verdict when it only left turns
	// unanswered, out_of_range for a measure outside its bounds,
	// function_calls for a call list that did not match, error when a required
	// measurement was unavailable; empty when it passed.
	FailureKind string
	// Criterion is the criterion each bot turn was judged on, as the
	// simulation worded it; empty for a measured metric.
	Criterion string
}

SimulationMetricScore is one quality metric's outcome for a simulation run.

type SimulationProgress added in v0.7.0

type SimulationProgress struct {
	// Status is "bot" for a response the bot finished, "user" for a turn the
	// persona spoke, or "ended" once the conversation is over.
	Status string
	// Text is what was said; for "ended", how the conversation ended (one of
	// SimulationEndings).
	Text string
	// Turn is the persona's turn count so far.
	Turn int
}

SimulationProgress is a progress record emitted while a simulation runs.

type SimulationResult added in v0.7.0

type SimulationResult struct {
	// SimulationName is the name of the simulation that was run.
	SimulationName string
	// Succeeded reports whether the judge decided the goal was achieved.
	Succeeded bool
	// Reason is the judge's justification for Succeeded, or the error.
	Reason string
	// Error, when set, means the run did not complete (a failed connect, a
	// harness error); Succeeded is then false and the run is neither a goal
	// success nor a goal failure.
	Error string
	// FailureKind is what kind of failure Error is, one of FailureKinds;
	// empty when no failure ended the run.
	FailureKind string
	// Metrics are the quality metrics' outcomes.
	Metrics []SimulationMetricScore
	// Messages is the conversation, with the persona's turns as user messages
	// and the bot's as assistant; the assistant messages are the bot turns the
	// metrics scored.
	Messages []map[string]any
	// Conversation is the conversation as a conversation file holds it: the
	// messages with the bot's function calls in place.
	Conversation []map[string]any
	// Turns is how many turns the persona took.
	Turns int
	// EndedBy is how the run ended, one of SimulationEndings.
	EndedBy string
	// EndCall is the persona's own end_call claim (success, reason) when it
	// made one; advisory, the judge decides Succeeded.
	EndCall map[string]any
	// DurationMS is the wall-clock time the run took, in milliseconds.
	DurationMS int
	// EventsSeen is every event observed, for diagnostics.
	EventsSeen []map[string]any
	// DebugLog is a timestamped trace of the harness's own decisions.
	DebugLog []string
	// Confidence is how sure the judge is of its goal verdict, from 0 to 1; nil
	// when it gave none.
	Confidence *float64
	// Probabilities is the probability of each answer to the goal question;
	// empty when the judge gave none.
	Probabilities map[string]float64
	// Success is the goal the conversation was judged on, the simulation's
	// success as it was worded.
	Success string
	// BotMetrics is every metrics report the bot sent during the run, in
	// order. These are the bot's own measurements, not the quality Metrics the
	// run was scored on.
	BotMetrics []BotMetricsReport
}

SimulationResult is the outcome of one run of a simulation.

func (*SimulationResult) Failure added in v0.7.0

func (r *SimulationResult) Failure() string

Failure is why the run did not pass, or "" when it did: the error, the goal, or the first failed metric.

func (*SimulationResult) Passed added in v0.7.0

func (r *SimulationResult) Passed() bool

Passed reports whether the run completed, achieved its goal, and no metric fell short.

type SimulationScenario added in v0.7.0

type SimulationScenario struct {
	// Name is the simulation's name.
	Name string
	// Persona is who the caller is, as free text for the persona LLM.
	Persona string
	// Goal is what the caller wants from the call.
	Goal string
	// Success is what counts as the bot having done its job, for the judge.
	Success string
	// Simulator is the persona LLM, the same shape as judge.eval:; its zero
	// value is the default local model.
	Simulator LLMServiceConfig
	// Metrics are the quality metrics.
	Metrics []SimulationMetric
	// Configured is the simulation's user: and judge: blocks.
	Configured
	// MaxTurns caps the persona's turns.
	MaxTurns int
	// MaxDurationS caps the run's wall clock, in seconds.
	MaxDurationS float64
	// MaxSilenceS caps a lull with no event from either side, in seconds.
	MaxSilenceS float64
	// Runs is how many times the suite runs the simulation; every run must
	// pass.
	Runs int
	// SourcePath is the file the simulation was loaded from.
	SourcePath string
}

SimulationScenario is a simulated scenario: a caller rather than a script. A persona LLM holds the conversation with the bot on its own, and a judge reads the whole conversation.

func (*SimulationScenario) ScenarioName added in v0.7.0

func (s *SimulationScenario) ScenarioName() string

ScenarioName is the simulation's name.

type SimulationSession added in v0.7.0

type SimulationSession struct {
	*Session[*SimulationResult]
	// contains filtered or unexported fields
}

SimulationSession runs one SimulationScenario against a bot.

The persona LLM answers the bot on its own inside the client's pipeline, and the judge decides the goal and the criteria at the end. Build one with SimulationSessionFromScenario, which constructs the persona LLM, the judge, and in audio mode the user TTS and the STT, then call Run:

file, _ := eval.LoadFile("scenarios/simulated/curious_caller.yaml")
for _, loaded := range file.Scenarios {
	scenario, ok := loaded.(*eval.SimulationScenario)
	if !ok {
		continue
	}
	session, err := eval.SimulationSessionFromScenario(scenario, "ws://localhost:7860/ws",
		eval.SessionParams{}, nil, nil, nil, nil)
	if err != nil { … }
	result, err := session.Run(ctx)
	…
}

func NewSimulationSession added in v0.7.0

func NewSimulationSession(
	scenario *SimulationScenario, botURL string, params SessionParams, personaLLM PersonaLLM,
	judge RunJudge, userTTS *CachingTTSService, botSTT SegmentedSTT,
) (*SimulationSession, error)

NewSimulationSession builds the session of scenario against the bot at botURL.

personaLLM is the persona LLM service, run inside the eval pipeline; it is required. judge decides the goal and the quality criteria, or is nil (the run then reports no verdict). userTTS speaks the persona's replies, or is nil for text mode; botSTT transcribes the bot's audio, or is nil in text mode.

func SimulationSessionFromScenario added in v0.7.0

func SimulationSessionFromScenario(
	scenario *SimulationScenario, botURL string, params SessionParams, personaLLM PersonaLLM,
	judge RunJudge, userTTS *CachingTTSService, botSTT SegmentedSTT,
) (*SimulationSession, error)

SimulationSessionFromScenario builds a ready-to-run session from scenario, constructing the services it needs. Pass personaLLM, judge, userTTS or botSTT to use your own: otherwise the persona LLM is built from the simulation's simulator: block, the judge from its judge: block, the user TTS from its user: block's speech in audio mode, and the bot STT from its judge: block's transcription in audio mode.

It fails when a service the simulation's blocks name cannot be built.

func (*SimulationSession) Driver added in v0.7.0

func (s *SimulationSession) Driver() *SimulationDriver

Driver is the session's simulation driver.

type SimulationTurnVerdict added in v0.7.0

type SimulationTurnVerdict struct {
	// Turn is the bot turn, from 1, counting the turns in which the bot said
	// something; it indexes the assistant messages of the run's conversation.
	Turn int
	// Passed reports whether the turn satisfied the criterion.
	Passed bool
	// Reason is the explainer's one-sentence reason for the verdict, or the
	// classifier's probabilities when nothing explained it.
	Reason string
	// Verdict is the judge's answer: yes, no, or none when it gave no verdict
	// on the turn, which counts as a no.
	Verdict string
	// Confidence is how sure the judge is of the verdict, from 0 to 1; nil when
	// it gave none.
	Confidence *float64
	// Probabilities is the probability of each outcome the classifier was
	// offered; empty when it gave no verdict.
	Probabilities map[string]float64
}

SimulationTurnVerdict is the judge's verdict on one bot turn, for a per-turn metric.

type SpeechConfig added in v0.7.0

type SpeechConfig struct {
	// Factory is the name a factory was registered under (see RegisterFactory);
	// it is given the whole block and returns the TTS.
	Factory string `yaml:"factory,omitempty"`
	// Service names a built-in TTS: "kokoro", or the deprecated "cartesia".
	Service string `yaml:"service,omitempty"`
	// Voice is the voice to speak in.
	Voice string `yaml:"voice,omitempty"`
	// Model is the TTS model; empty uses the service's default.
	Model string `yaml:"model,omitempty"`
	// Language is a language code such as "zh"; absent or blank keeps the
	// service's own default. It is read as written, so a value that is not a
	// string (YAML reads a bare `no` as false) is reported rather than passed
	// on.
	Language any `yaml:"language,omitempty"`
	// Speed is the speech rate multiplier; nil keeps the service's default.
	Speed *float64 `yaml:"speed,omitempty"`
	// SampleRate is the rate the user's audio is streamed at; zero uses 16 kHz.
	SampleRate int `yaml:"sample_rate,omitempty"`
	// APIKey is the deprecated Cartesia service's key; it falls back to
	// CARTESIA_API_KEY.
	APIKey string `yaml:"api_key,omitempty"`
	// Raw is the block as written, every key included, which is what a factory
	// is given. Filled when the block is read from YAML.
	Raw map[string]any `yaml:"-"`
}

SpeechConfig is a scenario's `user.speech:` block: the TTS the user's turns are spoken with.

func (*SpeechConfig) UnmarshalYAML added in v0.7.0

func (c *SpeechConfig) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML reads the block and keeps it as written in Raw.

type Suite added in v0.7.0

type Suite struct {
	event.Registry

	// Manifest is the parsed manifest.
	Manifest *Manifest
	// Runs is the suite's working set: the manifest's runs, narrowed by
	// Filter, executed by Run.
	Runs []*SuiteRun
	// contains filtered or unexported fields
}

Suite runs the (bot, scenario) runs of a Manifest, building and spawning each bot.

Each bot serves the harness on its own port and is driven by the harness, several at a time up to the manifest's Concurrency. The runs are updated in place as they go, and EventUpdate reports each change, so a live display can follow their progress.

manifest, err := eval.LoadManifest("manifest.yaml", eval.ManifestOverrides{})
suite := eval.NewSuite(manifest)
suite.Filter("voice", "", "")
event.On(&suite.Registry, eval.EventUpdate, func(_ context.Context, run *eval.SuiteRun) {
	fmt.Println(run.Scenario, run.Status)
})
err = suite.Run(ctx, "logs", eval.SuiteRunOptions{})

func NewSuite added in v0.7.0

func NewSuite(manifest *Manifest) *Suite

NewSuite is the suite of a parsed manifest; its runs become the suite's working set.

func (*Suite) Filter added in v0.7.0

func (s *Suite) Filter(pattern, scenario string, kind Kind) []*SuiteRun

Filter keeps only the runs matching a bot substring, a scenario name, and a kind, each when given.

pattern keeps only runs whose label or bot path contains it. scenario keeps only runs of this scenario: its full <file>/<scenario> name, or either half of it, so a file's name selects every scenario it holds. kind keeps only runs of this kind. It returns the matching runs, in their original order.

func (*Suite) Run added in v0.7.0

func (s *Suite) Run(ctx context.Context, logsDir string, opts SuiteRunOptions) error

Run runs all of the suite's runs, in place, with the manifest's concurrency.

It first builds each distinct bot once, into opts.BinDir. Each run gets its own port (BasePort + index). Concurrency workers each take the next run and run it until none is left. Runs are taken in manifest order, every entry's first attempt before any entry's second, so an entry's scenarios finish together and no worker waits while any entry still has runs. An entry with a Concurrency of its own never has more than that many runs in flight, across its attempts; a worker that finds it full takes the next entry's run.

While it runs, the default logger writes nothing, so the caller's display stays clean; a run's logs go to its debug log under opts.Debug. The default logger is restored when Run returns. A run's failure is in the run; the error is only a directory that could not be made.

type SuiteRun added in v0.7.0

type SuiteRun struct {
	// Bot is the manifest's `bot:` path, or the bot URL when the run connects
	// to a bot already running.
	Bot string
	// Name is the manifest entry's `name:`, or "" when it has none; Label is
	// what the display, the filters and the results use.
	Name string
	// Scenario is the display name: the scenario or simulation, without .yaml.
	Scenario string
	// ScenarioPath is the scenario or simulation file.
	ScenarioPath string
	// Loaded is the scenario, when the run was built from a loaded file; Load
	// returns it, or reads the file when it is nil.
	Loaded LoadedScenario
	// BotPath is the bot to build and spawn: a Go main package directory.
	// Empty when connecting to BotURL.
	BotPath string
	// BotURL is where to connect instead of spawning, or "".
	BotURL string
	// RunnerBodyPath is the optional --runner-body file for the bot's runner
	// args.
	RunnerBodyPath string
	// RunnerBody is the bot's runner-args body given inline, written to a file
	// for the bot when it is spawned; nil when there is none or it comes from
	// RunnerBodyPath.
	RunnerBody map[string]any
	// Concurrency is how many runs of this run's entry may be in flight at
	// once, when its manifest entry says; zero is as many as the suite runs.
	Concurrency int
	// Entry is the position of the run's entry in the manifest's suite: list.
	// The suite takes runs in entry order and applies each entry's Concurrency
	// to that entry's runs only.
	Entry int
	// Kind is KindScript, played by a ScriptSession, or KindSimulation; ""
	// is KindScript.
	Kind Kind
	// Attempts is how many times this (bot, scenario) pair runs: the
	// manifest's repeat, or a simulation's own runs; zero is one. Above one,
	// each attempt's artifacts carry its number.
	Attempts int
	// Sweep is whether the attempts come from a repeat (a measurement: the
	// suite reports a rate and a failure is data) rather than from a
	// simulation's runs (a requirement: every attempt must pass).
	Sweep bool
	// Attempt is the 1-based attempt number when the suite repeats; zero is
	// one.
	Attempt int
	// Status is RunPending (or ""), RunRunning or RunDone.
	Status string
	// Stopping is true while the bot is being stopped after the run is done.
	// The run still counts as in flight, so the next one waits.
	Stopping bool
	// ScriptResult is a scripted run's outcome, once the run is done.
	ScriptResult *ScriptResult
	// SimulationResult is a simulation run's outcome, once the run is done.
	SimulationResult *SimulationResult
	// Error is the build, spawn or connection error message, if the run failed
	// before producing a result.
	Error string
	// StartedAt is when the run started, for a live elapsed counter; zero
	// before it starts.
	StartedAt time.Time
	// DurationMS is the wall-clock time the run took, in milliseconds; nil
	// before it is done.
	DurationMS *int
}

SuiteRun is the mutable per-(bot, scenario) state, updated in place so a live display can read it.

func (*SuiteRun) Label added in v0.7.0

func (r *SuiteRun) Label() string

Label is the run's label: the entry's Name, or its Bot when it has none.

func (*SuiteRun) Load added in v0.7.0

func (r *SuiteRun) Load() (LoadedScenario, error)

Load is the run's scenario: as loaded when the run was built, else read from its file.

It fails when the file is missing or invalid, holds no scenario of this name, or the scenario is a rubric, which has nothing to run.

func (*SuiteRun) RunKind added in v0.7.0

func (r *SuiteRun) RunKind() Kind

RunKind is the run's kind, KindScript when Kind is unset.

func (*SuiteRun) Stem added in v0.7.0

func (r *SuiteRun) Stem() string

Stem is the scenario name as a file name stem: a group entry's / becomes __.

type SuiteRunOptions added in v0.7.0

type SuiteRunOptions struct {
	// RecordDir is the directory for per-run conversation recordings, or "".
	RecordDir string
	// ResultsPath is the JSONL file to append one record per finished run to,
	// or "" to write none. Each line is written as its run completes, so an
	// interrupted sweep keeps everything already finished.
	ResultsPath string
	// Debug saves each run's combined <run>.debug.log.
	Debug bool
	// Params is how each run behaves. The suite sets what it owns on each
	// run's copy: the connect timeout, the recording, and the manifest's cache
	// directory.
	Params SessionParams
	// BinDir is where the suite builds its bots; "" is a bin/ folder beside
	// the logs directory.
	BinDir string
}

SuiteRunOptions is how one Suite.Run call runs the suite's runs.

type TTSService added in v1.0.0

type TTSService interface {
	processor.Processor
	Synthesizer() tts.Synthesizer
}

TTSService is a text-to-speech service the harness can speak the user's turns with: the cache around it drives the synthesizer behind it directly. Every provider's TTS service satisfies it, as does a *tts.Base.

type TTSServiceBuilder added in v0.7.0

type TTSServiceBuilder func(cfg *SpeechConfig) (TTSService, error)

TTSServiceBuilder builds the TTS a built-in `user.speech.service:` name stands for. It should synthesize at CacheSampleRate, the rate the cache stores, so its audio is cached as it came.

type Trace added in v0.7.0

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

Trace is a timestamped, turn-tagged log of the harness's own decisions, kept as a result's DebugLog.

The tag is the turn the harness is processing (`[--]` before the first). An event that lands while a turn waits on send_after is tagged with that turn even though it is the previous turn's output; the send: lines mark the boundary. A Trace is safe for concurrent use.

func NewTrace added in v0.7.0

func NewTrace() *Trace

NewTrace returns an empty trace, outside any turn; Start anchors its clock.

func (*Trace) Lines added in v0.7.0

func (t *Trace) Lines() []string

Lines are the lines logged so far.

func (*Trace) Log added in v0.7.0

func (t *Trace) Log(msg string)

Log appends one line, stamped with the seconds since Start and the turn.

func (*Trace) SetTurn added in v0.7.0

func (t *Trace) SetTurn(turn int)

SetTurn sets the turn being processed, from 0, or -1 outside any turn.

func (*Trace) Start added in v0.7.0

func (t *Trace) Start()

Start anchors the trace's timestamps at now, the start of the run.

func (*Trace) Turn added in v0.7.0

func (t *Trace) Turn() int

Turn is the turn being processed, or -1 outside any turn.

type TranscriptionConfig added in v0.7.0

type TranscriptionConfig struct {
	// Factory is the name a factory was registered under (see RegisterFactory);
	// it is given the whole block and returns the STT.
	Factory string `yaml:"factory,omitempty"`
	// Service names a built-in STT: "moonshine" (the default) or "whisper".
	Service string `yaml:"service,omitempty"`
	// Model is the STT model; empty uses the service's default.
	Model string `yaml:"model,omitempty"`
	// Language is a language code such as "es"; absent or blank keeps the
	// service's own default. Read as written, as SpeechConfig.Language is.
	Language any `yaml:"language,omitempty"`
	// Device is where Whisper runs: "cpu" (the default) or "cuda".
	Device string `yaml:"device,omitempty"`
	// ComputeType is Whisper's compute type; empty uses int8 on the CPU.
	ComputeType string `yaml:"compute_type,omitempty"`
	// Raw is the block as written, every key included, which is what a factory
	// is given. Filled when the block is read from YAML.
	Raw map[string]any `yaml:"-"`
}

TranscriptionConfig is a scenario's `judge.transcription:` block: the STT that transcribes the bot's audio.

func (*TranscriptionConfig) UnmarshalYAML added in v0.7.0

func (c *TranscriptionConfig) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML reads the block and keeps it as written in Raw.

type TurnPart added in v0.7.0

type TurnPart struct {
	// Text is the text to speak, or empty for a pause.
	Text string
	// PauseMS is the pause in milliseconds, or zero for text.
	PauseMS int
}

TurnPart is one item of a turn that pauses: text to speak, or a pause.

type UserConfig added in v0.7.0

type UserConfig struct {
	// Modality is "text" (the default) or "audio".
	Modality string `yaml:"modality,omitempty"`
	// Speech is the TTS the user's turns are spoken with, in audio modality.
	Speech *SpeechConfig `yaml:"speech,omitempty"`
}

UserConfig is a scenario's `user:` block: how the user's turns reach the bot, as text or as speech a TTS synthesizes.

Jump to

Keyboard shortcuts

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