From d886a32e2ed3476998684d14c0149f8063e3eff2 Mon Sep 17 00:00:00 2001 From: Ryan Brooks Date: Sat, 21 Nov 2026 09:43:43 -0800 Subject: [PATCH 1/4] Cleanups and more cohesive example --- .github/workflows/evals.yml | 157 +++++++++ Makefile | 7 +- README.md | 8 +- VERSION | 2 +- core/PROTOCOL.md | 22 +- core/README.md | 15 +- core/src/cli/args.rs | 36 +- core/src/cli/flags.rs | 32 +- core/src/cli/mod.rs | 3 - core/src/cli/parse.rs | 17 + core/src/commands/auth.rs | 26 -- core/src/commands/catalog.rs | 56 --- core/src/commands/compare.rs | 3 +- core/src/commands/list.rs | 4 +- core/src/commands/mod.rs | 4 - core/src/commands/offline.rs | 24 +- core/src/commands/online.rs | 19 +- core/src/eac/config/dataset_yml.rs | 27 +- core/src/eac/config/mod.rs | 11 +- core/src/eac/phases/credentials.rs | 33 +- core/src/eac/phases/discover.rs | 2 +- core/src/eac/phases/execute.rs | 12 +- core/src/eac/phases/judge.rs | 2 - core/src/eac/run/manifest.rs | 21 +- core/src/eac/run/results.rs | 98 +++--- core/src/eac/select.rs | 87 +---- core/src/schema/protocol.schema.json | 55 +-- core/src/schema/types.rs | 17 + core/src/schema/worker_methods.rs | 12 +- core/tests/cli.rs | 210 ++++++++--- core/tests/fixtures/project/eac/worker.py | 7 +- .../tests/fixtures/project/evals/chat_eval.py | 8 +- core/tests/fixtures/project/evals/dataset.yml | 3 +- docs/README.md | 23 +- docs/app/cases-and-runners/page.mdx | 16 +- docs/app/cli/page.mdx | 3 +- docs/app/comparing-variants/page.mdx | 17 + docs/app/concepts/page.mdx | 18 +- docs/app/configuration/page.mdx | 2 +- docs/app/credentials/page.mdx | 8 +- docs/app/introduction/page.mdx | 146 +++++++- docs/app/judges/page.mdx | 9 +- docs/app/online-evals/page.mdx | 6 +- docs/app/quick-start/page.mdx | 114 ------ docs/app/sampling/page.mdx | 13 + docs/components/docsShell.tsx | 71 +++- docs/components/landing.tsx | 15 +- docs/components/mdx.tsx | 3 - docs/components/nav.ts | 37 +- docs/next.config.ts | 4 + examples/basic-example-python/README.md | 79 ----- examples/basic-example-python/eac.yml | 5 - .../evals/assistant/dataset.py | 142 -------- .../evals/assistant/dataset.yml | 12 - examples/sentry-assistant-python/.env.example | 11 + examples/sentry-assistant-python/.gitignore | 2 + examples/sentry-assistant-python/README.md | 60 ++++ examples/sentry-assistant-python/agent.py | 247 +++++++++++++ .../sentry-assistant-python/app/__init__.py | 0 examples/sentry-assistant-python/app/app.py | 18 + .../sentry-assistant-python/app/checkout.py | 32 ++ .../sentry-assistant-python/app/newsletter.py | 8 + examples/sentry-assistant-python/eac.yml | 4 + .../evals/triage/cases.py | 63 ++++ .../evals/triage/credentials/openrouter.py | 20 ++ .../evals/triage/credentials/sentry.py | 39 +++ .../evals/triage/dataset.yml | 13 + .../evals/triage/judges/found_cause_judge.py | 17 + .../evals/triage/judges/found_issue_judge.py | 19 + .../evals/triage/judges/triage_llm_judge.py | 51 +++ .../evals/triage/runners/offline.py | 15 + .../evals/triage/runners/online.py | 24 ++ .../evals/triage/seed.py | 57 +++ .../sentry-assistant-python/pyproject.toml | 21 ++ .../sentry-assistant-python/sentry_cli.py | 21 ++ examples/sentry-assistant-python/traces.py | 27 ++ examples/sentry-assistant-python/uv.lock | 325 ++++++++++++++++++ schemas/results.schema.json | 136 +++++++- scripts/upload_evals.py | 144 ++++++++ sdks/python/README.md | 48 +-- sdks/python/eac/credential.py | 25 +- sdks/python/eac/models.py | 50 ++- sdks/python/eac/protocol.py | 18 +- sdks/python/eac/worker.py | 65 +++- 84 files changed, 2354 insertions(+), 1009 deletions(-) create mode 100644 .github/workflows/evals.yml delete mode 100644 core/src/commands/auth.rs delete mode 100644 core/src/commands/catalog.rs create mode 100644 docs/app/comparing-variants/page.mdx delete mode 100644 docs/app/quick-start/page.mdx create mode 100644 docs/app/sampling/page.mdx delete mode 100644 examples/basic-example-python/README.md delete mode 100644 examples/basic-example-python/eac.yml delete mode 100644 examples/basic-example-python/evals/assistant/dataset.py delete mode 100644 examples/basic-example-python/evals/assistant/dataset.yml create mode 100644 examples/sentry-assistant-python/.env.example create mode 100644 examples/sentry-assistant-python/.gitignore create mode 100644 examples/sentry-assistant-python/README.md create mode 100644 examples/sentry-assistant-python/agent.py create mode 100644 examples/sentry-assistant-python/app/__init__.py create mode 100644 examples/sentry-assistant-python/app/app.py create mode 100644 examples/sentry-assistant-python/app/checkout.py create mode 100644 examples/sentry-assistant-python/app/newsletter.py create mode 100644 examples/sentry-assistant-python/eac.yml create mode 100644 examples/sentry-assistant-python/evals/triage/cases.py create mode 100644 examples/sentry-assistant-python/evals/triage/credentials/openrouter.py create mode 100644 examples/sentry-assistant-python/evals/triage/credentials/sentry.py create mode 100644 examples/sentry-assistant-python/evals/triage/dataset.yml create mode 100644 examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py create mode 100644 examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py create mode 100644 examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py create mode 100644 examples/sentry-assistant-python/evals/triage/runners/offline.py create mode 100644 examples/sentry-assistant-python/evals/triage/runners/online.py create mode 100644 examples/sentry-assistant-python/evals/triage/seed.py create mode 100644 examples/sentry-assistant-python/pyproject.toml create mode 100644 examples/sentry-assistant-python/sentry_cli.py create mode 100644 examples/sentry-assistant-python/traces.py create mode 100644 examples/sentry-assistant-python/uv.lock create mode 100755 scripts/upload_evals.py diff --git a/.github/workflows/evals.yml b/.github/workflows/evals.yml new file mode 100644 index 0000000..7b75566 --- /dev/null +++ b/.github/workflows/evals.yml @@ -0,0 +1,157 @@ +name: Evals + +# Runs examples/sentry-assistant-python's evals at a pull request's head and +# at its merge base, with real models, and uploads both runs to +# evals.sentry.dev. It compares them and comments on the pull request. +# +# Needs the OPENROUTER_API_KEY, SENTRY_AUTH_TOKEN and EVALS_API_TOKEN secrets. +# The Sentry token has to read and resolve issues in SENTRY_ORG/SENTRY_PROJECT. + +on: + pull_request: + paths: + - core/** + - sdks/python/** + - examples/sentry-assistant-python/** + - scripts/upload_evals.py + - .github/workflows/evals.yml + +permissions: + contents: read + +concurrency: + group: evals-${{ github.event.pull_request.number }} + cancel-in-progress: true + +env: + DATASET: triage + EXAMPLE: examples/sentry-assistant-python + # The project the example's seeds fill with issues. + SENTRY_ORG: sentry-evals + SENTRY_PROJECT: eac-example + +jobs: + compare: + name: Create the comparison + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + comparison: ${{ steps.create.outputs.comparison }} + base_sha: ${{ steps.create.outputs.base_sha }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - name: Create the comparison + id: create + env: + GH_TOKEN: ${{ github.token }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + EVALS_API_TOKEN: ${{ secrets.EVALS_API_TOKEN }} + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + run: | + # Pull requests that don't get secrets, like Dependabot's, skip the evals. + if [ -z "$EVALS_API_TOKEN" ] || [ -z "$OPENROUTER_API_KEY" ] || [ -z "$SENTRY_AUTH_TOKEN" ]; then + echo "::notice::Skipping the evals: a secret they need isn't set." + exit 0 + fi + base_sha=$(gh api "repos/$GITHUB_REPOSITORY/compare/$GITHUB_BASE_REF...$HEAD_SHA" --jq .merge_base_commit.sha) + echo "base_sha=$base_sha" >> "$GITHUB_OUTPUT" + echo "comparison=$(python3 scripts/upload_evals.py comparison "$DATASET")" >> "$GITHUB_OUTPUT" + + eval: + name: Evals (${{ matrix.arm }}) + needs: compare + if: needs.compare.outputs.comparison != '' + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + - arm: base + sha: ${{ needs.compare.outputs.base_sha }} + - arm: head + sha: ${{ github.event.pull_request.head.sha }} + base_sha: ${{ needs.compare.outputs.base_sha }} + steps: + # The upload script always comes from the pull request. The CLI, SDK + # and example come from the arm's commit, in arm/. + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + with: + ref: ${{ matrix.sha }} + path: arm + + - name: Update Rust + run: rustup update stable --no-self-update && rustup default stable + + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + + # The example's seed and agent work with Sentry through its CLI, which + # logs in with SENTRY_AUTH_TOKEN here. + - name: Install the Sentry CLI + run: npm install -g sentry@0.47.0 + + - name: Run the evals and upload them + id: run + env: + SHA: ${{ matrix.sha }} + BASE_SHA: ${{ matrix.base_sha }} + COMPARISON: ${{ needs.compare.outputs.comparison }} + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + EVALS_API_TOKEN: ${{ secrets.EVALS_API_TOKEN }} + run: | + # The pull request that adds the example has no base to compare against. + if [ ! -d "arm/$EXAMPLE" ]; then + echo "::notice::$EXAMPLE doesn't exist at the merge base, so there's no base run." + exit 0 + fi + cargo build --manifest-path arm/core/Cargo.toml + cd "arm/$EXAMPLE" + uv sync --locked + + # eac exits 1 when a case fails or errors, and 2 when eac itself + # fails. Low scores are worth uploading, so only 2 stops here. + status=0 + run=$(../../core/target/debug/eac offline run) || status=$? + if [ "$status" -gt 1 ]; then exit "$status"; fi + echo "run=$run" >> "$GITHUB_OUTPUT" + + python3 "$GITHUB_WORKSPACE/scripts/upload_evals.py" run ".eac/runs/$run" \ + --comparison "$COMPARISON" --sha "$SHA" ${BASE_SHA:+--base-sha "$BASE_SHA"} + + # A model's scores never fail the check. An errored case means a runner + # or judge threw, which on the head is likely this pull request's doing. + - name: Fail on errored cases + if: matrix.arm == 'head' + working-directory: arm/${{ env.EXAMPLE }} + env: + RUN: ${{ steps.run.outputs.run }} + run: | + errored=$(jq -s '[.[].cases[] | select(.status == "error")] | length' ".eac/runs/$RUN/results/"*.json) + if [ "$errored" -gt 0 ]; then + echo "::error::$errored cases errored. See the run's results above." + exit 1 + fi + + # Online runs can't join a comparison, so this only checks they work. + - name: Run the online evals + if: matrix.arm == 'head' + working-directory: arm/${{ env.EXAMPLE }} + env: + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} + run: ../../core/target/debug/eac online run --judge triage_llm_judge --since 1h > /dev/null + + # Resolves the issues this run's seeds created in Sentry, even if a + # step above failed. + - name: Clean up the seeds + if: always() + env: + SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} + run: | + if [ -d "arm/$EXAMPLE/.eac" ]; then + cd "arm/$EXAMPLE" && ../../core/target/debug/eac offline prune --all + fi diff --git a/Makefile b/Makefile index 0ebe252..8296f46 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,10 @@ CARGO ?= cargo PYTHON ?= python3 +PNPM ?= pnpm MANIFEST := core/Cargo.toml .DEFAULT_GOAL := help -.PHONY: help build install test lint fmt generate generate-check version version-check +.PHONY: help build install test lint fmt generate generate-check version version-check docs help: ## list the targets @awk -F ':.*## ' '/^[a-z-]+:.*## / {printf " %-15s %s\n", $$1, $$2}' $(MAKEFILE_LIST) @@ -35,3 +36,7 @@ version: ## copy the version in VERSION into the CLI and SDKs version-check: ## fail if the CLI or an SDK doesn't match VERSION $(PYTHON) scripts/version.py --check + +docs: ## install the docs' dependencies and serve them at http://localhost:3000 + $(PNPM) --dir docs install + $(PNPM) --dir docs dev diff --git a/README.md b/README.md index 6a1b6ae..0a826ad 100644 --- a/README.md +++ b/README.md @@ -91,9 +91,13 @@ RESULTS ## Learn more -The [docs](https://eac.sentry.dev) cover judges, seeds, [online evals](https://eac.sentry.dev/online-evals) and the full CLI reference. [`examples/`](examples/) has complete projects to start from. +[`examples/`](examples/) has full examples to start from. The [docs](https://eac.sentry.dev) cover everything about EAC. -For contributors: [`core/README.md`](core/README.md) covers the CLI, [`core/PROTOCOL.md`](core/PROTOCOL.md) how it talks to an SDK, and [`CONTRIBUTING.md`](CONTRIBUTING.md) releasing. +## Contributors + +- [`core/README.md`](core/README.md) covers the CLI +- [`core/PROTOCOL.md`](core/PROTOCOL.md) how the CLI talks to an SDK +- [`CONTRIBUTING.md`](CONTRIBUTING.md) covers releasing. ## License diff --git a/VERSION b/VERSION index 8acdd82..4e379d2 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.1 +0.0.2 diff --git a/core/PROTOCOL.md b/core/PROTOCOL.md index 14333ce..62e68df 100644 --- a/core/PROTOCOL.md +++ b/core/PROTOCOL.md @@ -58,8 +58,7 @@ offline run all three phases, then seed.teardown for uncached seeds (comp offline prune discover → seed.teardown online execute discover → args.validate → online.execute online judge args.validate → online.judge -list, catalog discover -auth discover → args.validate → credentials.check → credentials.login +list discover ``` Before each phase, eac also sends `credentials.check` for what the phase needs, and `credentials.login` if the user agrees to log in. The [credentials](#credentialscheck--credentialslogin) section covers both. @@ -105,6 +104,9 @@ These types show up in the params and results of many methods: "cache_write_tokens": 0, "reasoning_tokens": 0, "llm_duration_seconds": 0, "llm_calls": 0, "tool_calls": 0, "cost_usd": 0} +// Window: the production runs to collect, from since up to until (RFC 3339) +{"since": "2026-11-19T11:00:00Z", "until": "2026-11-19T12:00:00Z", "limit": 500, "sample_rate": 0.1} + ``` ## Worker methods @@ -115,7 +117,7 @@ The `dataset` param is always a DatasetRef. Every method that needs a dataset ge Params: `{"dataset"}`. -Imports the dataset's code and returns what only the code knows. It shouldn't have side effects beyond the import. Everything else, like the name, agent, comparisons, shard config and online judges, comes from the `dataset.yml`. +Imports the dataset's code and returns what only the code knows. It shouldn't have side effects beyond the import. Everything else, like the name, comparisons and online judges, comes from the `dataset.yml`. ```jsonc {"cases": [Case]} // offline: every case; online: nothing @@ -153,7 +155,7 @@ Runs the system under test on one case. ### `case.judge` -Params: `{"dataset", "case", "judges"?, "error"?, "seeds": {name: handle}, "judge_args"?, "trace"?, "agent"?, "started_at"?, "ended_at"?}`. +Params: `{"dataset", "case", "judges"?, "error"?, "seeds": {name: handle}, "judge_args"?, "trace"?, "started_at"?, "ended_at"?}`. Scores one case's output and returns `{"scores": [Score]}`. @@ -162,17 +164,19 @@ Scores one case's output and returns `{"scores": [Score]}`. - `judge_args` is `--judge-args`, keyed by judge name. - `trace` is the case's agent trace, if an earlier judge phase saved one. -**Agent traces.** Without a `trace`, the judges may fetch the agent run's trace, looking it up by the case's `conversation_id`, the dataset's `agent` and when the case ran (`started_at` and `ended_at`, RFC 3339). Give every judge the same trace, and return it as `"trace"`, with the LLM usage it records as `"trace_metrics"` (a Metrics). eac saves it under `traces/` in the run and sends it back as `trace` when the run is judged again. Its metrics replace the ones `case.run` returned. A failed fetch should only warn, since judges can run without a trace. +**Agent traces.** Without a `trace`, the judges may fetch the agent run's trace, looking it up by the case's `conversation_id` and when the case ran (`started_at` and `ended_at`, RFC 3339). Give every judge the same trace, and return it as `"trace"`, with the LLM usage it records as `"trace_metrics"` (a Metrics). eac saves it under `traces/` in the run and sends it back as `trace` when the run is judged again. Its metrics replace the ones `case.run` returned. A failed fetch should only warn, since judges can run without a trace. ### `online.execute` -Params: `{"dataset", "since", "until", "limit", "args"}`. +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]}`, the production runs from the window between `since` and `until` (both RFC 3339 times), at most `limit` of them. Each case has its `output`, 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"?, "agent"?}`. +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. @@ -186,7 +190,7 @@ Before each phase, eac sends `credentials.check {"credentials": [Credential]}` w **Logging in.** -For each credential that isn't set up, eac may send `credentials.login {"credential"}`, either when the user agrees to log in on a terminal or from `eac auth`. eac starts a separate worker for this with the terminal as its stdin and stderr, and its stdout going to eac's stderr, so login can prompt or run a command like `gh auth login`. +For each credential that isn't set up, eac may send `credentials.login {"credential"}`, when the user agrees to log in on a terminal. eac starts a separate worker for this with the terminal as its stdin and stderr, and its stdout going to eac's stderr, so login can prompt or run a command like `gh auth login`. Return `{"env": {...}}` with any variables the credential needs, or an error saying why login failed. diff --git a/core/README.md b/core/README.md index 0649793..2b255fe 100644 --- a/core/README.md +++ b/core/README.md @@ -94,7 +94,7 @@ eac online judge score each case with the picked judges **Execute** -Asks each dataset's online runner for the production runs in a time window (`--since`, `--window-end`, `--limit`), as cases with their outputs, and saves each output. +Asks each dataset's online runner for the production runs in a time window (`--since`, `--window-end`, `--limit`), sampled at `--sample-rate`, as cases with their outputs, and saves each output. **Judge** @@ -108,9 +108,9 @@ Seeds, runners and judges can declare the credentials they need, like a GitHub t On a terminal, eac offers to log in first. Whatever a login returns is saved to `/credentials/saved.json` (owner-only, git-ignored and never your `.env`), and later commands use it ahead of `.env` and your shell. If a saved value goes stale, its check fails and logging in again replaces it. -`eac auth` checks and logs in to everything the datasets need up front, which is handy on a new machine. Checks are skipped when `$CI` is set, since CI sets up its own credentials. +Checks are skipped when `$CI` is set, since CI sets up its own credentials. -`eac --help` lists every other command (`list`, `compare`, `catalog`, ...) and flag. +`eac --help` lists every other command (`list`, `compare`, ...) and flag. ## Build @@ -131,7 +131,7 @@ make version-check # fail if the CLI or an SDK doesn't match VERSION `cargo run` builds and runs the CLI in one step, and the example project makes a handy target: ```sh -cargo run --manifest-path core/Cargo.toml -- list -C examples/basic-example-python +cargo run --manifest-path core/Cargo.toml -- list -C examples/sentry-assistant-python ``` ### Tests @@ -174,13 +174,12 @@ Seed caches shared between machines and agent trace sources aren't config. They' ```yaml # evals/autofix/rca/dataset.yml name: autofix_rca # lowercase letters, digits and _; unique in the project -agent: autofix # optional: the production agent, for traces +metadata: {team: seer} # optional: recorded in its results runtime: python # required; python is the only one so far offline: runner: ./offline_runner.py:AutofixRcaEvalRunner # an OfflineRunner cases: ./offline_cases.py:AUTOFIX_RCA_CASES # a sequence of Cases - shard_config: {cases_per_shard: 12, max_shards: 10} concurrency: 4 # optional: cases run at once (default 1) comparisons: - name: coding_agents @@ -210,7 +209,7 @@ online: .eac/seed-cache.json cached seeds, shared across runs .eac/credentials/saved.json values from credential logins, owner-only and git-ignored .eac/runs// - manifest.json what was selected, the args, the source (git or CI), the variant + manifest.json what was selected, the args, the source (git or CI) seeds.json handles of every seed the run used outputs//.json traces//.json agent traces the judges fetched @@ -227,4 +226,4 @@ id=$(eac offline run --dataset chat); ./upload.py ".eac/runs/$id" ## Not built yet -Cost and token tracking, result caching, CI sharding and packaged binaries. +Cost and token tracking, result caching and packaged binaries. diff --git a/core/src/cli/args.rs b/core/src/cli/args.rs index ddf8aad..369df90 100644 --- a/core/src/cli/args.rs +++ b/core/src/cli/args.rs @@ -1,11 +1,6 @@ -//! Every command and its flags. Groups of flags several commands share are in -//! flags.rs. - -use std::path::PathBuf; - use clap::{Args, Parser, Subcommand, ValueEnum}; -use super::flags::{Project, RunFlags, Scope, Select, ShardFlags, WindowFlags}; +use super::flags::{Project, RunFlags, Scope, Select, WindowFlags}; use super::parse::{parse_count, parse_meta, parse_object}; use crate::eac::LATEST; use crate::schema::Object; @@ -26,17 +21,11 @@ pub struct Cli { pub enum Command { /// Show the datasets and cases eac can see List(ListArgs), - /// Print each dataset's cases, splits and comparisons as JSON - Catalog(CatalogArgs), - /// Run the system on your own cases and score it #[command(subcommand)] Offline(Offline), - /// Score what the system already did in production #[command(subcommand)] Online(Online), - /// Check the credentials the datasets need, and log in to any that aren't set up - Auth(Scope), - /// Print a JSON Schema, for `make generate` + /// Print a JSON Schema, for `make generate` which generates types based on JSON protocols #[command(hide = true)] Schema { #[arg(value_enum, default_value = "protocol")] @@ -54,18 +43,16 @@ pub enum SchemaKind { #[derive(Subcommand)] pub enum Offline { - /// Set up fixtures -> seeds.json, printing the new run's id + /// Set up fixtures Seed(SeedArgs), - /// Execute a seeded run by running the system under test on each case -> outputs/ + /// Execute the AI system we want to test Execute(PhaseArgs), - /// Score recorded outputs -> scores/, results/, summary.json + /// Score recorded outputs Judge(PhaseArgs), /// Seed, execute and judge in one go Run(RunArgs), /// Run a dataset comparison, one run per arm with shared seeds Compare(CompareArgs), - /// Print how many shards CI should run the selected cases in - Shards(ListArgs), /// Tear down the locally cached seeds no case uses Prune(PruneArgs), } @@ -95,15 +82,6 @@ pub struct ListArgs { pub select: Select, } -#[derive(Args)] -pub struct CatalogArgs { - #[command(flatten)] - pub scope: Scope, - /// Write the catalog to a file instead of stdout - #[arg(long, value_name = "FILE")] - pub output: Option, -} - #[derive(Args)] pub struct SeedArgs { #[command(flatten)] @@ -111,8 +89,6 @@ pub struct SeedArgs { #[command(flatten)] pub select: Select, #[command(flatten)] - pub shard: ShardFlags, - #[command(flatten)] pub run_flags: RunFlags, #[arg(long, value_name = "JSON", value_parser = parse_object, help = JUDGE_ARGS)] pub judge_args: Option, @@ -143,8 +119,6 @@ pub struct RunArgs { #[command(flatten)] pub select: Select, #[command(flatten)] - pub shard: ShardFlags, - #[command(flatten)] pub run_flags: RunFlags, #[arg(long, value_name = "JSON", value_parser = parse_object, help = JUDGE_ARGS)] pub judge_args: Option, diff --git a/core/src/cli/flags.rs b/core/src/cli/flags.rs index e0a0f1a..d83c55a 100644 --- a/core/src/cli/flags.rs +++ b/core/src/cli/flags.rs @@ -6,17 +6,19 @@ use std::time::Duration; use anyhow::Result; use clap::Args; -use super::parse::{parse_duration, parse_meta, parse_object}; -use crate::eac::{Config, Discovered, Engine, Selection, Shard}; +use super::parse::{parse_duration, parse_meta, parse_object, parse_sample_rate}; +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)] @@ -35,25 +37,12 @@ pub struct Select { pub splits: Vec, } -#[derive(Args)] -pub struct ShardFlags { - /// Run only this shard of the selected cases (0-based) - #[arg(long, value_name = "N")] - pub shard_index: Option, - /// Override the planned number of shards - #[arg(long, value_name = "N", requires = "shard_index")] - pub shard_count: Option, -} - -/// What a new run records: its runner args, variant and metadata. +/// 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 #[arg(long, value_name = "JSON", value_parser = parse_object)] pub args: Option, - /// Label telling this run apart from others at the same commit - #[arg(long)] - pub variant: Option, /// Extra metadata for results (repeatable) #[arg(long = "meta", value_name = "KEY=VALUE", value_parser = parse_meta)] pub meta: Vec<(String, String)>, @@ -71,6 +60,9 @@ pub struct WindowFlags { /// Most cases to collect per dataset #[arg(long, default_value_t = 500, allow_negative_numbers = true)] pub limit: i64, + /// Fraction of the window's production runs to collect, e.g. 0.1 + #[arg(long, value_name = "RATE", default_value_t = 1.0, value_parser = parse_sample_rate, allow_negative_numbers = true)] + pub sample_rate: f64, } impl Project { @@ -91,12 +83,8 @@ impl Scope { } impl Select { - pub fn selection(&self, shard: Option<&ShardFlags>) -> Selection { - Selection { - cases: self.cases.clone(), - splits: self.splits.clone(), - shard: shard.and_then(|s| Some(Shard { index: s.shard_index?, count: s.shard_count })), - } + pub fn selection(&self) -> Selection { + Selection { cases: self.cases.clone(), splits: self.splits.clone() } } pub fn is_empty(&self) -> bool { diff --git a/core/src/cli/mod.rs b/core/src/cli/mod.rs index 644c8d9..9b28a81 100644 --- a/core/src/cli/mod.rs +++ b/core/src/cli/mod.rs @@ -14,8 +14,6 @@ use crate::commands::{self, offline, online}; pub fn dispatch(command: Command) -> Result<()> { match command { Command::List(a) => commands::list(&a), - Command::Catalog(a) => commands::catalog(&a), - Command::Auth(scope) => commands::auth(&scope), 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), @@ -23,7 +21,6 @@ pub fn dispatch(command: Command) -> Result<()> { Command::Offline(Offline::Judge(a)) => offline::judge(&a), Command::Offline(Offline::Run(a)) => offline::run(&a), Command::Offline(Offline::Compare(a)) => commands::compare(&a), - Command::Offline(Offline::Shards(a)) => offline::shards(&a), Command::Offline(Offline::Prune(a)) => offline::prune(&a), Command::Online(Online::Execute(a)) => online::execute(&a), Command::Online(Online::Judge(a)) => online::judge(&a), diff --git a/core/src/cli/parse.rs b/core/src/cli/parse.rs index 9c82a90..452c7ec 100644 --- a/core/src/cli/parse.rs +++ b/core/src/cli/parse.rs @@ -22,6 +22,14 @@ pub fn parse_count(s: &str) -> Result { } } +/// Parses a fraction more than 0 and at most 1. +pub fn parse_sample_rate(s: &str) -> Result { + match s.parse::() { + Ok(rate) if rate > 0.0 && rate <= 1.0 => Ok(rate), + _ => Err("expected a fraction more than 0 and at most 1, e.g. 0.1".to_string()), + } +} + /// Parses a duration such as "30m", "1h30m", "1.5h" or "1d". pub fn parse_duration(s: &str) -> Result { humantime::parse_duration(s) @@ -45,6 +53,15 @@ mod tests { assert!(parse_duration("-1h").is_err()); } + #[test] + fn sample_rates() { + assert_eq!(parse_sample_rate("0.1"), Ok(0.1)); + assert_eq!(parse_sample_rate("1"), Ok(1.0)); + for bad in ["0", "-0.5", "1.5", "NaN", "inf", "", "half"] { + assert!(parse_sample_rate(bad).is_err(), "{bad:?}"); + } + } + #[test] fn meta_and_args() { assert_eq!(parse_meta("team=evals=x"), Ok(("team".into(), "evals=x".into()))); diff --git a/core/src/commands/auth.rs b/core/src/commands/auth.rs deleted file mode 100644 index cc0da5f..0000000 --- a/core/src/commands/auth.rs +++ /dev/null @@ -1,26 +0,0 @@ -use anyhow::Result; - -use crate::cli::Scope; -use crate::schema::{Mode, Object}; - -/// Checks every credential the selected datasets need, in any phase of -/// either mode, and logs in to the ones that aren't set up. Runners are -/// asked with their default args. -pub fn auth(scope: &Scope) -> Result<()> { - let mut engine = scope.project.engine()?; - let mut datasets = Vec::new(); - for d in scope.discover(&mut engine, None)? { - if d.config.offline.is_some() { - datasets.push(d.to_dataset(Mode::Offline, d.cases.clone())); - } - if let Some(o) = &d.config.online { - let mut online = d.to_dataset(Mode::Online, vec![]); - online.judges = o.judges.iter().map(|j| j.name.clone()).collect(); - datasets.push(online); - } - } - for d in &mut datasets { - engine.validate_args(d, &Object::new())?; - } - engine.set_up_credentials(&datasets) -} diff --git a/core/src/commands/catalog.rs b/core/src/commands/catalog.rs deleted file mode 100644 index 734d259..0000000 --- a/core/src/commands/catalog.rs +++ /dev/null @@ -1,56 +0,0 @@ -use std::fs; - -use anyhow::{Context, Result}; -use serde_json::{json, Value}; - -use super::list::splits_of; -use crate::cli::CatalogArgs; - -/// Everything a client like a web UI needs to offer runs of each dataset. -pub fn catalog(a: &CatalogArgs) -> Result<()> { - let mut engine = a.scope.project.engine()?; - let found = a.scope.discover(&mut engine, None)?; - let entries: Vec = (found.iter()) - .map(|d| { - let enabled = d.cases.iter().filter(|c| c.enabled).count(); - let cases: Vec = d - .cases - .iter() - .map(|c| json!({"name": c.name, "splits": c.splits, "enabled": c.enabled})) - .collect(); - json!({ - "name": d.config.name, - "file": d.config.file, - "offline": d.config.offline.as_ref().map(|o| json!({ - "runtime": d.config.runtime, - "agent": d.config.agent, - "runner": o.runner, - "cases_from": o.cases, - "cases": cases, - "splits": splits_of(d), - "comparisons": o.comparisons, - "shard_config": o.shard_config, - "shard_count": o.shard_config.shard_count(enabled), - })), - "online": d.config.online.as_ref().map(|o| json!({ - "runtime": d.config.runtime, - "agent": d.config.agent, - "runner": o.runner, - "judges": o.judges.iter().map(|j| &j.name).collect::>(), - })), - }) - }) - .collect(); - - let text = serde_json::to_string_pretty(&entries)?; - let Some(path) = &a.output else { - println!("{text}"); - return Ok(()); - }; - if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { - fs::create_dir_all(dir)?; - } - fs::write(path, text + "\n").with_context(|| format!("writing {}", path.display()))?; - info!("wrote {}", path.display()); - Ok(()) -} diff --git a/core/src/commands/compare.rs b/core/src/commands/compare.rs index c62ab67..5bcd52e 100644 --- a/core/src/commands/compare.rs +++ b/core/src/commands/compare.rs @@ -55,7 +55,7 @@ fn compare_dataset( } // The comparison's split selects like --split, so disabled cases are included. - let mut selection = a.select.selection(None); + let mut selection = a.select.selection(); if let Some(split) = &comparison.split { if selection.splits.is_empty() { selection.splits.push(split.clone()); @@ -106,7 +106,6 @@ fn compare_dataset( let mut rows = Vec::new(); for (arm, dataset) in arms { let m = Manifest { - variant: Some(arm.clone()), comparison: Some(ArmRef { comparison: comparison.name.clone(), arm: arm.clone() }), metadata: a.meta.iter().cloned().collect(), datasets: vec![dataset], diff --git a/core/src/commands/list.rs b/core/src/commands/list.rs index 20567cf..750722a 100644 --- a/core/src/commands/list.rs +++ b/core/src/commands/list.rs @@ -10,7 +10,7 @@ pub fn list(a: &ListArgs) -> Result<()> { let found = a.scope.discover(&mut engine, None)?; // With a selection, list only the cases a run would pick. let picked = - if a.select.is_empty() { None } else { Some(select(&found, &a.select.selection(None))?) }; + if a.select.is_empty() { None } else { Some(select(&found, &a.select.selection())?) }; for d in &found { let mut about = Vec::new(); @@ -54,6 +54,6 @@ pub fn list(a: &ListArgs) -> Result<()> { } /// Every split a dataset's cases are in, sorted. -pub fn splits_of(d: &Discovered) -> BTreeSet<&str> { +fn splits_of(d: &Discovered) -> BTreeSet<&str> { d.cases.iter().flat_map(|c| &c.splits).map(String::as_str).collect() } diff --git a/core/src/commands/mod.rs b/core/src/commands/mod.rs index 61a7af2..e920a5f 100644 --- a/core/src/commands/mod.rs +++ b/core/src/commands/mod.rs @@ -1,7 +1,5 @@ //! What each command does. `cli::dispatch` routes each command here. -mod auth; -mod catalog; mod compare; mod list; pub mod offline; @@ -10,8 +8,6 @@ mod runs; use anyhow::Result; -pub use auth::auth; -pub use catalog::catalog; pub use compare::compare; pub use list::list; pub use runs::FailedRun; diff --git a/core/src/commands/offline.rs b/core/src/commands/offline.rs index cff0ec5..d76be5e 100644 --- a/core/src/commands/offline.rs +++ b/core/src/commands/offline.rs @@ -8,7 +8,7 @@ use super::runs::{ check_judge_args, create_run, fail_on, judge_run, open_run, seed_execute_judge, seed_run, teardown_uncached, }; -use crate::cli::{ListArgs, PhaseArgs, PruneArgs, RunArgs, RunFlags, SeedArgs}; +use crate::cli::{PhaseArgs, PruneArgs, RunArgs, RunFlags, SeedArgs}; use crate::eac::{ seed_id, select, Discovered, Engine, Manifest, Phase, Run, Selection, ALL_PHASES, }; @@ -20,7 +20,7 @@ use crate::schema::{Mode, Object}; pub fn seed(a: &SeedArgs) -> Result<()> { let mut engine = a.scope.project.engine()?; let found = a.scope.discover(&mut engine, Some(Mode::Offline))?; - let selection = a.select.selection(Some(&a.shard)); + let selection = a.select.selection(); let (run, m) = start_run(&mut engine, &found, selection, &a.run_flags, &a.judge_args, &[Phase::Seed])?; seed_run(&mut engine, &run, &m)?; @@ -70,28 +70,12 @@ pub fn run(a: &RunArgs) -> Result<()> { let mut engine = a.scope.project.engine()?; engine.set_concurrency(a.concurrency); let found = a.scope.discover(&mut engine, Some(Mode::Offline))?; - let selection = a.select.selection(Some(&a.shard)); + let selection = a.select.selection(); let (run, m) = start_run(&mut engine, &found, selection, &a.run_flags, &a.judge_args, ALL_PHASES)?; fail_on(seed_execute_judge(&mut engine, &run, &m, a.keep_seeds)?) } -/// Prints the most shards any selected dataset plans, for CI to fan out. -pub fn shards(a: &ListArgs) -> Result<()> { - let mut engine = a.scope.project.engine()?; - let found = a.scope.discover(&mut engine, Some(Mode::Offline))?; - let mut most = 1; - for d in select(&found, &a.select.selection(None))? { - let config = - found.iter().find(|f| f.config.name == d.name).and_then(|f| f.config.offline.as_ref()); - let count = config.map(|o| o.shard_config).unwrap_or_default().shard_count(d.cases.len()); - info!("{:<24} {} cases -> {count} shards", d.name, d.cases.len()); - most = most.max(count); - } - println!("{most}"); - Ok(()) -} - /// Tears down the cached seeds no case uses anymore, or every one with --all. pub fn prune(a: &PruneArgs) -> Result<()> { let mut engine = a.project.engine()?; @@ -144,9 +128,7 @@ fn start_run( engine.check_credentials(&datasets, phases)?; let m = Manifest { - variant: run_flags.variant.clone(), metadata: run_flags.meta.iter().cloned().collect(), - shard: selection.shard, datasets, ..Default::default() }; diff --git a/core/src/commands/online.rs b/core/src/commands/online.rs index 0b89736..d1e50f1 100644 --- a/core/src/commands/online.rs +++ b/core/src/commands/online.rs @@ -5,9 +5,9 @@ use chrono::{DateTime, SecondsFormat, Utc}; use super::runs::{check_judge_args, create_run, judge_run, open_run}; use crate::cli::{OnlineExecuteArgs, OnlineJudgeArgs, OnlineRunArgs, RunFlags, Scope, WindowFlags}; -use crate::eac::{Dataset, Engine, Manifest, Phase, Run, Window}; +use crate::eac::{Dataset, Engine, Manifest, Phase, Run}; use crate::report::{self, join_or_none}; -use crate::schema::{Mode, Object}; +use crate::schema::{Mode, Object, Window}; /// Collects production runs from the window into a new run, printing its /// id on stdout so CI can pass it to `eac online judge`. @@ -95,7 +95,12 @@ fn parse_window(flags: &WindowFlags) -> Result { .and_then(|d| end.checked_sub_signed(d)) .context("--since is too far back")?; let rfc3339 = |t: DateTime| t.to_rfc3339_opts(SecondsFormat::Secs, true); - Ok(Window { since: rfc3339(start), until: rfc3339(end), limit: flags.limit as usize }) + Ok(Window { + since: rfc3339(start), + until: rfc3339(end), + limit: flags.limit as usize, + sample_rate: flags.sample_rate, + }) } /// The selected datasets that run online, as a new run's datasets. @@ -156,12 +161,16 @@ fn execute_run( run_flags: &RunFlags, ) -> Result<(Run, Manifest)> { report::phase("execute"); - detail!("{} -> {}, up to {} per dataset", window.since, window.until, window.limit); + let sampled = if window.sample_rate < 1.0 { + format!(", sample rate {}", window.sample_rate) + } else { + String::new() + }; + detail!("{} -> {}, up to {} per dataset{sampled}", window.since, window.until, window.limit); let outputs = engine.execute_online(&mut datasets, &window)?; let m = Manifest { online: true, window: Some(window), - variant: run_flags.variant.clone(), metadata: run_flags.meta.iter().cloned().collect(), datasets, ..Default::default() diff --git a/core/src/eac/config/dataset_yml.rs b/core/src/eac/config/dataset_yml.rs index 32bf01b..fd17f84 100644 --- a/core/src/eac/config/dataset_yml.rs +++ b/core/src/eac/config/dataset_yml.rs @@ -17,9 +17,9 @@ pub struct DatasetConfig { /// The dataset.yml, relative to root. #[serde(skip)] pub file: String, - /// The production agent it exercises, for trace attribution. + /// Anything to record in its results. #[serde(default)] - pub agent: Option, + pub metadata: Object, /// The SDK worker that runs it, one of RUNTIMES. pub runtime: String, #[serde(default)] @@ -37,8 +37,6 @@ pub struct OfflineConfig { pub runner: String, /// The sequence of Cases, as a code reference. pub cases: String, - #[serde(default)] - pub shard_config: Sharding, /// How many cases run at once, each on its own worker. #[serde(default = "default_concurrency")] pub concurrency: usize, @@ -92,27 +90,6 @@ pub struct ComparisonArm { pub args: Object, } -/// How CI splits a full run: ceil(cases / cases_per_shard) shards, at least -/// one and at most max_shards. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] -#[serde(default, deny_unknown_fields)] -pub struct Sharding { - pub cases_per_shard: usize, - pub max_shards: usize, -} - -impl Default for Sharding { - fn default() -> Self { - Sharding { cases_per_shard: 20, max_shards: 8 } - } -} - -impl Sharding { - pub fn shard_count(&self, cases: usize) -> usize { - cases.div_ceil(self.cases_per_shard.max(1)).clamp(1, self.max_shards.max(1)) - } -} - impl DatasetConfig { /// Reads and checks the dataset.yml at path. Its ./file references are /// relative to its folder, and are made relative to root, where workers diff --git a/core/src/eac/config/mod.rs b/core/src/eac/config/mod.rs index 78908e9..a23cede 100644 --- a/core/src/eac/config/mod.rs +++ b/core/src/eac/config/mod.rs @@ -250,7 +250,6 @@ fn read_saved_credentials(path: &Path) -> Result> { mod tests { use std::os::unix::fs::PermissionsExt; - use super::dataset_yml::Sharding; use super::*; fn write(path: &Path, text: &str) { @@ -277,12 +276,11 @@ mod tests { const CHAT: &str = " name: chat -agent: chat_agent +metadata: {team: chat} runtime: python offline: runner: ./runner.py:Runner cases: evals.chat.cases:CASES - shard_config: {cases_per_shard: 2} concurrency: 4 comparisons: - name: models @@ -304,13 +302,12 @@ online: let cfg = load("", &[(FILE, CHAT)]).unwrap(); let d = &cfg.datasets[0]; assert_eq!((d.name.as_str(), d.file.as_str()), ("chat", "evals/chat/dataset.yml")); - assert_eq!(d.agent.as_deref(), Some("chat_agent")); + assert_eq!(d.metadata["team"], "chat"); let (offline, online) = (d.offline.as_ref().unwrap(), d.online.as_ref().unwrap()); // ./ references are relative to the dataset.yml, and become relative // to the project root, where workers run. assert_eq!(offline.runner, "./evals/chat/runner.py:Runner"); assert_eq!(offline.cases, "evals.chat.cases:CASES"); - assert_eq!(offline.shard_config, Sharding { cases_per_shard: 2, max_shards: 8 }); assert_eq!(offline.concurrency, 4); // A section that doesn't say runs one case at a time. assert_eq!(online.concurrency, 1); @@ -392,7 +389,7 @@ online: bad("./runner.py:Runner", "./missing.py:Runner").contains("missing.py doesn't exist") ); assert!(bad("./runner.py:Runner", "../../../outside.py:Runner").contains("doesn't exist")); - assert!(bad(" shard_config:", " sandbox: true\n shard_config:") + assert!(bad(" concurrency: 4", " sandbox: true\n concurrency: 4") .contains("unknown field `sandbox`")); assert!(bad(" concurrency: 4", " concurrency: 0") .contains("offline.concurrency: must be at least 1")); @@ -410,7 +407,7 @@ online: // Judges are only defined per dataset, and run in its worker. assert!(err("online:\n judges: []\n", &[(FILE, CHAT)]).contains("unknown field `online`")); assert!(bad("Polite\"}", "Polite\", runtime: python}").contains("unknown field `runtime`")); - assert!(bad(" shard_config:", " agent_trace_provider: []\n shard_config:") + assert!(bad(" concurrency: 4", " agent_trace_provider: []\n concurrency: 4") .contains("unknown field `agent_trace_provider`")); } diff --git a/core/src/eac/phases/credentials.rs b/core/src/eac/phases/credentials.rs index bc38c44..f0e3e05 100644 --- a/core/src/eac/phases/credentials.rs +++ b/core/src/eac/phases/credentials.rs @@ -24,14 +24,6 @@ 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); -/// Whether to log in to the credentials that aren't set up. -#[derive(Clone, Copy, PartialEq, Eq)] -enum Login { - /// Only on a terminal, after asking. - Ask, - Always, -} - 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 @@ -41,7 +33,7 @@ impl Engine { if in_ci() { return Ok(()); } - self.ensure(needed(datasets, phases), Login::Ask) + self.ensure(needed(datasets, phases)) } /// Checks what tearing down the seeds needs. @@ -56,23 +48,12 @@ impl Engine { for e in entries { add(&mut needed, &e.runtime, &e.seed.credentials); } - self.ensure(needed, Login::Ask) - } - - /// Checks everything the datasets need in any phase, and logs in to the - /// credentials that aren't set up without asking. - pub fn set_up_credentials(&mut self, datasets: &[Dataset]) -> Result<()> { - let needed = needed(datasets, ALL_PHASES); - if needed.is_empty() { - info!("no dataset needs credentials"); - return Ok(()); - } - self.ensure(needed, Login::Always) + self.ensure(needed) } - /// Checks each credential and logs in to the ones that aren't set up as - /// `login` allows. Fails listing the ones that still aren't. - fn ensure(&mut self, needed: Vec, login: Login) -> Result<()> { + /// 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) -> Result<()> { if needed.is_empty() { return Ok(()); } @@ -89,9 +70,7 @@ impl Engine { if ok { continue; } - let log_in = !c.manual - && (login == Login::Always - || (on_terminal() && confirm(&format!("Set up {} now?", c.name))?)); + let log_in = !c.manual && on_terminal() && confirm(&format!("Set up {} now?", c.name))?; check_interrupted()?; if !log_in { failures.push(failure(&c, "missing or invalid")); diff --git a/core/src/eac/phases/discover.rs b/core/src/eac/phases/discover.rs index 80679cf..55d35fb 100644 --- a/core/src/eac/phases/discover.rs +++ b/core/src/eac/phases/discover.rs @@ -25,7 +25,7 @@ impl Discovered { code: self.config.code(mode), runtime: self.config.runtime.clone(), name: self.config.name.clone(), - agent: self.config.agent.clone(), + metadata: self.config.metadata.clone(), args: Object::new(), judges: vec![], judge_args: Object::new(), diff --git a/core/src/eac/phases/execute.rs b/core/src/eac/phases/execute.rs index 7601535..79314bb 100644 --- a/core/src/eac/phases/execute.rs +++ b/core/src/eac/phases/execute.rs @@ -5,10 +5,10 @@ use anyhow::{Context, Result}; use chrono::Utc; use super::seed::handles_for; -use crate::eac::{Dataset, Engine, Manifest, Output, Run, Seeds, Window}; +use crate::eac::{Dataset, Engine, Manifest, Output, Run, Seeds}; use crate::report::first_line; use crate::schema::{ - Case, CaseRunParams, CaseRunResult, Handle, OnlineExecuteParams, OnlineExecuteResult, + Case, CaseRunParams, CaseRunResult, Handle, OnlineExecuteParams, OnlineExecuteResult, Window, }; use crate::worker::{each, Interrupted, Worker}; @@ -35,13 +35,7 @@ impl Engine { ) -> Result> { let mut outputs = Vec::new(); for d in datasets { - let params = OnlineExecuteParams { - dataset: &d.code, - since: &window.since, - until: &window.until, - limit: window.limit, - args: &d.args, - }; + let params = OnlineExecuteParams { dataset: &d.code, window, args: &d.args }; let res: OnlineExecuteResult = self .call(&d.runtime, "online.execute", params) .with_context(|| format!("executing {}", d.name))?; diff --git a/core/src/eac/phases/judge.rs b/core/src/eac/phases/judge.rs index 5409a96..23bae92 100644 --- a/core/src/eac/phases/judge.rs +++ b/core/src/eac/phases/judge.rs @@ -140,7 +140,6 @@ impl Judging<'_> { judges: &d.judges, judge_args: &d.judge_args, trace: saved_trace, - agent: d.agent.as_deref(), }; return worker.call("online.judge", params); } @@ -152,7 +151,6 @@ impl Judging<'_> { seeds: handles_for(self.seeds, d, c, false)?, judge_args: &d.judge_args, trace: saved_trace, - agent: d.agent.as_deref(), started_at: out.started_at, ended_at: out.ended_at, }; diff --git a/core/src/eac/run/manifest.rs b/core/src/eac/run/manifest.rs index c9a3d7b..efb9854 100644 --- a/core/src/eac/run/manifest.rs +++ b/core/src/eac/run/manifest.rs @@ -6,8 +6,8 @@ use chrono::{DateTime, Utc}; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use crate::eac::{Shard, Source}; -use crate::schema::{nullable, Case, Credential, DatasetRef, Mode, Object}; +use crate::eac::Source; +use crate::schema::{nullable, Case, Credential, DatasetRef, Mode, Object, Window}; #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] pub struct Manifest { @@ -19,13 +19,8 @@ pub struct Manifest { pub online: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub window: Option, - /// Distinguishes runs of the same dataset at the same commit. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub variant: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub comparison: Option, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub shard: Option, /// From --meta, passed through to results. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub metadata: BTreeMap, @@ -45,14 +40,6 @@ impl Manifest { } } -/// The window of production runs an online run collected. -#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] -pub struct Window { - pub since: String, - pub until: String, - pub limit: usize, -} - /// Which comparison arm a run is. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct ArmRef { @@ -66,8 +53,8 @@ pub struct Dataset { pub code: DatasetRef, pub runtime: String, pub name: String, - #[serde(default, skip_serializing_if = "Option::is_none")] - pub agent: Option, + #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Object::is_empty")] + pub metadata: Object, /// --args, as given. #[serde(default, deserialize_with = "nullable", skip_serializing_if = "Object::is_empty")] pub args: Object, diff --git a/core/src/eac/run/results.rs b/core/src/eac/run/results.rs index dda27e6..bde0cd3 100644 --- a/core/src/eac/run/results.rs +++ b/core/src/eac/run/results.rs @@ -11,11 +11,11 @@ use serde_json::{json, Value}; use super::cases::{Output, Scored, Status}; use super::manifest::{Dataset, Manifest}; use crate::eac::Source; -use crate::schema::{schema_settings, Case, Metrics, Object, Score}; +use crate::schema::{schema_settings, Case, Metrics, Object, Score, Window}; /// The results format's version. Bump it on any change a reader could trip /// over, like a removed or renamed field or a new status. -pub const RESULTS_VERSION: u32 = 2; +pub const RESULTS_VERSION: u32 = 3; /// The results of judging one dataset in one run, saved as /// results/.json in the run's directory. @@ -25,19 +25,51 @@ pub struct RunResult { /// The version of this format. Changes that could break a reader bump it. #[schemars(extend("const" = RESULTS_VERSION))] pub schema_version: u32, + pub run_id: String, pub dataset_name: String, /// When the run started. pub created_at: DateTime, + pub args: Args, /// Every case judged, in the dataset's order. pub cases: Vec, /// How long judging the dataset took. pub duration_seconds: f64, - /// What sets this run apart from others of the same dataset, like the - /// variant, args and --meta values. + /// The dataset.yml's `metadata`, with the run's --meta values over it. pub metadata: Object, pub source: Source, } +/// What the run was asked to do. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(tag = "mode", rename_all = "lowercase")] +pub enum Args { + Offline(OfflineArgs), + Online(OnlineArgs), +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct OfflineArgs { + /// --args. + pub runner_args: Object, + /// A comparison's judges, replaces each case's defined judges. + pub judges: Vec, + /// --judge-args. + pub judge_args: Object, + pub comparison: Option, + pub arm: Option, +} + +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct OnlineArgs { + /// --args. + pub runner_args: Object, + /// --judge. + pub judges: Vec, + /// --judge-args. + pub judge_args: Object, + pub window: Window, +} + /// One case: what the runner returned and how the judges scored it. #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] pub struct CaseResult { @@ -108,54 +140,38 @@ pub fn run_result( ) -> RunResult { RunResult { schema_version: RESULTS_VERSION, + run_id: m.id.clone(), dataset_name: d.name.clone(), created_at: m.created_at, + args: run_args(m, d), + cases, duration_seconds, metadata: metadata(m, d), source: m.source.clone(), - cases, } } -/// What distinguishes this run from others of the same dataset, using seer's -/// metadata keys where it has them. Where the run came from is in `source`. fn metadata(m: &Manifest, d: &Dataset) -> Object { - let mut meta = Object::new(); - let mut put = |key: &str, value: Value| { - if !value.is_null() { - meta.insert(key.to_string(), value); + let mut metadata = d.metadata.clone(); + metadata.extend(m.metadata.iter().map(|(key, value)| (key.clone(), json!(value)))); + metadata +} + +fn run_args(m: &Manifest, d: &Dataset) -> Args { + let (runner_args, judges, judge_args) = + (d.args.clone(), d.judges.clone(), d.judge_args.clone()); + match &m.window { + Some(window) => { + Args::Online(OnlineArgs { runner_args, judges, judge_args, window: window.clone() }) } - }; - put("run_id", json!(m.id)); - put("variant", json!(m.variant)); - if let Some(arm) = &m.comparison { - put("comparison", json!(arm.comparison)); - put("arm", json!(arm.arm)); - } - if let Some(shard) = &m.shard { - put("shard_index", json!(shard.index)); - put("shard_count", json!(shard.count)); - } - if let Some(window) = &m.window { - put("online", json!(true)); - put("window_since", json!(window.since)); - put("window_until", json!(window.until)); - put("limit", json!(window.limit)); - } - put("agent", json!(d.agent)); - if !d.args.is_empty() { - put("args", Value::Object(d.args.clone())); - } - if !d.judges.is_empty() { - put("judges", json!(d.judges)); - } - if !d.judge_args.is_empty() { - put("judge_args", Value::Object(d.judge_args.clone())); - } - for (key, value) in &m.metadata { - put(key, json!(value)); + None => Args::Offline(OfflineArgs { + runner_args, + judges, + judge_args, + comparison: m.comparison.as_ref().map(|c| c.comparison.clone()), + arm: m.comparison.as_ref().map(|c| c.arm.clone()), + }), } - meta } /// The JSON Schema of results/.json, as eac writes it. diff --git a/core/src/eac/select.rs b/core/src/eac/select.rs index 9943bf8..067cd1a 100644 --- a/core/src/eac/select.rs +++ b/core/src/eac/select.rs @@ -1,82 +1,49 @@ use std::collections::BTreeSet; use anyhow::{bail, Result}; -use schemars::JsonSchema; -use serde::{Deserialize, Serialize}; use super::{Dataset, Discovered}; use crate::report::join_or_none; use crate::schema::{Case, Mode}; -/// Which offline cases a command runs, from --case, --split and the shard flags. +/// Which offline cases a command runs, from --case and --split. #[derive(Clone, Debug, Default)] pub struct Selection { pub cases: Vec, pub splits: Vec, - pub shard: Option, -} - -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] -pub struct Shard { - pub index: usize, - /// Overrides each dataset's planned shard count. - #[serde(default, skip_serializing_if = "Option::is_none")] - pub count: Option, } /// Picks each offline dataset's cases named by --case, or all of them, then /// filters by --split. A bare run skips disabled cases, but naming a case or -/// one of its splits opts it in. A shard takes every count-th case, except -/// that an explicit --case list is never sharded. +/// one of its splits opts it in. pub fn select(found: &[Discovered], sel: &Selection) -> Result> { - let offline: Vec<_> = - found.iter().filter_map(|d| Some((d, d.config.offline.as_ref()?))).collect(); + let offline: Vec<&Discovered> = found.iter().filter(|d| d.config.offline.is_some()).collect(); if offline.is_empty() { bail!("no selected dataset has offline cases"); } - let cases = || offline.iter().flat_map(|(d, _)| &d.cases); + let cases = || offline.iter().flat_map(|d| &d.cases); let known_cases: BTreeSet<&str> = cases().map(|c| c.name.as_str()).collect(); let known_splits: BTreeSet<&str> = cases().flat_map(|c| &c.splits).map(String::as_str).collect(); check_known("case", &sel.cases, &known_cases)?; check_known("split", &sel.splits, &known_splits)?; - let shard = sel.shard.filter(|_| sel.cases.is_empty()); - if let Some(Shard { index, count: Some(count) }) = shard { - if count == 0 || index >= count { - bail!("--shard-index {index} is out of range for {count} shards"); - } - } let explicit = !sel.cases.is_empty() || !sel.splits.is_empty(); let mut out = Vec::new(); - let mut most_shards = 0; - for (d, o) in offline { + for d in offline { let picked: Vec = (d.cases.iter()) .filter(|c| sel.cases.is_empty() || sel.cases.contains(&c.name)) .filter(|c| sel.splits.is_empty() || c.splits.iter().any(|s| sel.splits.contains(s))) .filter(|c| c.enabled || explicit) .cloned() .collect(); - let picked = match shard { - Some(s) => { - let count = s.count.unwrap_or_else(|| o.shard_config.shard_count(picked.len())); - most_shards = most_shards.max(count); - picked.into_iter().skip(s.index).step_by(count).collect() - } - None => picked, - }; if !picked.is_empty() { out.push(d.to_dataset(Mode::Offline, picked)); } } - if let Some(Shard { index, count: None }) = shard { - if index >= most_shards { - bail!("--shard-index {index} is out of range: these cases plan {most_shards} shards"); - } - } if out.is_empty() { bail!("no cases matched"); } @@ -106,12 +73,9 @@ mod tests { } } - fn found(cases: Vec, cases_per_shard: usize) -> Vec { - let yaml = format!( - "{{name: chat, runtime: python, offline: {{runner: 'evals.chat:Runner', cases: 'evals.chat:CASES', \ - shard_config: {{cases_per_shard: {cases_per_shard}}}}}}}" - ); - let config: DatasetConfig = serde_yaml::from_str(&yaml).unwrap(); + fn found(cases: Vec) -> Vec { + let yaml = "{name: chat, runtime: python, offline: {runner: 'evals.chat:Runner', cases: 'evals.chat:CASES'}}"; + let config: DatasetConfig = serde_yaml::from_str(yaml).unwrap(); vec![Discovered { config, cases }] } @@ -125,10 +89,11 @@ mod tests { #[test] fn disabled_cases_need_opting_in() { - let f = found( - vec![case("a", &["smoke"], true), case("b", &["smoke"], false), case("c", &[], true)], - 20, - ); + let f = found(vec![ + case("a", &["smoke"], true), + case("b", &["smoke"], false), + case("c", &[], true), + ]); assert_eq!(names(&f, Selection::default()), ["a", "c"]); assert_eq!( names(&f, Selection { splits: strings(&["smoke"]), ..Default::default() }), @@ -139,32 +104,10 @@ mod tests { #[test] fn cases_and_splits_intersect() { - let f = found(vec![case("a", &["smoke"], true), case("c", &["slow"], true)], 20); - let both = |cases, splits| Selection { - cases: strings(cases), - splits: strings(splits), - shard: None, - }; + let f = found(vec![case("a", &["smoke"], true), case("c", &["slow"], true)]); + let both = |cases, splits| Selection { cases: strings(cases), splits: strings(splits) }; assert_eq!(names(&f, both(&["a"], &["smoke"])), ["a"]); assert!(select(&f, &both(&["a"], &["slow"])).is_err()); assert!(select(&f, &both(&["smoke"], &[])).is_err(), "a split is not a case"); } - - #[test] - fn shards_round_robin_by_planned_count() { - let f = found((0..5).map(|i| case(&format!("c{i}"), &[], true)).collect(), 2); - let shard = - |index, count| Selection { shard: Some(Shard { index, count }), ..Default::default() }; - // 5 cases at 2 per shard plan 3 shards. - assert_eq!(names(&f, shard(0, None)), ["c0", "c3"]); - assert_eq!(names(&f, shard(2, None)), ["c2"]); - assert!(select(&f, &shard(3, None)).is_err()); - assert_eq!(names(&f, shard(1, Some(2))), ["c1", "c3"]); - let explicit = Selection { - cases: strings(&["c4"]), - shard: Some(Shard { index: 1, count: None }), - ..Default::default() - }; - assert_eq!(names(&f, explicit), ["c4"]); - } } diff --git a/core/src/schema/protocol.schema.json b/core/src/schema/protocol.schema.json index 257f951..5471ad1 100644 --- a/core/src/schema/protocol.schema.json +++ b/core/src/schema/protocol.schema.json @@ -116,13 +116,6 @@ }, "CaseJudgeParams": { "properties": { - "agent": { - "description": "The agent named in dataset.yml.", - "type": [ - "string", - "null" - ] - }, "case": { "$ref": "#/$defs/Case", "description": "With the runner's `output` and `conversation_id`." @@ -490,22 +483,13 @@ "dataset": { "$ref": "#/$defs/DatasetRef" }, - "limit": { - "type": "integer" - }, - "since": { - "description": "RFC 3339. Return runs from since up to, but not including, until.", - "type": "string" - }, - "until": { - "type": "string" + "window": { + "$ref": "#/$defs/Window" } }, "required": [ "dataset", - "since", - "until", - "limit" + "window" ], "type": "object" }, @@ -523,12 +507,6 @@ }, "OnlineJudgeParams": { "properties": { - "agent": { - "type": [ - "string", - "null" - ] - }, "case": { "$ref": "#/$defs/Case", "description": "A collected case, with its `output` and `conversation_id`." @@ -729,6 +707,33 @@ ], "type": "object" }, + "Window": { + "description": "The params to select cases from production", + "properties": { + "limit": { + "type": "integer" + }, + "sample_rate": { + "description": "The fraction of runs to collect, picked by a hash of each run's id.", + "type": "number" + }, + "since": { + "format": "date-time", + "type": "string" + }, + "until": { + "format": "date-time", + "type": "string" + } + }, + "required": [ + "since", + "until", + "limit", + "sample_rate" + ], + "type": "object" + }, "WorkerMethods": { "additionalProperties": false, "description": "The methods an SDK worker answers.", diff --git a/core/src/schema/types.rs b/core/src/schema/types.rs index f509253..1cd3504 100644 --- a/core/src/schema/types.rs +++ b/core/src/schema/types.rs @@ -145,6 +145,23 @@ pub struct Metrics { pub cost_usd: f64, } +/// The params to select cases from production +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct Window { + #[schemars(extend("format" = "date-time"))] + pub since: String, + #[schemars(extend("format" = "date-time"))] + pub until: String, + pub limit: usize, + /// The fraction of runs to collect, picked by a hash of each run's id. + #[serde(default = "full_sample")] + pub sample_rate: f64, +} + +fn full_sample() -> f64 { + 1.0 +} + /// A code reference, either `module.path:attr` or `./file.py:attr` relative /// to the project root. pub type CodeRef = String; diff --git a/core/src/schema/worker_methods.rs b/core/src/schema/worker_methods.rs index 1d3d927..752ef9a 100644 --- a/core/src/schema/worker_methods.rs +++ b/core/src/schema/worker_methods.rs @@ -9,7 +9,7 @@ use serde_json::Value; use super::fields::{no_object, no_strings, nullable}; use super::types::{ - Case, Credential, DatasetRef, Handle, HandleSchema, Metrics, Mode, Object, Score, Seed, + Case, Credential, DatasetRef, Handle, HandleSchema, Metrics, Mode, Object, Score, Seed, Window, }; #[derive(Serialize, JsonSchema)] @@ -149,9 +149,6 @@ pub struct CaseJudgeParams<'a> { /// may fetch it by the case's conversation_id. #[serde(skip_serializing_if = "Option::is_none")] pub trace: Option<&'a Value>, - /// The agent named in dataset.yml. - #[serde(skip_serializing_if = "Option::is_none")] - pub agent: Option<&'a str>, /// When the runner started. #[serde(skip_serializing_if = "Option::is_none")] pub started_at: Option>, @@ -177,10 +174,7 @@ pub struct CaseJudgeResult { #[derive(Serialize, JsonSchema)] pub struct OnlineExecuteParams<'a> { pub dataset: &'a DatasetRef, - /// RFC 3339. Return runs from since up to, but not including, until. - pub since: &'a str, - pub until: &'a str, - pub limit: usize, + pub window: &'a Window, #[serde(skip_serializing_if = "no_object")] pub args: &'a Object, } @@ -206,6 +200,4 @@ pub struct OnlineJudgeParams<'a> { /// As in case.judge. The case's conversation_id identifies the trace. #[serde(skip_serializing_if = "Option::is_none")] pub trace: Option<&'a Value>, - #[serde(skip_serializing_if = "Option::is_none")] - pub agent: Option<&'a str>, } diff --git a/core/tests/cli.rs b/core/tests/cli.rs index a9223a4..57bdc73 100644 --- a/core/tests/cli.rs +++ b/core/tests/cli.rs @@ -1,10 +1,14 @@ //! Runs the eac binary against tests/fixtures/project, whose stand-in worker //! logs every call it gets. -use std::fs; +use std::fs::{self, File}; +use std::io::{Read, Write}; +use std::os::fd::{AsRawFd, FromRawFd}; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; -use std::process::Command; +use std::process::{Command, Stdio}; +use std::time::Duration; +use std::{ptr, thread}; use serde_json::{json, Value}; @@ -76,7 +80,61 @@ impl Project { /// Runs eac in dir with env set on top of the tests' environment. fn eac_with(&self, dir: &str, env: &[(&str, &str)], args: &[&str]) -> Ran { - let out = Command::new(env!("CARGO_BIN_EXE_eac")) + let out = self.command(dir, env, args).output().unwrap(); + Ran { + code: out.status.code().unwrap_or(-1), + stdout: String::from_utf8_lossy(&out.stdout).into_owned(), + stderr: String::from_utf8_lossy(&out.stderr).into_owned(), + } + } + + /// Runs eac as someone at a terminal would, typing the next of `answers` + /// each time it asks a yes or no question. What eac shows on the terminal + /// comes back as stderr. + fn eac_on_terminal(&self, env: &[(&str, &str)], args: &[&str], answers: &[&str]) -> Ran { + let (mut terminal, tty) = pty(); + let mut child = self + .command(".", env, args) + .stdin(tty.try_clone().unwrap()) + .stderr(tty.try_clone().unwrap()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + // Reads as eac writes, so it never blocks on a full terminal. Holding + // tty open until eac exits keeps its last output from being dropped. + let mut shown = Vec::new(); + let mut chunk = [0; 4096]; + let mut answered = 0; + loop { + let exited = child.try_wait().unwrap().is_some(); + match terminal.read(&mut chunk) { + Ok(n) if n > 0 => shown.extend_from_slice(&chunk[..n]), + _ if exited => break, + _ => thread::sleep(Duration::from_millis(10)), + } + let asked = String::from_utf8_lossy(&shown).matches("[Y/n] ").count(); + if asked > answers.len() { + child.kill().unwrap(); + panic!("eac asked more than {answers:?}:\n{}", String::from_utf8_lossy(&shown)); + } + for answer in &answers[answered..asked] { + terminal.write_all(format!("{answer}\n").as_bytes()).unwrap(); + } + answered = asked; + } + drop(tty); + let mut stdout = String::new(); + child.stdout.take().unwrap().read_to_string(&mut stdout).unwrap(); + Ran { + code: child.wait().unwrap().code().unwrap_or(-1), + stdout, + stderr: String::from_utf8_lossy(&shown).replace("\r\n", "\n"), + } + } + + fn command(&self, dir: &str, env: &[(&str, &str)], args: &[&str]) -> Command { + let mut command = Command::new(env!("CARGO_BIN_EXE_eac")); + command .args(args) .current_dir(self.path(dir)) .env("NO_COLOR", "1") @@ -91,14 +149,8 @@ impl Project { .env_remove("TOKEN_B") .env_remove("TOKEN_C") .env_remove("TOKEN_REFUSED") - .envs(env.iter().copied()) - .output() - .unwrap(); - Ran { - code: out.status.code().unwrap_or(-1), - stdout: String::from_utf8_lossy(&out.stdout).into_owned(), - stderr: String::from_utf8_lossy(&out.stderr).into_owned(), - } + .envs(env.iter().copied()); + command } fn lines(&self, file: &str) -> Vec { @@ -145,6 +197,23 @@ fn copy_dir(from: &Path, to: &Path) { } } +/// A pseudo-terminal: the test reads and types on the first file, and eac +/// gets the second as its terminal. Reading the first never blocks. +fn pty() -> (File, File) { + let (mut terminal, mut tty) = (0, 0); + let opened = unsafe { + libc::openpty(&mut terminal, &mut tty, ptr::null_mut(), ptr::null_mut(), ptr::null_mut()) + }; + assert_eq!(opened, 0, "openpty: {}", std::io::Error::last_os_error()); + let (terminal, tty) = unsafe { (File::from_raw_fd(terminal), File::from_raw_fd(tty)) }; + let flags = unsafe { libc::fcntl(terminal.as_raw_fd(), libc::F_GETFL) }; + assert_ne!( + unsafe { libc::fcntl(terminal.as_raw_fd(), libc::F_SETFL, flags | libc::O_NONBLOCK) }, + -1 + ); + (terminal, tty) +} + fn names<'a>(values: &'a [Value], key: &str) -> Vec<&'a str> { values.iter().map(|v| v[key].as_str().unwrap()).collect() } @@ -173,9 +242,20 @@ fn run_writes_results_and_fails_on_a_wrong_case() { assert_eq!(greets["expected_output"], json!({"reply": "hello"})); assert_eq!(greets["attributes"], json!({"turns": 1, "splits": ["smoke"]})); assert!(greets["conversation_id"].as_str().unwrap().starts_with("eval-")); - assert!(results["metadata"].get("args").is_none(), "args are recorded as given, and none were"); - assert_eq!(results["metadata"]["agent"], "chat_agent"); - assert_eq!(results["schema_version"], 2); + assert_eq!(results["run_id"], id); + assert_eq!( + results["args"], + json!({ + "mode": "offline", + "runner_args": {}, + "judges": [], + "judge_args": {}, + "comparison": null, + "arm": null, + }) + ); + assert_eq!(results["metadata"], json!({"team": "chat", "tier": 1})); + assert_eq!(results["schema_version"], 3); assert_eq!(results["source"]["trigger"], "local"); assert!(results.get("summary").is_none(), "totals come from the cases"); @@ -245,7 +325,7 @@ fn prune_tears_down_cached_seeds_no_case_uses() { } #[test] -fn selection_checks_names_and_shards_round_robin() { +fn selection_checks_case_and_dataset_names() { let p = Project::new(&base()); let listed = p.eac(&["list", "--split", "smoke"]); listed.code(0).says("chat/greets [smoke]").says("chat/slow [smoke] (disabled)"); @@ -257,18 +337,12 @@ fn selection_checks_names_and_shards_round_robin() { p.eac(&["offline", "run", "--dataset", "nope"]) .code(2) .says("unknown offline dataset \"nope\"; try one of: chat"); - - // Two enabled cases at one per shard. - assert_eq!(p.eac(&["offline", "shards"]).stdout.trim(), "2"); - p.eac(&["offline", "run", "--shard-index", "1"]).code(1); - assert_eq!(case_names(&p.json(&p.latest().join("results/chat.json"))), ["wrong"]); - p.eac(&["offline", "run", "--shard-index", "2"]).code(2).says("out of range"); } #[test] fn concurrency_runs_cases_at_once_on_workers_of_their_own() { let p = Project::new(&base()); - p.edit("evals/dataset.yml", " shard_config:", " concurrency: 4\n shard_config:"); + p.edit("evals/dataset.yml", " comparisons:", " concurrency: 4\n comparisons:"); p.write("rendezvous", "2"); let ran = p.eac(&["offline", "run"]); ran.code(1).says("starting python worker 2"); @@ -321,16 +395,16 @@ fn invalid_args_fail_before_anything_is_set_up() { } #[test] -fn args_variant_and_metadata_reach_the_runner_and_results() { +fn args_and_metadata_reach_the_runner_and_results() { let p = Project::new(&base()); - let args = ["--args", r#"{"model": "big"}"#, "--variant", "v2", "--meta", "team=evals"]; + let args = ["--args", r#"{"model": "big"}"#, "--meta", "team=evals"]; p.eac(&[&["offline", "run", "--split", "smoke"][..], &args].concat()).code(0); assert!(p.events("run").iter().all(|e| e["args"] == json!({"model": "big"}))); - let meta = &p.json(&p.latest().join("results/chat.json"))["metadata"]; - assert_eq!(meta["variant"], "v2"); - assert_eq!(meta["team"], "evals"); - assert_eq!(meta["args"]["model"], "big"); + let results = p.json(&p.latest().join("results/chat.json")); + assert_eq!(results["args"]["runner_args"], json!({"model": "big"})); + // --meta goes over the dataset.yml's metadata. + assert_eq!(results["metadata"], json!({"team": "evals", "tier": 1})); } #[test] @@ -399,7 +473,6 @@ fn judges_fetch_traces_that_are_saved_for_judging_again() { // The judge got what it looks the trace up by, and fetched it. let judged = &p.events("judge")[0]; assert!(judged["conversation_id"].as_str().unwrap().starts_with("eval-")); - assert_eq!(judged["agent"], "chat_agent"); assert_eq!(judged["timed"], true); assert_eq!(judged["trace"]["spans"], 3); // eac saved it, and its metrics replace the runner's. @@ -443,9 +516,13 @@ fn compare_runs_each_arm_with_its_args() { let runs = p.runs(); assert_eq!(runs.len(), 2); let manifests: Vec = runs.iter().map(|r| p.json(&r.join("manifest.json"))).collect(); - assert_eq!(names(&manifests, "variant"), ["small", "big"]); + assert_eq!(manifests[0]["comparison"]["arm"], "small"); assert_eq!(manifests[1]["comparison"], json!({"comparison": "models", "arm": "big"})); assert_eq!(manifests[1]["datasets"][0]["args"], json!({"model": "big"})); + let args = &p.json(&runs[1].join("results/chat.json"))["args"]; + assert_eq!(args["comparison"], "models"); + assert_eq!(args["arm"], "big"); + assert_eq!(args["runner_args"], json!({"model": "big"})); // The cached seed was set up once and shared by both arms. assert_eq!(p.events("seed_setup").len(), 1); // The comparison names no judges, so each case keeps its own. @@ -515,16 +592,30 @@ fn online_run_fetches_the_window_with_judge_args() { assert_eq!(fetched["since"], "2026-10-31T10:00:00Z"); assert_eq!(fetched["until"], "2026-10-31T12:00:00Z"); assert_eq!(fetched["limit"], 5); + assert_eq!(fetched["sample_rate"], 1.0); assert_eq!(fetched["args"], json!({})); assert!(p .events("online_judge") .iter() - .all(|e| e["judge_args"] == json!({"polite": {"strict": true}}) - && e["agent"] == "chat_agent")); + .all(|e| e["judge_args"] == json!({"polite": {"strict": true}}))); let results = p.json(&p.latest().join("results/chat.json")); assert_eq!(case_names(&results), ["trace_0", "trace_1"]); - assert_eq!(results["metadata"]["online"], true); + assert_eq!( + results["args"], + json!({ + "mode": "online", + "runner_args": {}, + "judges": ["nonempty", "polite"], + "judge_args": {"polite": {"strict": true}}, + "window": { + "since": "2026-10-31T10:00:00Z", + "until": "2026-10-31T12:00:00Z", + "limit": 5, + "sample_rate": 1.0, + }, + }) + ); // Only conv-0 has a trace. assert_eq!(results["cases"][0]["otel_metrics"]["total_tokens"], 99.0); assert_eq!(results["cases"][1]["otel_metrics"]["total_tokens"], 0.0); @@ -532,6 +623,26 @@ fn online_run_fetches_the_window_with_judge_args() { p.eac(&["online", "run", "--judge", "rude"]).code(2).says("has no online judge rude"); } +#[test] +fn online_runs_ask_for_a_sample_and_record_its_rate() { + let p = Project::new(&base()); + let executed = p.eac(&["online", "execute", "--sample-rate", "0.25"]); + executed.code(0).says("sample rate 0.25"); + assert_eq!(p.events("collect")[0]["sample_rate"], 0.25); + + let id = executed.stdout.trim().to_string(); + p.eac(&["online", "judge", "--run", &id, "--judge", "nonempty"]).code(0); + let results = p.json(&p.latest().join("results/chat.json")); + assert_eq!(results["args"]["window"]["sample_rate"], 0.25); + + for bad in ["0", "1.5", "-1", "half"] { + p.eac(&["online", "run", "--judge", "nonempty", "--sample-rate", bad]) + .code(2) + .says("expected a fraction more than 0 and at most 1"); + } + assert_eq!(p.events("collect").len(), 1); +} + #[test] fn online_runs_can_execute_then_judge() { let p = Project::new(&base()); @@ -580,20 +691,6 @@ fn datasets_are_picked_by_name_or_the_directory_eac_runs_in() { p.eac(&["list", "--dataset", "nope"]) .code(2) .says("unknown dataset \"nope\"; try one of: chat, more"); - - let ran = p.eac(&["catalog"]); - ran.code(0); - let catalog: Value = serde_json::from_str(&ran.stdout).unwrap(); - let entries = catalog.as_array().unwrap(); - assert_eq!(names(entries, "name"), ["chat", "more"]); - assert_eq!(names(entries, "file"), ["evals/dataset.yml", "more/dataset.yml"]); - let chat = &entries[0]; - assert_eq!(chat["offline"]["splits"], json!(["hard", "smoke"])); - assert_eq!(chat["offline"]["comparisons"][1]["judges"], json!(["matches"])); - assert_eq!(chat["offline"]["shard_count"], 2); - assert_eq!(chat["offline"]["agent"], "chat_agent"); - assert_eq!(chat["online"]["judges"], json!(["nonempty", "polite"])); - assert!(entries[1]["online"].is_null()); } #[test] @@ -642,13 +739,17 @@ fn credentials_arent_checked_in_ci() { } #[test] -fn auth_saves_logins_for_later_commands() { +fn logins_on_a_terminal_are_saved_for_later_commands() { let p = Project::new(&base()); p.write("needs.json", r#"{"seed": ["TOKEN_A"], "runner": ["TOKEN_C"], "judge": ["TOKEN_B"]}"#); p.write(".env", "# kept\nTOKEN_B=stale\n"); - // A stale TOKEN_A in the environment loses to the one login saves. - let ran = p.eac_with(".", &[("TOKEN_A", "stale")], &["auth"]); + // Before seeding, eac offers to log in to everything the run needs, and + // Enter means yes. A stale TOKEN_A in the environment loses to the one + // login saves. + let args = ["offline", "run", "--split", "smoke"]; + let ran = p.eac_on_terminal(&[("TOKEN_A", "stale")], &args, &["", "", ""]); ran.code(0) + .says("Set up token_a now? [Y/n]") .says("✓ token_c") .says("saved TOKEN_A, TOKEN_B, TOKEN_C to .eac/credentials/saved.json"); // Login runs on the terminal, so its output isn't indented like a log. @@ -674,7 +775,14 @@ fn auth_saves_logins_for_later_commands() { fn a_failed_login_says_how_to_set_up_by_hand() { let p = Project::new(&base()); p.write("needs.json", r#"{"runner": ["TOKEN_REFUSED", "TOKEN_MANUAL"]}"#); - p.eac(&["auth"]) + let args = ["offline", "run", "--split", "smoke"]; + // Saying no leaves it to be set up by hand. + p.eac_on_terminal(&[], &args, &["n"]).code(2).says("token_refused: missing or invalid"); + assert!(p.events("credentials_login").is_empty()); + // Off a terminal, eac doesn't ask. + p.eac(&args).code(2).says("token_refused: missing or invalid"); + + p.eac_on_terminal(&[], &args, &["y"]) .code(2) .says("token_refused: RuntimeError: the login was refused\n Set TOKEN_REFUSED.") .says("token_manual: missing or invalid\n Set TOKEN_MANUAL."); diff --git a/core/tests/fixtures/project/eac/worker.py b/core/tests/fixtures/project/eac/worker.py index 1111046..17d87bf 100644 --- a/core/tests/fixtures/project/eac/worker.py +++ b/core/tests/fixtures/project/eac/worker.py @@ -62,14 +62,15 @@ def handle(method, p): return ds.run_case(p["case"], p.get("seeds", {}), p.get("args", {}), p["conversation_id"]) if method == "case.judge": case = p["case"] - run = {k: p[k] for k in ("agent", "started_at", "ended_at") if k in p} + run = {k: p[k] for k in ("started_at", "ended_at") if k in p} if "conversation_id" in case: run["conversation_id"] = case["conversation_id"] return ds.judge(case, case.get("output"), p.get("judges", []), p.get("seeds", {}), p.get("trace"), run) if method == "online.execute": - return {"cases": ds.collect(p["since"], p["until"], p["limit"], p.get("args", {}))} + w = p["window"] + return {"cases": ds.collect(w["since"], w["until"], w["limit"], w["sample_rate"], p.get("args", {}))} if method == "online.judge": - return ds.online_judge(p["case"], p["judges"], p.get("judge_args", {}), p.get("trace"), p.get("agent")) + return ds.online_judge(p["case"], p["judges"], p.get("judge_args", {}), p.get("trace")) raise ValueError(f"unknown method {method!r}") diff --git a/core/tests/fixtures/project/evals/chat_eval.py b/core/tests/fixtures/project/evals/chat_eval.py index 6464fd8..140efd3 100644 --- a/core/tests/fixtures/project/evals/chat_eval.py +++ b/core/tests/fixtures/project/evals/chat_eval.py @@ -175,7 +175,6 @@ def judge(case, output, judges, seeds, trace, run): seeds=sorted(seeds), trace=trace, conversation_id=run.get("conversation_id"), - agent=run.get("agent"), timed="started_at" in run and "ended_at" in run, together=together("judge", case["name"]), ) @@ -192,8 +191,8 @@ def judge(case, output, judges, seeds, trace, run): return {"scores": scores, **(fetched or {})} -def collect(since, until, limit, args): - log("collect", since=since, until=until, limit=limit, args=args) +def collect(since, until, limit, sample_rate, args): + log("collect", since=since, until=until, limit=limit, sample_rate=sample_rate, args=args) cases = [ {"name": "trace_0", "conversation_id": "conv-0", "input": {"q": "hi"}, "output": {"reply": "thanks!"}}, {"name": "trace_1", "conversation_id": "conv-1", "input": {"q": "hey"}, "output": {"reply": ""}}, @@ -201,14 +200,13 @@ def collect(since, until, limit, args): return cases[:limit] -def online_judge(case, judges, judge_args, trace, agent): +def online_judge(case, judges, judge_args, trace): fetched = fetch_trace(case.get("conversation_id")) if trace is None else None log( "online_judge", case=case["name"], judges=judges, judge_args=judge_args, - agent=agent, together=together("online_judge", case["name"]), ) reply = (case.get("output") or {}).get("reply", "") diff --git a/core/tests/fixtures/project/evals/dataset.yml b/core/tests/fixtures/project/evals/dataset.yml index 9b775f5..1f7d458 100644 --- a/core/tests/fixtures/project/evals/dataset.yml +++ b/core/tests/fixtures/project/evals/dataset.yml @@ -1,11 +1,10 @@ name: chat -agent: chat_agent +metadata: {team: chat, tier: 1} runtime: python offline: runner: ./chat_eval.py:Runner cases: ./chat_eval.py:CASES - shard_config: {cases_per_shard: 1, max_shards: 4} comparisons: - name: models arms: diff --git a/docs/README.md b/docs/README.md index b5e9394..e3b925c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -3,16 +3,13 @@ eac docs - a Next.js app with pages written in MDX and styled with [`@sentry/scraps`](https://www.npmjs.com/package/@sentry/scraps). ```sh -pnpm install -pnpm dev # http://localhost:3000 -pnpm build +make docs # (from root of repo) + +# Other commands pnpm lint # ESLint, failing on any warning pnpm typecheck # TypeScript ``` -CI runs `pnpm lint` and `pnpm typecheck` on pull requests that change -`docs/` (`.github/workflows/docs.yml`). - ## Landing page `/` is a full-width landing page (`app/page.tsx`, `components/landing.tsx`) with @@ -48,17 +45,3 @@ The dropdown at the top of the sidebar picks the SDK language, and pages show co `` shows the sample whose label matches the selected language. For a sample whose label doesn't say the language, like a shell command, wrap it in `` or give its `` a `lang`. When a language has no sample yet, the first one shows with a note. `` also works on its own, for examples that only apply to some languages. - -## Light and dark - -The switcher in the header toggles Scraps' `lightTheme` and `darkTheme` -(`components/themeContext.tsx`). Until a reader picks one, the site follows -their OS. The choice is kept in a cookie that `app/layout.tsx` reads, so the -server renders the right theme and there's no flash of the wrong one. Reading -the cookie makes pages render per request rather than at build time. - -## Version - -The version in the header comes from `VERSION` at the repo root, which -`next.config.ts` reads at build time. Run `make version` from the root after -changing it, so the CLI and SDKs match. diff --git a/docs/app/cases-and-runners/page.mdx b/docs/app/cases-and-runners/page.mdx index b8d28cc..a28176c 100644 --- a/docs/app/cases-and-runners/page.mdx +++ b/docs/app/cases-and-runners/page.mdx @@ -64,18 +64,4 @@ Return plain JSON and leave the scoring to your judges. Along with the case, you Runners, judges and seeds can be sync or async. Use whichever fits your code. -## Comparing variants - -Want to compare two models or agents on the same cases? Add a comparison to `dataset.yml`: - -```yaml -offline: - comparisons: - - name: models - arms: - - name: small - - name: big - args: {model: big} -``` - -Then run `eac offline compare models`. Each arm gets its own run, and they share fixtures. Each arm's `args` reach the runner as `self.args`. +To run the same cases against two models or agents, see [Comparing variants](/comparing-variants). diff --git a/docs/app/cli/page.mdx b/docs/app/cli/page.mdx index bde81b6..026ece2 100644 --- a/docs/app/cli/page.mdx +++ b/docs/app/cli/page.mdx @@ -20,8 +20,6 @@ Run `eac --help` any time for the full list. ['`eac online run`', 'Collect production runs and judge them.'], ['`eac online execute`', 'Collect production runs into a new run.'], ['`eac online judge`', 'Judge a collected run.'], - ['`eac auth`', 'Log in to every credential your datasets need.'], - ['`eac catalog`', 'Print every dataset, case and split as JSON.'], ]} /> @@ -40,6 +38,7 @@ Run `eac --help` any time for the full list. ['`--concurrency N`', 'How many cases to run at once.'], ['`--judge NAME`', 'Online: which judge to score with.'], ['`--since 24h`', 'Online: how far back to collect. Defaults to 1h.'], + ['`--sample-rate 0.1`', 'Online: the share of production runs to collect. Defaults to 1.'], ['`-C DIR`', 'Run as if from another directory.'], ]} /> diff --git a/docs/app/comparing-variants/page.mdx b/docs/app/comparing-variants/page.mdx new file mode 100644 index 0000000..2beb159 --- /dev/null +++ b/docs/app/comparing-variants/page.mdx @@ -0,0 +1,17 @@ +export const metadata = {title: 'Comparing variants'}; + +# Comparing variants + +Want to compare two models or agents on the same cases? Add a comparison to `dataset.yml`: + +```yaml +offline: + comparisons: + - name: models + arms: + - name: small + - name: big + args: {model: big} +``` + +Then run `eac offline compare models`. Each arm gets its own run, and they share fixtures. Each arm's `args` reach the runner as `self.args`. diff --git a/docs/app/concepts/page.mdx b/docs/app/concepts/page.mdx index 3fbe467..074fed6 100644 --- a/docs/app/concepts/page.mdx +++ b/docs/app/concepts/page.mdx @@ -1,16 +1,10 @@ export const metadata = {title: 'How eac works'}; -# How eac works +# EAC concepts -## Projects and datasets +## datasets -A **project** is your repo, or the folder with an `eac.yml` in it if you need shared settings. A **dataset** is a `dataset.yml` and the code next to it. eac finds every dataset under the project root on its own, so adding one never means editing shared config. - -## Workers - -The CLI doesn't run your code itself. Instead, it starts a **worker** process for your language and sends it work over a small JSON protocol. That's what lets eac support more than one language. - -Workers handle one thing at a time, so you never have to think about thread safety. To run cases in parallel, set `concurrency` and eac starts more workers. +A **dataset** is a `dataset.yml` and the code next to it. eac finds every dataset under the project root on its own, so adding one never means editing shared config. ## Runs @@ -24,9 +18,9 @@ An offline run has three phases: diff --git a/docs/app/configuration/page.mdx b/docs/app/configuration/page.mdx index e0b3151..cb73ee0 100644 --- a/docs/app/configuration/page.mdx +++ b/docs/app/configuration/page.mdx @@ -23,7 +23,7 @@ If you don't set a Python command, eac uses `$EAC_PYTHON`, then your active virt ```yaml name: chat # lowercase, digits and underscores runtime: python -agent: chat_agent # optional, used to look up traces +metadata: {team: chat} # optional, recorded in results offline: runner: ./dataset.py:ChatRunner diff --git a/docs/app/credentials/page.mdx b/docs/app/credentials/page.mdx index c86aa5d..0d8ad74 100644 --- a/docs/app/credentials/page.mdx +++ b/docs/app/credentials/page.mdx @@ -7,13 +7,13 @@ If your evals need a token or a login, declare it as a credential. eac checks th ```python -from dataclasses import dataclass from eac import Credential -@dataclass(frozen=True) class GitHub(Credential): name = "github" - repo: str + + def __init__(self, repo): + self.repo = repo def is_authenticated(self, env) -> bool: return bool(env.get("GITHUB_TOKEN")) @@ -35,7 +35,7 @@ Then add it to the `credentials` of whatever needs it: a seed, a runner or a jud If a credential isn't set up, eac offers to run `authenticate()` for you. Whatever it returns is saved to `.eac/credentials/saved.json` (never your `.env`) and reused next time. If there's no `authenticate()`, eac shows the `setup_instructions` instead. -Run `eac auth` on a new machine to log in to everything at once. In CI, where `$CI` is set, the checks are skipped. +In CI, where `$CI` is set, the checks are skipped. Create API clients when you first use them, not in `__init__`. eac checks credentials after building your seeds and judges. diff --git a/docs/app/introduction/page.mdx b/docs/app/introduction/page.mdx index c5547e9..911105a 100644 --- a/docs/app/introduction/page.mdx +++ b/docs/app/introduction/page.mdx @@ -1,37 +1,145 @@ export const metadata = {title: 'Introduction'}; -# eac: evals as code +# eac: Evals-as-Code -eac lets you write evals as plain code and run them with a single CLI. +eac lets you write evals, then run them and judge the results with a single CLI. -You bring three things: +EAC provides SDKs for Python to write evals (more languages coming soon). -- A **runner** that calls your system. -- Some **cases** to run it on. -- **Judges** that score what comes back. +You create three things: -eac handles everything else: setting up fixtures, running each case, scoring the results and saving the run so you can look at it later. +- A **runner** that runs your system you want to evaluate. +- Some **cases** to run it on. +- **Judges** that score the output of each case. - +eac handles everything else: setting up fixtures, running cases, scoring the results and saving the run so you can look at it later. ## Offline and online -**Offline evals** run your system on cases you wrote. Use them in development and CI to catch regressions. +**Offline evals** run your system on cases you wrote. Use them in development and CI to catch regressions or drive improvements. + +**Online evals** score what your system did in production. eac collects recent production runs as cases and judges them. -**Online evals** score what your system already did in production. Nothing gets re-run. eac just collects recent production runs as cases and judges them. +Both offline and online evals in eac use the same judges, so scoring is consistent. ## Why eac? +- **Language-agnostic.** You write your evals code in any SDK eac supports. eac handles the rest. - **Evals live with your code.** A dataset is a `dataset.yml` plus some code, anywhere in your repo. +- **Your results stay yours.** Each run is just a folder of JSON, process the results however you want. - **Phases are separate commands.** Seed in one CI job and judge in another, or re-judge an old run without running it again. -- **Your results stay yours.** Each run is just a folder of JSON. eac never uploads anything. -## Next steps +## Quick start + +Set up a project and run a first eval. It takes about five minutes. + +### Install + +eac doesn't have packaged releases yet, so build the CLI from the repo. You'll need Rust 1.87+. + +```sh +make install # puts eac on your PATH +``` + +Then install the SDK into the environment your evals run in: + + + + + +```sh +pip install -e sdks/python # needs Python 3.11+ +``` + + + + + +### Add a dataset + +Each dataset gets its own folder, anywhere in your repo. eac finds it on its own, so there's no project config to write: + + + + + +```text +evals/chat/ + dataset.yml + dataset.py +``` + + + + + +The `dataset.yml` tells eac where your code is: + + + + + +```yaml +name: chat +runtime: python +offline: + runner: ./dataset.py:ChatRunner + cases: ./dataset.py:CASES +``` + + + + + +Then write the runner, a judge and the cases: + + + + + +```python +from eac import Case, Judge, OfflineRunner, Score + + +def reply(query: str) -> str: + return "hello there" # call your system here + + +class ChatRunner(OfflineRunner): + def run_case(self, case, *, seeds, conversation_id): + return {"response": reply(case.input["query"])} + + +class Greets(Judge): + name = "greets" + + def judge(self, case, *, seeds, agent_trace=None): + ok = "hello" in case.output.get("response", "") + return Score(name=self.name, score=1.0 if ok else 0.0) + + +CASES = [Case(name="greets", input={"query": "hi"}, judges=[Greets()])] +``` + + + + + +### Run it + +From the root of your repo: + +```sh +eac list # see what eac found +eac offline run # seed, execute and judge +``` + +That's it. The results are saved in `.eac/runs//`. + + + Changed a judge? Run `eac offline judge` to re-score the last run without running your system again. + + +For a real agent with seeds, an LLM judge and online evals, see [`examples/sentry-assistant-python`](https://github.com/getsentry/eac/tree/main/examples/sentry-assistant-python). -Start with the [Quick start](/quick-start), or read [how eac works](/concepts) first. +Next, read [how eac works](/concepts). diff --git a/docs/app/judges/page.mdx b/docs/app/judges/page.mdx index e136f76..207677a 100644 --- a/docs/app/judges/page.mdx +++ b/docs/app/judges/page.mdx @@ -26,12 +26,9 @@ class CalledTool(Judge): self.tool = tool def judge(self, case, *, seeds, agent_trace=None): - ok = self.tool in case.output.get("tool_calls", []) - return Score( - name=self.name, - score=1.0 if ok else 0.0, - explanation=None if ok else f"{self.tool} wasn't called", - ) + if self.tool in case.output.get("tool_calls", []): + return Score.passed(self.name) + return Score.failed(self.name, f"{self.tool} wasn't called") ``` diff --git a/docs/app/online-evals/page.mdx b/docs/app/online-evals/page.mdx index 96e588b..af84ed1 100644 --- a/docs/app/online-evals/page.mdx +++ b/docs/app/online-evals/page.mdx @@ -1,6 +1,6 @@ -export const metadata = {title: 'Online evals'}; +export const metadata = {title: 'Online runners'}; -# Online evals +# Online runners Online evals score what your system already did in production. Nothing is re-run and there are no fixtures. You collect recent production runs as cases and judge them. @@ -72,3 +72,5 @@ eac online run --judge greets --since 24h `--args` reach the runner as `self.args`, like offline. To use a judge in several datasets, point each `dataset.yml` at the same code. + +To judge only a share of production, see [Sampling](/sampling). diff --git a/docs/app/quick-start/page.mdx b/docs/app/quick-start/page.mdx deleted file mode 100644 index 35784b2..0000000 --- a/docs/app/quick-start/page.mdx +++ /dev/null @@ -1,114 +0,0 @@ -export const metadata = {title: 'Quick start'}; - -# Quick start - -Let's set up a project and run a first eval. It takes about five minutes. - -## Install - -eac doesn't have packaged releases yet, so build the CLI from the repo. You'll need Rust 1.87+. - -```sh -make install # puts eac on your PATH -``` - -Then install the SDK into the environment your evals run in: - - - - - -```sh -pip install -e sdks/python # needs Python 3.11+ -``` - - - - - -## Add a dataset - -Each dataset gets its own folder, anywhere in your repo. eac finds it on its own, so there's no project config to write: - - - - - -```text -evals/chat/ - dataset.yml - dataset.py -``` - - - - - -The `dataset.yml` tells eac where your code is: - - - - - -```yaml -name: chat -runtime: python -offline: - runner: ./dataset.py:ChatRunner - cases: ./dataset.py:CASES -``` - - - - - -Then write the runner, a judge and the cases: - - - - - -```python -from eac import Case, Judge, OfflineRunner, Score - - -def reply(query: str) -> str: - return "hello there" # call your system here - - -class ChatRunner(OfflineRunner): - def run_case(self, case, *, seeds, conversation_id): - return {"response": reply(case.input["query"])} - - -class Greets(Judge): - name = "greets" - - def judge(self, case, *, seeds, agent_trace=None): - ok = "hello" in case.output.get("response", "") - return Score(name=self.name, score=1.0 if ok else 0.0) - - -CASES = [Case(name="greets", input={"query": "hi"}, judges=[Greets()])] -``` - - - - - -## Run it - -From the root of your repo: - -```sh -eac list # see what eac found -eac offline run # seed, execute and judge -``` - -That's it. The results are saved in `.eac/runs//`. - - - Changed a judge? Run `eac offline judge` to re-score the last run without running your system again. - - -For a bigger example with seeds and online evals, see [`examples/basic-example-python`](https://github.com/getsentry/eac/tree/main/examples/basic-example-python). diff --git a/docs/app/sampling/page.mdx b/docs/app/sampling/page.mdx new file mode 100644 index 0000000..7bc2caa --- /dev/null +++ b/docs/app/sampling/page.mdx @@ -0,0 +1,13 @@ +export const metadata = {title: 'Sampling'}; + +# Sampling + +To judge a share of production, pass `--sample-rate 0.1` and keep the runs `window.samples()` picks by a stable id: + + + +```python +rows = [row for row in query_production(window.since, window.until) if window.samples(row.trace_id)] +``` + + diff --git a/docs/components/docsShell.tsx b/docs/components/docsShell.tsx index df4c7bb..1a24828 100644 --- a/docs/components/docsShell.tsx +++ b/docs/components/docsShell.tsx @@ -12,11 +12,9 @@ import {Link} from '@sentry/scraps/link'; import {Prose, Text} from '@sentry/scraps/text'; import {LanguageSelect} from './languageContext'; -import {NAV} from './nav'; +import {isNavGroup, NAV, PAGES, type NavItem} from './nav'; import {useThemeMode} from './themeContext'; -const PAGES = NAV.flatMap(section => section.items); - export function DocsShell({children}: {children: React.ReactNode}) { const pathname = usePathname(); const index = PAGES.findIndex(page => page.href === pathname); @@ -51,16 +49,24 @@ export function DocsShell({children}: {children: React.ReactNode}) { {section.title} - {section.items.map(item => ( -
  • - - {item.title} - -
  • - ))} + {section.items.map(entry => + isNavGroup(entry) ? ( + + + + {entry.title} + + + + {entry.items.map(item => ( + + ))} + + + ) : ( + + ) + )}
    ))} @@ -96,17 +102,27 @@ export function DocsShell({children}: {children: React.ReactNode}) { ); } +function NavListItem({item, pathname}: {item: NavItem; pathname: string}) { + return ( +
  • + + {item.title} + +
  • + ); +} + function SiteHeader() { return (
    - + - eac + EAC - evals as code + Evals-as-Code @@ -171,10 +187,9 @@ const Header = styled('header')` } `; +// Full width, so the sidebar sits against the left edge of the window. const Body = styled('div')` display: flex; - max-width: 1200px; - margin: 0 auto; `; const Sidebar = styled('nav')` @@ -219,10 +234,28 @@ const NavLink = styled(Link)` } `; +const NavGroupItem = styled('li')` + display: flex; + flex-direction: column; + gap: ${p => p.theme.space.xs}; + padding-top: ${p => p.theme.space.sm}; +`; + +const NavGroupTitle = styled('div')` + padding: 0 ${p => p.theme.space.md}; +`; + +const NavGroupList = styled(Stack)` + margin-left: ${p => p.theme.space.md}; + padding-left: ${p => p.theme.space.xs}; + border-left: 1px solid ${p => p.theme.tokens.border.secondary}; +`; + const Main = styled('main')` flex: 1; min-width: 0; - max-width: 820px; + max-width: 1040px; + margin: 0 auto; padding: ${p => `${p.theme.space['3xl']} ${p.theme.space['3xl']} 96px`}; font-size: ${p => p.theme.font.size.lg}; line-height: 1.6; diff --git a/docs/components/landing.tsx b/docs/components/landing.tsx index 16d1552..2145e41 100644 --- a/docs/components/landing.tsx +++ b/docs/components/landing.tsx @@ -11,9 +11,10 @@ import {Heading, Text} from '@sentry/scraps/text'; const REPO_URL = 'https://github.com/getsentry/eac'; -const INSTALL = `git clone ${REPO_URL}.git && cd eac -make install # needs Rust 1.87+ -pip install -e sdks/python # needs Python 3.11+`; +const INSTALL = `brew tap getsentry/tap +brew install getsentry/tap/eac + +pip install -e sdks/python # needs Python 3.11+`; const DATASET_YML = `name: chat runtime: python @@ -33,7 +34,7 @@ class ChatRunner(OfflineRunner): return {"response": reply(case.input["query"])} -class Greets(Judge): +class GreetsJudge(Judge): name = "greets_judge" def judge(self, case, *, seeds, agent_trace=None): @@ -49,8 +50,8 @@ class Greets(Judge): CASES = [ - Case(name="greeting", input={"query": "hi"}, judges=[Greets()]), - Case(name="goodbye", input={"query": "bye"}, judges=[Greets()]), + Case(name="greeting", input={"query": "hi"}, judges=[GreetsJudge()]), + Case(name="goodbye", input={"query": "bye"}, judges=[GreetsJudge()]), ]`; const RUN = 'eac offline run --dataset chat'; @@ -215,7 +216,7 @@ const Wrapper = styled('main')` `; const Hero = styled('section')` - padding: 112px 0 72px; + padding: 84px 0 24px; text-align: center; p { diff --git a/docs/components/mdx.tsx b/docs/components/mdx.tsx index 9fb2d37..960d1c2 100644 --- a/docs/components/mdx.tsx +++ b/docs/components/mdx.tsx @@ -366,9 +366,6 @@ export function PhaseFlow({ {phase.description} - - → {phase.writes} - diff --git a/docs/components/nav.ts b/docs/components/nav.ts index e8ce757..8546714 100644 --- a/docs/components/nav.ts +++ b/docs/components/nav.ts @@ -3,28 +3,50 @@ export interface NavItem { title: string; } -export interface NavSection { +/** A sub-heading inside a section, with its own pages. */ +export interface NavGroup { items: NavItem[]; title: string; } +export interface NavSection { + items: Array; + title: string; +} + +export function isNavGroup(entry: NavItem | NavGroup): entry is NavGroup { + return 'items' in entry; +} + export const NAV: NavSection[] = [ { title: 'Getting started', items: [ {title: 'Introduction', href: '/introduction'}, - {title: 'Quick start', href: '/quick-start'}, {title: 'How eac works', href: '/concepts'}, ], }, { title: 'Writing evals', items: [ - {title: 'Cases and runners', href: '/cases-and-runners'}, + // Shared by offline and online evals, so above both groups. {title: 'Judges', href: '/judges'}, - {title: 'Seeds', href: '/seeds'}, - {title: 'Online evals', href: '/online-evals'}, {title: 'Credentials', href: '/credentials'}, + { + title: 'Offline evals', + items: [ + {title: 'Cases and runners', href: '/cases-and-runners'}, + {title: 'Seeds', href: '/seeds'}, + {title: 'Comparing variants', href: '/comparing-variants'}, + ], + }, + { + title: 'Online evals', + items: [ + {title: 'Online runners', href: '/online-evals'}, + {title: 'Sampling', href: '/sampling'}, + ], + }, ], }, { @@ -37,3 +59,8 @@ export const NAV: NavSection[] = [ ], }, ]; + +/** Every page in sidebar order, for the previous and next links. */ +export const PAGES: NavItem[] = NAV.flatMap(section => + section.items.flatMap(entry => (isNavGroup(entry) ? entry.items : [entry])) +); diff --git a/docs/next.config.ts b/docs/next.config.ts index e4d5af8..8033753 100644 --- a/docs/next.config.ts +++ b/docs/next.config.ts @@ -13,6 +13,10 @@ const nextConfig: NextConfig = { pageExtensions: ['ts', 'tsx', 'mdx'], // Scraps ships untranspiled ESM that imports Emotion's JSX runtime. transpilePackages: ['@sentry/scraps'], + // The quick start is now a section of the introduction. + redirects: async () => [ + {source: '/quick-start', destination: '/introduction#quick-start', permanent: true}, + ], }; const withMDX = createMDX(); diff --git a/examples/basic-example-python/README.md b/examples/basic-example-python/README.md deleted file mode 100644 index cdf2244..0000000 --- a/examples/basic-example-python/README.md +++ /dev/null @@ -1,79 +0,0 @@ -# basic-example-python - -A complete eval with no network calls and no API keys, laid out as an eac -project: one dataset, in its own folder. - -``` -eac.yml the project root, and settings every dataset shares -evals/assistant/ - dataset.yml the dataset: its name, and the code it runs offline and online - dataset.py that code: runners, cases, a seed and judges -``` - -The system under test is the `assistant()` function at the bottom of -`dataset.py`. Replace it with a call to your product to make this a real eval. - -Run from this directory, or from `evals/assistant/`, which picks only that -dataset: - -```sh -eac list # the datasets eac found, and their cases -eac offline run # seed, execute, judge -eac offline run --dataset assistant # only this dataset, once there are more -eac offline run --case get_dsn -eac offline run --split smoke -eac online run --judge replied # collect and score "production" runs -eac offline prune # tear down the cached seed -``` - -Its `eac.yml` points `PYTHONPATH` at `sdks/python` because the SDK isn't -installed inside this repo. In your own project, `pip install` the SDK and you -won't need an `eac.yml` at all. - -It shows: - -- A `dataset.yml` that points at its code in `dataset.py`. Offline, that's the - runner and `CASES`. Online, it's the runner and the judge it names - `replied`. -- An offline runner that calls the system under test and returns raw output. - It doesn't score or decide pass/fail. -- An online runner, `ProdChats`, that collects production runs as cases, and - the online judge that `eac online run --judge replied` picks. -- A seed, `FakeProject`, with a `key()`. All three cases ask for the same - fixture, so setup runs once and is shared. The seed phase prints - "creating project demo" only once. The seed is cached, so later runs reuse it - until `eac offline prune`. -- Judges, which are your own code: `Mentions` checks the reply's words and - `CalledTool` checks which tools ran. - -## Add a dataset of your own - -Make a folder next to `evals/assistant/` with a runner, its cases, and a -`dataset.yml` that points at them with paths relative to itself. eac finds it -on its own. - -```yaml -# evals/my_feature/dataset.yml -name: my_feature -runtime: python -offline: - runner: ./runner.py:Runner - cases: ./cases.py:CASES -``` - -Code in the folder can import its neighbors as `evals.my_feature.runner` and -so on, because eac imports `./runner.py` under that same name. `python` is the -only runtime so far. - -## Common mistakes - -- Returning live objects from a runner. The output is written to disk and read - back by the judge phase, maybe in another process on another day. Return ids - and text, not clients. eac fails the case with an error instead of dropping - the value. -- A `key()` that misses something that changes the fixture. Seeds with equal - keys are set up once and shared, so if two cases need different fixtures but - hash the same, one of them gets the wrong one. -- Re-running the system to tweak a judge. `eac offline judge --run latest` - re-scores the recorded output without running anything again, which is fast - and free. diff --git a/examples/basic-example-python/eac.yml b/examples/basic-example-python/eac.yml deleted file mode 100644 index 04355d5..0000000 --- a/examples/basic-example-python/eac.yml +++ /dev/null @@ -1,5 +0,0 @@ -artifacts: .eac - -runtimes: - python: - env: {PYTHONPATH: ../../sdks/python} diff --git a/examples/basic-example-python/evals/assistant/dataset.py b/examples/basic-example-python/evals/assistant/dataset.py deleted file mode 100644 index 7f21e97..0000000 --- a/examples/basic-example-python/evals/assistant/dataset.py +++ /dev/null @@ -1,142 +0,0 @@ -"""A complete eval in one file, with no network calls and no API keys. - -The system under test is `assistant()` at the bottom. Swap that for your own -call and this becomes a real eval. The dataset.yml next to this file points -at the runners, the cases and the online judge below. -""" - -from __future__ import annotations - -from typing import Any - -from eac import Case, Handle, Judge, OfflineRunner, OnlineRunner, Score, Seed, Window, stable_hash - - -class FakeProject(Seed): - """Stands in for a fixture you would really create, like a Sentry project.""" - - name = "fake_project" - - def __init__(self, slug: str = "demo"): - super().__init__() - self.slug = slug - - def key(self) -> str: - # Cases asking for the same key share one setup. - return stable_hash({"seed": self.name, "slug": self.slug}) - - def setup(self) -> dict[str, Any]: - print(f"creating project {self.slug}") - return { - "project_id": 42, - "slug": self.slug, - "dsn": f"https://abc123@o0.ingest.sentry.io/{self.slug}", - } - - def cleanup(self, handle: dict[str, Any]) -> None: - print(f"deleting project {handle['slug']}") - - -class AssistantRunner(OfflineRunner): - async def run_case(self, case: Case, *, seeds: dict[str, Handle], conversation_id: str) -> dict[str, Any]: - reply, tools = assistant(case.input["query"], seeds["fake_project"]) - return {"response": reply, "tool_calls": tools} - - -class Mentions(Judge): - """The fraction of the given words the reply mentions.""" - - name = "mentions" - - def __init__(self, *words: str): - self.words = words - - def judge(self, case: Case, *, seeds: dict[str, Handle], agent_trace: Any = None) -> Score: - reply = (case.output.get("response") or "").lower() - missing = [word for word in self.words if word.lower() not in reply] - return Score( - name=self.name, - score=1 - len(missing) / len(self.words), - explanation=f"missing: {', '.join(missing)}" if missing else None, - ) - - -class CalledTool(Judge): - """Passes if the assistant called the given tool.""" - - name = "called_tool" - - def __init__(self, tool: str): - self.tool = tool - - def judge(self, case: Case, *, seeds: dict[str, Handle], agent_trace: Any = None) -> Score: - called = case.output.get("tool_calls") or [] - ok = self.tool in called - return Score( - name=self.name, - score=1.0 if ok else 0.0, - explanation=None if ok else f"{self.tool} was not called; called {called}", - metadata={"expected": self.tool, "called": called}, - ) - - -class Replied(Judge): - """The online judge. Production runs have no expected output, so it checks - the reply alone.""" - - name = "replied" - - def judge(self, case: Case, *, seeds: dict[str, Handle], agent_trace: Any = None) -> Score: - ok = bool(case.output.get("response")) - return Score(name=self.name, score=1.0 if ok else 0.0, explanation=None if ok else "empty reply") - - -class ProdChats(OnlineRunner): - """A real online runner would query your production traces. This one - returns fixed runs so the example works offline.""" - - def collect_cases(self, window: Window) -> list[Case]: - print(f"collecting chats from {window.since:%Y-%m-%d %H:%M} to {window.until:%H:%M}") - replies = [ - "Your DSN is https://abc123@o0.ingest.sentry.io/demo", - "You're in the demo project.", - "", # a bad one, to show up in the aggregate - ] - return [ - Case(name=f"trace-{i}", input={"query": "..."}, output={"response": reply}) - for i, reply in enumerate(replies[: window.limit]) - ] - - -CASES = [ - Case( - name="get_dsn", - input={"query": "What's my DSN?"}, - seeds=[FakeProject()], - judges=[CalledTool("get_dsn"), Mentions("DSN", "ingest.sentry.io")], - splits=["smoke"], - ), - Case( - name="project_slug", - input={"query": "Which project am I in?"}, - seeds=[FakeProject()], - judges=[Mentions("demo")], - splits=["smoke"], - ), - Case( - name="refuses_unknown", - input={"query": "What is the airspeed velocity of an unladen swallow?"}, - seeds=[FakeProject()], - judges=[Mentions("don't know")], - ), -] - - -def assistant(query: str, project: dict[str, Any]) -> tuple[str, list[str]]: - """Pretend LLM. Replace with a real call to your product.""" - lowered = query.lower() - if "dsn" in lowered: - return f"Your DSN is {project['dsn']}", ["get_dsn"] - if "project" in lowered: - return f"You're in the {project['slug']} project.", ["get_project"] - return "I don't know.", [] diff --git a/examples/basic-example-python/evals/assistant/dataset.yml b/examples/basic-example-python/evals/assistant/dataset.yml deleted file mode 100644 index cb0a20f..0000000 --- a/examples/basic-example-python/evals/assistant/dataset.yml +++ /dev/null @@ -1,12 +0,0 @@ -name: assistant -runtime: python - -offline: - runner: ./dataset.py:AssistantRunner - cases: ./dataset.py:CASES - -online: - runner: ./dataset.py:ProdChats - judges: - - name: replied - path: ./dataset.py:Replied diff --git a/examples/sentry-assistant-python/.env.example b/examples/sentry-assistant-python/.env.example new file mode 100644 index 0000000..5b4861a --- /dev/null +++ b/examples/sentry-assistant-python/.env.example @@ -0,0 +1,11 @@ +# Copy to .env + +# An empty Sentry project for the seed to fill with issues. +SENTRY_ORG= +SENTRY_PROJECT= + +# Optional. Without them, eac offers to log in to Sentry through its CLI, and +# asks for an OpenRouter key, which it saves outside .env. A token here is used +# over the CLI's login. +# SENTRY_AUTH_TOKEN= +# OPENROUTER_API_KEY= diff --git a/examples/sentry-assistant-python/.gitignore b/examples/sentry-assistant-python/.gitignore new file mode 100644 index 0000000..3d832d5 --- /dev/null +++ b/examples/sentry-assistant-python/.gitignore @@ -0,0 +1,2 @@ +# Conversations agent.py logged, standing in for production traces +.traces/ diff --git a/examples/sentry-assistant-python/README.md b/examples/sentry-assistant-python/README.md new file mode 100644 index 0000000..b432dce --- /dev/null +++ b/examples/sentry-assistant-python/README.md @@ -0,0 +1,60 @@ +# sentry-assistant-python + +A Sentry triage agent and its evals. + +Given an alert like "checkout fails with coupons since shop@1.4.2", the agent searches Sentry, reads the shop's code and reports which issue is behind it and what to fix. + +## Run it + +You'll need [uv](https://docs.astral.sh/uv/), eac (`make install` from the repo root), the [Sentry CLI](https://cli.sentry.dev) and an [OpenRouter](https://openrouter.ai) key. + +The evals fill a Sentry project with real issues, so create an empty one first. A free account works. + +```sh +cp .env.example .env # set SENTRY_ORG and SENTRY_PROJECT +uv sync +eac offline run # offers to log in to Sentry and OpenRouter if you haven't +``` + +The first run takes about 30s while the seed waits on Sentry. Later runs reuse it. To start over, run `eac offline prune --all`. + +The agent uses GPT-6 Luna. To try another model: + +```sh +eac offline run --args '{"model": "openai/gpt-6.2-sol"}' +``` + +## How it works + +`agent.py`, `traces.py`, `sentry_cli.py` and `app/` are the product being evaluated. You don't need to read them to follow the evals. + +The evals are in [`evals/triage/`](evals/triage/). Read them in this order: + +1. [`dataset.yml`](evals/triage/dataset.yml) is where eac starts. It points at everything else. +2. [`cases.py`](evals/triage/cases.py) has the four alerts, and what the agent should find for each. +3. [`seed.py`](evals/triage/seed.py) sets up the incident the cases investigate. It releases a new version of the shop and sends it requests that fail, so three checkout bugs and an unrelated newsletter error show up in Sentry as real issues. +4. [`runners/offline.py`](evals/triage/runners/offline.py) runs the agent on each case. +5. [`judges/`](evals/triage/judges/) scores the answers. `FoundIssue` and `FoundCause` check them against the case's `expected_output` and the issues the seed created. `TriageLLMJudge` has a model review the whole investigation. + +Each case is hard in its own way. The agent has to pick the right issue out of four, read the code when the stack trace blames the wrong function, and say so when nothing explains the alert. + +### Online evals + +The agent saves every conversation to `.traces/`, standing in for a real product's traces. [`runners/online.py`](evals/triage/runners/online.py) collects them as production traffic, and `TriageLLMJudge` scores them: + +```sh +eac online run --judge triage_llm_judge +``` + +### Credentials + +[`credentials/`](evals/triage/credentials/) has what the evals log in to. Each seed, runner and judge lists what it needs, and eac checks them all before starting. + +- `SentryLogin` hands off to `sentry auth login`, which keeps its own login, then asks which project to use. +- `OpenRouterKey` asks for a key, which eac saves for later runs. + +## CI + +[`evals.yml`](../../.github/workflows/evals.yml) runs the evals on each pull request and on its merge base. It uploads both runs to [evals.sentry.dev](https://evals.sentry.dev), which comments the comparison on the pull request. In this repo, that makes the example an integration test too. + +The upload is [`scripts/upload_evals.py`](../../scripts/upload_evals.py). It needs `EVALS_API_TOKEN`, and reads `GITHUB_SERVER_URL` and `GITHUB_REPOSITORY`, which GitHub Actions sets. Copy the workflow and the script to do the same in your own repo. diff --git a/examples/sentry-assistant-python/agent.py b/examples/sentry-assistant-python/agent.py new file mode 100644 index 0000000..fb0f768 --- /dev/null +++ b/examples/sentry-assistant-python/agent.py @@ -0,0 +1,247 @@ +"""A simple triage agent for the shop in app/. Given an alert, it finds the +Sentry issue behind it and works out the root cause, with tools to search +Sentry and read the shop's code. + +Every conversation is saved to .traces/ (see traces.py). + + uv run --env-file .env python agent.py "Checkout is failing since shop@1.4.0" +""" + +import asyncio +import json +import os +import sys +import uuid +from datetime import UTC, datetime +from pathlib import Path + +from openrouter import OpenRouter +from openrouter.utils import BackoffStrategy, RetryConfig + +from sentry_cli import ORG, PROJECT, cli +from traces import save_conversation + +DEFAULT_MODEL = "openai/gpt-6-luna" + +# Stops an agent that keeps calling tools. +MAX_TURNS = 10 + +ROOT = Path(__file__).parent + +SYSTEM_PROMPT = """\ +You triage production errors in an online shop, whose code is in app/. Given an \ +alert, find the Sentry issue behind it and work out its root cause, reading the code \ +when the stack trace isn't enough. Sentry's search matches error messages rather than \ +symptoms, so start from all of a release's issues. If no issue explains the alert, say so. + +Reply with JSON: {"issue": "", "function": "", "root_cause": "", \ +"fix": ""}""" + + +async def triage(alert, *, conversation_id, model=DEFAULT_MODEL): + """Investigate `alert` and return the agent's answer, saving the conversation.""" + log(conversation_id, f"{model}: {alert}") + + messages = [ + {"role": "system", "content": SYSTEM_PROMPT}, + {"role": "user", "content": alert}, + ] + + usage = { + "input_tokens": 0, + "output_tokens": 0, + "total_tokens": 0, + "cost_usd": 0.0, + "llm_calls": 0, + "tool_calls": 0, + } + started_at = datetime.now(UTC) + + async with client() as openrouter: + for _ in range(MAX_TURNS): + result = await openrouter.chat.send_async( + model=model, + messages=messages, + tools=TOOLS, + response_format={"type": "json_object"}, + temperature=0, + ) + for key, value in usage_of(result).items(): + usage[key] += value + + message = result.choices[0].message + messages.append(message.model_dump(exclude_none=True)) + + # No tool calls means the model has given its answer. + if not message.tool_calls: + break + + for call in message.tool_calls: + usage["tool_calls"] += 1 + messages.append(run_tool(call, conversation_id)) + + if message.tool_calls: + log(conversation_id, f"gave up after {MAX_TURNS} turns") + + answer = json.loads(message.content or "{}") + usage["llm_duration_seconds"] = (datetime.now(UTC) - started_at).total_seconds() + log( + conversation_id, + f"answer: {answer.get('issue')} in {answer.get('function')} " + f"({usage['llm_calls']} model calls, ${usage['cost_usd']:.4f})", + ) + + save_conversation( + { + "conversation_id": conversation_id, + "started_at": started_at.isoformat(), + "model": model, + "alert": alert, + "answer": answer, + "messages": messages, + "usage": usage, + } + ) + return answer + + +def run_tool(call, conversation_id): + """Run a tool the model called, and return the message with its output. + An error goes back to the model as the output, so it can try something else.""" + name = call.function.name + log(conversation_id, f"{name} {call.function.arguments}") + try: + arguments = json.loads(call.function.arguments) + output = FUNCTIONS[name](**arguments) + except Exception as error: + output = f"{type(error).__name__}: {error}" + log(conversation_id, f" failed: {output}") + return {"role": "tool", "tool_call_id": call.id, "content": json.dumps(output)} + + +# Tools + + +def search_issues(query): + fields = "shortId,title,culprit,count" + issues = cli("issue", "list", PROJECT, "--query", f"is:unresolved {query}", "--fields", fields) + return issues["data"] + + +def get_issue(id): + event = cli("issue", "view", f"{ORG}/{id}")["event"] + + exception = None + for entry in event["entries"]: + if entry["type"] == "exception": + exception = entry + break + if exception is None: + return "This issue's latest event has no error." + + # With chained errors, the last one is the error that was raised. + error = exception["data"]["values"][-1] + + stack_trace = [] + for frame in error["stacktrace"]["frames"]: + source = dict(frame["context"]).get(frame["lineNo"], "").strip() + stack_trace.append(f"{frame['filename']}:{frame['lineNo']} in {frame['function']}: {source}") + + return {"error": f"{error['type']}: {error['value']}", "stack_trace": stack_trace} + + +def read_file(path): + file = (ROOT / path).resolve() + if not file.is_relative_to(ROOT / "app"): + return "Only the shop's code, in app/, can be read." + return file.read_text() + + +# What runs when the model calls a tool, by name. +FUNCTIONS = { + "search_issues": search_issues, + "get_issue": get_issue, + "read_file": read_file, +} + +# What the model is told about each tool. +TOOLS = [ + { + "type": "function", + "function": { + "name": "search_issues", + "description": "Search the shop's unresolved Sentry issues.", + "parameters": { + "type": "object", + "properties": { + "query": {"type": "string", "description": "Sentry search syntax, like release:shop@1.0.0"}, + }, + "required": ["query"], + }, + }, + }, + { + "type": "function", + "function": { + "name": "get_issue", + "description": "An issue's latest error and its stack trace.", + "parameters": { + "type": "object", + "properties": { + "id": {"type": "string", "description": "The issue's short ID"}, + }, + "required": ["id"], + }, + }, + }, + { + "type": "function", + "function": { + "name": "read_file", + "description": "Read one of the shop's files.", + "parameters": { + "type": "object", + "properties": { + "path": {"type": "string", "description": "Like app/app.py"}, + }, + "required": ["path"], + }, + }, + }, +] + + +# Helpers + + +def client(): + """An OpenRouter client that gives up on a failing provider after 20 + seconds. The SDK's default is to keep retrying for an hour.""" + return OpenRouter( + api_key=os.environ["OPENROUTER_API_KEY"], + timeout_ms=60_000, + retry_config=RetryConfig("backoff", BackoffStrategy(500, 5_000, 2, 20_000), retry_connection_errors=True), + ) + + +def usage_of(result): + """What one model call used, in the shape of eac's LLMMetrics.""" + return { + "input_tokens": result.usage.prompt_tokens, + "output_tokens": result.usage.completion_tokens, + "total_tokens": result.usage.total_tokens, + "cost_usd": result.usage.cost or 0.0, + "llm_calls": 1, + } + + +def log(conversation_id, message): + """Print what the agent is doing, which eac shows as the run's logs. Cases + run at the same time, so each line starts with its conversation.""" + print(f"[{conversation_id[-6:]}] {message}", flush=True) + + +if __name__ == "__main__": + answer = asyncio.run(triage(" ".join(sys.argv[1:]), conversation_id=str(uuid.uuid4()))) + print(json.dumps(answer, indent=2)) diff --git a/examples/sentry-assistant-python/app/__init__.py b/examples/sentry-assistant-python/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/examples/sentry-assistant-python/app/app.py b/examples/sentry-assistant-python/app/app.py new file mode 100644 index 0000000..8fe8394 --- /dev/null +++ b/examples/sentry-assistant-python/app/app.py @@ -0,0 +1,18 @@ +"""The shop's request handlers. Errors are reported to Sentry and the customer gets a 500.""" + +import sentry_sdk + +from app import checkout, newsletter + +ROUTES = { + "/checkout": checkout.place_order, + "/newsletter": newsletter.subscribe, +} + + +def handle(path, body): + try: + return 200, ROUTES[path](**body) + except Exception: + sentry_sdk.capture_exception() + return 500, {"error": "Something went wrong"} diff --git a/examples/sentry-assistant-python/app/checkout.py b/examples/sentry-assistant-python/app/checkout.py new file mode 100644 index 0000000..fc074a0 --- /dev/null +++ b/examples/sentry-assistant-python/app/checkout.py @@ -0,0 +1,32 @@ +PRICES = {"MUG": 12.00, "TEE": 24.00, "CAP": 18.00} +COUPONS = {"WELCOME10": 0.10, "SPRING25": 0.25} +SHIPPING = {"US": 5.00, "CA": 8.50} + + +def place_order(cart, country, coupon=None): + items = [parse_line(line) for line in cart] + subtotal = sum(item["price"] * item["quantity"] for item in items) + if coupon: + subtotal = apply_coupon(subtotal, coupon) + + return { + "total": round(subtotal + shipping_cost(country), 2), + "average_item_price": average_price(items), + } + + +def parse_line(line): + sku, _, quantity = line.partition(":") + return {"sku": sku, "price": PRICES[sku], "quantity": quantity or 1} + + +def apply_coupon(subtotal, code): + return subtotal * (1 - COUPONS[code.upper()]) + + +def shipping_cost(country): + return SHIPPING.get(country, 15.00) + + +def average_price(items): + return round(sum(item["price"] for item in items) / len(items), 2) diff --git a/examples/sentry-assistant-python/app/newsletter.py b/examples/sentry-assistant-python/app/newsletter.py new file mode 100644 index 0000000..6ed7a14 --- /dev/null +++ b/examples/sentry-assistant-python/app/newsletter.py @@ -0,0 +1,8 @@ +import smtplib + + +def subscribe(email): + with smtplib.SMTP("localhost", 2525, timeout=1) as smtp: + smtp.sendmail("news@shop.example", [email], "Subject: Welcome!\n\nThanks for subscribing.") + + return {"subscribed": email} diff --git a/examples/sentry-assistant-python/eac.yml b/examples/sentry-assistant-python/eac.yml new file mode 100644 index 0000000..6d1f065 --- /dev/null +++ b/examples/sentry-assistant-python/eac.yml @@ -0,0 +1,4 @@ +# This file marks this folder as the eac project root, so eac reads .env from here and saves runs to the artifacts directory defined here. + +# The artifacts directory to save eac outputs to.. +artifacts: .eac \ No newline at end of file diff --git a/examples/sentry-assistant-python/evals/triage/cases.py b/examples/sentry-assistant-python/evals/triage/cases.py new file mode 100644 index 0000000..1524361 --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/cases.py @@ -0,0 +1,63 @@ +from eac import Case + +from evals.triage.judges.found_cause_judge import FoundCauseJudge +from evals.triage.judges.found_issue_judge import FoundIssueJudge +from evals.triage.judges.triage_llm_judge import TriageLLMJudge +from evals.triage.seed import Incident + +JUDGES = [FoundIssueJudge(), FoundCauseJudge(), TriageLLMJudge()] + +# Every case shares one incident: a release with three checkout bugs and an +# unrelated error, so the agent has to pick the right issue for each alert. +# "error" is the one in seed.REQUESTS behind the alert, and "function" is the +# one the fix changes. +OFFLINE_CASES = [ + Case( + name="coupon", + input={ + "alert": "Since {release} went out, customers say checkout fails when they use a coupon code.", + }, + expected_output={ + "error": "coupon", + "function": "apply_coupon", + }, + seeds=[Incident()], + judges=JUDGES, + ), + Case( + name="quantity", + input={ + "alert": "Since {release}, customers can't check out when they order more than one of something." + }, + expected_output={ + "error": "quantity", + "function": "parse_line", + }, + seeds=[Incident()], + judges=JUDGES, + ), + Case( + name="empty_cart", + input={ + "alert": "Since {release}, checkout crashes when a customer's cart is empty." + }, + expected_output={ + "error": "empty_cart", + "function": "average_price" + }, + seeds=[Incident()], + judges=JUDGES, + ), + Case( + name="false_alarm", + input={ + "alert": "A customer says checkout has been broken since {release}. Is it?", + }, + expected_output={ + "error": None, + "function": None, + }, + seeds=[Incident()], + judges=JUDGES, + ), +] diff --git a/examples/sentry-assistant-python/evals/triage/credentials/openrouter.py b/examples/sentry-assistant-python/evals/triage/credentials/openrouter.py new file mode 100644 index 0000000..a894cca --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/credentials/openrouter.py @@ -0,0 +1,20 @@ +import getpass + +from eac import Credential + + +class OpenRouterKey(Credential): + """An OpenRouter API key. Logging in asks for one, and eac saves it for later runs.""" + + name = "openrouter" + + def is_authenticated(self, env): + return bool(env.get("OPENROUTER_API_KEY")) + + def authenticate(self): + print("Create a key at https://openrouter.ai/settings/keys") + return {"OPENROUTER_API_KEY": getpass.getpass("OpenRouter API key: ").strip()} + + @property + def setup_instructions(self): + return "Set OPENROUTER_API_KEY. Get a key at https://openrouter.ai/settings/keys." diff --git a/examples/sentry-assistant-python/evals/triage/credentials/sentry.py b/examples/sentry-assistant-python/evals/triage/credentials/sentry.py new file mode 100644 index 0000000..b253411 --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/credentials/sentry.py @@ -0,0 +1,39 @@ +import os +import shutil +import subprocess + +from eac import Credential + +from sentry_cli import cli_env + + +class SentryLogin(Credential): + """A Sentry login that can see the project the evals fill with issues. + + Logging in runs `sentry auth login`, which keeps its own login, then asks + for the org and project if they aren't set, which eac saves. When + $SENTRY_AUTH_TOKEN, $SENTRY_ORG and $SENTRY_PROJECT are set, as in CI, + they're used instead.""" + + name = "sentry" + + def is_authenticated(self, env): + if not (shutil.which("sentry") and env.get("SENTRY_ORG") and env.get("SENTRY_PROJECT")): + return False + project = f"{env['SENTRY_ORG']}/{env['SENTRY_PROJECT']}" + return subprocess.run(["sentry", "project", "view", project], env=cli_env(env), capture_output=True).returncode == 0 + + def authenticate(self): + # A token, when set, is the login. Otherwise use the CLI's, logging in if there isn't one. + if not os.environ.get("SENTRY_AUTH_TOKEN") and subprocess.run(["sentry", "auth", "whoami"], capture_output=True).returncode: + subprocess.run(["sentry", "auth", "login"], check=True) + # Only what isn't set already, so eac saves just what you entered. + prompts = {"SENTRY_ORG": "Sentry org: ", "SENTRY_PROJECT": "Sentry project, an empty one the evals can fill with issues: "} + return {key: input(prompt).strip() for key, prompt in prompts.items() if not os.environ.get(key)} + + @property + def setup_instructions(self): + return ( + "Install the Sentry CLI (https://cli.sentry.dev) and log in with `sentry auth login`, or set " + "SENTRY_AUTH_TOKEN. Set SENTRY_ORG and SENTRY_PROJECT to an empty project the evals can fill with issues." + ) diff --git a/examples/sentry-assistant-python/evals/triage/dataset.yml b/examples/sentry-assistant-python/evals/triage/dataset.yml new file mode 100644 index 0000000..312277c --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/dataset.yml @@ -0,0 +1,13 @@ +name: triage +runtime: python + +offline: + runner: ./runners/offline.py:OfflineTriageRunner + cases: ./cases.py:OFFLINE_CASES + concurrency: 4 + +online: + runner: ./runners/online.py:OnlineTriageRunner + judges: + - name: triage_llm_judge + path: ./judges/triage_llm_judge.py:TriageLLMJudge diff --git a/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py b/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py new file mode 100644 index 0000000..2dc8b55 --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py @@ -0,0 +1,17 @@ +from eac import Judge, Score + + +class FoundCauseJudge(Judge): + """Passes if the agent named the function that needs fixing.""" + + name = "found_cause" + + def judge(self, case, *, seeds, agent_trace=None): + expected = case.expected_output["function"] + actual = case.output.get("function") + + # Accepts "checkout.apply_coupon()" for "apply_coupon". + if (actual or "").split(".")[-1].removesuffix("()") == (expected or ""): + return Score.passed(self.name) + + return Score.failed(self.name, f"expected {expected}, actual {actual}") diff --git a/examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py b/examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py new file mode 100644 index 0000000..dc804c7 --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py @@ -0,0 +1,19 @@ +from eac import Judge, Score + + +class FoundIssueJudge(Judge): + """Passes if the agent named the issue the seed created for the expected + error, or no issue when there's nothing to find.""" + + name = "found_issue" + + def judge(self, case, *, seeds, agent_trace=None): + error = case.expected_output["error"] + + expected = seeds["incident"]["issues"][error] if error else None + actual = case.output.get("issue") + + if actual == expected: + return Score.passed(self.name) + + return Score.failed(self.name, f"expected {expected}, actual {actual}") diff --git a/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py b/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py new file mode 100644 index 0000000..0b3727e --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py @@ -0,0 +1,51 @@ +import json + +from eac import AgentTrace, Judge, LLMMetrics, Score + +from agent import client, usage_of +from evals.triage.credentials.openrouter import OpenRouterKey +from traces import load_conversation + +# TODO: Better judge +JUDGE_MODEL = "openai/gpt-6-luna" + + +class TriageLLMJudge(Judge): + """Has a model review the investigation. It reads the agent trace (conversation history) the agent.py saved, so it works online too.""" + + name = "triage_llm_judge" + credentials = [OpenRouterKey()] + + PROMPT = """\ +You review a triage agent's investigation of an alert about an online shop. Grade \ +its final answer: is the root cause backed by what its tools returned, and would \ +the fix solve the problem without breaking anything else? When no issue explains \ +the alert, the right answer says so. +Reply with JSON: {"score": , "explanation": ""}""" + + def get_agent_trace(self, run): + conversation = load_conversation(run.conversation_id) + if conversation is None: + return None + return AgentTrace(trace=conversation["messages"], metrics=LLMMetrics(**conversation["usage"])) + + async def judge(self, case, *, seeds, agent_trace=None): + if agent_trace is None: + return None + async with client() as openrouter: + result = await openrouter.chat.send_async( + model=self.args.get("model", JUDGE_MODEL), + messages=[ + {"role": "system", "content": self.PROMPT}, + {"role": "user", "content": json.dumps(agent_trace)}, + ], + response_format={"type": "json_object"}, + temperature=0, + ) + grade = json.loads(result.choices[0].message.content) + return Score( + name=self.name, + score=float(grade["score"]), + explanation=grade.get("explanation"), + llm_judge_metrics=LLMMetrics(**usage_of(result)), + ) diff --git a/examples/sentry-assistant-python/evals/triage/runners/offline.py b/examples/sentry-assistant-python/evals/triage/runners/offline.py new file mode 100644 index 0000000..a511477 --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/runners/offline.py @@ -0,0 +1,15 @@ +from eac import OfflineRunner + +from agent import DEFAULT_MODEL, triage +from evals.triage.credentials.openrouter import OpenRouterKey +from evals.triage.credentials.sentry import SentryLogin + + +class OfflineTriageRunner(OfflineRunner): + """Runs the agent on each case's alert, about the release the seed made.""" + + credentials = [OpenRouterKey(), SentryLogin()] + + async def run_case(self, case, *, seeds, conversation_id): + alert = case.input["alert"].format(release=seeds["incident"]["release"]) + return await triage(alert, conversation_id=conversation_id, model=self.args.get("model", DEFAULT_MODEL)) diff --git a/examples/sentry-assistant-python/evals/triage/runners/online.py b/examples/sentry-assistant-python/evals/triage/runners/online.py new file mode 100644 index 0000000..e413ca5 --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/runners/online.py @@ -0,0 +1,24 @@ +from eac import Case, OnlineRunner + +from traces import recent_conversations + + +class OnlineTriageRunner(OnlineRunner): + """Collects the conversations agent.py saved as production traffic.""" + + def collect_cases(self, window): + conversations = recent_conversations(window.since, window.until) + sampled = [c for c in conversations if window.samples(c["conversation_id"])] + + cases = [] + for c in sampled[: window.limit]: + cases.append( + Case( + name=c["conversation_id"], + input={"alert": c["alert"]}, + output=c["answer"], + conversation_id=c["conversation_id"], + ) + ) + + return cases diff --git a/examples/sentry-assistant-python/evals/triage/seed.py b/examples/sentry-assistant-python/evals/triage/seed.py new file mode 100644 index 0000000..b6d2723 --- /dev/null +++ b/examples/sentry-assistant-python/evals/triage/seed.py @@ -0,0 +1,57 @@ +import secrets +import time + +import sentry_sdk +from eac import Seed + +from app import app +from evals.triage.credentials.sentry import SentryLogin +from sentry_cli import ORG, PROJECT, cli + +# A request to the shop that hits each error. +REQUESTS = { + "coupon": ("/checkout", {"cart": ["MUG"], "country": "US", "coupon": "SPRING"}), + "quantity": ("/checkout", {"cart": ["TEE:2"], "country": "US"}), + "empty_cart": ("/checkout", {"cart": [], "country": "US"}), + "newsletter": ("/newsletter", {"email": "ada@example.com"}), +} + + +class Incident(Seed): + """Releases a new version of the shop, sends it a request for each error in REQUESTS, and waits for their issues to show up in Sentry.""" + + name = "incident" + credentials = [SentryLogin()] + + def setup(self): + release = f"shop@1.4.{secrets.token_hex(3)}" + dsn = cli("dsn", "list", PROJECT)["data"][0]["dsn"] + sentry_sdk.init(dsn=dsn, release=release, default_integrations=False) + + for error, request in REQUESTS.items(): + with sentry_sdk.new_scope() as scope: + # Keeps each run's issues apart, instead of grouping them with + # the same error from other runs. + scope.fingerprint = ["{{ default }}", release] + scope.set_tag("eac_error", error) + app.handle(*request) + + sentry_sdk.flush() + + return { + "release": release, + "issues": {error: self.wait_for_issue(release, error) for error in REQUESTS}, + } + + def wait_for_issue(self, release, error): + """The short ID of the issue `error` created, once Sentry has it.""" + for _ in range(60): + issues = cli("issue", "list", PROJECT, "--query", f"release:{release} eac_error:{error}")["data"] + if issues: + return issues[0]["shortId"] + time.sleep(2) + raise TimeoutError(f"the {error} issue didn't show up in Sentry within 2 minutes") + + def cleanup(self, handle): + for short_id in handle["issues"].values(): + cli("issue", "resolve", f"{ORG}/{short_id}") diff --git a/examples/sentry-assistant-python/pyproject.toml b/examples/sentry-assistant-python/pyproject.toml new file mode 100644 index 0000000..172e131 --- /dev/null +++ b/examples/sentry-assistant-python/pyproject.toml @@ -0,0 +1,21 @@ +[project] +name = "sentry-assistant-python" +version = "0.0.0" +requires-python = ">=3.11" +dependencies = [ + "openrouter>=1.3", + "sentry-sdk>=2", +] + +# Only the evals use the SDK, so the product doesn't ship with it. +[dependency-groups] +dev = [ + "eac-sdk", +] + +[tool.uv] +package = false + +# The SDK from this checkout. In your own project, depend on eac-sdk from PyPI. +[tool.uv.sources] +eac-sdk = { path = "../../sdks/python", editable = true } diff --git a/examples/sentry-assistant-python/sentry_cli.py b/examples/sentry-assistant-python/sentry_cli.py new file mode 100644 index 0000000..d8188ad --- /dev/null +++ b/examples/sentry-assistant-python/sentry_cli.py @@ -0,0 +1,21 @@ +"""The Sentry CLI (https://cli.sentry.dev) for the agent's tools and the evals' seed. The project comes from $SENTRY_ORG and $SENTRY_PROJECT.""" + +import json +import os +import subprocess + +ORG = os.environ.get("SENTRY_ORG") +PROJECT = f"{ORG}/{os.environ.get('SENTRY_PROJECT')}" + + +def cli_env(env=os.environ): + """The environment to run `sentry` in. A $SENTRY_AUTH_TOKEN is used over the CLI's own login, which the CLI otherwise prefers.""" + return {**env, "SENTRY_FORCE_ENV_TOKEN": "1"} if env.get("SENTRY_AUTH_TOKEN") else dict(env) + + +def cli(*args): + """Runs a `sentry` command and returns its JSON output.""" + result = subprocess.run(["sentry", *args, "--json"], env=cli_env(), capture_output=True, text=True) + if result.returncode: + raise RuntimeError(result.stderr.strip()) + return json.loads(result.stdout) diff --git a/examples/sentry-assistant-python/traces.py b/examples/sentry-assistant-python/traces.py new file mode 100644 index 0000000..4d1a65d --- /dev/null +++ b/examples/sentry-assistant-python/traces.py @@ -0,0 +1,27 @@ +"""The agent's saved conversations, in .traces/. +They represent agent traces a real product would send to Sentry: the offline runs make them, and the online evals read them back as production traffic. +See https://docs.sentry.io/product/agents for full docs. +""" + +import json +from datetime import datetime +from pathlib import Path + +TRACES = Path(__file__).parent / ".traces" + + +def save_conversation(conversation): + TRACES.mkdir(exist_ok=True) + (TRACES / f"{conversation['conversation_id']}.json").write_text(json.dumps(conversation, indent=2)) + + +def load_conversation(conversation_id): + path = TRACES / f"{conversation_id}.json" + return json.loads(path.read_text()) if path.exists() else None + + +def recent_conversations(since, until): + """The conversations started in [since, until), oldest first.""" + conversations = [json.loads(path.read_text()) for path in TRACES.glob("*.json")] + in_window = [c for c in conversations if since <= datetime.fromisoformat(c["started_at"]) < until] + return sorted(in_window, key=lambda c: c["started_at"]) diff --git a/examples/sentry-assistant-python/uv.lock b/examples/sentry-assistant-python/uv.lock new file mode 100644 index 0000000..be92dc8 --- /dev/null +++ b/examples/sentry-assistant-python/uv.lock @@ -0,0 +1,325 @@ +version = 1 +revision = 5 +requires-python = ">=3.11" + +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + +[[package]] +name = "anyio" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "typing-extensions", marker = "python_full_version < '3.15'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a1/98/7e457a3b014976887a050561955c0b76e1e7e2d6e27b78ecef2ef80518f2/anyio-4.16.0.tar.gz", hash = "sha256:59bb03251907983d1603d27c3087ddb1e93299ea2163adcdba37899a4fb12ffb", size = 310971, upload-time = "2026-11-01T11:20:07.282Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a9/16/7757fb84c819accc7d7e9af5291b261e4abb8627ee040f99e7d35ef2457a/anyio-4.16.0-py3-none-any.whl", hash = "sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026", size = 134521, upload-time = "2026-11-01T11:20:05.59Z" }, +] + +[[package]] +name = "certifi" +version = "2026.10.23" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, +] + +[[package]] +name = "eac-sdk" +source = { editable = "../../sdks/python" } + +[[package]] +name = "h11" +version = "0.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/ee/02a2c011bdab74c6fb3c75474d40b3052059d95df7e73351460c8588d963/h11-0.16.0.tar.gz", hash = "sha256:4e35b956cf45792e4caa5885e69fba00bdbc6ffafbfa020300e549b208ee5ff1", size = 101250, upload-time = "2025-04-24T03:35:25.427Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, +] + +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + +[[package]] +name = "httpx" +version = "0.28.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "certifi" }, + { name = "httpcore" }, + { name = "idna" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b1/df/48c586a5fe32a0f01324ee087459e112ebb7224f646c0b5023f5e79e9956/httpx-0.28.1.tar.gz", hash = "sha256:75e98c5f16b0f35b567856f597f06ff2270a374470a5c2392242528e3e3e42fc", size = 141406, upload-time = "2024-12-06T15:37:23.222Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "jsonpath-python" +version = "1.1.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/98/18/4ca8742534a5993ff383f7602e325ce2d5d7cc93d72ac5e1cdedbea8a458/jsonpath_python-1.1.6.tar.gz", hash = "sha256:dded9932b4ec41fb8726e09c83afa4e6be618f938c2db287cc2a81723c639671", size = 88178, upload-time = "2026-05-07T01:26:34.482Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/55/8a/1270a6803bd821cbfcdda387eaa13cb41a7b1f7b9bd145979b3bfb9d6cb7/jsonpath_python-1.1.6-py3-none-any.whl", hash = "sha256:a1c50afd8d3fbbaf47a4873bc890dcb3c15da96f5c020327977d844d8731a2d4", size = 14453, upload-time = "2026-05-07T01:26:33.306Z" }, +] + +[[package]] +name = "openrouter" +version = "1.3.200" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "httpcore" }, + { name = "httpx" }, + { name = "jsonpath-python" }, + { name = "pydantic" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/67/fc/533b0fdf0034e63f41cd1e2b792494dd69d59086329cebd9f5a596a83114/openrouter-1.3.200.tar.gz", hash = "sha256:d83e164c09b8b55f558d0c0bc446907584a1021dfec4084309498b8a2bd5ddb3", size = 700231, upload-time = "2026-11-20T15:29:30.676Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bb/26/7e5cb46752668009c2748b733f19032cd54986d5bf95b1845382c1311fb8/openrouter-1.3.200-py3-none-any.whl", hash = "sha256:378e714684d248c4f32b360572519c73c8e11681212a5b123f85e8407a55f5f2", size = 1507991, upload-time = "2026-11-20T15:29:29.165Z" }, +] + +[[package]] +name = "pydantic" +version = "2.14.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8e/25/3ec212432a6031b65f043eaca9c820ddf87c0d0aa330023e64f79fcb5db6/pydantic-2.14.4.tar.gz", hash = "sha256:7c19f1d46f8accf55a4617a6116e1ade64840870f397b846a2c53fb9019414ba", size = 927354, upload-time = "2026-11-19T12:57:39.767Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8a/8c/824a686c4ba815ddb0722f9e66272088bccd4e1ae1d2f7015375e4a4fc7f/pydantic-2.14.4-py3-none-any.whl", hash = "sha256:653a2ad9f6d8858529c77c72717d0ea991d6c6837fe683246b2f4b2bbfc3fadc", size = 494865, upload-time = "2026-11-19T12:57:37.688Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.50.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/fb/63/0ceb815a7762576027ce388544c573d440574f95afb1302a2496b96db548/pydantic_core-2.50.5.tar.gz", hash = "sha256:1e740886083ff95530d694e6a3f09ed914bcf92a496d16acd307c6c3484fc36d", size = 523285, upload-time = "2026-11-19T12:56:38.067Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2e/13/38388fd381879499d83dec38826fdb9457ab67b77f6e32c2dddcfc604dae/pydantic_core-2.50.5-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:bcc830e4f48499fd30a870f07c30752273ae2ddccce34d65d51c9fc880c380ab", size = 2173303, upload-time = "2026-11-19T12:53:40.749Z" }, + { url = "https://files.pythonhosted.org/packages/e6/3b/8b75df5dbcd09d81e536edc17d1d77767a4044fa5b90cf875c4100bb7ce7/pydantic_core-2.50.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:40d5da89a632e6c6c938f93fdf54c534882d258a80f51ccfe1650cdedc12e82c", size = 2135436, upload-time = "2026-11-19T12:53:42.276Z" }, + { url = "https://files.pythonhosted.org/packages/de/55/862dcd360026869daa74e828375a5f8d4071d160c4499121c4eb6748d325/pydantic_core-2.50.5-cp311-cp311-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:f7509c6f8a0f9d9eac58340dd567f0eb71ce2f762df09f0d51280e30da3fe687", size = 2287206, upload-time = "2026-11-19T12:53:43.562Z" }, + { url = "https://files.pythonhosted.org/packages/8f/bd/029b44924c3df7cf74f2127384ed628aa9070df05881582cca17e5a113c8/pydantic_core-2.50.5-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ba2b34529984a8e3cb1bc62a7687617722695a2cb4e57958de32a0eba128a07a", size = 2133843, upload-time = "2026-11-19T12:53:45.093Z" }, + { url = "https://files.pythonhosted.org/packages/f3/6e/48927f3224125c67939d70c697b9785a15cb53dccf2300b4fafec788da9e/pydantic_core-2.50.5-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:f8dc2008577c5e02eaa1eb3fbfa8fe0eba9af27ff6a740e9f1dae6661e88efcb", size = 2215985, upload-time = "2026-11-19T12:53:46.384Z" }, + { url = "https://files.pythonhosted.org/packages/4c/18/b7dc6bb4e46f6c6a097d44c16bfb917d6b1af905a7c77a4d0d17799c9787/pydantic_core-2.50.5-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:4dcf7b2cdfb9c59c1d377de318f3c8462121f32db939299999484ea0b1eadf18", size = 2408931, upload-time = "2026-11-19T12:53:47.884Z" }, + { url = "https://files.pythonhosted.org/packages/8e/cb/7be07fe1a633d915f8b02d6d3740a016521e826914216c179974b7b02f4c/pydantic_core-2.50.5-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:ed4a01922af0d41b2a3b9433818cbb73b6b28e8dea344c90917c1fdcceb9960f", size = 2458757, upload-time = "2026-11-19T12:53:49.451Z" }, + { url = "https://files.pythonhosted.org/packages/bd/77/9520ca4c8f9bac81c2c4124389a8413c9d0e97e054b1d0c854b71e104297/pydantic_core-2.50.5-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:488319076ec92908b91fc6265ce761f1d78748f69f85518564fd16bf333e1b70", size = 2257712, upload-time = "2026-11-19T12:53:50.865Z" }, + { url = "https://files.pythonhosted.org/packages/0a/47/53ee8d0124583ec6ad88bd9797dcd95d8269cd02e2524d4f9d63bf5fcbcf/pydantic_core-2.50.5-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:50d12ba7cab98b355ba65d65655e969f66934ab7a3d2d0c8abd61ae2282efce5", size = 2284545, upload-time = "2026-11-19T12:53:52.338Z" }, + { url = "https://files.pythonhosted.org/packages/78/af/69816722a0847162b5e7127f29bba0694cd2cfd5ec42d88a19941ac985f0/pydantic_core-2.50.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:be4615d4b5f90c65dce2295dcf32eff7f05ea5d0d3a82421c03c572785cb9bf8", size = 2323712, upload-time = "2026-11-19T12:53:53.779Z" }, + { url = "https://files.pythonhosted.org/packages/cb/f7/07e5551c38c1997f02079ee89b6094d3bb94dd1febfb8852724b69f0275d/pydantic_core-2.50.5-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:65b0f52abcd06dbb53961db9cc3610929f4f6518c3726d965a9babdaf7bd79c9", size = 2492159, upload-time = "2026-11-19T12:53:55.072Z" }, + { url = "https://files.pythonhosted.org/packages/92/fc/48f6134b7691ea8453f0f8f1b41761118ff2a27a47599f276a34303c9074/pydantic_core-2.50.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:05815bbe2c7bec58d1ce456cc0a98f368e6ef9345b1d9311f42b814d34ad7086", size = 2500209, upload-time = "2026-11-19T12:53:57.775Z" }, + { url = "https://files.pythonhosted.org/packages/f6/dc/ca894248073c89beb14944493c587be807cbb7327f1befdc2ca8b2a5865c/pydantic_core-2.50.5-cp311-cp311-win32.whl", hash = "sha256:e65f78eb3d930ac30ff3557fc74a0771300096fb002f588a6fe8d946e83f14ad", size = 2137200, upload-time = "2026-11-19T12:53:58.973Z" }, + { url = "https://files.pythonhosted.org/packages/ac/61/5948dca31a355a03bbc4284cfb6f93e9d8add875ebcb38c90b848c28b522/pydantic_core-2.50.5-cp311-cp311-win_amd64.whl", hash = "sha256:d4ebf349b1b60049e80df5d9ea6725b1b7e434a7d006474b0f664fa72a6b3c75", size = 2271411, upload-time = "2026-11-19T12:54:00.291Z" }, + { url = "https://files.pythonhosted.org/packages/80/df/453c5e77d90768c576d2881474882e958197fa41e48f644b2250efb02eef/pydantic_core-2.50.5-cp311-cp311-win_arm64.whl", hash = "sha256:736782cfbca37b4d81e6f3c7a3414de25db045dcdb7a05e55b64191a33c5ac45", size = 2202753, upload-time = "2026-11-19T12:54:01.573Z" }, + { url = "https://files.pythonhosted.org/packages/2e/ce/c79f87db419571137da902afa5cb16f7a981943bb9e0a520886fc4ed06e6/pydantic_core-2.50.5-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:24d23de96195ff9637e5940a7fbde3bea6a355b26fb5f491737dd803aa5d5a93", size = 2233897, upload-time = "2026-11-19T12:54:02.758Z" }, + { url = "https://files.pythonhosted.org/packages/9f/6f/4e172894c2a4ca3bacd6c5f823ea5576df25eafe7593ffeb3576895b92aa/pydantic_core-2.50.5-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a9bcf23628860d5a90cacdc188ee3b7d0547a38eb985214f03e7002a6ca0e558", size = 2111013, upload-time = "2026-11-19T12:54:04.084Z" }, + { url = "https://files.pythonhosted.org/packages/08/3f/80d4525a45660f1a8d9ccc33fbd81c5650e62857d75e008c2ac37c1b2717/pydantic_core-2.50.5-cp312-cp312-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:30988977d38909df645183a9869a9d12211485639ac4757de18585f0ccb6f3dc", size = 2262195, upload-time = "2026-11-19T12:54:05.347Z" }, + { url = "https://files.pythonhosted.org/packages/5d/55/02aacb1a5294a227e44dfba6ae921d1ffe3fd296fad6caceef3ec685d10f/pydantic_core-2.50.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:07a62d44515d674d750cfd86b7ce1dd93111be870f378d7c27b37aeb78d0cb4a", size = 2131910, upload-time = "2026-11-19T12:54:06.821Z" }, + { url = "https://files.pythonhosted.org/packages/ed/5e/38190b580e1cd1c9264ccbf3ac6baeedf5b0459887abfdd9a44a0879b4d0/pydantic_core-2.50.5-cp312-cp312-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:7dfc0431e94659ae8449303ca4fb1588dc1e00282d6636d00d72bb4bd6459b4d", size = 2198229, upload-time = "2026-11-19T12:54:08.316Z" }, + { url = "https://files.pythonhosted.org/packages/9a/ef/467df68c04913f359b8b388def9229c5a3df52aafa20bc185073e6e94d67/pydantic_core-2.50.5-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:004c784d4642bd1112a9fa9a022543aa17793fd32004f7e903ee97df2086bad4", size = 2387400, upload-time = "2026-11-19T12:54:09.832Z" }, + { url = "https://files.pythonhosted.org/packages/a6/36/d7d90c0180f543904bea4b1c2a2464f3fe638d2fa570e001c391e22ce9d7/pydantic_core-2.50.5-cp312-cp312-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:fa66340c6d3e08a276803812e7665312dfc75dd24eedfa8e09f18a0f8e3e0e8f", size = 2463534, upload-time = "2026-11-19T12:54:11.406Z" }, + { url = "https://files.pythonhosted.org/packages/be/5b/897bf2e3cc5f65dc01507d90323c13cab659c0432cc3c70b353e5be40f2f/pydantic_core-2.50.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:470bbc2495367f60d3ca849a8039e4c164701d10637e7743f4427d92651bdb6d", size = 2264846, upload-time = "2026-11-19T12:54:13.244Z" }, + { url = "https://files.pythonhosted.org/packages/4a/85/2646b0e6f74805325dc8582fec6b5fecb289cd54515d25213e6c5b5aef1c/pydantic_core-2.50.5-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:43a6eaee9eeac4a54f2ff6567e1b0ec51651b37a40d862cab2e6fd16109e6528", size = 2264716, upload-time = "2026-11-19T12:54:14.59Z" }, + { url = "https://files.pythonhosted.org/packages/c2/3d/dc7a1ceb248a04047e744b70b8f0d8b3b64eafdd49005b67c4e8447c1b4c/pydantic_core-2.50.5-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:b66f2434c895652ac21c030d5a3a92c7811f0f9b98af41bf35be899c2d34aa4c", size = 2303511, upload-time = "2026-11-19T12:54:16.1Z" }, + { url = "https://files.pythonhosted.org/packages/de/93/8ab4188a5884e6aa8a632b80dbefc60872b1419ed3f69aeceeaa02907b88/pydantic_core-2.50.5-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:2cb80e0323b31d4669c4d72a466d99c885e13deb06205aa079ea6594e7ad1ef8", size = 2474575, upload-time = "2026-11-19T12:54:17.379Z" }, + { url = "https://files.pythonhosted.org/packages/08/b6/697b1f2af3fc0ea26934dc269458d72ef2340797a9dbe60e79ca36a589f9/pydantic_core-2.50.5-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:3cf575867ecaf89aca440e5a4253d2facf1ca37bab30a4e8c205ec611228126a", size = 2501161, upload-time = "2026-11-19T12:54:18.653Z" }, + { url = "https://files.pythonhosted.org/packages/dc/de/6c5e2096f2f76939f554bdb5ce0892ebaf3aa46e7261815204ae2ec37efe/pydantic_core-2.50.5-cp312-cp312-win32.whl", hash = "sha256:57d4350167130c9c136b7efa35e6e7ee9539779698755b01007834d32c7a1f7d", size = 2125052, upload-time = "2026-11-19T12:54:19.992Z" }, + { url = "https://files.pythonhosted.org/packages/65/9d/666343e8bf3c1540f82e3a7bd1d3a844746e6827889c9b0a68561795e933/pydantic_core-2.50.5-cp312-cp312-win_amd64.whl", hash = "sha256:baa107902f8e38011a5f79836d905eb6bfaac1d4b0bd09fc86509b711d0b09c8", size = 2269672, upload-time = "2026-11-19T12:54:21.23Z" }, + { url = "https://files.pythonhosted.org/packages/db/16/65761cc402edd31a37cf9e91975ea1b230af89f6baeb33d9ef6f01f9f14b/pydantic_core-2.50.5-cp312-cp312-win_arm64.whl", hash = "sha256:2d785ae9ff0ac485567f27f4fc53712268916e04be4a590160e5bf55b096225a", size = 2171863, upload-time = "2026-11-19T12:54:22.86Z" }, + { url = "https://files.pythonhosted.org/packages/60/32/1a87aca62759be630ef981b735d732ffa17ec8defac0271fa7894a815f9c/pydantic_core-2.50.5-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:e5d5d77a9446f44688a5ef420d92c9facac0865ef5565215db54be184ab7906f", size = 2235184, upload-time = "2026-11-19T12:54:24.697Z" }, + { url = "https://files.pythonhosted.org/packages/6f/8a/53d7448d3e0c3fd8fb30621ef493e5340d6779f80cba2d515fc81915f96e/pydantic_core-2.50.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:639a51931869c0594d8723b2f529c547db1aa33dc9571d001dc205d896170c08", size = 2110593, upload-time = "2026-11-19T12:54:26.231Z" }, + { url = "https://files.pythonhosted.org/packages/ac/66/fa127513da383218051a4e7c76ec63b42eb0b073d010d94215f930fa9a4d/pydantic_core-2.50.5-cp313-cp313-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:c69eb2e09d2830949e6e8f395d4eb8c714ba083213ccff64932ded681fe69a4e", size = 2261527, upload-time = "2026-11-19T12:54:27.79Z" }, + { url = "https://files.pythonhosted.org/packages/e8/35/70928b77f724fa0f4824e0527891df02cf9b34101aab6e2ab348fd127f06/pydantic_core-2.50.5-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:8bbe282e79dc71b24ba7be284eacf27c8ddff8f26911e2030a0dd123c6aed326", size = 2131539, upload-time = "2026-11-19T12:54:29.441Z" }, + { url = "https://files.pythonhosted.org/packages/e3/e0/7d03f6521da1cb43de3fa2c1740e7d0e0d34f971acdd5f6c6462d360f195/pydantic_core-2.50.5-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:43917f090dfda561575a72f75814f76a0680964b70d7b44c84e44d217bdeade7", size = 2197447, upload-time = "2026-11-19T12:54:31.007Z" }, + { url = "https://files.pythonhosted.org/packages/b9/57/bacad2d6251565b1b428383175f0b7edcb841d96e37130a85e87636ecb15/pydantic_core-2.50.5-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:93ee3b4f9c64fb1c39892413c4196d0a84790a7e0e5d72b463882c432c1ffafe", size = 2387397, upload-time = "2026-11-19T12:54:32.779Z" }, + { url = "https://files.pythonhosted.org/packages/fb/f7/95e23d389b7bd796127f783950aeaee408ffea4d77d165cdce2c3f3b5638/pydantic_core-2.50.5-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:57b79401d870c9df395799c596d81875b647ecf3030129d86659a54f6bfcc0db", size = 2463652, upload-time = "2026-11-19T12:54:34.303Z" }, + { url = "https://files.pythonhosted.org/packages/13/c2/62015187d0e986dafc530ea4df390fce3d3379c744959148806668d40ab9/pydantic_core-2.50.5-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cbfde3ad127786f1dea1a6cd89a5eb824a16203f24743ad2b4e07506f43bc844", size = 2264332, upload-time = "2026-11-19T12:54:35.918Z" }, + { url = "https://files.pythonhosted.org/packages/73/22/e4421a2018ee909a5e0cfd4410ed88d12481e31fe37abe272bc392f74675/pydantic_core-2.50.5-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:1793ec63c8f247131aa4dfc8c4da645b9c5872cf26b53ce240f143f59ad116e4", size = 2264563, upload-time = "2026-11-19T12:54:37.356Z" }, + { url = "https://files.pythonhosted.org/packages/28/a0/3cd863a51470341405579257cc84d4df2e70ddb5ed17160859687868cc9d/pydantic_core-2.50.5-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:5027c263fbceb821cfb4b385d36d485e19efca1d9adcc4e5bec69c04ca3cdc83", size = 2302938, upload-time = "2026-11-19T12:54:38.777Z" }, + { url = "https://files.pythonhosted.org/packages/c6/50/0b71fafde186b95a7a9fd704ef5dfd7c28b2b9a4645449912267c7457884/pydantic_core-2.50.5-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:dac78f91e263c4c9a4d587b9d97b3b5b2561293b33247452cc3cfe5b500e8cfb", size = 2473911, upload-time = "2026-11-19T12:54:40.3Z" }, + { url = "https://files.pythonhosted.org/packages/6b/8f/0106ea256e51e9b0d21c8aa7b32091d5f8869597282c5c09a7144f2208bc/pydantic_core-2.50.5-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:b9348cfd798b8199d34da5258becf2fc8f5e4e7a3b51da30c34b81b996a07b34", size = 2501611, upload-time = "2026-11-19T12:54:41.758Z" }, + { url = "https://files.pythonhosted.org/packages/da/b8/d3923395ada2e5738eaa985e2d9c623cb00f6687f94565a2abc0ddf573f8/pydantic_core-2.50.5-cp313-cp313-win32.whl", hash = "sha256:22f5f0c37251611191a55e801a5150aa21f348fa10eac8eac9fa43c29937a7b1", size = 2125035, upload-time = "2026-11-19T12:54:43.281Z" }, + { url = "https://files.pythonhosted.org/packages/7b/08/2759efbffc5643787a5a0a6e19b98805d102346a8e52ad2a181a92bd55ea/pydantic_core-2.50.5-cp313-cp313-win_amd64.whl", hash = "sha256:d34c0d4dd4a318f2be788a60a972c3a1ed5da0155a7c06d6dd810dc5d60ad704", size = 2268229, upload-time = "2026-11-19T12:54:44.905Z" }, + { url = "https://files.pythonhosted.org/packages/c7/18/b4491f24c42f6d31b149d30c2b1bb5a062e3a79ee626cc0aa2161e86eb5a/pydantic_core-2.50.5-cp313-cp313-win_arm64.whl", hash = "sha256:cbec4aad328be58961c738b83fc2c7bd993242d2366f949d914e8c09266dee0e", size = 2172693, upload-time = "2026-11-19T12:54:46.368Z" }, + { url = "https://files.pythonhosted.org/packages/91/86/570c4fedb8eeab9062032bc45875490090477fddce932328a20b9cb834ff/pydantic_core-2.50.5-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:00598ae680c6e4a17cda01910e49c0da8ce15610505e6c57cec3f15d83daef88", size = 2239820, upload-time = "2026-11-19T12:54:47.806Z" }, + { url = "https://files.pythonhosted.org/packages/5b/a6/5bc38ad74a5705bcfdf1fd4e2009a62638a45dc246e3b0fc8a86e8c9ff4b/pydantic_core-2.50.5-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:e8fe516a4b3b06e4ff83b9adee4a786d28a617e5fb5fe90bda49fb6f52a5ac19", size = 2111039, upload-time = "2026-11-19T12:54:49.244Z" }, + { url = "https://files.pythonhosted.org/packages/d8/b5/a494d5d4ffd2dc1b06f1572d7651a4d6ada7881c5a527930be8f0171fc34/pydantic_core-2.50.5-cp314-cp314-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:63a0ba0d7ccf37c8c724bb7ed13c3aa0aa4c743f4f5f376c92c47e584844c7b1", size = 2264771, upload-time = "2026-11-19T12:54:50.701Z" }, + { url = "https://files.pythonhosted.org/packages/cc/13/099f19c4be6dbe10e327b17447e137ebd679cc64a3833a87f4597dcffc2a/pydantic_core-2.50.5-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:27bc22dc8d50335bc62296261a7dc4c2572149910ba7c274ef0f945b5be0d570", size = 2133839, upload-time = "2026-11-19T12:54:52.33Z" }, + { url = "https://files.pythonhosted.org/packages/10/4c/9eec8f71877124a093a0fc0033747489ea7e18d364ec562a7d170c483f4f/pydantic_core-2.50.5-cp314-cp314-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:2f6a8c9b8647378c0dc128805e6b98da39d36019a0e7cac134badeaedb14f849", size = 2200176, upload-time = "2026-11-19T12:54:53.745Z" }, + { url = "https://files.pythonhosted.org/packages/51/45/79ed6028c3e19a5376057da8545977d6f74d37afccdeb684ee7274d05994/pydantic_core-2.50.5-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:feb8c87dbc4684777ddafbf37c922d9e2748272ba61e362ebf85db73ebda6234", size = 2393117, upload-time = "2026-11-19T12:54:55.28Z" }, + { url = "https://files.pythonhosted.org/packages/c6/cc/0b9d5b6652e55cbe6d2eb5c56947bb19c106be388157a410847362b2fd8e/pydantic_core-2.50.5-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:e0a7ae307b4e1eff195cd23a757da07f70a115e45175039caf5f3979a20c7edb", size = 2469324, upload-time = "2026-11-19T12:54:56.758Z" }, + { url = "https://files.pythonhosted.org/packages/79/e3/df03dc4e10c460d37dad8921ec9c6f177bc33d4f2da808d5ae4d8f11acfe/pydantic_core-2.50.5-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:88b543705849d0c59343f97c38296dbf59eb7b3c9565bd4fe1ed638ba38da5ed", size = 2269323, upload-time = "2026-11-19T12:54:58.209Z" }, + { url = "https://files.pythonhosted.org/packages/d5/28/4779dd7ba7f2187222c4ee42f492a451d3425202fdd2b5970b701feab16c/pydantic_core-2.50.5-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:4ae5c9f84dfa43643d10328a212f709c7602c5e70df376d217ae5770d374ccd9", size = 2271462, upload-time = "2026-11-19T12:54:59.719Z" }, + { url = "https://files.pythonhosted.org/packages/0c/48/51f4d0d26e36341330a933c9c5660696023101a0e933552dbc00db49b1cd/pydantic_core-2.50.5-cp314-cp314-musllinux_1_1_aarch64.whl", hash = "sha256:922455cc5baddb0f2c82b7ba649e57e89183442b32fe512670db6ebb9b66b251", size = 2305488, upload-time = "2026-11-19T12:55:01.168Z" }, + { url = "https://files.pythonhosted.org/packages/53/53/17892228fd2e66aa2791f97f984bdd34081c1d6ec98997c8e5b8467d04c3/pydantic_core-2.50.5-cp314-cp314-musllinux_1_1_armv7l.whl", hash = "sha256:aa69eaeed433cfe5de809fb84c95536a5aed991b28290d0db059fe6766c69274", size = 2475854, upload-time = "2026-11-19T12:55:02.687Z" }, + { url = "https://files.pythonhosted.org/packages/58/11/c4daab94156b26f779aca920b710138dda04882f295f7e802f237da1082d/pydantic_core-2.50.5-cp314-cp314-musllinux_1_1_x86_64.whl", hash = "sha256:9f2bf218dbc93363fe3e31cc53d36db8d6ff4122179406bec05f33bb79c0e2c1", size = 2505669, upload-time = "2026-11-19T12:55:04.137Z" }, + { url = "https://files.pythonhosted.org/packages/83/47/375ab34f3907a0f40cebe2c3cea3e2c25dcf58e0f591991b85604b7258fc/pydantic_core-2.50.5-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:b2910ec0fa5aeb9bef70156f2b79f4783978fdcfaa7b2f1b5d1814458d2e79a1", size = 1496394, upload-time = "2026-11-19T12:55:05.468Z" }, + { url = "https://files.pythonhosted.org/packages/48/e7/e64fa77d1d335ad21d821adbe3d2590b9d7cc05d210ca11fa524a1c6902d/pydantic_core-2.50.5-cp314-cp314-win32.whl", hash = "sha256:1deb966176b1b66be4281c83f10a0b6b1cecedeb25f53ee894bf27b22376facd", size = 2128110, upload-time = "2026-11-19T12:55:06.797Z" }, + { url = "https://files.pythonhosted.org/packages/bd/da/feb489c6252364355d1f314a284a542cd6788cebe83f9507d4af81c95f4a/pydantic_core-2.50.5-cp314-cp314-win_amd64.whl", hash = "sha256:887424ba7c2145e97f131bc2cc73383a8c464d7bcd56eb98bbd941afb6868b95", size = 2278977, upload-time = "2026-11-19T12:55:08.188Z" }, + { url = "https://files.pythonhosted.org/packages/cd/81/a3bc7bee867be70ec58b3ef3d84e88420fc2d6fd52a8830a3f3a75f0891e/pydantic_core-2.50.5-cp314-cp314-win_arm64.whl", hash = "sha256:e7dd59f498ef42077f22db607571249db41997227018cb84644ba0059f8b5719", size = 2169842, upload-time = "2026-11-19T12:55:09.474Z" }, + { url = "https://files.pythonhosted.org/packages/2d/18/24bc9decf37a81ed5ab979a19ac0a23b457633d525e2c71d4b96476b1bf9/pydantic_core-2.50.5-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:372f4ab3e67b2387871950cfa27d94d644c3475e650836ea52e25c2e4fbd7975", size = 2227397, upload-time = "2026-11-19T12:55:11.022Z" }, + { url = "https://files.pythonhosted.org/packages/46/4f/d958789f577f91af3c9639e6c127cd729be7117d6318fcfa4b773e3bb220/pydantic_core-2.50.5-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0c9f0002e4ec37db931e4ee8b7dafab2c7288ef66354e74fe16484e60eac6616", size = 2091300, upload-time = "2026-11-19T12:55:12.395Z" }, + { url = "https://files.pythonhosted.org/packages/16/86/b2f630ebb50c18df1603a3d2b03b4722005c27dd4a54e3291b302dcaa54a/pydantic_core-2.50.5-cp314-cp314t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:d16cb794449c2bc0e5cb0ab0022813419bf5283266f2a7ff1fc54e5c6e27dcee", size = 2277674, upload-time = "2026-11-19T12:55:13.728Z" }, + { url = "https://files.pythonhosted.org/packages/91/8e/06b5d2da6c7bd8e817edd1dcce595a904ef295e66f1e243cc768ccfcaa41/pydantic_core-2.50.5-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:71633f82d51d4796a48026bd6eca5ec83e4a0edbe6187d59bbc45ace1111ebae", size = 2116208, upload-time = "2026-11-19T12:55:14.971Z" }, + { url = "https://files.pythonhosted.org/packages/40/0e/b818e7903883e6e51d10fd6ec43d2837cdea3861571d050942ff5d873327/pydantic_core-2.50.5-cp314-cp314t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:f20c692c599ebac7f04f3a0102b969f3f9d6667ffe1e72629fc7fbf8b6375234", size = 2210100, upload-time = "2026-11-19T12:55:16.308Z" }, + { url = "https://files.pythonhosted.org/packages/d0/aa/8c062145581453ac1b0fb3577ec193926b8973dc4b990283c304a955d80b/pydantic_core-2.50.5-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:2f0a86887c644247eff4cc7b9e609042a49833dcd72f84574e7b8beea89729ab", size = 2410440, upload-time = "2026-11-19T12:55:17.611Z" }, + { url = "https://files.pythonhosted.org/packages/18/08/a4782611257ce1a85d194348a011dea09f0bf6344b28b8f8fee6c501b8a9/pydantic_core-2.50.5-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:655d0cc2ddbc3fb1f4f8a8e3724552ee2ba6b8561289e9e6e06186982b27bceb", size = 2474759, upload-time = "2026-11-19T12:55:18.847Z" }, + { url = "https://files.pythonhosted.org/packages/48/64/6391407d76fdd16b43c0e377998f38142b433e2f28325764bcea37e8b1e5/pydantic_core-2.50.5-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1d53befcfd415bd9212e685372c825e62f29b83820db78512c9d3659f13d29e9", size = 2264144, upload-time = "2026-11-19T12:55:20.163Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d3/54c432da68129a4e5b9d83f01fc0359b87abb72929fd0ed19f208fb72889/pydantic_core-2.50.5-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:5f33c92da4aa5714fb6fcb086358274598e8ff62b6607afd132a38657aa64f02", size = 2267290, upload-time = "2026-11-19T12:55:21.551Z" }, + { url = "https://files.pythonhosted.org/packages/18/b9/4f1fb301cf4ea6c325da205e82887260e71a780ac21b2f0baf837b82c0cd/pydantic_core-2.50.5-cp314-cp314t-musllinux_1_1_aarch64.whl", hash = "sha256:3129b52ee2861d0270db8bd140fc9b53ee9821247ca47fda2613a899ce9a1ea3", size = 2308710, upload-time = "2026-11-19T12:55:22.858Z" }, + { url = "https://files.pythonhosted.org/packages/eb/a2/423f7defa257419098f186ad3c4bd5e7e983956d8ff7c3e65582a70a6835/pydantic_core-2.50.5-cp314-cp314t-musllinux_1_1_armv7l.whl", hash = "sha256:041f4730fa7a8bf975e88436d439bdc72f3f16e584a470ffbe47392628d99de6", size = 2485824, upload-time = "2026-11-19T12:55:24.175Z" }, + { url = "https://files.pythonhosted.org/packages/ce/7f/3b9148a4d9df1a8f682b3dc7cd70b8855e0e3b27ce49180aa7dd18f164a3/pydantic_core-2.50.5-cp314-cp314t-musllinux_1_1_x86_64.whl", hash = "sha256:48b5deaaee4f1b99603173cd291127523e43ee9f51db58c7ff98d16dc5c6fc93", size = 2518300, upload-time = "2026-11-19T12:55:25.422Z" }, + { url = "https://files.pythonhosted.org/packages/52/f4/ff11826851f17477e6e0ac28da74dcabb9d5848db450fd67bfddfc147f89/pydantic_core-2.50.5-cp314-cp314t-win32.whl", hash = "sha256:8c7244134b93ce028e9166c1b5d3e4537349307ccf3e65d746b4c6b1bbed8c89", size = 2107419, upload-time = "2026-11-19T12:55:27.203Z" }, + { url = "https://files.pythonhosted.org/packages/8b/6c/41c3e9f11befcb6fe576e95703d2d8d9dde3f3fa0de5e4c432d60644aeed/pydantic_core-2.50.5-cp314-cp314t-win_amd64.whl", hash = "sha256:159f6bc1b616e0ca0938eb568d87ca03c633d6f06306ac47b9c3e5dd8c14d39a", size = 2246337, upload-time = "2026-11-19T12:55:28.704Z" }, + { url = "https://files.pythonhosted.org/packages/b6/98/ae8e3f2182a0ddf5f868b4e7830032d9b0ff34cbdd64549bb0b57a2e52c4/pydantic_core-2.50.5-cp314-cp314t-win_arm64.whl", hash = "sha256:5274f8314ce3be1df07ae8ebceeb97a73b8409d842fd7677c5d0a85a68793ec1", size = 2174036, upload-time = "2026-11-19T12:55:30.029Z" }, + { url = "https://files.pythonhosted.org/packages/34/7c/7ab4dd1eaad75d20c596a4b2a36961a98f344aa0bad2938edbe644214baa/pydantic_core-2.50.5-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:c4c4313dc66f45822b3d7f39aa74e59e7987cf7572b3309005b26d956a0098a9", size = 2245524, upload-time = "2026-11-19T12:55:31.444Z" }, + { url = "https://files.pythonhosted.org/packages/ac/29/2cc2423f489d4526825d2371d047de505760260462eb72d838fc5e934aca/pydantic_core-2.50.5-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:e93587aaa5660536b9188686e8fe0544b577ec57d896d424b5b2118b151a6845", size = 2116389, upload-time = "2026-11-19T12:55:32.66Z" }, + { url = "https://files.pythonhosted.org/packages/b5/f7/f7fdfbb6ccacf4ef3a4757eab9ecb9d5809b2568bf38e8f41b1872524f23/pydantic_core-2.50.5-cp315-cp315-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:0a7d599d0c5afbab98c0e4441f5b76163c6fcfd2ecf73dd6418e468a7ac452b8", size = 2266368, upload-time = "2026-11-19T12:55:34.366Z" }, + { url = "https://files.pythonhosted.org/packages/91/3f/8d12c17b4a55097c164759b38136bbd2abe3f2668f0d908fd3d0d4a7e0fd/pydantic_core-2.50.5-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:568e928322f0b6b94671fc1a4dbc867627af74695b0c060ac6d4f25b6a7425d8", size = 2138673, upload-time = "2026-11-19T12:55:35.629Z" }, + { url = "https://files.pythonhosted.org/packages/5c/c0/54c3746f13409b9674f812cd37c98da25df970d030d9260e9e904205893c/pydantic_core-2.50.5-cp315-cp315-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:bdafd6b05bf012772b7d7325a98d26f19b7918e21dabdd5970c885262245aae3", size = 2203145, upload-time = "2026-11-19T12:55:37.366Z" }, + { url = "https://files.pythonhosted.org/packages/79/3a/91f0e7ffc5626a673804fdd33a007186c06352020199653e3df4b5a43ad5/pydantic_core-2.50.5-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:008de9d97f2b0c8e596fb5d93d49b63be158e8be5ac35856903b338cbcfd21f3", size = 2397558, upload-time = "2026-11-19T12:55:38.615Z" }, + { url = "https://files.pythonhosted.org/packages/a6/51/bc916df37f46f77d5159e4a438033702bdbde47814dd407e97fb1aef6fb1/pydantic_core-2.50.5-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:f8fd7e9c44bb4c9214d41c3bef79cba5a513b29c3bcbfdaaf0440ca6f5fb65ea", size = 2478927, upload-time = "2026-11-19T12:55:39.847Z" }, + { url = "https://files.pythonhosted.org/packages/e9/8f/a8f56878763b6fdeca69b73d9b4c44aa4526bfa6a386da21792ed0b766ce/pydantic_core-2.50.5-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0d6e614776c8c99495dcfc6ce8f826277fb4388a5e5cbee23c199cbe39e6dcb3", size = 2276148, upload-time = "2026-11-19T12:55:41.379Z" }, + { url = "https://files.pythonhosted.org/packages/a5/bf/2c28071bb81fe07595ca8d08011ea1005bae92d2b0cb43ce768a135105e0/pydantic_core-2.50.5-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:bcd9d9b38e61dfd43e00f621ce00da2ffed35047fad532c4afcadf4f9ca0d672", size = 2279590, upload-time = "2026-11-19T12:55:42.856Z" }, + { url = "https://files.pythonhosted.org/packages/62/d9/905d95bdb65ce24ca27149796fba3869db2bed08e0688c8dbe863d916b56/pydantic_core-2.50.5-cp315-cp315-musllinux_1_1_aarch64.whl", hash = "sha256:4888829471cd8d85c096ef0e1f41a066c7d76e88309a4fbff4069f70d07673be", size = 2310233, upload-time = "2026-11-19T12:55:44.114Z" }, + { url = "https://files.pythonhosted.org/packages/08/d0/6d63888afef31cda359ba122d768ae83c59213afc3cde4a528a67f4e7d80/pydantic_core-2.50.5-cp315-cp315-musllinux_1_1_armv7l.whl", hash = "sha256:ad0e0221deec2a2385300d76b9259da7036c0ed784502c154ae237dafd67605f", size = 2478319, upload-time = "2026-11-19T12:55:45.299Z" }, + { url = "https://files.pythonhosted.org/packages/33/f6/de8de17435f95dd8ad0db86d74beea9195cfbfce5434946a0bb53e025be5/pydantic_core-2.50.5-cp315-cp315-musllinux_1_1_x86_64.whl", hash = "sha256:20337f547d79911457cd4739bb6699213a53089f946af87633a48fad3f74f5e1", size = 2508289, upload-time = "2026-11-19T12:55:46.634Z" }, + { url = "https://files.pythonhosted.org/packages/f4/39/aae7e3187162752675094b970cb6294bf10ba091f33eebc35376d1b3f0aa/pydantic_core-2.50.5-cp315-cp315-win32.whl", hash = "sha256:09c732c097816c89d46ddb70f89d72e853e3a1bbac6475961c60a88aad9fe612", size = 2131982, upload-time = "2026-11-19T12:55:47.819Z" }, + { url = "https://files.pythonhosted.org/packages/c6/81/abd633f5fafcb06991a311293b37783ea3ea0b23c11845282bf24d7ddab8/pydantic_core-2.50.5-cp315-cp315-win_amd64.whl", hash = "sha256:0d4edc3350e21e0ef773ef9395227ca072832f05e484cadcf4d8663b63a231c0", size = 2285739, upload-time = "2026-11-19T12:55:49.198Z" }, + { url = "https://files.pythonhosted.org/packages/69/6c/0b678e369c45edf0e47b4ceefcb9ac86cf81d7440ad780c384dfeddf7eff/pydantic_core-2.50.5-cp315-cp315-win_arm64.whl", hash = "sha256:af453c0c20372ca8acf3c46de2a89b242491853dc61d0171ba24608d33310e09", size = 2176798, upload-time = "2026-11-19T12:55:50.779Z" }, + { url = "https://files.pythonhosted.org/packages/4e/f2/9907ab2bb673ae2f4ccb6b026e201a5d38cbf9a4f109050b681b8aebf7e9/pydantic_core-2.50.5-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:9e255e7c32d9c2f396d3daa833e7d8d701eec7bf8e13ca092b4b83ce7d9487fd", size = 2235810, upload-time = "2026-11-19T12:55:52.04Z" }, + { url = "https://files.pythonhosted.org/packages/65/c4/caa101ff8599aedb41816c987f44bd7c9d8d5ae42740589da1cf60ce4545/pydantic_core-2.50.5-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:c334b8759496f9e597b68e1309b2fb3d824fd24a29e562afa86b61005eb9d54d", size = 2094628, upload-time = "2026-11-19T12:55:53.353Z" }, + { url = "https://files.pythonhosted.org/packages/91/34/253060ed9f5df44edc3632261b0a457407935b3454dfd40230f5a60f6503/pydantic_core-2.50.5-cp315-cp315t-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:90dabbf4f38f37de1663ce932d37c6f694a005f6470ae2f0d97755d9e3f90ffd", size = 2275436, upload-time = "2026-11-19T12:55:55.061Z" }, + { url = "https://files.pythonhosted.org/packages/9f/bb/2c0b69f1959370f21abb84751c1ef42d73edad84ee6ed67975e6ca6aa194/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:5ec2e8caf5eadea7be683fc7025d60563e920f1f52fe18ae46c49558e67b8cd0", size = 2118960, upload-time = "2026-11-19T12:55:56.573Z" }, + { url = "https://files.pythonhosted.org/packages/3f/74/f6c32d48da403d63fd8860af73c2edf7f0b05346078fa7d3fa7b9af59492/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:44e6c35bf3a9b6785db0c083df8a6929343f9c8fc27186991d21653242c77c19", size = 2204816, upload-time = "2026-11-19T12:55:57.807Z" }, + { url = "https://files.pythonhosted.org/packages/fb/10/a2cb0da341bd09c2d102d50f126827fe79d78611526f8d26c55e1d9e13a5/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:f33be114a0ee27870cffd31057ed60bf5a0cd522dcbdc1dda0bdad70f8302cb0", size = 2420693, upload-time = "2026-11-19T12:55:59.129Z" }, + { url = "https://files.pythonhosted.org/packages/40/31/f8c0ab3f77fb4e348ff818f49f272d2f833aadd3478de4919ccfce10736e/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:12178e58af383bd4c32b2fe141188bc7e540c5eb33ad550856fa5863b4c31bd5", size = 2482316, upload-time = "2026-11-19T12:56:00.438Z" }, + { url = "https://files.pythonhosted.org/packages/82/fc/134b0a1a06971c84f2a3bc6e1123cac9c3d58e8a67b6ef951a0b97f160d1/pydantic_core-2.50.5-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:679f15dd3bd2a82bde350ec8c94c0f8f05f05dba39fb3464cd4136a724da9844", size = 2268676, upload-time = "2026-11-19T12:56:01.985Z" }, + { url = "https://files.pythonhosted.org/packages/7b/c0/b5f34860606866a918cd934172b24fd6069ffbac13179635f65ca3516aea/pydantic_core-2.50.5-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:11806d9b4888f1645d74fc24237f21dad559b42fb8930481b3df414997be6ee5", size = 2276349, upload-time = "2026-11-19T12:56:03.265Z" }, + { url = "https://files.pythonhosted.org/packages/7a/6c/728833b2c94a446f0bfcb5fc82e039aa6da648fdcd925aa8b612e66e142c/pydantic_core-2.50.5-cp315-cp315t-musllinux_1_1_aarch64.whl", hash = "sha256:b43115385de7db83bd2fe7a08dea8580bce3acc3f54200c4f4fe32a4a49688d4", size = 2320015, upload-time = "2026-11-19T12:56:04.519Z" }, + { url = "https://files.pythonhosted.org/packages/4b/c6/c9a9c08eb46517a2028d40cf6cd58674c82ba0912e172ed7a37362e1219c/pydantic_core-2.50.5-cp315-cp315t-musllinux_1_1_armv7l.whl", hash = "sha256:86bd5aad5ccbaced98139d08b4314f253c086897830f4bcf9c1d1f02f740683d", size = 2480855, upload-time = "2026-11-19T12:56:05.809Z" }, + { url = "https://files.pythonhosted.org/packages/4b/e4/7cdac28f4e0b587d66ef34ec5a0e3114ed8a383db958122495d85c03377a/pydantic_core-2.50.5-cp315-cp315t-musllinux_1_1_x86_64.whl", hash = "sha256:90ff55049623eccbfa997332e2b91358dc2c4c30ca6e664b45438723cbe181df", size = 2525363, upload-time = "2026-11-19T12:56:07.301Z" }, + { url = "https://files.pythonhosted.org/packages/82/99/70305ab96334631da7cf3b20de4ea433589a5a022b28b9a3a0cc1c08b435/pydantic_core-2.50.5-cp315-cp315t-win32.whl", hash = "sha256:7c3faea08d44b4a7b57b30f1113e6404e6aa62a4f3489a22359fb27d6003d8b1", size = 2114429, upload-time = "2026-11-19T12:56:08.521Z" }, + { url = "https://files.pythonhosted.org/packages/fc/f2/98c0c74b43877bad2aa16332498626b375ff63d4e5f85c4d09b08d14f861/pydantic_core-2.50.5-cp315-cp315t-win_amd64.whl", hash = "sha256:b2b64d3204f9c33f03ed3111eb754902ea76ca5aa61ab4b2bdf9f767a4a1f279", size = 2251995, upload-time = "2026-11-19T12:56:09.711Z" }, + { url = "https://files.pythonhosted.org/packages/70/17/8ead84e326315b8c99165f3388ccc2b2355a4a2c8bdcba4b9241823dc064/pydantic_core-2.50.5-cp315-cp315t-win_arm64.whl", hash = "sha256:8ba2dcbeea0ab8836e804c54e905075125c702cf78e592d998eecf2764b64144", size = 2185080, upload-time = "2026-11-19T12:56:10.948Z" }, + { url = "https://files.pythonhosted.org/packages/28/f0/9d804817a9c0d599c43fbf20cf6e7e8c196c97962f85c4f63a58fe7c227b/pydantic_core-2.50.5-graalpy312-graalpy250_312_native-macosx_10_12_x86_64.whl", hash = "sha256:68334f281460fb2a85bbb9e2545438bf2fd2c9a166823a60b84541a3c8f2d2e0", size = 2216148, upload-time = "2026-11-19T12:56:12.439Z" }, + { url = "https://files.pythonhosted.org/packages/27/45/1cba006b06e017732c40960bce5bd7a17ec4fc6f49bea40435517e3124a4/pydantic_core-2.50.5-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:851a78a30265bb203186fd0e19712c1a4431083eb5a1e1715f758a029cd8aa6e", size = 2053985, upload-time = "2026-11-19T12:56:13.736Z" }, + { url = "https://files.pythonhosted.org/packages/87/35/0ce9aae400887cfe1d2699f53542cf5ae25bb8ce6c26a84f1b007f653165/pydantic_core-2.50.5-graalpy312-graalpy250_312_native-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:47f4d79fe4876feace216a5b2263c40d792476b4a6508c38d66a2facd3f1f4cc", size = 2125321, upload-time = "2026-11-19T12:56:14.973Z" }, + { url = "https://files.pythonhosted.org/packages/d4/d1/a720b66b4e13e0b5623370bd71b1e376a193d92e20e7dbef7748678c00df/pydantic_core-2.50.5-graalpy312-graalpy250_312_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:98b92dad690e6578cc0b504eda53d53adaa4f34bd09c97a547a957e419544eb7", size = 2283625, upload-time = "2026-11-19T12:56:16.458Z" }, + { url = "https://files.pythonhosted.org/packages/ed/1d/0e2d5bb47dc729ddf21fb846cb1ac85baf6290eca5ef1ee3d871712496f4/pydantic_core-2.50.5-graalpy313-graalpy253_313_native-macosx_11_0_arm64.whl", hash = "sha256:d7826407ed74ff8e6cc6e6df7ffbf180e9b449ab1516f28eb5f6e2a489bc5129", size = 2054207, upload-time = "2026-11-19T12:56:17.916Z" }, + { url = "https://files.pythonhosted.org/packages/59/61/f1b75d2dffa662c4326adc6b16881f98158717cfd461936c2f0c36d9d1c8/pydantic_core-2.50.5-graalpy313-graalpy253_313_native-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c415a8da7c89a3dd32d988a9117bf0a52371769b77b0943bcfd50b281ecefb8d", size = 2125491, upload-time = "2026-11-19T12:56:19.202Z" }, + { url = "https://files.pythonhosted.org/packages/e5/78/104a8c414f58132acaa6b2ce4cc3441b8cc556df0f7fcc9ca8c07473f17a/pydantic_core-2.50.5-graalpy313-graalpy253_313_native-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ea7429e3adb2f2fd81e2d6e8942e5c1cd760a6e6be5b7574d2ee5499b5e19e67", size = 2284742, upload-time = "2026-11-19T12:56:20.825Z" }, + { url = "https://files.pythonhosted.org/packages/c6/fa/9cb4e5a3de7bd4444746cc8013b9e2e4c418ca231e5030d08b19ff951623/pydantic_core-2.50.5-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:ea215f7f5d2df866e3b5448c0bbb4a35285086ac6ab18687796704cbd5f2c5a3", size = 2170574, upload-time = "2026-11-19T12:56:22.059Z" }, + { url = "https://files.pythonhosted.org/packages/41/f7/288ed9853187c415adf6145351ffbb43a00fd778901a9932675f9c93bb8a/pydantic_core-2.50.5-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:4ac243e358837f62d085f07b98625fa3831abdb28e8f77196934345bbff0fb0b", size = 2091109, upload-time = "2026-11-19T12:56:23.3Z" }, + { url = "https://files.pythonhosted.org/packages/58/3a/fe47e18113c6f194202a27b1f307db8ff17bad527f7edecea13da6be21d4/pydantic_core-2.50.5-pp311-pypy311_pp73-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:d3ada66d0601feeeba504a6daac73e47ed164357e46930366f135c4121594d53", size = 2288892, upload-time = "2026-11-19T12:56:24.647Z" }, + { url = "https://files.pythonhosted.org/packages/60/30/b335f56abe44aea1f78e80742eb160e17835069c71af5d7488ae7ca2aaf1/pydantic_core-2.50.5-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0dd037d96e98f6db8b69a44ab7d5c20a07fb0a2051775746a9e1b5fc8f52867f", size = 2281693, upload-time = "2026-11-19T12:56:25.898Z" }, + { url = "https://files.pythonhosted.org/packages/d5/07/4db8ee1ed1837344e288cb5b999d9734410617ba6fde93485ec529c751b7/pydantic_core-2.50.5-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:3f800fc0f304f3b0e09d07d4287f9f0bc9bfe5319d1d7cabeaf265737c516083", size = 2301333, upload-time = "2026-11-19T12:56:27.362Z" }, + { url = "https://files.pythonhosted.org/packages/a9/d7/31f5d05507b9f851693188965cd31925192f20cffb662c091c07db6b4ed2/pydantic_core-2.50.5-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:a5f6622451fa3cd71c8ff15df24307cb3f8b5dc35a723de281646c34872d7179", size = 2471021, upload-time = "2026-11-19T12:56:28.797Z" }, + { url = "https://files.pythonhosted.org/packages/34/ce/5075d634804891e31f52c8cfc419a6b11bf60be84937b68cffceb077fec2/pydantic_core-2.50.5-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:2f5f29ff80ce0cf93102198cddebdbb3411881de177359c770e5c9c99495a6b3", size = 2506558, upload-time = "2026-11-19T12:56:30.267Z" }, + { url = "https://files.pythonhosted.org/packages/c3/66/a6fa0aa7f5b6a3f9acdee809f1f05a36a27668cc00fc57dc936e2a6db0a5/pydantic_core-2.50.5-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:6a069ceeca397bd8da2e8ef6383595c63ea17de37d5f2d5cde729bdc0dfe6774", size = 2339507, upload-time = "2026-11-19T12:56:31.581Z" }, + { url = "https://files.pythonhosted.org/packages/c6/51/7ee80cc035e5d3503cea953c9edb8f90dd453cec154abb94079399138f45/pydantic_core-2.50.5-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:e8faa73de2e9231f604cfa44c471d0986e7e9c45129d7888839a34196e46a7df", size = 2170571, upload-time = "2026-11-19T12:56:32.864Z" }, + { url = "https://files.pythonhosted.org/packages/85/4c/9c4e2eff5ab28816b5ab3d615d193294f80a945671cb4e2daa16cd0dd6c8/pydantic_core-2.50.5-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:ef461e9299ae665fab67c6f054847178b8fd510da10b4ef745a074b922efbf0a", size = 2091110, upload-time = "2026-11-19T12:56:34.328Z" }, + { url = "https://files.pythonhosted.org/packages/a5/38/f0790736e0baf5307b473d123555af947d9bedec509726db5e670c09cd76/pydantic_core-2.50.5-pp311-pypy311_pp80-manylinux_2_28_x86_64.whl", hash = "sha256:1f22c36d952f33bac936273ca0be115693a1d7c1c9496ca7d699e6a338656d6e", size = 2282074, upload-time = "2026-11-19T12:56:35.597Z" }, + { url = "https://files.pythonhosted.org/packages/78/85/8c9120a1910ace8990fdfecbf9beb785e7d642fff94281df2df2b5735a16/pydantic_core-2.50.5-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:b6f48c4bf1c77ace644b125f168418438fbc9b8e4c3b290915cc7d055d83c8b1", size = 2339507, upload-time = "2026-11-19T12:56:36.826Z" }, +] + +[[package]] +name = "sentry-assistant-python" +version = "0.0.0" +source = { virtual = "." } +dependencies = [ + { name = "openrouter" }, + { name = "sentry-sdk" }, +] + +[package.dev-dependencies] +dev = [ + { name = "eac-sdk" }, +] + +[package.metadata] +requires-dist = [ + { name = "openrouter", specifier = ">=1.3" }, + { name = "sentry-sdk", specifier = ">=2" }, +] + +[package.metadata.requires-dev] +dev = [{ name = "eac-sdk", editable = "../../sdks/python" }] + +[[package]] +name = "sentry-sdk" +version = "2.75.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d2/95/121b20d75e738d249a0e26e6476a2acb178673e8228002748fc0cd85ce55/sentry_sdk-2.75.0.tar.gz", hash = "sha256:c38ac2d4b2435c11da821e173bb9d9088c98f41ae92f559ce0e424170a8e1a29", size = 1092308, upload-time = "2026-11-12T13:24:13.977Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/ee/fbfe67386d64a7218013c8346b88b89d72f279b4ddb434ed5e94bea3d389/sentry_sdk-2.75.0-py3-none-any.whl", hash = "sha256:9a10e97de2cbd42ad7e4a6e02a0d5af19de9811eb02445077d41ba14c08e170c", size = 555165, upload-time = "2026-11-12T13:24:11.923Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab716bb0a813abea4cc394bfa17a92a189f021a34859af/typing_inspection-0.4.5.tar.gz", hash = "sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7", size = 81194, upload-time = "2026-11-04T14:13:23.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] diff --git a/schemas/results.schema.json b/schemas/results.schema.json index 0fa4a77..a75f36b 100644 --- a/schemas/results.schema.json +++ b/schemas/results.schema.json @@ -1,5 +1,34 @@ { "$defs": { + "Args": { + "description": "What the run was asked to do.", + "oneOf": [ + { + "$ref": "#/$defs/OfflineArgs", + "properties": { + "mode": { + "const": "offline" + } + }, + "required": [ + "mode" + ], + "type": "object" + }, + { + "$ref": "#/$defs/OnlineArgs", + "properties": { + "mode": { + "const": "online" + } + }, + "required": [ + "mode" + ], + "type": "object" + } + ] + }, "CaseResult": { "description": "One case: what the runner returned and how the judges scored it.", "properties": { @@ -139,6 +168,74 @@ ], "type": "object" }, + "OfflineArgs": { + "properties": { + "arm": { + "type": [ + "string", + "null" + ] + }, + "comparison": { + "type": [ + "string", + "null" + ] + }, + "judge_args": { + "description": "--judge-args.", + "type": "object" + }, + "judges": { + "description": "A comparison's judges, replaces each case's defined judges.", + "items": { + "type": "string" + }, + "type": "array" + }, + "runner_args": { + "description": "--args.", + "type": "object" + } + }, + "required": [ + "runner_args", + "judges", + "judge_args", + "comparison", + "arm" + ], + "type": "object" + }, + "OnlineArgs": { + "properties": { + "judge_args": { + "description": "--judge-args.", + "type": "object" + }, + "judges": { + "description": "--judge.", + "items": { + "type": "string" + }, + "type": "array" + }, + "runner_args": { + "description": "--args.", + "type": "object" + }, + "window": { + "$ref": "#/$defs/Window" + } + }, + "required": [ + "runner_args", + "judges", + "judge_args", + "window" + ], + "type": "object" + }, "Score": { "description": "A judge's score from 0 to 1. A null score is recorded but doesn't count toward pass or fail.", "properties": { @@ -276,11 +373,41 @@ "schedule" ], "type": "string" + }, + "Window": { + "description": "The params to select cases from production", + "properties": { + "limit": { + "type": "integer" + }, + "sample_rate": { + "description": "The fraction of runs to collect, picked by a hash of each run's id.", + "type": "number" + }, + "since": { + "format": "date-time", + "type": "string" + }, + "until": { + "format": "date-time", + "type": "string" + } + }, + "required": [ + "since", + "until", + "limit", + "sample_rate" + ], + "type": "object" } }, "$schema": "https://json-schema.org/draft/2020-12/schema", "description": "The results of judging one dataset in one run, saved as results/.json in the run's directory.", "properties": { + "args": { + "$ref": "#/$defs/Args" + }, "cases": { "description": "Every case judged, in the dataset's order.", "items": { @@ -301,11 +428,14 @@ "type": "number" }, "metadata": { - "description": "What sets this run apart from others of the same dataset, like the variant, args and --meta values.", + "description": "The dataset.yml's `metadata`, with the run's --meta values over it.", "type": "object" }, + "run_id": { + "type": "string" + }, "schema_version": { - "const": 2, + "const": 3, "description": "The version of this format. Changes that could break a reader bump it." }, "source": { @@ -314,8 +444,10 @@ }, "required": [ "schema_version", + "run_id", "dataset_name", "created_at", + "args", "cases", "duration_seconds", "metadata", diff --git a/scripts/upload_evals.py b/scripts/upload_evals.py new file mode 100755 index 0000000..2393e31 --- /dev/null +++ b/scripts/upload_evals.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +"""Upload eac runs to evals.sentry.dev, which compares a pull request's head +run against its base run and comments on the pull request. + + upload_evals.py comparison + upload_evals.py run --comparison --sha [--base-sha ] + +Needs $EVALS_API_TOKEN, and $GITHUB_SERVER_URL and $GITHUB_REPOSITORY, which +GitHub Actions sets. Standard library only, so CI can run it with any python3. +""" + +import argparse +import json +import os +import sys +import urllib.error +import urllib.request +from pathlib import Path + +API_URL = os.environ.get("EVALS_API_URL") or "https://evals.sentry.dev" + +# The fields of each case in eac's results that evals.sentry.dev takes. +CASE_FIELDS = [ + "name", + "status", + "input", + "output", + "error", + "conversation_id", + "attributes", + "otel_metrics", + "duration_seconds", +] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + commands = parser.add_subparsers(dest="command", required=True) + + comparison = commands.add_parser("comparison", help="Create a comparison and print its id.") + comparison.add_argument("dataset") + + run = commands.add_parser("run", help="Upload each dataset's results from a run.") + run.add_argument("run_dir", type=Path) + run.add_argument("--comparison", required=True) + run.add_argument("--sha", required=True) + run.add_argument("--base-sha") + + args = parser.parse_args() + + if args.command == "comparison": + print(create_comparison(args.dataset)) + else: + for path in sorted((args.run_dir / "results").glob("*.json")): + results = json.loads(path.read_text()) + url = upload_run(results, args.comparison, args.sha, args.base_sha) + print(f"{results['dataset_name']}: {url}") + + +def create_comparison(dataset): + comparison = post("/api/comparisons", {"name": "head_vs_base", "dataset": dataset}) + return comparison["id"] + + +def upload_run(results, comparison_id, sha, base_sha): + """Upload one dataset's results, and return the run's URL.""" + run = post( + "/api/runs", + { + "dataset": results["dataset_name"], + "comparison_id": comparison_id, + "created_at": results["created_at"], + "metadata": results["metadata"], + "source": source_of(results, sha, base_sha), + "scenarios": [{"name": case["name"]} for case in results["cases"]], + }, + ) + + cases = [] + for case in results["cases"]: + cases.append(case_of(case)) + + uploaded = post(f"/api/runs/{run['id']}/cases", {"run_id": run["id"], "scenarios": cases}) + if uploaded["reported"] != uploaded["total"]: + sys.exit(f"evals.sentry.dev took {uploaded['reported']} of {uploaded['total']} cases") + return run["url"] + + +def source_of(results, sha, base_sha): + """Where the run came from. eac attributes a pull request's runs to its + head, so this sets the commit the run actually tested.""" + repo = f"{os.environ['GITHUB_SERVER_URL']}/{os.environ['GITHUB_REPOSITORY']}" + source = dict(results["source"]) + source["sha"] = sha + source["base_sha"] = base_sha + source["commit_url"] = f"{repo}/commit/{sha}" + return without_nulls(source) + + +def case_of(case): + """A case as evals.sentry.dev takes it. A null error is kept, since it + clears the error an earlier upload of the case set. The same goes for a + score's score and explanation.""" + body = {} + for field in CASE_FIELDS: + body[field] = case.get(field) + body = without_nulls(body, keep=["error"]) + + body["scores"] = [] + for score in case["scores"]: + body["scores"].append(without_nulls(score, keep=["score", "explanation"])) + return body + + +def without_nulls(values, keep=()): + """`values` without its null fields, except the ones in `keep`.""" + result = {} + for key, value in values.items(): + if value is not None or key in keep: + result[key] = value + return result + + +def post(path, body): + request = urllib.request.Request( + API_URL + path, + data=json.dumps(body).encode(), + headers={ + "Authorization": f"Bearer {os.environ['EVALS_API_TOKEN']}", + "Content-Type": "application/json", + }, + method="POST", + ) + try: + with urllib.request.urlopen(request, timeout=60) as response: + return json.load(response) + except urllib.error.HTTPError as error: + sys.exit(f"POST {path}: {error.code} {error.read().decode()}") + except urllib.error.URLError as error: + sys.exit(f"POST {path}: {error.reason}") + + +if __name__ == "__main__": + main() diff --git a/sdks/python/README.md b/sdks/python/README.md index 9ab7172..c7d3386 100644 --- a/sdks/python/README.md +++ b/sdks/python/README.md @@ -1,8 +1,8 @@ # eac Python SDK Write evals in Python and run them with the `eac` CLI. -[`examples/basic-example-python`](../../examples/basic-example-python) uses -most of what's below in one file. +[`examples/sentry-assistant-python`](../../examples/sentry-assistant-python) +uses most of what's below on a small, real agent. ## Install @@ -57,7 +57,7 @@ real environment already sets them. ```yaml name: chat # lowercase letters, digits and _ -agent: chat_agent # optional: the production agent, for traces +metadata: {team: chat} # optional: recorded in its results runtime: python offline: # run your system on your cases @@ -75,12 +75,8 @@ A dataset needs at least one of `offline` and `online`. References to code are runner or judge reference can name a class, which eac builds with no arguments, or an instance you've configured. -The `offline` section can also have: - -- `shard_config: {cases_per_shard: 20, max_shards: 8}`, for splitting runs - across CI jobs with `--shard-index`. -- `comparisons`, named sets of arms that run the cases with different - `--args`, for `eac offline compare `. +The `offline` section can also have `comparisons`: named sets of arms that run +the cases with different `--args`, for `eac offline compare `. ## Cases @@ -152,8 +148,9 @@ class Matches(Judge): expected = case.expected_output.get("response") if expected is None: return None # doesn't apply, e.g. online - ok = case.output.get("response") == expected - return Score(name=self.name, score=1.0 if ok else 0.0, explanation=None if ok else "wrong reply") + if case.output.get("response") == expected: + return Score.passed(self.name) + return Score.failed(self.name, "wrong reply") class CalledTool(Judge): name = "called_tool" @@ -210,9 +207,9 @@ class UsedTheRightTool(SentryJudge): ... ``` -- `run` is an `AgentRun`: the case's `conversation_id`, the dataset, its - `agent` from `dataset.yml`, the case's name, and when the runner ran it, - which is `None` for collected production runs. +- `run` is an `AgentRun`: the case's `conversation_id`, the dataset, the + case's name, and when the runner ran it, which is `None` for collected + production runs. - Before judging a case, eac asks its judges in order and gives the first trace found to every one of them. Each class's `get_agent_trace()` is asked once per case, so judges sharing a base class cost one lookup. One that @@ -316,6 +313,13 @@ class ProdChats(OnlineRunner): `collect_cases` returns at most `window.limit` cases from `[window.since, window.until)`. As offline, `self.args` is the run's `--args`. +With `--sample-rate 0.1`, keep the tenth of runs `window.samples()` picks +by a stable id: + +```python +rows = [row for row in query_traces(window.since, window.until) if window.samples(row.trace_id)] +``` + Online judges are named in each `dataset.yml` and picked with `--judge `. `eac online run --judge ` collects cases and judges them in one go, or `eac online execute` saves them in a run for @@ -338,15 +342,15 @@ instead of halfway through. ```python import subprocess -from dataclasses import dataclass import httpx from eac import Credential -@dataclass(frozen=True) class GitHub(Credential): name = "github" # shown in status lines and prompts - repo: str + + def __init__(self, repo): + self.repo = repo def is_authenticated(self, env) -> bool: token = env.get("GITHUB_TOKEN", "") @@ -376,18 +380,16 @@ Build clients when they're first used, not in `__init__`, since eac checks credentials after building your seeds and judges. Every distinct credential is checked once, and credentials with the same class -and fields are the same. On a terminal, eac offers to log in to the ones that +and arguments are the same. On a terminal, eac offers to log in to the ones that aren't set up. `authenticate()` runs on the terminal, so it can prompt or run a login command. Once the credential checks out, eac saves the variables it returned in `.eac/credentials/saved.json`, never your `.env`, and later commands use them ahead of `.env` and your shell. A credential without `authenticate()` can only be set up by hand, so eac shows its -`setup_instructions` instead. `eac auth` logs in to every missing credential -the datasets need, and CI, where `$CI` is set, skips the checks. +`setup_instructions` instead. CI, where `$CI` is set, skips the checks. -eac rebuilds credentials in other processes from their class and fields, so -make each one a frozen dataclass whose fields are JSON values, or a class that -takes no arguments. +eac rebuilds credentials in other processes from their class and +arguments, so build them with plain values like strings. ## Running diff --git a/sdks/python/eac/credential.py b/sdks/python/eac/credential.py index 0f05df6..7b79850 100644 --- a/sdks/python/eac/credential.py +++ b/sdks/python/eac/credential.py @@ -2,7 +2,7 @@ from abc import ABC, abstractmethod from collections.abc import Mapping -from typing import ClassVar +from typing import Any, Self class Credential(ABC): @@ -11,18 +11,23 @@ class Credential(ABC): List them in `credentials` on a Seed, Judge or runner. Before each phase, eac checks every distinct credential the phase needs and stops if one - isn't set up. On a terminal it offers to log in first, and `eac auth` logs - in to every one. + isn't set up. On a terminal it offers to log in first. - eac rebuilds credentials in other processes from their class and fields, - so make each a frozen dataclass whose fields are JSON values, or a class - that takes no arguments. Credentials with the same class and fields are - checked once. A list field comes back as a tuple. + eac rebuilds credentials in other processes from their class and + arguments, so build them with JSON values. Credentials with the same class + and arguments are checked once. """ - #: Shown in status lines and prompts, e.g. "github". A dataclass field - #: with a default can replace it, to name instances differently. - name: ClassVar[str] + #: Shown in status lines and prompts, e.g. "github". + name: str + + def __new__(cls, /, *args: Any, **kwargs: Any) -> Self: + if cls.__init__ is object.__init__ and (args or kwargs): + raise TypeError(f"{cls.__qualname__}() takes no arguments") + credential = super().__new__(cls) + # object.__setattr__ works on frozen dataclasses too. + object.__setattr__(credential, "_eac_built_with", (args, kwargs)) + return credential @abstractmethod def is_authenticated(self, env: Mapping[str, str]) -> bool: diff --git a/sdks/python/eac/models.py b/sdks/python/eac/models.py index 4cfa11d..bc8e331 100644 --- a/sdks/python/eac/models.py +++ b/sdks/python/eac/models.py @@ -46,6 +46,40 @@ def __post_init__(self) -> None: if self.score is not None and not (0.0 <= self.score <= 1.0): raise ValueError(f"score must be between 0 and 1, got {self.score}") + @classmethod + def passed( + cls, + name: str, + explanation: str | None = None, + *, + metadata: dict[str, Any] | None = None, + llm_judge_metrics: LLMMetrics | None = None, + ) -> Score: + return cls( + name=name, + score=1.0, + explanation=explanation, + metadata=metadata or {}, + llm_judge_metrics=llm_judge_metrics, + ) + + @classmethod + def failed( + cls, + name: str, + explanation: str | None = None, + *, + metadata: dict[str, Any] | None = None, + llm_judge_metrics: LLMMetrics | None = None, + ) -> Score: + return cls( + name=name, + score=0.0, + explanation=explanation, + metadata=metadata or {}, + llm_judge_metrics=llm_judge_metrics, + ) + @dataclass(frozen=True) class Case: @@ -83,11 +117,23 @@ def __post_init__(self) -> None: @dataclass(frozen=True) class Window: """The production runs an OnlineRunner collects: at most `limit` of them, - from `since` up to, but not including, `until`.""" + from `since` up to, but not including, `until`, sampled at + `sample_rate`.""" since: datetime until: datetime limit: int + sample_rate: float = 1.0 + + def __post_init__(self) -> None: + if not 0 < self.sample_rate <= 1: + raise ValueError(f"sample_rate must be more than 0 and at most 1, got {self.sample_rate}") + + def samples(self, key: Any) -> bool: + """Whether the run with this id, like its trace id, is in the sample. + It hashes the id, so reruns pick the same runs.""" + digest = hashlib.sha256(str(key).encode()).digest() + return int.from_bytes(digest[:8], "big") < self.sample_rate * 2**64 @dataclass(frozen=True) @@ -98,8 +144,6 @@ class AgentRun: conversation_id: str #: The dataset's name, from its dataset.yml. dataset: str - #: The production agent, from dataset.yml's `agent`. - agent: str | None #: The case's name. case: str #: When the runner ran the case. None for collected production runs. diff --git a/sdks/python/eac/protocol.py b/sdks/python/eac/protocol.py index 129d163..75f4815 100644 --- a/sdks/python/eac/protocol.py +++ b/sdks/python/eac/protocol.py @@ -73,8 +73,6 @@ class Case(TypedDict): class CaseJudgeParams(TypedDict): - #: The agent named in dataset.yml. - agent: NotRequired[str | None] #: With the runner's `output` and `conversation_id`. case: Case dataset: DatasetRef @@ -221,10 +219,7 @@ class Metrics(TypedDict): class OnlineExecuteParams(TypedDict): args: NotRequired[dict[str, Any]] dataset: DatasetRef - limit: int - #: RFC 3339. Return runs from since up to, but not including, until. - since: str - until: str + window: Window class OnlineExecuteResult(TypedDict): @@ -234,7 +229,6 @@ class OnlineExecuteResult(TypedDict): class OnlineJudgeParams(TypedDict): - agent: NotRequired[str | None] #: A collected case, with its `output` and `conversation_id`. case: Case dataset: DatasetRef @@ -310,3 +304,13 @@ class SeedTeardownParams(TypedDict): dataset: DatasetRef handle: Handle seed: Seed + + +class Window(TypedDict): + """The params to select cases from production""" + + limit: int + #: The fraction of runs to collect, picked by a hash of each run's id. + sample_rate: float + since: str + until: str diff --git a/sdks/python/eac/worker.py b/sdks/python/eac/worker.py index 9a3b668..e25e3b7 100644 --- a/sdks/python/eac/worker.py +++ b/sdks/python/eac/worker.py @@ -16,6 +16,7 @@ import sys import traceback from datetime import datetime +from inspect import Parameter from pathlib import Path from types import ModuleType from typing import Any, BinaryIO, Callable, Iterable, Sequence @@ -256,8 +257,13 @@ async def run_case(self, params: wire.CaseRunParams) -> wire.CaseRunResult: return {"output": _json_dict(output, f"{type(runner).__name__}.run_case()")} async def collect_cases(self, params: wire.OnlineExecuteParams) -> wire.OnlineExecuteResult: - since, until = datetime.fromisoformat(params["since"]), datetime.fromisoformat(params["until"]) - window = Window(since=since, until=until, limit=params["limit"]) + sent = params["window"] + window = Window( + since=datetime.fromisoformat(sent["since"]), + until=datetime.fromisoformat(sent["until"]), + limit=sent["limit"], + sample_rate=sent["sample_rate"], + ) runner = self.with_args(self.runner, params.get("args") or {}) what = f"{type(runner).__name__}.collect_cases()" cases = await _call(runner.collect_cases, window) @@ -296,7 +302,6 @@ async def judge(self, params: wire.CaseJudgeParams | wire.OnlineJudgeParams) -> run = AgentRun( conversation_id=case.conversation_id, dataset=self.name, - agent=params.get("agent"), case=case.name, started_at=_time(params.get("started_at")), ended_at=_time(params.get("ended_at")), @@ -539,10 +544,7 @@ def _credentials(credentials: Iterable[Credential]) -> list[wire.Credential]: cls = type(credential) if "" in cls.__qualname__: raise WorkerError(f"{cls.__qualname__} must be defined at the top level of a module") - fields: dict[str, Any] = {} - if dataclasses.is_dataclass(credential): - fields = {f.name: getattr(credential, f.name) for f in dataclasses.fields(credential) if f.init} - _require_serializable(fields, f"{cls.__qualname__}'s fields") + fields = _built_with(credential) name = getattr(credential, "name", None) if not isinstance(name, str): raise WorkerError(f"{cls.__qualname__} needs a name") @@ -557,6 +559,55 @@ def _credentials(credentials: Iterable[Credential]) -> list[wire.Credential]: return list(out.values()) +def _built_with(credential: Credential) -> dict[str, Any]: + """What _credential() rebuilds the credential from.""" + cls = type(credential) + if dataclasses.is_dataclass(credential): + fields = {f.name: getattr(credential, f.name) for f in dataclasses.fields(credential) if f.init} + else: + fields = _keyword_arguments(cls, *getattr(credential, "_eac_built_with", ((), {}))) + if bad := [name for name, value in fields.items() if not _is_json(value)]: + raise WorkerError(f"{cls.__qualname__}'s {bad[0]} must be JSON, since eac rebuilds credentials from their arguments") + return fields + + +def _keyword_arguments(cls: type, args: tuple[Any, ...], kwargs: dict[str, Any]) -> dict[str, Any]: + """The arguments as keywords, with JSON defaults filled in.""" + init = inspect.signature(cls.__init__) + try: + bound = init.bind(None, *args, **kwargs) # None for self + except TypeError as exc: + raise WorkerError(f"can't rebuild {cls.__qualname__}: {exc}") from None + given = set(bound.arguments) + bound.apply_defaults() + arguments = bound.arguments + self_param = next(iter(init.parameters.values())) + if self_param.kind is Parameter.VAR_POSITIONAL: + arguments[self_param.name] = arguments[self_param.name][1:] + else: + del arguments[self_param.name] + + out: dict[str, Any] = {} + for name, value in arguments.items(): + kind = init.parameters[name].kind + if kind is Parameter.VAR_KEYWORD: + out.update(value) + elif kind in (Parameter.POSITIONAL_ONLY, Parameter.VAR_POSITIONAL): + if name in given and (kind is Parameter.POSITIONAL_ONLY or value): + raise WorkerError(f"build {cls.__qualname__} with keyword arguments, so eac can rebuild it") + elif name in given or _is_json(value): + out[name] = value + return out + + +def _is_json(value: Any) -> bool: + try: + json.dumps(value) + except (TypeError, ValueError): + return False + return True + + def _class_ref(cls: type) -> str: """A reference import_ref resolves to cls. A file loaded by path has no module name to import, so it's referenced by path.""" From 6fcff5efba675e553d06dce706ae21fe7f585847 Mon Sep 17 00:00:00 2001 From: Ryan Brooks Date: Sat, 21 Nov 2026 20:51:39 -0800 Subject: [PATCH 2/4] Logging and tweaks --- core/src/commands/offline.rs | 1 + core/src/commands/online.rs | 4 ++ core/src/commands/runs.rs | 9 +++- core/src/eac/run/dir.rs | 21 ++++++-- core/src/report/mod.rs | 9 ++++ core/tests/cli.rs | 17 ++++++ examples/sentry-assistant-python/README.md | 54 ++++++++----------- .../evals/triage/judges/triage_llm_judge.py | 30 ++++++++--- 8 files changed, 100 insertions(+), 45 deletions(-) diff --git a/core/src/commands/offline.rs b/core/src/commands/offline.rs index d76be5e..336b778 100644 --- a/core/src/commands/offline.rs +++ b/core/src/commands/offline.rs @@ -52,6 +52,7 @@ pub fn execute(a: &PhaseArgs) -> Result<()> { let seeds = run.read_seeds()?; report::phase("execute"); engine.execute(&run, &m, &seeds)?; + report::saved(&run.outputs_dir()); info!("run {}", run.id); Ok(()) } diff --git a/core/src/commands/online.rs b/core/src/commands/online.rs index d1e50f1..c83ba3c 100644 --- a/core/src/commands/online.rs +++ b/core/src/commands/online.rs @@ -179,5 +179,9 @@ fn execute_run( for out in &outputs { run.write_output(out)?; } + // Nothing collected means nothing saved. + if !outputs.is_empty() { + report::saved(&run.outputs_dir()); + } Ok((run, m)) } diff --git a/core/src/commands/runs.rs b/core/src/commands/runs.rs index eaa7c77..b28d36d 100644 --- a/core/src/commands/runs.rs +++ b/core/src/commands/runs.rs @@ -63,6 +63,7 @@ pub fn seed_run(engine: &mut Engine, run: &Run, m: &Manifest) -> Result { report::phase("seed"); let seeds = engine.seed(m)?; run.write_seeds(&seeds)?; + report::saved(&run.seeds_file()); Ok(seeds) } @@ -76,7 +77,10 @@ pub fn seed_execute_judge( ) -> Result { let seeds = seed_run(engine, run, m)?; report::phase("execute"); - let summary = engine.execute(run, m, &seeds).and_then(|()| judge_run(engine, run, m)); + let summary = engine.execute(run, m, &seeds).and_then(|()| { + report::saved(&run.outputs_dir()); + judge_run(engine, run, m) + }); if !keep_seeds { let _ = teardown_uncached(engine, &seeds); } @@ -100,6 +104,9 @@ pub fn judge_run(engine: &mut Engine, run: &Run, m: &Manifest) -> Result PathBuf { + self.dir.join("seeds.json") + } + + /// What the execute phase saved: outputs//.json. + pub fn outputs_dir(&self) -> PathBuf { + self.dir.join("outputs") + } + + /// What the judge phase saved for a dataset: its cases and their scores. + pub fn results_file(&self, dataset: &str) -> PathBuf { + self.dir.join("results").join(format!("{dataset}.json")) + } + /// //.json, e.g. outputs/chat/greets.json. fn case_path(&self, kind: &str, dataset: &str, case: &str) -> PathBuf { self.dir.join(kind).join(dataset).join(format!("{case}.json")) @@ -72,7 +87,7 @@ impl Run { } pub fn write_seeds(&self, s: &Seeds) -> Result<()> { - write_json(&self.dir.join("seeds.json"), s) + write_json(&self.seeds_file(), s) } pub fn write_summary(&self, s: &Summary) -> Result<()> { @@ -93,7 +108,7 @@ impl Run { pub fn write_results(&self, results: &[RunResult]) -> Result<()> { for r in results { - write_json(&self.dir.join("results").join(format!("{}.json", r.dataset_name)), r)?; + write_json(&self.results_file(&r.dataset_name), r)?; } Ok(()) } @@ -105,7 +120,7 @@ impl Run { /// Returns no seeds if the run was never seeded. pub fn read_seeds(&self) -> Result { - read_json_or_default(&self.dir.join("seeds.json")) + read_json_or_default(&self.seeds_file()) } pub fn read_output(&self, dataset: &str, case: &str) -> Result { diff --git a/core/src/report/mod.rs b/core/src/report/mod.rs index cd08db1..9bcf18c 100644 --- a/core/src/report/mod.rs +++ b/core/src/report/mod.rs @@ -3,6 +3,7 @@ use std::fmt; use std::io::IsTerminal; +use std::path::Path; use std::sync::LazyLock; // Before the submodules, so they can use them too. @@ -40,6 +41,14 @@ pub fn warning(args: fmt::Arguments) { eprintln!(" {}", paint(YELLOW, &args.to_string())); } +/// Where a phase saved what it made. Relative to the working directory when +/// it's under it, so it's short enough to read and copy. +pub fn saved(path: &Path) { + let cwd = std::env::current_dir().unwrap_or_default(); + let shown = path.strip_prefix(&cwd).unwrap_or(path); + info!("saved {}", shown.display()); +} + /// A check's result, such as whether a credential is set up. pub fn checked(ok: bool, what: &str) { let mark = if ok { paint(GREEN, "✓") } else { paint(RED, "✗") }; diff --git a/core/tests/cli.rs b/core/tests/cli.rs index 57bdc73..56b6a85 100644 --- a/core/tests/cli.rs +++ b/core/tests/cli.rs @@ -290,6 +290,23 @@ fn phases_run_separately() { assert_eq!(names(&p.events("seed_teardown"), "name"), ["scratch"]); } +#[test] +fn each_phase_says_where_it_saved_its_output() { + let p = Project::new(&base()); + let seeded = p.eac(&["offline", "seed", "--case", "wrong"]); + let id = seeded.stdout.trim().to_string(); + seeded.says(&format!("saved .eac/runs/{id}/seeds.json")); + p.eac(&["offline", "execute", "--run", &id]).says(&format!("saved .eac/runs/{id}/outputs")); + p.eac(&["offline", "judge", "--run", &id]) + .says(&format!("saved .eac/runs/{id}/results/chat.json")); + + let online = p.eac(&["online", "run", "--judge", "nonempty"]); + let id = online.stdout.trim().to_string(); + online + .says(&format!("saved .eac/runs/{id}/outputs")) + .says(&format!("saved .eac/runs/{id}/results/chat.json")); +} + #[test] fn cached_seeds_are_reused_until_pruned() { let p = Project::new(&base()); diff --git a/examples/sentry-assistant-python/README.md b/examples/sentry-assistant-python/README.md index b432dce..eb588cd 100644 --- a/examples/sentry-assistant-python/README.md +++ b/examples/sentry-assistant-python/README.md @@ -1,60 +1,48 @@ # sentry-assistant-python -A Sentry triage agent and its evals. +A Sentry triage agent evals. -Given an alert like "checkout fails with coupons since shop@1.4.2", the agent searches Sentry, reads the shop's code and reports which issue is behind it and what to fix. +Given a Sentry alert like "checkout fails with coupons since shop@1.4.2", the agent searches Sentry, reads the app's code and says which issue is behind it and what to fix. -## Run it +## Get started -You'll need [uv](https://docs.astral.sh/uv/), eac (`make install` from the repo root), the [Sentry CLI](https://cli.sentry.dev) and an [OpenRouter](https://openrouter.ai) key. +### 1. Set up -The evals fill a Sentry project with real issues, so create an empty one first. A free account works. +You'll need [uv](https://docs.astral.sh/uv/), eac (`make install` from the repo root), the [Sentry CLI](https://cli.sentry.dev), an [OpenRouter](https://openrouter.ai) key and an empty Sentry project. A free account works. ```sh -cp .env.example .env # set SENTRY_ORG and SENTRY_PROJECT +cp .env.example .env # set SENTRY_ORG and SENTRY_PROJECT uv sync -eac offline run # offers to log in to Sentry and OpenRouter if you haven't ``` -The first run takes about 30s while the seed waits on Sentry. Later runs reuse it. To start over, run `eac offline prune --all`. - -The agent uses GPT-6 Luna. To try another model: +### 2. Run the evals ```sh -eac offline run --args '{"model": "openai/gpt-6.2-sol"}' +eac offline run # with GPT-6 Luna +eac offline run --args '{"model": "openai/gpt-6.2-sol"}' # with another model ``` -## How it works - -`agent.py`, `traces.py`, `sentry_cli.py` and `app/` are the product being evaluated. You don't need to read them to follow the evals. - -The evals are in [`evals/triage/`](evals/triage/). Read them in this order: +eac offers to log in to Sentry and OpenRouter the first time. The first run takes about 30s while the seed waits on Sentry, and later runs reuse it. `eac offline prune --all` starts over. -1. [`dataset.yml`](evals/triage/dataset.yml) is where eac starts. It points at everything else. -2. [`cases.py`](evals/triage/cases.py) has the four alerts, and what the agent should find for each. -3. [`seed.py`](evals/triage/seed.py) sets up the incident the cases investigate. It releases a new version of the shop and sends it requests that fail, so three checkout bugs and an unrelated newsletter error show up in Sentry as real issues. -4. [`runners/offline.py`](evals/triage/runners/offline.py) runs the agent on each case. -5. [`judges/`](evals/triage/judges/) scores the answers. `FoundIssue` and `FoundCause` check them against the case's `expected_output` and the issues the seed created. `TriageLLMJudge` has a model review the whole investigation. +### 3. Judge production traffic -Each case is hard in its own way. The agent has to pick the right issue out of four, read the code when the stack trace blames the wrong function, and say so when nothing explains the alert. - -### Online evals - -The agent saves every conversation to `.traces/`, standing in for a real product's traces. [`runners/online.py`](evals/triage/runners/online.py) collects them as production traffic, and `TriageLLMJudge` scores them: +The agent saves each conversation to `.traces/`, standing in for production traces. ```sh eac online run --judge triage_llm_judge ``` -### Credentials +## How it works -[`credentials/`](evals/triage/credentials/) has what the evals log in to. Each seed, runner and judge lists what it needs, and eac checks them all before starting. +`agent.py`, `traces.py`, `sentry_cli.py` and `app/` are the product being evaluated. The evals are in [`evals/triage/`](evals/triage/): -- `SentryLogin` hands off to `sentry auth login`, which keeps its own login, then asks which project to use. -- `OpenRouterKey` asks for a key, which eac saves for later runs. +- [`dataset.yml`](evals/triage/dataset.yml) points at everything else +- [`cases.py`](evals/triage/cases.py) has four alerts and what the agent should find for each +- [`seed.py`](evals/triage/seed.py) releases the shop and sends it requests that fail, so three checkout bugs and an unrelated error show up in Sentry +- [`runners/`](evals/triage/runners/) runs the agent offline, and collects saved conversations online +- [`judges/`](evals/triage/judges/) checks the answer against the case and the seed, and has a model check the root cause and fix +- [`credentials/`](evals/triage/credentials/) logs in to Sentry and OpenRouter ## CI -[`evals.yml`](../../.github/workflows/evals.yml) runs the evals on each pull request and on its merge base. It uploads both runs to [evals.sentry.dev](https://evals.sentry.dev), which comments the comparison on the pull request. In this repo, that makes the example an integration test too. - -The upload is [`scripts/upload_evals.py`](../../scripts/upload_evals.py). It needs `EVALS_API_TOKEN`, and reads `GITHUB_SERVER_URL` and `GITHUB_REPOSITORY`, which GitHub Actions sets. Copy the workflow and the script to do the same in your own repo. +[`evals.yml`](../../.github/workflows/evals.yml) runs the evals on each pull request and its merge base, then uploads both to [evals.sentry.dev](https://evals.sentry.dev), which comments the comparison on the pull request. It needs the `OPENROUTER_API_KEY`, `SENTRY_AUTH_TOKEN` and `EVALS_API_TOKEN` secrets. diff --git a/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py b/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py index 0b3727e..629b77c 100644 --- a/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py +++ b/examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py @@ -6,22 +6,27 @@ from evals.triage.credentials.openrouter import OpenRouterKey from traces import load_conversation -# TODO: Better judge JUDGE_MODEL = "openai/gpt-6-luna" class TriageLLMJudge(Judge): - """Has a model review the investigation. It reads the agent trace (conversation history) the agent.py saved, so it works online too.""" + """A separate model judges the triage. It reads the agent trace (conversation history) that agent.py saved, allowing it to work for offline and online evaluation.""" name = "triage_llm_judge" credentials = [OpenRouterKey()] PROMPT = """\ -You review a triage agent's investigation of an alert about an online shop. Grade \ -its final answer: is the root cause backed by what its tools returned, and would \ -the fix solve the problem without breaking anything else? When no issue explains \ -the alert, the right answer says so. -Reply with JSON: {"score": , "explanation": ""}""" +You review a triage agent's investigation of an alert about an online shop. Answer \ +two questions about its final answer, each with true or false: + +- grounded: Is the root cause backed by what the agent's tools returned, rather than \ +guessed? When no issue explains the alert, the right answer says so instead of \ +picking one anyway. +- fix_works: Would the fix solve the problem without breaking anything else? When \ +there's nothing to fix, the right answer doesn't change any code. + +Reply with JSON: {"grounded": , "fix_works": , \ +"explanation": ""}""" def get_agent_trace(self, run): conversation = load_conversation(run.conversation_id) @@ -43,9 +48,18 @@ async def judge(self, case, *, seeds, agent_trace=None): temperature=0, ) grade = json.loads(result.choices[0].message.content) + + # Anything but a JSON true, like a missing answer, counts as false. + grounded = grade.get("grounded") is True + fix_works = grade.get("fix_works") is True + + # Each check is worth half the score: 0, 0.5 or 1. + score = (int(grounded) + int(fix_works)) / 2 + return Score( name=self.name, - score=float(grade["score"]), + score=score, explanation=grade.get("explanation"), + metadata={"grounded": grounded, "fix_works": fix_works}, llm_judge_metrics=LLMMetrics(**usage_of(result)), ) From 7fecddf0328b6d6c3492065fd1799dc7d6da4069 Mon Sep 17 00:00:00 2001 From: Ryan Brooks Date: Sat, 21 Nov 2026 21:05:52 -0800 Subject: [PATCH 3/4] Cohesion --- .github/workflows/evals.yml | 13 +-- docs/app/cases-and-runners/page.mdx | 52 ++++++--- docs/app/comparing-variants/page.mdx | 12 +- docs/app/configuration/page.mdx | 21 +++- docs/app/credentials/page.mdx | 41 +++++-- docs/app/introduction/page.mdx | 2 +- docs/app/judges/page.mdx | 110 +++++++++++++----- docs/app/online-evals/page.mdx | 51 ++++---- docs/app/sampling/page.mdx | 10 +- docs/app/seeds/page.mdx | 58 ++++++--- docs/components/mdx.tsx | 34 +++++- .../evals/triage/dataset.yml | 6 + 12 files changed, 284 insertions(+), 126 deletions(-) diff --git a/.github/workflows/evals.yml b/.github/workflows/evals.yml index 7b75566..00bf046 100644 --- a/.github/workflows/evals.yml +++ b/.github/workflows/evals.yml @@ -1,12 +1,5 @@ name: Evals -# Runs examples/sentry-assistant-python's evals at a pull request's head and -# at its merge base, with real models, and uploads both runs to -# evals.sentry.dev. It compares them and comments on the pull request. -# -# Needs the OPENROUTER_API_KEY, SENTRY_AUTH_TOKEN and EVALS_API_TOKEN secrets. -# The Sentry token has to read and resolve issues in SENTRY_ORG/SENTRY_PROJECT. - on: pull_request: paths: @@ -75,8 +68,6 @@ jobs: sha: ${{ github.event.pull_request.head.sha }} base_sha: ${{ needs.compare.outputs.base_sha }} steps: - # The upload script always comes from the pull request. The CLI, SDK - # and example come from the arm's commit, in arm/. - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -89,9 +80,7 @@ jobs: - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 - # The example's seed and agent work with Sentry through its CLI, which - # logs in with SENTRY_AUTH_TOKEN here. - - name: Install the Sentry CLI + - name: Install Sentry CLI run: npm install -g sentry@0.47.0 - name: Run the evals and upload them diff --git a/docs/app/cases-and-runners/page.mdx b/docs/app/cases-and-runners/page.mdx index a28176c..d2740b5 100644 --- a/docs/app/cases-and-runners/page.mdx +++ b/docs/app/cases-and-runners/page.mdx @@ -4,24 +4,39 @@ export const metadata = {title: 'Cases and runners'}; A **case** is one input to test. A **runner** takes a case, calls your system, and returns whatever it got back. +The samples here come from [the Sentry triage example](https://github.com/getsentry/eac/tree/main/examples/sentry-assistant-python), where an agent gets an alert and has to find the Sentry issue behind it and the function to fix. + ## Cases + + ```python from eac import Case -CASES = [ +JUDGES = [FoundIssueJudge(), FoundCauseJudge(), TriageLLMJudge()] # your own judges, see Judges + +OFFLINE_CASES = [ Case( - name="greets", - input={"query": "hi"}, - expected_output={"response": "hello"}, - judges=[Matches()], # your own judges, see Judges - splits=["smoke"], + name="coupon", + input={"alert": "Since {release} went out, customers say checkout fails when they use a coupon code."}, + expected_output={"error": "coupon", "function": "apply_coupon"}, + seeds=[Incident()], + judges=JUDGES, + ), + Case( + name="false_alarm", + input={"alert": "A customer says checkout has been broken since {release}. Is it?"}, + expected_output={"error": None, "function": None}, + seeds=[Incident()], + judges=JUDGES, ), ] ``` + + A case also has an `output`, which is what your system returned. eac fills it in after your runner runs, so your judges can read it. @@ -30,7 +45,7 @@ A few other options you might want: - `seeds=[...]` for fixtures the case needs. See [Seeds](/seeds). - `enabled=False` to skip a case unless you ask for it by name. -- `splits` to group cases, then run a group with `--split smoke`. +- `splits=["smoke"]` to group cases, then run a group with `--split smoke`. @@ -42,24 +57,35 @@ Prefer keeping cases in data files? `from_jsonl("cases/*.jsonl", judges=[...])` + + ```python from eac import OfflineRunner -class ChatRunner(OfflineRunner): - def run_case(self, case, *, seeds, conversation_id): - model = self.args.get("model", "small") - reply = my_chatbot(case.input["query"], model=model, tag=conversation_id) - return {"response": reply} +from agent import DEFAULT_MODEL, triage + + +class OfflineTriageRunner(OfflineRunner): + credentials = [OpenRouterKey(), SentryLogin()] + + async def run_case(self, case, *, seeds, conversation_id): + alert = case.input["alert"].format(release=seeds["incident"]["release"]) + model = self.args.get("model", DEFAULT_MODEL) + return await triage(alert, conversation_id=conversation_id, model=model) ``` + + Return plain JSON and leave the scoring to your judges. Along with the case, you get: -- `seeds`, each fixture's handle by name, like `seeds["project"]`. +- `seeds`, each fixture's handle by name. Here the seed made a new release, so the runner puts it in the alert. - `conversation_id` to tag your agent's run, so judges can find its trace later. - `self.args`, whatever was passed with `--args`, as a plain dict. eac doesn't check it, so check anything you rely on. +`credentials` lists what the runner needs, which eac checks before running anything. See [Credentials](/credentials). + Runners, judges and seeds can be sync or async. Use whichever fits your code. diff --git a/docs/app/comparing-variants/page.mdx b/docs/app/comparing-variants/page.mdx index 2beb159..452066a 100644 --- a/docs/app/comparing-variants/page.mdx +++ b/docs/app/comparing-variants/page.mdx @@ -4,14 +4,18 @@ export const metadata = {title: 'Comparing variants'}; Want to compare two models or agents on the same cases? Add a comparison to `dataset.yml`: + + ```yaml offline: comparisons: - name: models arms: - - name: small - - name: big - args: {model: big} + - name: luna + - name: sol + args: {model: openai/gpt-6.2-sol} ``` -Then run `eac offline compare models`. Each arm gets its own run, and they share fixtures. Each arm's `args` reach the runner as `self.args`. + + +Then run `eac offline compare models`. Each arm gets its own run, and they share fixtures. Each arm's `args` reach the runner as `self.args`, so here the `sol` arm runs the agent with another model. diff --git a/docs/app/configuration/page.mdx b/docs/app/configuration/page.mdx index cb73ee0..92111f8 100644 --- a/docs/app/configuration/page.mdx +++ b/docs/app/configuration/page.mdx @@ -20,20 +20,29 @@ If you don't set a Python command, eac uses `$EAC_PYTHON`, then your active virt ## dataset.yml +This one is from [the Sentry triage example](https://github.com/getsentry/eac/blob/main/examples/sentry-assistant-python/evals/triage/dataset.yml), with the optional `metadata` added: + ```yaml -name: chat # lowercase, digits and underscores +name: triage # lowercase, digits and underscores runtime: python -metadata: {team: chat} # optional, recorded in results +metadata: {team: triage} # optional, recorded in results offline: - runner: ./dataset.py:ChatRunner - cases: ./dataset.py:CASES + runner: ./runners/offline.py:OfflineTriageRunner + cases: ./cases.py:OFFLINE_CASES concurrency: 4 # optional, defaults to 1 + comparisons: # optional, see Comparing variants + - name: models + arms: + - name: luna + - name: sol + args: {model: openai/gpt-6.2-sol} online: - runner: ./dataset.py:ProdChats + runner: ./runners/online.py:OnlineTriageRunner judges: - - {name: polite, path: ./judges.py:Polite} + - name: triage_llm_judge + path: ./judges/triage_llm_judge.py:TriageLLMJudge ``` A dataset needs `offline`, `online`, or both. Code can be referenced as `./file.py:name` (relative to the YAML file) or `module.path:name`. A runner or judge reference can be a class, which eac builds with no arguments, or an instance you've configured. diff --git a/docs/app/credentials/page.mdx b/docs/app/credentials/page.mdx index 0d8ad74..282de5b 100644 --- a/docs/app/credentials/page.mdx +++ b/docs/app/credentials/page.mdx @@ -6,35 +6,54 @@ If your evals need a token or a login, declare it as a credential. eac checks th + + ```python +import getpass + from eac import Credential -class GitHub(Credential): - name = "github" - def __init__(self, repo): - self.repo = repo +class OpenRouterKey(Credential): + name = "openrouter" - def is_authenticated(self, env) -> bool: - return bool(env.get("GITHUB_TOKEN")) + def is_authenticated(self, env): + return bool(env.get("OPENROUTER_API_KEY")) - def authenticate(self) -> dict[str, str]: - token = run_login_flow() - return {"GITHUB_TOKEN": token} + def authenticate(self): + print("Create a key at https://openrouter.ai/settings/keys") + return {"OPENROUTER_API_KEY": getpass.getpass("OpenRouter API key: ").strip()} @property - def setup_instructions(self) -> str: - return "Set GITHUB_TOKEN in .env." + def setup_instructions(self): + return "Set OPENROUTER_API_KEY. Get a key at https://openrouter.ai/settings/keys." ``` + + Then add it to the `credentials` of whatever needs it: a seed, a runner or a judge. + + + + +```python +class OfflineTriageRunner(OfflineRunner): + credentials = [OpenRouterKey(), SentryLogin()] +``` + + + + + ## Logging in If a credential isn't set up, eac offers to run `authenticate()` for you. Whatever it returns is saved to `.eac/credentials/saved.json` (never your `.env`) and reused next time. If there's no `authenticate()`, eac shows the `setup_instructions` instead. +`authenticate()` can also hand off to a tool's own login. The example's [`SentryLogin`](https://github.com/getsentry/eac/blob/main/examples/sentry-assistant-python/evals/triage/credentials/sentry.py) runs `sentry auth login`, which keeps its own login, and only returns the project to use. + In CI, where `$CI` is set, the checks are skipped. diff --git a/docs/app/introduction/page.mdx b/docs/app/introduction/page.mdx index 911105a..f0f7e66 100644 --- a/docs/app/introduction/page.mdx +++ b/docs/app/introduction/page.mdx @@ -140,6 +140,6 @@ That's it. The results are saved in `.eac/runs//`. Changed a judge? Run `eac offline judge` to re-score the last run without running your system again. -For a real agent with seeds, an LLM judge and online evals, see [`examples/sentry-assistant-python`](https://github.com/getsentry/eac/tree/main/examples/sentry-assistant-python). +For a real agent with seeds, an LLM judge and online evals, see [`examples/sentry-assistant-python`](https://github.com/getsentry/eac/tree/main/examples/sentry-assistant-python). Given an alert, its agent searches Sentry and the app's code, and reports which issue is behind it and what to fix. The samples in the rest of these docs come from it. Next, read [how eac works](/concepts). diff --git a/docs/app/judges/page.mdx b/docs/app/judges/page.mdx index 207677a..870a536 100644 --- a/docs/app/judges/page.mdx +++ b/docs/app/judges/page.mdx @@ -6,62 +6,112 @@ A judge looks at one case's output and gives it a score between 0 and 1. Judges + + ```python from eac import Judge, Score -class Matches(Judge): - name = "matches" - - def judge(self, case, *, seeds, agent_trace=None): - expected = case.expected_output.get("response") - if expected is None: - return None # doesn't apply to this case - ok = case.output.get("response") == expected - return Score(name=self.name, score=1.0 if ok else 0.0) -class CalledTool(Judge): - name = "called_tool" +class FoundIssueJudge(Judge): + """Passes if the agent named the issue the seed created for the expected + error, or no issue when there's nothing to find.""" - def __init__(self, tool: str): - self.tool = tool + name = "found_issue" def judge(self, case, *, seeds, agent_trace=None): - if self.tool in case.output.get("tool_calls", []): + error = case.expected_output["error"] + expected = seeds["incident"]["issues"][error] if error else None + actual = case.output.get("issue") + + if actual == expected: return Score.passed(self.name) - return Score.failed(self.name, f"{self.tool} wasn't called") + return Score.failed(self.name, f"expected {expected}, actual {actual}") ``` + + +`seeds` holds the case's fixtures by name, the same ones the runner got. This judge needs them because the issue's ID only exists once the seed has created it. + If the judge doesn't apply to a case, return `None`. A score of `None` is saved but doesn't count toward pass or fail. If a judge throws, it scores 0, with an explanation starting "judge error". -`seeds` holds the case's fixtures by name, the same ones the runner got. +## Reading agent traces -## Settings per run +Some judges need more than the final output, like the agent's full conversation or the tools it called. Implement `get_agent_trace()` to fetch it: -Need settings that change per run, like a rubric? Pass them with `--judge-args`, keyed by the judge's name: + -```sh -eac offline run --judge-args '{"called_tool": {"strict": true}}' + + +```python +from eac import AgentTrace, Judge, LLMMetrics + + +class TriageLLMJudge(Judge): + name = "triage_llm_judge" + + def get_agent_trace(self, run): + conversation = load_conversation(run.conversation_id) + if conversation is None: + return None + return AgentTrace(trace=conversation["messages"], metrics=LLMMetrics(**conversation["usage"])) ``` -The judge gets its entry as `self.args`, a plain dict, or `{}` without one. eac doesn't check what's inside, so check anything you rely on. It does reject a name that no judge in the run has, to catch typos. + -## Reading agent traces + -Some judges need more than the final output, like the agent's full conversation or the tools it called. Implement `get_agent_trace()` to fetch it: +eac fetches the trace once per case and hands it to every judge as `agent_trace`. It's saved with the run, so re-judging doesn't fetch it again. Since it doesn't depend on the case's expected output, a judge like this works on [online evals](/online-evals) too. + +## LLM judges + +An LLM judge asks a model to grade the trace. This one asks two true-or-false questions, and each is worth half the score: -```python -from eac import AgentTrace, Judge + -class TraceJudge(Judge): - def get_agent_trace(self, run): - trace = fetch_trace(run.conversation_id) - return AgentTrace(trace=trace.spans) if trace else None +```python + async def judge(self, case, *, seeds, agent_trace=None): + if agent_trace is None: + return None + async with client() as openrouter: + result = await openrouter.chat.send_async( + model=self.args.get("model", JUDGE_MODEL), + messages=[ + {"role": "system", "content": self.PROMPT}, + {"role": "user", "content": json.dumps(agent_trace)}, + ], + response_format={"type": "json_object"}, + temperature=0, + ) + grade = json.loads(result.choices[0].message.content) + + grounded = grade.get("grounded") is True + fix_works = grade.get("fix_works") is True + + return Score( + name=self.name, + score=(int(grounded) + int(fix_works)) / 2, + explanation=grade.get("explanation"), + metadata={"grounded": grounded, "fix_works": fix_works}, + llm_judge_metrics=LLMMetrics(**usage_of(result)), + ) ``` + + -eac fetches the trace once per case and hands it to every judge as `agent_trace`. It's saved with the run, so re-judging doesn't fetch it again. +`metadata` is saved with the score, so you can see which question failed. `llm_judge_metrics` records what judging cost, kept apart from what the agent cost. + +## Settings per run + +Need settings that change per run, like the judge's model? Pass them with `--judge-args`, keyed by the judge's name: + +```sh +eac offline run --judge-args '{"triage_llm_judge": {"model": "openai/gpt-6.2-sol"}}' +``` + +The judge gets its entry as `self.args`, a plain dict, or `{}` without one. eac doesn't check what's inside, so check anything you rely on. It does reject a name that no judge in the run has, to catch typos. diff --git a/docs/app/online-evals/page.mdx b/docs/app/online-evals/page.mdx index af84ed1..c8ceb3f 100644 --- a/docs/app/online-evals/page.mdx +++ b/docs/app/online-evals/page.mdx @@ -10,61 +10,60 @@ Add an `online` section to your dataset, with a runner and the judges you want t - + ```yaml -name: chat +name: triage runtime: python online: - runner: ./dataset.py:ProdChats + runner: ./runners/online.py:OnlineTriageRunner judges: - - {name: greets, path: ./dataset.py:Greets} + - name: triage_llm_judge + path: ./judges/triage_llm_judge.py:TriageLLMJudge ``` -The runner's `collect_cases` returns what happened in a time window, as cases with their `output` already filled in: +The runner's `collect_cases` returns what happened in a time window, as cases with their `output` already filled in. In [the Sentry triage example](https://github.com/getsentry/eac/tree/main/examples/sentry-assistant-python), the agent saves each conversation to a local folder, standing in for production traces: - + ```python -from eac import Case, Judge, OnlineRunner, Score +from eac import Case, OnlineRunner -class ProdChats(OnlineRunner): +class OnlineTriageRunner(OnlineRunner): def collect_cases(self, window): - rows = query_production(window.since, window.until, window.limit) - return [ - Case( - name=row.id, - input={"query": row.query}, - output={"response": row.reply}, - conversation_id=row.trace_id, # lets judges fetch the agent trace + conversations = recent_conversations(window.since, window.until) + sampled = [c for c in conversations if window.samples(c["conversation_id"])] + + cases = [] + for c in sampled[: window.limit]: + cases.append( + Case( + name=c["conversation_id"], + input={"alert": c["alert"]}, + output=c["answer"], + conversation_id=c["conversation_id"], # lets judges fetch the agent trace + ) ) - for row in rows - ] - - -class Greets(Judge): - name = "greets" - - def judge(self, case, *, seeds, agent_trace=None): - ok = "hello" in case.output.get("response", "") - return Score(name=self.name, score=1.0 if ok else 0.0) + return cases ``` +The judge is the same one the offline cases use. It reads the agent's trace rather than an expected output, so it works on production runs too. See [Judges](/judges#reading-agent-traces). + ## Run it ```sh -eac online run --judge greets --since 24h +eac online run --judge triage_llm_judge --since 24h ``` diff --git a/docs/app/sampling/page.mdx b/docs/app/sampling/page.mdx index 7bc2caa..1a924c4 100644 --- a/docs/app/sampling/page.mdx +++ b/docs/app/sampling/page.mdx @@ -2,12 +2,18 @@ export const metadata = {title: 'Sampling'}; # Sampling -To judge a share of production, pass `--sample-rate 0.1` and keep the runs `window.samples()` picks by a stable id: +To judge a share of production, pass `--sample-rate 0.1` and keep the runs `window.samples()` picks by a stable id, like a trace or conversation id: + + ```python -rows = [row for row in query_production(window.since, window.until) if window.samples(row.trace_id)] +sampled = [c for c in conversations if window.samples(c["conversation_id"])] ``` + + + +The same id is always in or out of the sample, so judging the same window again picks the same runs. diff --git a/docs/app/seeds/page.mdx b/docs/app/seeds/page.mdx index a310b1e..a1c72aa 100644 --- a/docs/app/seeds/page.mdx +++ b/docs/app/seeds/page.mdx @@ -4,41 +4,69 @@ export const metadata = {title: 'Seeds'}; Seeds set up the fixtures your cases need, like a test project or user, and clean them up afterwards. +This one, from [the Sentry triage example](https://github.com/getsentry/eac/tree/main/examples/sentry-assistant-python), releases a new version of a shop and sends it requests that fail, so the agent has real Sentry issues to investigate: + + + ```python -from eac import Seed, stable_hash +from eac import Seed + + +class Incident(Seed): + name = "incident" + credentials = [SentryLogin()] -class Project(Seed): - name = "project" + def setup(self): + release = f"shop@1.4.{secrets.token_hex(3)}" + dsn = cli("dsn", "list", PROJECT)["data"][0]["dsn"] + sentry_sdk.init(dsn=dsn, release=release, default_integrations=False) - def __init__(self, slug: str = "demo"): - super().__init__() - self.slug = slug + for error, request in REQUESTS.items(): + with sentry_sdk.new_scope() as scope: + scope.fingerprint = ["{{ default }}", release] + scope.set_tag("eac_error", error) + app.handle(*request) # fails, and reports the error to Sentry - def key(self) -> str: - return stable_hash({"seed": self.name, "slug": self.slug}) + sentry_sdk.flush() - def setup(self) -> dict: - project = create_project(self.slug) - return {"id": project.id, "slug": self.slug} + # wait_for_issue() polls Sentry until the error's issue shows up. + return { + "release": release, + "issues": {error: self.wait_for_issue(release, error) for error in REQUESTS}, + } - def cleanup(self, handle: dict) -> None: - delete_project(handle["id"]) + def cleanup(self, handle): + for short_id in handle["issues"].values(): + cli("issue", "resolve", f"{ORG}/{short_id}") ``` + + -Attach it with `Case(seeds=[Project()])`, then read its handle in your runner and judges as `seeds["project"]`. +`setup()` returns a **handle**: plain JSON, like IDs and URLs, that says what it made. Attach the seed with `Case(seeds=[Incident()])`, then read its handle in your runner and judges as `seeds["incident"]`. `cleanup()` gets the same handle back. ## Caching Setting up fixtures can be slow, so eac caches them between runs: -- Seeds with the same `key()` are set up once and shared. +- Seeds with the same `key()` are set up once and shared. Every triage case uses `Incident()`, so they all share one incident. - By default, the key changes when you edit the seed's code. - `eac offline prune` cleans up seeds nothing uses anymore. +If instances of a seed differ by their constructor arguments, add those to the key: + + + +```python +def key(self): + return stable_hash([super().key(), self.slug]) +``` + + + If a case changes its fixtures, use `Case(cache=False)` to get a fresh one each run. If a seed can never be reused, set `cacheable = False` on it. ## Sharing across machines diff --git a/docs/components/mdx.tsx b/docs/components/mdx.tsx index 960d1c2..467dd9b 100644 --- a/docs/components/mdx.tsx +++ b/docs/components/mdx.tsx @@ -90,14 +90,17 @@ export function Anchor({href = '', children}: React.AnchorHTMLAttributes{children}; } -const FilenameContext = createContext(undefined); +// Set by for the fenced code block inside it. +const CodeFileContext = createContext<{filename?: string; source?: string}>({}); + +const REPO_URL = 'https://github.com/getsentry/eac/blob/main'; /** * MDX renders fenced code as
    ...
    . * Pull the language and source out of that and hand them to Scraps' CodeBlock. */ export function Pre({children}: {children?: React.ReactNode}) { - const filename = use(FilenameContext); + const {filename, source: sourcePath} = use(CodeFileContext); const code = Children.toArray(children).find(child => isValidElement(child)); if (!isValidElement<{children?: React.ReactNode; className?: string}>(code)) { return
    {children}
    ; @@ -108,6 +111,13 @@ export function Pre({children}: {children?: React.ReactNode}) { + View on GitHub + + ) : undefined + } language={language === 'text' ? undefined : language} > {source} @@ -116,16 +126,25 @@ export function Pre({children}: {children?: React.ReactNode}) { ); } +// CodeBlock puts its icon before the filename. Move it to the right, by the +// copy button. +const SourceLink = styled('span')` + order: 1; + margin-left: auto; + font-size: ${p => p.theme.font.size.sm}; +`; + const BlockSpacing = styled('div')` margin-bottom: ${p => p.theme.space['2xl']}; `; /** - * Wrap a fenced code block to show a filename above it: + * Wrap a fenced code block to show a filename above it, and with `source`, a + * link to the file in the repo: * - * + * * - * ```yaml + * ```python * ... * ``` * @@ -134,13 +153,16 @@ const BlockSpacing = styled('div')` export function CodeFile({ children, filename, + source, }: { children: React.ReactNode; filename: string; /** Inside , the language this file is for. Overrides the fence. */ lang?: string; + /** The file's path from the repo root, linked to on GitHub. */ + source?: string; }) { - return {children}; + return {children}; } /** diff --git a/examples/sentry-assistant-python/evals/triage/dataset.yml b/examples/sentry-assistant-python/evals/triage/dataset.yml index 312277c..6217229 100644 --- a/examples/sentry-assistant-python/evals/triage/dataset.yml +++ b/examples/sentry-assistant-python/evals/triage/dataset.yml @@ -5,6 +5,12 @@ offline: runner: ./runners/offline.py:OfflineTriageRunner cases: ./cases.py:OFFLINE_CASES concurrency: 4 + comparisons: + - name: models + arms: + - name: luna + - name: sol + args: {model: openai/gpt-6.2-sol} online: runner: ./runners/online.py:OnlineTriageRunner From 51d76e783ea331ad2bc24060cf2f29bfa8a8a6c8 Mon Sep 17 00:00:00 2001 From: Ryan Brooks Date: Sat, 21 Nov 2026 21:18:58 -0800 Subject: [PATCH 4/4] lower version --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index 4e379d2..8acdd82 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.2 +0.0.1