Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ def reply(query: str) -> str:


class ChatRunner(OfflineRunner):
def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]:
def run_case(self, case: Case, *, seed_results: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]:
return {"response": reply(case.input["query"])}


class Greets(Judge):
name = "greets_judge"

def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None:
response = case.output.get("response", "")
def judge(self, case: Case, *, seed_results: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None:
response = case.run_results.get("response", "")
if "hello" in response:
return Score(name=self.name, score=1.0)

Expand Down
30 changes: 16 additions & 14 deletions core/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ eac writes requests to the process's **fd 3** and reads responses from its **fd

**Ready line.**

The first line a process writes to fd 4 is its ready line, which says which protocol version it speaks. After that, every response carries the `id` of the request it answers.
The first line a process writes to fd 4 is its ready line, which says which protocol version it speaks. After that, every line is the response to the request eac just sent, carrying that request's `id`. eac stops with an error on any other line.

```jsonc
{"protocol": 1} // ready line
Expand Down Expand Up @@ -70,14 +70,14 @@ These types show up in the params and results of many methods:
```jsonc
// Case: an offline case, or a production run collected for online judging
{"name": "get_dsn", "input": {}, "expected_output": {},
"output": {}, "conversation_id": "abc", // what the system produced: set by online.execute, and by eac when judging
"run_results": {}, "conversation_id": "abc", // what the system produced: set by online.execute, and by eac when judging
"splits": ["smoke"], "enabled": true, // disabled cases run only when picked by name or split
"seeds": [Seed], "judges": ["regex"]} // judge names are for display; judges run in the worker

// Seed: key is a content hash, and seeds with the same key are set up once
{"name": "project", "key": "4d950d98...",
"cache": true, // false: torn down after each run (e.g. the agent mutates it)
"credentials": [Credential]} // optional: what setting it up and tearing it down need, children's included
"credentials": [Credential]} // optional: what setting it up and tearing it down need

// Credential: a token, CLI login and so on that something needs. The SDK
// rebuilds it from path and fields, and the same path and fields are the
Expand All @@ -96,7 +96,8 @@ These types show up in the params and results of many methods:

// Score: 0..1; null is a diagnostic that doesn't gate pass/fail
{"name": "regex", "score": 1.0, "explanation": null, "metadata": {},
"llm_judge_metrics": Metrics} // optional: what an LLM judge spent on this score
"llm_judge_metrics": Metrics, // optional: what an LLM judge spent on this score
"error": "TimeoutError: ..."} // optional: why the judge raised instead of scoring, which errors the case

