Embedded DSLs

Native AI evals

An eval declares cases and the result you expect from them. Run it with vary eval, which selects the suites, applies a named binding and finite limits, and writes a report. vary test checks deterministic behaviour; vary mutate checks whether those tests catch defects. Eval bodies run only under vary eval.

The compiler checks the eval syntax and types. The bundled ai library supplies EvalCase, AiContext, and the adapters. The small example below runs entirely from a checked-in fixture.

Declare a suite

A declarative suite has cases, run, score, and require clauses in that order. Cases have typed inputs, expected values, and unique stable IDs. The operation receives one input and a managed AiContext; a pure scorer checks its output against the expected value.

from ai.evals import EvalCase
from ai.context import AiContext
from ai.types import AiError

let samples: List[EvalCase[Str, Str]] = [
    EvalCase("same", "alpha", "alpha"),
    EvalCase("different", "beta", "gamma")
]

pure def copy(message: Str, _context: AiContext) -> Result[Str, AiError] {
    return Ok(message)
}

pure def exact(output: Str, expected: Str) -> Bool {
    return output == expected
}

eval "copy quality" {
    cases samples
    run copy
    score exact
    require { pass_rate >= 50% error_rate == 0% }
}

The first case passes and the second fails, giving a pass rate of 1/2. The 50% gate accepts that result. A false score counts as a measured failure, not an execution error. If you add named scorers for separate properties, the runner still calls the operation only once per case and repetition.

The document refinement example (examples/ai-refine) scores identifier retention and length separately. Its gates name each property, such as identifier.pass_rate. The runner does not combine them into one quality score.

Use a custom body when needed

The custom form runs its body once per repetition. Each observe checks a Boolean value. A trial with no observations is invalid.

from ai.evals import eval_context
from ai.capabilities import GenerationInput

eval "generation reply" {
    run {
        let reply = eval_context().generate(
            GenerationInput("Reply with one word.", "hello")
        ).unwrap()
        observe reply == "world"
    }
    require { pass_rate == 100% error_rate == 0% }
}

Call eval_context() inside a custom body to get its managed context. Declarative operations receive the context as an argument. Put reusable scoring rules in pure functions and test them normally.

Choose a profile and mode

Put a named profile in the project's vary.toml:

[eval]
default_profile = "fixture"

[eval.profiles.fixture]
adapter = "chat_completions"
protocol_version = "1"
endpoint = "https://example.test/v1"
model = "fixture-model"
fixture_script = "fixture.json"
max_attempts = 4
deadline_ms = 10000

Fixture mode is the default. Its versioned script lists expected requests in order, with each HTTPS URL, exact request-body hash, response status, and response body. Missing or mismatched steps fail the run; so do unused required steps. A passing fixture says nothing about live provider compatibility or model quality.

Live mode requires --live, an explicit profile with credential_env, and a populated environment variable. An unset credential or invalid profile is a setup error; the runner does not silently switch to fixtures. The profile binds a protocol adapter, endpoint, and configured model. For a workflow that needs both TypeSafe judgment and Chat Completions generation, use the typesafe_chat_completions adapter with generation_endpoint and generation_model as well as the judgment endpoint and model. Both bindings share the run-wide budget.

Run the example

From the repository root, with the checked-in fixture:

vary eval examples/ai-eval-smoke --fixture --json
vary eval examples/ai-eval-smoke --only 'quality::generation reply'

The first command runs both suite forms. One copy case scores false, but its suite accepts because the pass rate meets the 50% gate. An ordinary test in the project checks that vary test leaves eval bodies dormant, even with a key-present recording transport. --repeat N repeats each case; fixture scripts must include the corresponding ordered request steps for every repeated dispatch.

For an explicitly configured live run, bound the total dispatches and time:

vary eval my-project --profile production --live \
  --max-attempts 20 --deadline-ms 30000 --report-file eval-report.json

Attempt and time limits cover every suite, repeated case, helper, and retry in the run. If the budget runs out, remaining trials are marked not run and the command fails. There is currently no random-seed CLI option.

Read the result

Human output and versioned JSON include selected suites, mode, configured binding, nonsecret fingerprint, source/scorer/case hashes when known, trial counts, attempt counts, observations, independent score dimensions, and gate numerators and denominators. Returned model and token usage appear only when an adapter supplies them. Credentials and raw prompts or completions are omitted by default.

All started trials, including operation-error trials, count in rate denominators. Gates compare exact ratios before display rounding. A scorer error, fixture integrity error, or incomplete run cannot be made acceptable with a lenient gate. A case hash covers representable loaded case values; arbitrary file I/O does not automatically yield byte-for-byte dataset provenance.

ExitMeaning
0Every selected suite completed and met its declared gates.
1A gate failed, execution or scoring invalidated the run, or the run was incomplete.
2Selection, profile, compilation, or case loading failed before evaluation.

The three domain examples are examples/ai-triage, examples/ai-refine, and examples/ai-review. Their offline results prove the harness and application wiring against scripted responses. Read Semantic AI control flow for the language constructs used inside those applications.

← Semantic AI control flow