// Metrics: every field optional, default 0
{"input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "cache_read_tokens": 0,
Expand Down Expand Up @@ -133,32 +134,33 @@ eac calls this before setting anything up. `judges` is an online run's chosen ju

### `seed.setup` / `seed.teardown`

- `seed.setup` takes `{"dataset", "seed"}` and returns `{"handle": {...}}`. The handle must be JSON, since later phases read it back from `seeds.json`.
- `seed.teardown` takes `{"dataset", "seed", "handle"}`.
- `seed.setup` takes `{"dataset", "seed"}` and returns `{"seed_results": {...}}`, whatever the seed's setup returned. It must be JSON, since later phases read it back from `seeds.json`.
- `seed.teardown` takes `{"dataset", "seed", "seed_results"}`.

eac keeps cached seeds (`cache: true`) in `<artifacts>/seed-cache.json` and only sends `seed.setup` for one it doesn't have there. A seed can also have a cache of its own, shared between machines, like a bucket:

- In `seed.setup` for a cached seed, look the seed's `key` up in its own cache first. If it's there, return `{"handle": {...}, "from_cache": true}` without setting anything up. Otherwise set it up and save the handle to its cache. A cache that fails to load or save should only warn.
- In `seed.setup` for a cached seed, look the seed's `key` up in its own cache first. If it's there, return `{"seed_results": {...}, "from_cache": true}` without setting anything up. Otherwise set it up and save its results to its cache. A cache that fails to load or save should only warn.
- In `seed.teardown` for a cached seed, remove `key` from its own cache before tearing the seed down, and fail without tearing it down if that fails, so no machine loads a fixture that's gone. `key` is the one the seed was set up with, which may not be the seed's current key, as when pruning.

`eac offline prune` tears down the seeds in eac's local seed cache that no case uses. Seeds in a seed's own cache that no machine has locally are the seed's to clean up.

### `case.run`

Params: `{"dataset", "case", "seeds": {name: handle}, "args", "conversation_id"}`.
Params: `{"dataset", "case", "seed_results": {name: seed_results}, "args", "conversation_id"}`.

Runs the system under test on one case.

- Tag the agent run with `conversation_id`, so a judge can fetch its trace later.
- Return `{"output": {...}, "conversation_id"?, "metrics"?}`. If the agent used its own conversation id, return it and it replaces eac's.
- Return `{"run_results": {...}, "conversation_id"?, "metrics"?}`. If the agent used its own conversation id, return it and it replaces eac's.

### `case.judge`

Params: `{"dataset", "case", "judges"?, "error"?, "seeds": {name: handle}, "judge_args"?, "trace"?, "started_at"?, "ended_at"?}`.
Params: `{"dataset", "case", "judges"?, "error"?, "seed_results": {name: seed_results}, "judge_args"?, "trace"?, "started_at"?, "ended_at"?}`.

Scores one case's output and returns `{"scores": [Score]}`.
Scores one case's run results and returns `{"judge_results": [Score]}`.

- `case` carries the runner's `output` and `conversation_id`. If the runner failed, it has no `output`, `error` says why, and there's nothing to score.
- A judge that raises gets a Score with its `error` and no `score`.
- `case` carries its `run_results` and `conversation_id`. If the runner failed, it has no `run_results`, `error` says why, and there's nothing to score.
- `judges`, when given, names judges to score with instead of the case's own, as in a comparison. Build each one from the class of the case's judge with that name.
- `judge_args` is `--judge-args`, keyed by judge name.
- `trace` is the case's agent trace, if an earlier judge phase saved one.
Expand All @@ -169,15 +171,15 @@ Scores one case's output and returns `{"scores": [Score]}`.

Params: `{"dataset", "window", "args"}`.

Returns `{"cases": [Case]}`, at most `limit` of the window's runs. Each case has its `output`, and its `conversation_id` if it has one.
Returns `{"cases": [Case]}`, at most `limit` of the window's runs. Each case has its `run_results`, and its `conversation_id` if it has one.

Return only sampled runs: those whose id's SHA-256 has its first 8 bytes, as a big-endian integer, below `sample_rate × 2^64`. SDKs should give runners a helper for this, so every SDK picks the same runs.

### `online.judge`

Params: `{"dataset", "case", "judges", "judge_args"?, "trace"?}`.

Scores a collected case, with its `output` and `conversation_id`, with the named online judges and returns `{"scores": [Score]}`. The names are the ones in the DatasetRef, and `judge_args` is keyed by them. Agent traces work as in `case.judge`, and collected cases have no run times.
Scores a collected case, with its `run_results` and `conversation_id`, with the named online judges and returns `{"judge_results": [Score]}`. The names are the ones in the DatasetRef, and `judge_args` is keyed by them. Judge errors and agent traces work as in `case.judge`, and collected cases have no run times.

### `credentials.check` / `credentials.login`

Expand Down
8 changes: 3 additions & 5 deletions core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ Offline evals run evals on cases you wrote, in three phases:
```
eac offline seed pick the cases, create a run, set up its seeds -> seeds.json
eac offline execute run the system under test on each case & save its output -> outputs/
eac offline judge score each output -> scores/ traces/ results/ summary.json
eac offline judge score each output -> traces/ results/
```

**Seed**
Expand All @@ -89,7 +89,7 @@ Online evals judge what your system already did in production. There are no seed

```
eac online execute collect production runs from a time window as cases -> outputs/
eac online judge score each case with the picked judges -> scores/ traces/ results/ summary.json
eac online judge score each case with the picked judges -> traces/ results/
```

**Execute**
Expand Down Expand Up @@ -211,12 +211,10 @@ online:
.eac/credentials/saved.json values from credential logins, owner-only and git-ignored
.eac/runs/<id>/
manifest.json what was selected, the args, the source (git or CI)
seeds.json handles of every seed the run used
seeds.json results of every seed the run used
outputs/<ds>/<case>.json
traces/<ds>/<case>.json agent traces the judges fetched
scores/<ds>/<case>.json
results/<ds>.json each dataset's results, see schemas/results.schema.json
summary.json
```

To store or upload results, run your own script on the run's directory after the judge phase. Read only `results/`, whose format [`schemas/results.schema.json`](../schemas/results.schema.json) describes. The other files are eac's own and may change. Every command that judges, `run` included, prints the run's id to stdout, even when cases fail (`compare` prints one per arm). Judging exits with `1` when a case fails, so run the script whatever eac's exit code is:
Expand Down
21 changes: 14 additions & 7 deletions core/src/cli/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub enum Offline {
/// Execute the AI system we want to test
Execute(PhaseArgs),
/// Score recorded outputs
Judge(PhaseArgs),
Judge(OfflineJudgeArgs),
/// Seed, execute and judge in one go
Run(RunArgs),
/// Run a dataset comparison, one run per arm with shared seeds
Expand All @@ -61,7 +61,7 @@ pub enum Offline {
pub enum Online {
/// Collect production runs from a window as cases -> outputs/, printing the new run's id
Execute(OnlineExecuteArgs),
/// Score a collected run's cases with --judge -> scores/, results/, summary.json
/// Score a collected run's cases with --judge -> results/
Judge(OnlineJudgeArgs),
/// Execute and judge in one go
Run(OnlineRunArgs),
Expand Down Expand Up @@ -92,22 +92,29 @@ pub struct SeedArgs {
pub run_flags: RunFlags,
#[arg(long, value_name = "JSON", value_parser = parse_object, help = JUDGE_ARGS)]
pub judge_args: Option<Object>,
/// Tear down an existing run's uncached seeds instead
#[arg(long)]
pub teardown: bool,
}

// For `eac offline execute`, which works on an existing run.
#[derive(Args)]
pub struct PhaseArgs {
#[command(flatten)]
pub project: Project,
/// Run id to operate on
#[arg(long, value_name = "ID", default_value = LATEST)]
pub run: String,
#[arg(long, value_name = "N", value_parser = parse_count, help = CONCURRENCY)]
pub concurrency: Option<usize>,
}

// For the offline phases that work on an existing run.
#[derive(Args)]
pub struct PhaseArgs {
pub struct OfflineJudgeArgs {
#[command(flatten)]
pub project: Project,
/// Run id to operate on
#[arg(long, value_name = "ID", default_value = LATEST)]
pub run: String,
#[arg(long, value_name = "JSON", value_parser = parse_object, help = JUDGE_ARGS)]
pub judge_args: Option<Object>,
#[arg(long, value_name = "N", value_parser = parse_count, help = CONCURRENCY)]
pub concurrency: Option<usize>,
}
Expand Down
4 changes: 1 addition & 3 deletions core/src/cli/flags.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,12 @@ use crate::eac::{Config, Discovered, Engine, Selection};
use crate::report;
use crate::schema::{Mode, Object};

/// TODO: Rename
#[derive(Args)]
pub struct Project {
#[arg(short = 'C', value_name = "DIR", default_value = ".")]
pub dir: PathBuf,
}

/// TODO
#[derive(Args)]
pub struct Scope {
#[command(flatten)]
Expand All @@ -40,7 +38,7 @@ pub struct Select {
/// What a new run records: its runner args and metadata.
#[derive(Args)]
pub struct RunFlags {
/// JSON args for the runner, checked by the dataset's SDK
/// JSON args for the runner, e.g. '{"model": "big"}'
#[arg(long, value_name = "JSON", value_parser = parse_object)]
pub args: Option<Object>,
/// Extra metadata for results (repeatable)
Expand Down
1 change: 0 additions & 1 deletion core/src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ pub fn dispatch(command: Command) -> Result<()> {
match command {
Command::List(a) => commands::list(&a),
Command::Schema { which } => commands::schema(which),
Command::Offline(Offline::Seed(a)) if a.teardown => offline::teardown(&a),
Command::Offline(Offline::Seed(a)) => offline::seed(&a),
Command::Offline(Offline::Execute(a)) => offline::execute(&a),
Command::Offline(Offline::Judge(a)) => offline::judge(&a),
Expand Down
33 changes: 15 additions & 18 deletions core/src/commands/offline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ use anyhow::Result;

use super::runs::{
check_judge_args, create_run, fail_on, judge_run, open_run, seed_execute_judge, seed_run,
teardown_uncached,
};
use crate::cli::{PhaseArgs, PruneArgs, RunArgs, RunFlags, SeedArgs};
use crate::cli::{OfflineJudgeArgs, PhaseArgs, PruneArgs, RunArgs, RunFlags, SeedArgs};
use crate::eac::{
seed_id, select, Discovered, Engine, Manifest, Phase, Run, Selection, ALL_PHASES,
};
Expand All @@ -29,19 +28,6 @@ pub fn seed(a: &SeedArgs) -> Result<()> {
Ok(())
}

/// Tears down a run's uncached seeds. Cached ones are kept for later runs.
pub fn teardown(a: &SeedArgs) -> Result<()> {
let mut engine = a.scope.project.engine()?;
let run = Run::open(&engine.config().artifacts, &a.run)?;
let seeds = run.read_seeds()?;
if seeds.seeds.values().all(|e| e.cached) {
info!("run {} has no uncached seeds; 'eac offline prune' tears down cached ones", run.id);
return Ok(());
}
engine.check_seed_credentials(seeds.seeds.values().filter(|e| !e.cached))?;
teardown_uncached(&mut engine, &seeds)
}

/// Executes a seeded run: runs the system under test on each case and saves
/// its output.
pub fn execute(a: &PhaseArgs) -> Result<()> {
Expand All @@ -57,11 +43,22 @@ pub fn execute(a: &PhaseArgs) -> Result<()> {
Ok(())
}

/// Re-scores a run's recorded outputs without re-running the system.
pub fn judge(a: &PhaseArgs) -> Result<()> {
/// Re-scores a run's recorded outputs without re-running the system, with
/// the judge args the run recorded unless --judge-args replaces them.
pub fn judge(a: &OfflineJudgeArgs) -> Result<()> {
let mut engine = a.project.engine()?;
engine.set_concurrency(a.concurrency);
let (run, m) = open_run(&engine, &a.run, Mode::Offline, "judge")?;
let (run, mut m) = open_run(&engine, &a.run, Mode::Offline, "judge")?;
if let Some(judge_args) = &a.judge_args {
check_judge_args(judge_args, m.datasets.iter().flat_map(|d| d.used_judges()))?;
for d in &mut m.datasets {
d.judge_args = judge_args.clone();
let args = d.args.clone();
engine.validate_args(d, &args)?;
}
// Recorded, so results and a later re-judge use them.
run.write_manifest(&m)?;
}
engine.check_credentials(&m.datasets, &[Phase::Judge])?;
fail_on(judge_run(&mut engine, &run, &m)?)
}
Expand Down
1 change: 0 additions & 1 deletion core/src/commands/runs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ pub fn teardown_uncached(engine: &mut Engine, seeds: &Seeds) -> Result<()> {
pub fn judge_run(engine: &mut Engine, run: &Run, m: &Manifest) -> Result<Summary> {
report::phase("judge");
let (summary, results) = engine.judge(run, m)?;
run.write_summary(&summary)?;
run.write_results(&results)?;
for r in &results {
report::saved(&run.results_file(&r.dataset_name));
Expand Down
21 changes: 10 additions & 11 deletions core/src/eac/phases/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@ pub enum Phase {

pub const ALL_PHASES: &[Phase] = &[Phase::Seed, Phase::Execute, Phase::Judge];

/// A credential to check, with the runtime whose SDK checks it.
type Needed = (String, Credential);

impl Engine {
/// Checks what the datasets need for phases before any phase starts. On a
/// terminal, offers to log in to the credentials that aren't set up. CI
Expand Down Expand Up @@ -51,9 +48,10 @@ impl Engine {
self.ensure(needed)
}

/// Checks each credential and, on a terminal, offers to log in to the ones
/// that aren't set up. Fails listing the ones that still aren't.
fn ensure(&mut self, needed: Vec<Needed>) -> Result<()> {
/// Checks each credential, which comes with the runtime whose SDK checks
/// it, and on a terminal offers to log in to the ones that aren't set up.
/// Fails listing the ones that still aren't.
fn ensure(&mut self, needed: Vec<(String, Credential)>) -> Result<()> {
if needed.is_empty() {
return Ok(());
}
Expand All @@ -65,7 +63,7 @@ impl Engine {

let mut failures = Vec::new();
// Each credential logged in to, with the variables its login set.
let mut logins: Vec<(Needed, BTreeMap<String, String>)> = Vec::new();
let mut logins: Vec<((String, Credential), BTreeMap<String, String>)> = Vec::new();
for ((runtime, c), ok) in needed.into_iter().zip(checked) {
if ok {
continue;
Expand All @@ -86,7 +84,8 @@ impl Engine {
if !logins.is_empty() {
// Workers restart once, after every login, since imports can be slow.
self.add_login_env(logins.iter().flat_map(|(_, env)| env.clone()).collect());
let logged_in: Vec<Needed> = logins.iter().map(|(n, _)| n.clone()).collect();
let logged_in: Vec<(String, Credential)> =
logins.iter().map(|(n, _)| n.clone()).collect();
let rechecked = self.check(&logged_in)?;
let mut working = BTreeMap::new();
for (((_, c), env), ok) in logins.into_iter().zip(rechecked) {
Expand All @@ -107,7 +106,7 @@ impl Engine {
}

/// Whether each credential works, asking the SDK of each one's runtime.
fn check(&mut self, needed: &[Needed]) -> Result<Vec<bool>> {
fn check(&mut self, needed: &[(String, Credential)]) -> Result<Vec<bool>> {
let mut ok = vec![false; needed.len()];
let runtimes: BTreeSet<&str> = needed.iter().map(|(r, _)| r.as_str()).collect();
for runtime in runtimes {
Expand Down Expand Up @@ -163,7 +162,7 @@ impl Engine {
}

/// What the datasets need for phases, each credential once.
fn needed(datasets: &[Dataset], phases: &[Phase]) -> Vec<Needed> {
fn needed(datasets: &[Dataset], phases: &[Phase]) -> Vec<(String, Credential)> {
let mut needed = Vec::new();
for d in datasets {
if phases.contains(&Phase::Seed) {
Expand All @@ -184,7 +183,7 @@ fn needed(datasets: &[Dataset], phases: &[Phase]) -> Vec<Needed> {
/// Adds the credentials needed doesn't have yet. Credentials with the same
/// key are the same, and each runtime checks its own.
fn add<'a>(
needed: &mut Vec<Needed>,
needed: &mut Vec<(String, Credential)>,
runtime: &str,
credentials: impl IntoIterator<Item = &'a Credential>,
) {
Expand Down
2 changes: 1 addition & 1 deletion core/src/eac/phases/discover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ impl Engine {
judge_args: &d.judge_args,
};
let res: ArgsValidateResult = (self.call(&d.runtime, "args.validate", params))
.with_context(|| format!("invalid --args or --judge-args for {}", d.name))?;
.with_context(|| format!("validating dataset {}", d.name))?;
d.args = args.clone();
d.runner_credentials = res.runner_credentials;
d.judge_credentials = res.judge_credentials;
Expand Down
Loading
Loading