diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f8420a9..f6adbda 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,19 @@ jobs: - name: Lint run: make lint + typecheck: + name: make typecheck + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + # The SDK ships its types (eac/py.typed), so they must be right. + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + + - name: Type-check the Python SDK + run: make typecheck + generate: name: make generate-check runs-on: ubuntu-latest diff --git a/Makefile b/Makefile index 8296f46..5325127 100644 --- a/Makefile +++ b/Makefile @@ -1,10 +1,11 @@ CARGO ?= cargo PYTHON ?= python3 PNPM ?= pnpm +MYPY ?= uvx mypy==2.4.1 MANIFEST := core/Cargo.toml .DEFAULT_GOAL := help -.PHONY: help build install test lint fmt generate generate-check version version-check docs +.PHONY: help build install test lint fmt typecheck generate generate-check version version-check docs help: ## list the targets @awk -F ':.*## ' '/^[a-z-]+:.*## / {printf " %-15s %s\n", $$1, $$2}' $(MAKEFILE_LIST) @@ -25,6 +26,9 @@ lint: ## check formatting and run clippy on the CLI and its tests, failing on an fmt: ## format the CLI's code $(CARGO) fmt --manifest-path $(MANIFEST) +typecheck: ## type-check the Python SDK with mypy --strict + cd sdks/python && $(MYPY) + generate: ## regenerate the protocol's and results' JSON Schemas and the Python SDK's protocol.py $(PYTHON) scripts/generate.py diff --git a/README.md b/README.md index 0a826ad..65d841d 100644 --- a/README.md +++ b/README.md @@ -37,14 +37,14 @@ def reply(query: str) -> str: class ChatRunner(OfflineRunner): - def run_case(self, case, *, seeds, conversation_id): + def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: return {"response": reply(case.input["query"])} class Greets(Judge): name = "greets_judge" - def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: response = case.output.get("response", "") if "hello" in response: return Score(name=self.name, score=1.0) diff --git a/core/PROTOCOL.md b/core/PROTOCOL.md index 62e68df..5a3bd84 100644 --- a/core/PROTOCOL.md +++ b/core/PROTOCOL.md @@ -84,7 +84,6 @@ These types show up in the params and results of many methods: // same credential. {"path": "evals.auth:GitHub", "fields": {"repo": "getsentry/sentry"}, "name": "github", // for status lines and prompts - "setup_instructions": "Set GITHUB_TOKEN...", // optional: shown when it isn't set up "manual": false} // true: it can only be set up by hand, so eac doesn't offer to log in // DatasetRef: where a dataset's code is. References are "module.path:attr" diff --git a/core/README.md b/core/README.md index 2b255fe..be088e2 100644 --- a/core/README.md +++ b/core/README.md @@ -122,6 +122,7 @@ make install # install eac into ~/.cargo/bin make test # unit and end-to-end tests make lint # rustfmt check and clippy, failing on any warning make fmt # format the code +make typecheck # mypy --strict on the Python SDK make generate # regenerate the JSON schemas and SDK models make generate-check # fail if a generated file is out of date make version # copy the version in VERSION into the CLI and SDKs diff --git a/core/src/eac/phases/credentials.rs b/core/src/eac/phases/credentials.rs index f0e3e05..862d404 100644 --- a/core/src/eac/phases/credentials.rs +++ b/core/src/eac/phases/credentials.rs @@ -218,13 +218,9 @@ fn confirm(question: &str) -> Result { Ok(answer.is_empty() || answer == "y" || answer == "yes") } -/// A credential that isn't set up, with how to set it up by hand. +/// A credential that isn't set up, and why. fn failure(c: &Credential, why: &str) -> String { - let mut failure = format!(" {}: {why}", c.name); - if !c.setup_instructions.is_empty() { - failure += &format!("\n {}", c.setup_instructions); - } - failure + format!(" {}: {why}", c.name) } /// Why logging in failed. An SDK's error leaves out its traceback, since diff --git a/core/src/schema/protocol.schema.json b/core/src/schema/protocol.schema.json index 5471ad1..ea0aef3 100644 --- a/core/src/schema/protocol.schema.json +++ b/core/src/schema/protocol.schema.json @@ -265,7 +265,7 @@ "type": "object" }, "manual": { - "description": "Can only be set up by hand, so eac shows the instructions instead of offering to log in.", + "description": "Can only be set up by hand, so eac doesn't offer to log in.", "type": "boolean" }, "name": { @@ -275,10 +275,6 @@ "path": { "description": "The credential's class, as a code reference.", "type": "string" - }, - "setup_instructions": { - "description": "How to set it up by hand, shown when it isn't set up.", - "type": "string" } }, "required": [ diff --git a/core/src/schema/types.rs b/core/src/schema/types.rs index 1cd3504..2739b79 100644 --- a/core/src/schema/types.rs +++ b/core/src/schema/types.rs @@ -82,11 +82,7 @@ pub struct Credential { pub fields: Object, /// Shown in status lines and prompts, like "github". pub name: String, - /// How to set it up by hand, shown when it isn't set up. - #[serde(default, deserialize_with = "nullable", skip_serializing_if = "String::is_empty")] - pub setup_instructions: String, - /// Can only be set up by hand, so eac shows the instructions instead of - /// offering to log in. + /// Can only be set up by hand, so eac doesn't offer to log in. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub manual: bool, } diff --git a/core/tests/cli.rs b/core/tests/cli.rs index 56b6a85..4c3f7fe 100644 --- a/core/tests/cli.rs +++ b/core/tests/cli.rs @@ -724,10 +724,7 @@ fn every_dataset_needs_its_own_name() { fn credentials_are_checked_before_the_phases_that_need_them() { let p = Project::new(&base()); p.write("needs.json", r#"{"seed": ["TOKEN_A"], "runner": ["TOKEN_B"]}"#); - p.eac(&["offline", "run"]) - .code(2) - .says("✗ token_a") - .says("token_a: missing or invalid\n Set TOKEN_A."); + p.eac(&["offline", "run"]).code(2).says("✗ token_a").says("token_a: missing or invalid"); assert!(p.runs().is_empty(), "nothing is set up"); // Both seeds need TOKEN_A, which is checked once. let checks = p.events("credentials_check"); @@ -789,7 +786,7 @@ fn logins_on_a_terminal_are_saved_for_later_commands() { } #[test] -fn a_failed_login_says_how_to_set_up_by_hand() { +fn a_failed_login_says_why() { let p = Project::new(&base()); p.write("needs.json", r#"{"runner": ["TOKEN_REFUSED", "TOKEN_MANUAL"]}"#); let args = ["offline", "run", "--split", "smoke"]; @@ -801,8 +798,8 @@ fn a_failed_login_says_how_to_set_up_by_hand() { 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."); + .says("token_refused: RuntimeError: the login was refused") + .says("token_manual: missing or invalid"); // A credential that can only be set up by hand isn't logged in to. let logins = p.events("credentials_login"); assert_eq!(names(&logins, "name"), ["token_refused"]); diff --git a/core/tests/fixtures/project/evals/chat_eval.py b/core/tests/fixtures/project/evals/chat_eval.py index 140efd3..c7a1d27 100644 --- a/core/tests/fixtures/project/evals/chat_eval.py +++ b/core/tests/fixtures/project/evals/chat_eval.py @@ -72,7 +72,6 @@ def needs(part): "path": "fixture:Token", "fields": {"var": var}, "name": var.lower(), - "setup_instructions": f"Set {var}.", "manual": var.endswith("MANUAL"), } for var in names diff --git a/docs/app/cases-and-runners/page.mdx b/docs/app/cases-and-runners/page.mdx index d2740b5..8690661 100644 --- a/docs/app/cases-and-runners/page.mdx +++ b/docs/app/cases-and-runners/page.mdx @@ -60,18 +60,16 @@ Prefer keeping cases in data files? `from_jsonl("cases/*.jsonl", judges=[...])` ```python -from eac import OfflineRunner - -from agent import DEFAULT_MODEL, triage +from eac import Case, OfflineRunner class OfflineTriageRunner(OfflineRunner): credentials = [OpenRouterKey(), SentryLogin()] - async def run_case(self, case, *, seeds, conversation_id): + def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: 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 triage(alert, conversation_id=conversation_id, model=model) ``` @@ -86,8 +84,4 @@ Return plain JSON and leave the scoring to your judges. Along with the case, you `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. - - To run the same cases against two models or agents, see [Comparing variants](/comparing-variants). diff --git a/docs/app/credentials/page.mdx b/docs/app/credentials/page.mdx index 282de5b..794519a 100644 --- a/docs/app/credentials/page.mdx +++ b/docs/app/credentials/page.mdx @@ -9,24 +9,18 @@ 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 OpenRouterKey(Credential): name = "openrouter" - def is_authenticated(self, env): + def is_authenticated(self, env: Mapping[str, str]) -> bool: return bool(env.get("OPENROUTER_API_KEY")) - def authenticate(self): + def authenticate(self) -> dict[str, str]: 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." ``` @@ -50,7 +44,7 @@ class OfflineTriageRunner(OfflineRunner): ## 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. +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 `authenticate()` raises, eac shows the error, so say what to do by hand in it. If there's no `authenticate()`, the credential can only be set up by hand, so eac doesn't offer to log in. `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. diff --git a/docs/app/introduction/page.mdx b/docs/app/introduction/page.mdx index f0f7e66..66c5531 100644 --- a/docs/app/introduction/page.mdx +++ b/docs/app/introduction/page.mdx @@ -106,14 +106,14 @@ def reply(query: str) -> str: class ChatRunner(OfflineRunner): - def run_case(self, case, *, seeds, conversation_id): + def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: return {"response": reply(case.input["query"])} class Greets(Judge): name = "greets" - def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: ok = "hello" in case.output.get("response", "") return Score(name=self.name, score=1.0 if ok else 0.0) diff --git a/docs/app/judges/page.mdx b/docs/app/judges/page.mdx index 870a536..d7dc5da 100644 --- a/docs/app/judges/page.mdx +++ b/docs/app/judges/page.mdx @@ -9,7 +9,7 @@ A judge looks at one case's output and gives it a score between 0 and 1. Judges ```python -from eac import Judge, Score +from eac import Case, Judge, Score class FoundIssueJudge(Judge): @@ -18,7 +18,7 @@ class FoundIssueJudge(Judge): name = "found_issue" - def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: error = case.expected_output["error"] expected = seeds["incident"]["issues"][error] if error else None actual = case.output.get("issue") @@ -45,13 +45,13 @@ Some judges need more than the final output, like the agent's full conversation ```python -from eac import AgentTrace, Judge, LLMMetrics +from eac import AgentRun, AgentTrace, Case, Judge, LLMMetrics, Score class TriageLLMJudge(Judge): name = "triage_llm_judge" - def get_agent_trace(self, run): + def get_agent_trace(self, run: AgentRun) -> AgentTrace | None: conversation = load_conversation(run.conversation_id) if conversation is None: return None @@ -73,11 +73,11 @@ An LLM judge asks a model to grade the trace. This one asks two true-or-false qu ```python - async def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: if agent_trace is None: return None - async with client() as openrouter: - result = await openrouter.chat.send_async( + with client() as openrouter: + result = openrouter.chat.send( model=self.args.get("model", JUDGE_MODEL), messages=[ {"role": "system", "content": self.PROMPT}, @@ -86,15 +86,15 @@ An LLM judge asks a model to grade the trace. This one asks two true-or-false qu response_format={"type": "json_object"}, temperature=0, ) - grade = json.loads(result.choices[0].message.content) + judge = json.loads(result.choices[0].message.content) - grounded = grade.get("grounded") is True - fix_works = grade.get("fix_works") is True + grounded = judge.get("grounded") is True + fix_works = judge.get("fix_works") is True return Score( name=self.name, score=(int(grounded) + int(fix_works)) / 2, - explanation=grade.get("explanation"), + explanation=judge.get("explanation"), metadata={"grounded": grounded, "fix_works": fix_works}, llm_judge_metrics=LLMMetrics(**usage_of(result)), ) diff --git a/docs/app/online-evals/page.mdx b/docs/app/online-evals/page.mdx index c8ceb3f..4568fc0 100644 --- a/docs/app/online-evals/page.mdx +++ b/docs/app/online-evals/page.mdx @@ -33,11 +33,11 @@ The runner's `collect_cases` returns what happened in a time window, as cases wi ```python -from eac import Case, OnlineRunner +from eac import Case, OnlineRunner, Window class OnlineTriageRunner(OnlineRunner): - def collect_cases(self, window): + def collect_cases(self, window: Window) -> list[Case]: conversations = recent_conversations(window.since, window.until) sampled = [c for c in conversations if window.samples(c["conversation_id"])] diff --git a/docs/app/seeds/page.mdx b/docs/app/seeds/page.mdx index a1c72aa..8a01d03 100644 --- a/docs/app/seeds/page.mdx +++ b/docs/app/seeds/page.mdx @@ -18,7 +18,7 @@ class Incident(Seed): name = "incident" credentials = [SentryLogin()] - def setup(self): + def setup(self) -> dict[str, Any]: 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) @@ -37,7 +37,7 @@ class Incident(Seed): "issues": {error: self.wait_for_issue(release, error) for error in REQUESTS}, } - def cleanup(self, handle): + def cleanup(self, handle: dict[str, Any]) -> None: for short_id in handle["issues"].values(): cli("issue", "resolve", f"{ORG}/{short_id}") ``` @@ -61,7 +61,7 @@ If instances of a seed differ by their constructor arguments, add those to the k ```python -def key(self): +def key(self) -> str: return stable_hash([super().key(), self.slug]) ``` @@ -77,13 +77,13 @@ The cache lives on your machine by default. To share fixtures across CI jobs, st ```python class SharedSeed(Seed): - def load_cached(self, key): + def load_cached(self, key: str) -> dict[str, Any] | None: return bucket.get(f"seeds/{self.name}/{key}") - def save_cached(self, key, handle): + def save_cached(self, key: str, handle: dict[str, Any]) -> None: bucket.put(f"seeds/{self.name}/{key}", handle) - def delete_cached(self, key): + def delete_cached(self, key: str) -> None: bucket.delete(f"seeds/{self.name}/{key}") ``` diff --git a/docs/components/landing.tsx b/docs/components/landing.tsx index 2145e41..239f241 100644 --- a/docs/components/landing.tsx +++ b/docs/components/landing.tsx @@ -30,14 +30,14 @@ def reply(query: str) -> str: class ChatRunner(OfflineRunner): - def run_case(self, case, *, seeds, conversation_id): + def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: return {"response": reply(case.input["query"])} class GreetsJudge(Judge): name = "greets_judge" - def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: response = case.output.get("response", "") if "hello" in response: return Score(name=self.name, score=1.0) diff --git a/examples/sentry-assistant-python/agent.py b/examples/sentry-assistant-python/agent.py index fb0f768..7c9e84c 100644 --- a/examples/sentry-assistant-python/agent.py +++ b/examples/sentry-assistant-python/agent.py @@ -7,7 +7,6 @@ uv run --env-file .env python agent.py "Checkout is failing since shop@1.4.0" """ -import asyncio import json import os import sys @@ -39,7 +38,7 @@ "fix": ""}""" -async def triage(alert, *, conversation_id, model=DEFAULT_MODEL): +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}") @@ -58,9 +57,9 @@ async def triage(alert, *, conversation_id, model=DEFAULT_MODEL): } started_at = datetime.now(UTC) - async with client() as openrouter: + with client() as openrouter: for _ in range(MAX_TURNS): - result = await openrouter.chat.send_async( + result = openrouter.chat.send( model=model, messages=messages, tools=TOOLS, @@ -243,5 +242,5 @@ def log(conversation_id, message): if __name__ == "__main__": - answer = asyncio.run(triage(" ".join(sys.argv[1:]), conversation_id=str(uuid.uuid4()))) + answer = triage(" ".join(sys.argv[1:]), conversation_id=str(uuid.uuid4())) print(json.dumps(answer, indent=2)) diff --git a/examples/sentry-assistant-python/evals/triage/credentials/openrouter.py b/examples/sentry-assistant-python/evals/triage/credentials/openrouter.py index a894cca..9f7693c 100644 --- a/examples/sentry-assistant-python/evals/triage/credentials/openrouter.py +++ b/examples/sentry-assistant-python/evals/triage/credentials/openrouter.py @@ -1,4 +1,5 @@ import getpass +from collections.abc import Mapping from eac import Credential @@ -8,13 +9,9 @@ class OpenRouterKey(Credential): name = "openrouter" - def is_authenticated(self, env): + def is_authenticated(self, env: Mapping[str, str]) -> bool: return bool(env.get("OPENROUTER_API_KEY")) - def authenticate(self): + def authenticate(self) -> dict[str, str]: 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 index b253411..304b9d6 100644 --- a/examples/sentry-assistant-python/evals/triage/credentials/sentry.py +++ b/examples/sentry-assistant-python/evals/triage/credentials/sentry.py @@ -1,6 +1,7 @@ import os import shutil import subprocess +from collections.abc import Mapping from eac import Credential @@ -17,23 +18,18 @@ class SentryLogin(Credential): name = "sentry" - def is_authenticated(self, env): + def is_authenticated(self, env: Mapping[str, str]) -> bool: 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): + def authenticate(self) -> dict[str, str]: + if not shutil.which("sentry"): + raise RuntimeError("install the Sentry CLI (https://cli.sentry.dev), then run eac again") # 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/judges/found_cause_judge.py b/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py index 2dc8b55..4860e55 100644 --- a/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py +++ b/examples/sentry-assistant-python/evals/triage/judges/found_cause_judge.py @@ -1,4 +1,6 @@ -from eac import Judge, Score +from typing import Any + +from eac import Case, Judge, Score class FoundCauseJudge(Judge): @@ -6,7 +8,7 @@ class FoundCauseJudge(Judge): name = "found_cause" - def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: expected = case.expected_output["function"] actual = case.output.get("function") 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 index dc804c7..8e6952d 100644 --- a/examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py +++ b/examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py @@ -1,4 +1,6 @@ -from eac import Judge, Score +from typing import Any + +from eac import Case, Judge, Score class FoundIssueJudge(Judge): @@ -7,7 +9,7 @@ class FoundIssueJudge(Judge): name = "found_issue" - def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: error = case.expected_output["error"] expected = seeds["incident"]["issues"][error] if error else None 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 629b77c..be089db 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 @@ -1,6 +1,7 @@ import json +from typing import Any -from eac import AgentTrace, Judge, LLMMetrics, Score +from eac import AgentRun, AgentTrace, Case, Judge, LLMMetrics, Score from agent import client, usage_of from evals.triage.credentials.openrouter import OpenRouterKey @@ -28,17 +29,17 @@ class TriageLLMJudge(Judge): Reply with JSON: {"grounded": , "fix_works": , \ "explanation": ""}""" - def get_agent_trace(self, run): + def get_agent_trace(self, run: AgentRun) -> AgentTrace | None: 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): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: if agent_trace is None: return None - async with client() as openrouter: - result = await openrouter.chat.send_async( + with client() as openrouter: + result = openrouter.chat.send( model=self.args.get("model", JUDGE_MODEL), messages=[ {"role": "system", "content": self.PROMPT}, @@ -47,11 +48,11 @@ async def judge(self, case, *, seeds, agent_trace=None): response_format={"type": "json_object"}, temperature=0, ) - grade = json.loads(result.choices[0].message.content) + judge = 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 + grounded = judge.get("grounded") is True + fix_works = judge.get("fix_works") is True # Each check is worth half the score: 0, 0.5 or 1. score = (int(grounded) + int(fix_works)) / 2 @@ -59,7 +60,7 @@ async def judge(self, case, *, seeds, agent_trace=None): return Score( name=self.name, score=score, - explanation=grade.get("explanation"), + explanation=judge.get("explanation"), metadata={"grounded": grounded, "fix_works": fix_works}, 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 index a511477..a35cac7 100644 --- a/examples/sentry-assistant-python/evals/triage/runners/offline.py +++ b/examples/sentry-assistant-python/evals/triage/runners/offline.py @@ -1,4 +1,6 @@ -from eac import OfflineRunner +from typing import Any + +from eac import Case, OfflineRunner from agent import DEFAULT_MODEL, triage from evals.triage.credentials.openrouter import OpenRouterKey @@ -10,6 +12,6 @@ class OfflineTriageRunner(OfflineRunner): credentials = [OpenRouterKey(), SentryLogin()] - async def run_case(self, case, *, seeds, conversation_id): + def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: alert = case.input["alert"].format(release=seeds["incident"]["release"]) - return await triage(alert, conversation_id=conversation_id, model=self.args.get("model", DEFAULT_MODEL)) + return 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 index e413ca5..4041949 100644 --- a/examples/sentry-assistant-python/evals/triage/runners/online.py +++ b/examples/sentry-assistant-python/evals/triage/runners/online.py @@ -1,4 +1,4 @@ -from eac import Case, OnlineRunner +from eac import Case, OnlineRunner, Window from traces import recent_conversations @@ -6,7 +6,7 @@ class OnlineTriageRunner(OnlineRunner): """Collects the conversations agent.py saved as production traffic.""" - def collect_cases(self, window): + def collect_cases(self, window: Window) -> list[Case]: conversations = recent_conversations(window.since, window.until) sampled = [c for c in conversations if window.samples(c["conversation_id"])] diff --git a/examples/sentry-assistant-python/evals/triage/seed.py b/examples/sentry-assistant-python/evals/triage/seed.py index b6d2723..0d05726 100644 --- a/examples/sentry-assistant-python/evals/triage/seed.py +++ b/examples/sentry-assistant-python/evals/triage/seed.py @@ -1,5 +1,6 @@ import secrets import time +from typing import Any import sentry_sdk from eac import Seed @@ -23,7 +24,7 @@ class Incident(Seed): name = "incident" credentials = [SentryLogin()] - def setup(self): + def setup(self) -> dict[str, Any]: 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) @@ -43,7 +44,7 @@ def setup(self): "issues": {error: self.wait_for_issue(release, error) for error in REQUESTS}, } - def wait_for_issue(self, release, error): + def wait_for_issue(self, release: str, error: str) -> str: """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"] @@ -52,6 +53,6 @@ def wait_for_issue(self, release, error): time.sleep(2) raise TimeoutError(f"the {error} issue didn't show up in Sentry within 2 minutes") - def cleanup(self, handle): + def cleanup(self, handle: dict[str, Any]) -> None: for short_id in handle["issues"].values(): cli("issue", "resolve", f"{ORG}/{short_id}") diff --git a/scripts/generate.py b/scripts/generate.py index fa79683..3ac49fe 100644 --- a/scripts/generate.py +++ b/scripts/generate.py @@ -21,8 +21,8 @@ GENERATED = f"Generated by `make generate` from {PROTOCOL}; DO NOT EDIT." -# The method tables in $defs, and the name each one's union of method names gets. -TABLES = {"WorkerMethods": "WorkerMethod"} +# The table of methods in $defs, for the schema's readers. Python doesn't use it. +METHODS = "WorkerMethods" PYTHON_KEYWORDS = { "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", @@ -75,19 +75,11 @@ def read(path: str) -> str | None: # on anything else. def python(schema: dict[str, Any]) -> str: version = schema["$defs"]["Ready"]["properties"]["protocol"]["const"] - aliases: list[list[str]] = [] - classes: list[list[str]] = [] - for name, d in schema["$defs"].items(): - if name in TABLES: - methods = [literal(method) for method in d["properties"]] - aliases.append([*comment(key(d, "description")), *assign(TABLES[name], methods)]) - elif key(d, "type") == "object" and key(d, "properties") is not None: - classes.append(typed_dict(name, d)) - elif key(d, "enum") is not None: - values = [literal(value) for value in d["enum"]] - aliases.append([*comment(key(d, "description")), *assign(name, values)]) - else: - aliases.append([*comment(key(d, "description")), f"{name} = {python_type(d)}"]) + defs = schema["$defs"] + # Objects become TypedDicts and enums Literals, shared so they stay in sync. + # Anything else, like dict[str, Any], is written out where it's used. + enums = [enum(name, d) for name, d in defs.items() if is_enum(d)] + classes = [typed_dict(name, d, defs) for name, d in defs.items() if name != METHODS and is_class(d)] lines = [ f'"""The worker protocol\'s types, v{version}.', "", @@ -96,27 +88,20 @@ def python(schema: dict[str, Any]) -> str: "", "from __future__ import annotations", "", - "from typing import Any, Literal, NotRequired, TypedDict", + "from typing import Any, Final, Literal, NotRequired, TypedDict", "", - f"PROTOCOL_VERSION = {version}", + # Final, so type checkers see Literal[1] and accept it as a Ready. + f"PROTOCOL_VERSION: Final = {version}", "", ] - for alias in aliases: + for alias in enums: lines += ["", *alias] for cls in classes: lines += ["", "", *cls] return "\n".join(lines) + "\n" -# name = Literal[...], a value per line if it won't fit on one. -def assign(name: str, values: list[str]) -> list[str]: - line = f"{name} = Literal[{', '.join(values)}]" - if len(line) <= 88: - return [line] - return [f"{name} = Literal[", *(f" {value}," for value in values), "]"] - - -def typed_dict(name: str, d: dict[str, Any]) -> list[str]: +def typed_dict(name: str, d: dict[str, Any], defs: dict[str, Any]) -> list[str]: required = set(d.get("required") or []) lines = [f"class {name}(TypedDict):"] if d.get("description"): @@ -124,7 +109,7 @@ def typed_dict(name: str, d: dict[str, Any]) -> list[str]: for field, prop in d["properties"].items(): if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", field) or field in PYTHON_KEYWORDS: raise ValueError(f"{name}.{field} can't be a TypedDict field name") - type_ = python_type(prop) + type_ = python_type(prop, defs) lines += [ *comment(key(prop, "description"), " "), f" {field}: {type_ if field in required else f'NotRequired[{type_}]'}", @@ -132,22 +117,37 @@ def typed_dict(name: str, d: dict[str, Any]) -> list[str]: return lines -def python_type(s: Any) -> str: +def enum(name: str, d: dict[str, Any]) -> list[str]: + values = ", ".join(literal(value) for value in d["enum"]) + return [*comment(key(d, "description")), f"{name} = Literal[{values}]"] + + +def is_enum(d: Any) -> bool: + return key(d, "enum") is not None + + +def is_class(d: Any) -> bool: + return key(d, "type") == "object" and key(d, "properties") is not None + + +def python_type(s: Any, defs: dict[str, Any]) -> str: if s is True: return "Any" if not isinstance(s, dict): raise ValueError(f"no Python type for {json.dumps(s)}") if s.get("$ref"): - return s["$ref"].split("/")[-1] + name = s["$ref"].split("/")[-1] + d = defs[name] + return name if is_class(d) or is_enum(d) else python_type(d, defs) if "const" in s: return f"Literal[{literal(s['const'])}]" if s.get("enum") is not None: return f"Literal[{', '.join(literal(value) for value in s['enum'])}]" variants = s["anyOf"] if s.get("anyOf") is not None else s.get("oneOf") if variants is not None: - return union([python_type(variant) for variant in variants]) + return union([python_type(variant, defs) for variant in variants]) if isinstance(s.get("type"), list): - return union([python_type({**s, "type": type_}) for type_ in s["type"]]) + return union([python_type({**s, "type": type_}, defs) for type_ in s["type"]]) if "type" not in s: return "Any" simple = { @@ -160,9 +160,9 @@ def python_type(s: Any) -> str: if s["type"] in simple: return simple[s["type"]] if s["type"] == "array": - return f"list[{python_type(nullish(s.get('items'), True))}]" + return f"list[{python_type(nullish(s.get('items'), True), defs)}]" if s["type"] == "object" and s.get("properties") is None: - return f"dict[str, {python_type(nullish(s.get('additionalProperties'), True))}]" + return f"dict[str, {python_type(nullish(s.get('additionalProperties'), True), defs)}]" raise ValueError(f"no Python type for {json.dumps(s)}") diff --git a/sdks/python/README.md b/sdks/python/README.md index c7d3386..40ca59b 100644 --- a/sdks/python/README.md +++ b/sdks/python/README.md @@ -117,7 +117,7 @@ is left to the judges. from eac import Case, OfflineRunner class ChatRunner(OfflineRunner): - def run_case(self, case: Case, *, seeds, conversation_id) -> dict: + def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: model = self.args.get("model", "small") reply = my_chatbot(case.input["query"], model=model, tag=conversation_id) return {"response": reply} @@ -139,12 +139,12 @@ A judge scores one case's output from 0 to 1. Judges are your own code: subclass `Judge` and read `case.output`. ```python -from eac import Judge, Score +from eac import Case, Judge, Score class Matches(Judge): name = "matches" # what its scores are called - def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: expected = case.expected_output.get("response") if expected is None: return None # doesn't apply, e.g. online @@ -158,7 +158,7 @@ class CalledTool(Judge): def __init__(self, tool: str): self.tool = tool - def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: ok = self.tool in (case.output.get("tool_calls") or []) return Score(name=self.name, score=1.0 if ok else 0.0) ``` @@ -187,14 +187,14 @@ calls, by implementing `get_agent_trace()`. A base class shares it between judges: ```python -from eac import AgentTrace, Judge, LLMMetrics +from eac import AgentRun, AgentTrace, Case, Judge, LLMMetrics, Score class SentryJudge(Judge): """A base for judges that read the agent's trace from Sentry.""" credentials = (SentryToken(),) - def get_agent_trace(self, run): + def get_agent_trace(self, run: AgentRun) -> AgentTrace | None: trace = fetch_trace(run.conversation_id, since=run.started_at) if trace is None: return None @@ -203,7 +203,7 @@ class SentryJudge(Judge): class UsedTheRightTool(SentryJudge): name = "used_the_right_tool" - def judge(self, case, *, seeds, agent_trace=None): + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: ... ``` @@ -235,11 +235,11 @@ class Project(Seed): def key(self) -> str: return stable_hash({"seed": self.name, "slug": self.slug}) - def setup(self) -> dict: + def setup(self) -> dict[str, Any]: project = create_project(self.slug) return {"id": project.id, "slug": self.slug} - def cleanup(self, handle: dict) -> None: + def cleanup(self, handle: dict[str, Any]) -> None: delete_project(handle["id"]) ``` @@ -266,13 +266,13 @@ CI jobs, give the seed a cache of its own: class SharedSeed(Seed): """A base for seeds that machines share through a bucket.""" - def load_cached(self, key): + def load_cached(self, key: str) -> dict[str, Any] | None: return bucket.get(f"seeds/{self.name}/{key}") # the handle, or None - def save_cached(self, key, handle): + def save_cached(self, key: str, handle: dict[str, Any]) -> None: bucket.put(f"seeds/{self.name}/{key}", handle) - def delete_cached(self, key): + def delete_cached(self, key: str) -> None: bucket.delete(f"seeds/{self.name}/{key}") ``` @@ -295,10 +295,10 @@ cases with their outputs, so the online judges can score them. Nothing is re-run. ```python -from eac import Case, OnlineRunner +from eac import Case, OnlineRunner, Window class ProdChats(OnlineRunner): - def collect_cases(self, window): + def collect_cases(self, window: Window) -> list[Case]: return [ Case( name=row.id, @@ -341,18 +341,15 @@ that phase needs, so a missing token stops the run before anything is set up instead of halfway through. ```python -import subprocess - -import httpx from eac import Credential class GitHub(Credential): name = "github" # shown in status lines and prompts - def __init__(self, repo): + def __init__(self, repo: str): self.repo = repo - def is_authenticated(self, env) -> bool: + def is_authenticated(self, env: Mapping[str, str]) -> bool: token = env.get("GITHUB_TOKEN", "") url = f"https://api.github.com/repos/{self.repo}" return bool(token) and httpx.get(url, headers={"Authorization": f"Bearer {token}"}).is_success @@ -361,10 +358,6 @@ class GitHub(Credential): subprocess.run(["gh", "auth", "login"], check=True) token = subprocess.run(["gh", "auth", "token"], capture_output=True, text=True).stdout.strip() return {"GITHUB_TOKEN": token} # saved for later commands - - @property - def setup_instructions(self) -> str: - return f"Set GITHUB_TOKEN in .env to a token that can read {self.repo}." ``` Declare credentials on whatever needs them: @@ -384,9 +377,10 @@ 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. CI, where `$CI` is set, skips the checks. +commands use them ahead of `.env` and your shell. If `authenticate()` raises, +eac shows the error, so say what to do by hand in it. A credential without +`authenticate()` can only be set up by hand, so eac doesn't offer to log in. +CI, where `$CI` is set, skips the checks. eac rebuilds credentials in other processes from their class and arguments, so build them with plain values like strings. @@ -406,8 +400,10 @@ with `--args '{"model": "big"}'`. Each run is saved under `.eac/runs//`. eac exits with `0` when no case failed or errored, `1` when any did, and `2` when eac itself failed. -Runner, judge and seed methods can be sync or async. Async ones run -on the worker's event loop and sync ones in a thread, so sync code can call -`asyncio.run()`. +Runner, judge, seed and credential methods are plain `def`s. To call async +code from one, use `asyncio.run()`. Each call starts a new event loop, so +create async clients inside it rather than keeping them on `self`. eac runs +cases in parallel with `concurrency`, which starts more workers, so your code +handles one case at a time. [`core/README.md`](../../core/README.md) is the CLI's full reference. diff --git a/sdks/python/eac/__init__.py b/sdks/python/eac/__init__.py index 0dae3e6..433419f 100644 --- a/sdks/python/eac/__init__.py +++ b/sdks/python/eac/__init__.py @@ -1,7 +1,7 @@ from eac._version import __version__ from eac.credential import Credential from eac.judge import Judge -from eac.models import AgentRun, AgentTrace, Case, Handle, LLMMetrics, Score, Window, from_jsonl, stable_hash +from eac.models import AgentRun, AgentTrace, Case, LLMMetrics, Score, Window, from_jsonl, stable_hash from eac.protocol import PROTOCOL_VERSION from eac.runner import OfflineRunner, OnlineRunner from eac.seed import Seed, current_week_salt @@ -12,7 +12,6 @@ "AgentTrace", "Case", "Credential", - "Handle", "Judge", "LLMMetrics", "OfflineRunner", diff --git a/sdks/python/eac/credential.py b/sdks/python/eac/credential.py index 7b79850..58a8119 100644 --- a/sdks/python/eac/credential.py +++ b/sdks/python/eac/credential.py @@ -32,22 +32,17 @@ def __new__(cls, /, *args: Any, **kwargs: Any) -> Self: @abstractmethod def is_authenticated(self, env: Mapping[str, str]) -> bool: """Whether the credentials are present and still work. `env` is the - environment, which includes the .env next to eac.yml. May be async.""" + environment, which includes the .env next to eac.yml.""" def authenticate(self) -> dict[str, str]: """Obtain the credentials and return any environment variables they need. Once the credential checks out, eac saves them for later commands in its artifacts directory, never in .env. It runs on the terminal, so it can prompt or run a command like `gh auth login`. - Raise RuntimeError saying what went wrong when it can't finish. May - be async. + Raise RuntimeError saying what went wrong when it can't finish, which + eac shows. - Without it, eac shows `setup_instructions` instead of offering to log - in. + Without it, the credential can only be set up by hand, so eac doesn't + offer to log in. """ raise RuntimeError("it can't be set up from eac") - - @property - def setup_instructions(self) -> str: - """How to set the credentials up by hand.""" - return "" diff --git a/sdks/python/eac/judge/judge.py b/sdks/python/eac/judge/judge.py index 24904c1..1a21919 100644 --- a/sdks/python/eac/judge/judge.py +++ b/sdks/python/eac/judge/judge.py @@ -5,7 +5,7 @@ if TYPE_CHECKING: from eac.credential import Credential - from eac.models import AgentRun, AgentTrace, Case, Handle, Score + from eac.models import AgentRun, AgentTrace, Case, Score class Judge(ABC): @@ -25,10 +25,9 @@ class Judge(ABC): credentials: Sequence[Credential] = () @abstractmethod - def judge(self, case: Case, *, seeds: dict[str, Handle], agent_trace: Any = None) -> Score | None: + def judge(self, case: Case, *, seeds: dict[str, dict[str, Any]], agent_trace: Any = None) -> Score | None: """Score `case.output`, or return None if this judge doesn't apply to the case, e.g. one without the expected output it compares against. - May be async. Cases whose runner raised are never judged. `seeds` maps each of the case's seed names to its handle, and is empty online. `agent_trace` is @@ -37,7 +36,7 @@ def judge(self, case: Case, *, seeds: dict[str, Handle], agent_trace: Any = None def get_agent_trace(self, run: AgentRun) -> AgentTrace | None: """Return the agent trace of `run`, e.g. from Sentry, or None if there - isn't one. Defaults to None. May be async. + isn't one. Defaults to None. Before judging a case, eac asks its judges in order and gives the first trace found to all of them. Each class's implementation is diff --git a/sdks/python/eac/models.py b/sdks/python/eac/models.py index bc8e331..cfb8126 100644 --- a/sdks/python/eac/models.py +++ b/sdks/python/eac/models.py @@ -13,10 +13,6 @@ from eac.judge import Judge from eac.seed import Seed -#: What a seed's setup() returned: plain JSON, like ids and URLs. -Handle = dict[str, Any] - - @dataclass(frozen=True) class LLMMetrics: input_tokens: float = 0 diff --git a/sdks/python/eac/protocol.py b/sdks/python/eac/protocol.py index 75f4815..69b8409 100644 --- a/sdks/python/eac/protocol.py +++ b/sdks/python/eac/protocol.py @@ -5,31 +5,13 @@ from __future__ import annotations -from typing import Any, Literal, NotRequired, TypedDict +from typing import Any, Final, Literal, NotRequired, TypedDict -PROTOCOL_VERSION = 1 +PROTOCOL_VERSION: Final = 1 -#: What a seed's setup returned. Saved to seeds.json for later phases, so it must be -#: JSON. -Handle = dict[str, Any] - Mode = Literal["offline", "online"] -#: The methods an SDK worker answers. -WorkerMethod = Literal[ - "args.validate", - "case.judge", - "case.run", - "credentials.check", - "credentials.login", - "discover", - "online.execute", - "online.judge", - "seed.setup", - "seed.teardown", -] - class ArgsValidateParams(TypedDict): args: dict[str, Any] @@ -84,7 +66,7 @@ class CaseJudgeParams(TypedDict): #: Judges to use instead of the case's own, as in a comparison. Empty keeps the #: case's judges. judges: NotRequired[list[str]] - seeds: NotRequired[dict[str, Handle]] + seeds: NotRequired[dict[str, dict[str, Any]]] #: When the runner started. started_at: NotRequired[str | None] #: The agent trace an earlier judge phase saved. Without one, the judges may fetch @@ -111,7 +93,7 @@ class CaseRunParams(TypedDict): conversation_id: str dataset: DatasetRef #: Each seed's handle, by seed name. - seeds: NotRequired[dict[str, Handle]] + seeds: NotRequired[dict[str, dict[str, Any]]] class CaseRunResult(TypedDict): @@ -129,15 +111,12 @@ class Credential(TypedDict): #: The arguments its class is built with. fields: NotRequired[dict[str, Any]] - #: Can only be set up by hand, so eac shows the instructions instead of offering to - #: log in. + #: Can only be set up by hand, so eac doesn't offer to log in. manual: NotRequired[bool] #: Shown in status lines and prompts, like "github". name: str #: The credential's class, as a code reference. path: str - #: How to set it up by hand, shown when it isn't set up. - setup_instructions: NotRequired[str] class CredentialsCheckParams(TypedDict): @@ -295,14 +274,14 @@ class SeedSetupParams(TypedDict): class SeedSetupResult(TypedDict): #: The seed's own cache had it, so nothing was set up. from_cache: NotRequired[bool] - handle: NotRequired[Handle] + handle: NotRequired[dict[str, Any]] class SeedTeardownParams(TypedDict): """A cached seed is also removed from its own cache before it's torn down.""" dataset: DatasetRef - handle: Handle + handle: dict[str, Any] seed: Seed diff --git a/sdks/python/eac/py.typed b/sdks/python/eac/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/sdks/python/eac/runner/offline_runner.py b/sdks/python/eac/runner/offline_runner.py index 7103444..2b1bc90 100644 --- a/sdks/python/eac/runner/offline_runner.py +++ b/sdks/python/eac/runner/offline_runner.py @@ -3,7 +3,7 @@ from abc import abstractmethod from typing import Any -from eac.models import Case, Handle +from eac.models import Case from eac.runner.runner import Runner @@ -15,9 +15,8 @@ class OfflineRunner(Runner): """ @abstractmethod - def run_case(self, case: Case, *, seeds: dict[str, Handle], conversation_id: str) -> dict[str, Any]: + def run_case(self, case: Case, *, seeds: dict[str, dict[str, Any]], conversation_id: str) -> dict[str, Any]: """Run the case and return its output as a JSON-serializable dict. - May be async. `seeds` maps each of the case's seed names to its handle. Tag the agent's run with `conversation_id`, so a judge's get_agent_trace() can diff --git a/sdks/python/eac/runner/online_runner.py b/sdks/python/eac/runner/online_runner.py index 016707f..7583084 100644 --- a/sdks/python/eac/runner/online_runner.py +++ b/sdks/python/eac/runner/online_runner.py @@ -19,4 +19,4 @@ class OnlineRunner(Runner): def collect_cases(self, window: Window) -> Iterable[Case]: """Return at most `window.limit` production runs from the window, each as a Case with its `output`, and its `conversation_id` for - get_agent_trace(). May be async.""" + get_agent_trace().""" diff --git a/sdks/python/eac/seed/seed.py b/sdks/python/eac/seed/seed.py index 0d64ced..94d088a 100644 --- a/sdks/python/eac/seed/seed.py +++ b/sdks/python/eac/seed/seed.py @@ -57,7 +57,7 @@ def key(self) -> str: @abstractmethod def setup(self) -> dict[str, Any]: - """Create the fixture and return a handle. May be async. + """Create the fixture and return a handle. The handle is saved to seeds.json and read back by a later phase, so return ids and URLs, not live clients. If setup fails partway, @@ -74,11 +74,11 @@ def share(self, handle: dict[str, Any]) -> Any: return handle def cleanup(self, handle: dict[str, Any]) -> None: - """Release the fixture. Default is a no-op. May be async.""" + """Release the fixture. Default is a no-op.""" def load_cached(self, key: str) -> dict[str, Any] | None: """Return the handle a cache shared between machines, like a bucket, - has for this seed with key, or None. Defaults to None. May be async. + has for this seed with key, or None. Defaults to None. Only called for cached seeds that eac's local seed cache doesn't have. A handle it returns is used instead of setting the seed and its @@ -89,14 +89,14 @@ def load_cached(self, key: str) -> dict[str, Any] | None: def save_cached(self, key: str, handle: dict[str, Any]) -> None: """Save the handle a cached seed was just set up with, children's included, for load_cached() to return. A failure only warns, since - the fixture exists either way. Default is a no-op. May be async.""" + the fixture exists either way. Default is a no-op.""" def delete_cached(self, key: str) -> None: """Remove this seed from the shared cache before eac tears it down, so no machine loads a deleted fixture. key is the one it was set up with, which differs from key() once the seed has changed, as when pruning. If it raises, the seed isn't torn down and stays cached. - Default is a no-op. May be async.""" + Default is a no-op.""" def current_week_salt() -> str: diff --git a/sdks/python/eac/worker.py b/sdks/python/eac/worker.py index e25e3b7..8e5a8ec 100644 --- a/sdks/python/eac/worker.py +++ b/sdks/python/eac/worker.py @@ -5,7 +5,6 @@ from __future__ import annotations -import asyncio import copy import dataclasses import importlib @@ -15,72 +14,65 @@ import os import sys import traceback +from concurrent.futures import ThreadPoolExecutor from datetime import datetime from inspect import Parameter from pathlib import Path from types import ModuleType -from typing import Any, BinaryIO, Callable, Iterable, Sequence +from typing import Any, BinaryIO, Callable, Iterable, Sequence, cast from eac import protocol as wire from eac.credential import Credential from eac.judge import Judge -from eac.models import AgentRun, AgentTrace, Case, Score, Window, stable_hash +from eac.models import AgentRun, AgentTrace, Case, LLMMetrics, Score, Window, stable_hash from eac.runner import OfflineRunner, OnlineRunner, Runner from eac.seed.seed import Seed, walk REQUEST_FD, RESPONSE_FD = 3, 4 -# Outputs and handles can exceed asyncio's 64 KiB default line limit. -STREAM_LIMIT = 64 * 1024 * 1024 - class WorkerError(Exception): """Reported to the CLI rather than crashed on.""" class Worker: - """Answers the CLI's requests, each in a task of its own.""" + """Answers the CLI's requests, one at a time. The CLI runs several workers + to run cases in parallel.""" - def __init__(self, reader: asyncio.StreamReader, out: BinaryIO): - self._reader = reader + def __init__(self, requests: BinaryIO, out: BinaryIO): + self._requests = requests self._out = out #: Each imported dataset, by its DatasetRef. self._datasets: dict[str, LoadedDataset] = {} - async def serve(self) -> None: + def serve(self) -> None: self._send({"protocol": wire.PROTOCOL_VERSION}) - tasks: set[asyncio.Task[None]] = set() - while line := await self._reader.readline(): - task = asyncio.create_task(self._respond(line)) - tasks.add(task) - task.add_done_callback(tasks.discard) - if tasks: - await asyncio.gather(*tasks, return_exceptions=True) + for line in self._requests: + self._respond(line) def _send(self, message: wire.Ready | wire.Response) -> None: - # A blocking write with no await, so concurrent responses can't interleave. self._out.write(json.dumps(message, default=str).encode() + b"\n") self._out.flush() - async def _respond(self, line: bytes) -> None: + def _respond(self, line: bytes) -> None: try: request = json.loads(line) except json.JSONDecodeError: return request_id = request.get("id") try: - result = await self._dispatch(request.get("method", ""), request.get("params") or {}) + result = self._dispatch(request.get("method", ""), request.get("params") or {}) self._send({"id": request_id, "result": result}) except Exception as exc: error: wire.Error = {"message": f"{type(exc).__name__}: {exc}", "traceback": traceback.format_exc()} self._send({"id": request_id, "error": error}) - async def _dispatch(self, method: str, params: dict[str, Any]) -> Any: + def _dispatch(self, method: str, params: Any) -> Any: match method: case "credentials.check": - return await _check_credentials(params["credentials"]) + return _check_credentials(params["credentials"]) case "credentials.login": - return await _log_in(params["credential"]) + return _log_in(params["credential"]) dataset = self._load(params["dataset"]) match method: case "discover": @@ -88,15 +80,16 @@ async def _dispatch(self, method: str, params: dict[str, Any]) -> Any: case "args.validate": return dataset.validate_args(params.get("judges") or []) case "seed.setup": - return await dataset.seed_setup(params["seed"]) + return dataset.seed_setup(params["seed"]) case "seed.teardown": - return await dataset.seed_teardown(params["seed"], params.get("handle") or {}) + return dataset.seed_teardown(params["seed"], params.get("handle") or {}) case "case.run": - return await dataset.run_case(params) + return dataset.run_case(params) case "online.execute": - return await dataset.collect_cases(params) + return dataset.collect_cases(params) case "case.judge" | "online.judge": - return await dataset.judge(params) + # online.judge's params are a subset of case.judge's. + return dataset.judge(params) case _: raise WorkerError(f"unknown method {method!r}") @@ -119,7 +112,9 @@ def __init__(self, ref: wire.DatasetRef): self.judges: dict[str, Judge] = {} if self.offline: self.runner: Any = _build(ref["runner"], OfflineRunner) - self.cases = _import_cases(ref["cases"]) + if not (cases := ref.get("cases")): + raise WorkerError(f"offline dataset {self.name!r} has no cases") + self.cases = _import_cases(cases) else: self.runner = _build(ref["runner"], OnlineRunner) self.judges = {entry["name"]: _build(entry["path"], Judge) for entry in ref.get("judges") or []} @@ -225,38 +220,38 @@ def validate_args(self, judge_names: list[str]) -> wire.ArgsValidateResult: result["judge_credentials"] = judge_credentials return result - async def seed_setup(self, sent: wire.Seed) -> wire.SeedSetupResult: + def seed_setup(self, sent: wire.Seed) -> wire.SeedSetupResult: """Set the seed up, or load it from its own cache if it's cached.""" key = sent["key"] seed = self.seed(sent["name"], key) cached = sent.get("cache", True) - if cached and (handle := await _load_cached(seed, key)) is not None: + if cached and (handle := _load_cached(seed, key)) is not None: return {"handle": handle, "from_cache": True} - handle = await _set_up(seed) + handle = _set_up(seed) if cached: try: - await _call(seed.save_cached, key, handle) + _call(seed.save_cached, key, handle) except Exception as exc: _warn(f"saving {seed.name} to its cache", exc) return {"handle": handle} - async def seed_teardown(self, sent: wire.Seed, handle: wire.Handle) -> dict[str, Any]: + def seed_teardown(self, sent: wire.Seed, handle: dict[str, Any]) -> dict[str, Any]: seed = self.seed(sent["name"], sent["key"], cleanup=True) # Forgotten first, so the cache never points at a fixture that's gone. # If forgetting fails, the fixture stays. if sent.get("cache", True): - await _call(seed.delete_cached, sent["key"]) - await _clean_up(seed, handle) + _call(seed.delete_cached, sent["key"]) + _clean_up(seed, handle) return {} - async def run_case(self, params: wire.CaseRunParams) -> wire.CaseRunResult: + def run_case(self, params: wire.CaseRunParams) -> wire.CaseRunResult: case = self.case(params["case"]["name"]) runner = self.with_args(self.runner, params.get("args") or {}) seeds = _seed_handles(case, params.get("seeds") or {}) - output = await _call(runner.run_case, case, seeds=seeds, conversation_id=params["conversation_id"]) + output = _call(runner.run_case, case, seeds=seeds, conversation_id=params["conversation_id"]) return {"output": _json_dict(output, f"{type(runner).__name__}.run_case()")} - async def collect_cases(self, params: wire.OnlineExecuteParams) -> wire.OnlineExecuteResult: + def collect_cases(self, params: wire.OnlineExecuteParams) -> wire.OnlineExecuteResult: sent = params["window"] window = Window( since=datetime.fromisoformat(sent["since"]), @@ -266,21 +261,21 @@ async def collect_cases(self, params: wire.OnlineExecuteParams) -> wire.OnlineEx ) runner = self.with_args(self.runner, params.get("args") or {}) what = f"{type(runner).__name__}.collect_cases()" - cases = await _call(runner.collect_cases, window) + cases = _call(runner.collect_cases, window) out: list[wire.Case] = [] for case in cases: if len(out) >= window.limit: break if not isinstance(case, Case): raise WorkerError(f"{what} must return Cases, got {type(case).__name__}") - sent: wire.Case = {"name": case.name, "input": case.input, "output": case.output} + collected: wire.Case = {"name": case.name, "input": case.input, "output": case.output} if case.conversation_id is not None: - sent["conversation_id"] = case.conversation_id - _require_serializable(sent, what) - out.append(sent) + collected["conversation_id"] = case.conversation_id + _require_serializable(collected, what) + out.append(collected) return {"cases": out} - async def judge(self, params: wire.CaseJudgeParams | wire.OnlineJudgeParams) -> wire.CaseJudgeResult: + def judge(self, params: wire.CaseJudgeParams) -> wire.CaseJudgeResult: """Score the case with the judges named in params, or else its own. Without the trace eac saved, the judges fetch it, and it's returned for eac to save.""" @@ -306,22 +301,22 @@ async def judge(self, params: wire.CaseJudgeParams | wire.OnlineJudgeParams) -> started_at=_time(params.get("started_at")), ended_at=_time(params.get("ended_at")), ) - if (fetched := await _fetch_trace(judges, run)) is not None: + if (fetched := _fetch_trace(judges, run)) is not None: agent_trace = result["trace"] = fetched.trace if fetched.metrics is not None: - result["trace_metrics"] = dataclasses.asdict(fetched.metrics) + result["trace_metrics"] = _wire_metrics(fetched.metrics) seeds = _seed_handles(case, params.get("seeds") or {}) - scores = [await _score(judge, case, seeds, agent_trace) for _, judge in judges] + scores = [_score(judge, case, seeds, agent_trace) for _, judge in judges] result["scores"] = [score for score in scores if score is not None] return result -async def _score(judge: Judge, case: Case, seeds: dict[str, wire.Handle], agent_trace: Any) -> wire.Score | None: +def _score(judge: Judge, case: Case, seeds: dict[str, dict[str, Any]], agent_trace: Any) -> wire.Score | None: """The judge's score, or None if it doesn't apply. A judge that raises scores 0.""" try: - score = await _call(judge.judge, case, seeds=seeds, agent_trace=agent_trace) + score = _call(judge.judge, case, seeds=seeds, agent_trace=agent_trace) if score is None: return None if not isinstance(score, Score): @@ -336,11 +331,16 @@ async def _score(judge: Judge, case: Case, seeds: dict[str, wire.Handle], agent_ "metadata": score.metadata, } if score.llm_judge_metrics is not None: - result["llm_judge_metrics"] = dataclasses.asdict(score.llm_judge_metrics) + result["llm_judge_metrics"] = _wire_metrics(score.llm_judge_metrics) return result -async def _fetch_trace(judges: Sequence[tuple[str, Judge]], run: AgentRun) -> AgentTrace | None: +def _wire_metrics(metrics: LLMMetrics) -> wire.Metrics: + # LLMMetrics has the same fields as the protocol's Metrics. + return cast("wire.Metrics", dataclasses.asdict(metrics)) + + +def _fetch_trace(judges: Sequence[tuple[str, Judge]], run: AgentRun) -> AgentTrace | None: """The first trace the judges' get_agent_trace() finds, asking each class's implementation once. A judge that fails to fetch only warns.""" asked = set() @@ -351,7 +351,7 @@ async def _fetch_trace(judges: Sequence[tuple[str, Judge]], run: AgentRun) -> Ag asked.add(get) what = f"{type(judge).__name__}.get_agent_trace()" try: - found = await _call(judge.get_agent_trace, run) + found = _call(judge.get_agent_trace, run) except Exception as exc: _warn(f"fetching the trace of {run.case} for {name}", exc) continue @@ -459,41 +459,41 @@ def _protocol_seed(case: Case, seed: Seed) -> wire.Seed: return out -async def _load_cached(seed: Seed, key: str) -> wire.Handle | None: +def _load_cached(seed: Seed, key: str) -> dict[str, Any] | None: """The handle the seed's own cache has, or None. A cache that fails only warns, so the seed is set up instead.""" try: - handle = await _call(seed.load_cached, key) + handle = _call(seed.load_cached, key) except Exception as exc: _warn(f"loading {seed.name} from its cache", exc) return None return None if handle is None else _json_dict(handle, f"{type(seed).__name__}.load_cached()") -async def _set_up(seed: Seed) -> wire.Handle: +def _set_up(seed: Seed) -> dict[str, Any]: """Set up the seed, then its children. A seed with children gets the handle {"handle": its own, "children": {name: child's handle}}. If a child fails, what was already set up is cleaned up before raising.""" - handle = _json_dict(await _call(seed.setup), f"{type(seed).__name__}.setup()") + handle = _json_dict(_call(seed.setup), f"{type(seed).__name__}.setup()") if not seed.children: return handle - tree: wire.Handle = {"handle": handle, "children": {}} + tree: dict[str, Any] = {"handle": handle, "children": {}} try: shared = seed.share(handle) for child in seed.children: child.parent = shared - tree["children"][child.name] = await _set_up(child) + tree["children"][child.name] = _set_up(child) except BaseException: try: - await _clean_up(seed, tree) + _clean_up(seed, tree) except Exception as exc: _warn(f"cleaning up {seed.name} after its setup failed", exc) raise return tree -async def _clean_up(seed: Seed, handle: wire.Handle) -> None: +def _clean_up(seed: Seed, handle: dict[str, Any]) -> None: """Clean up the seed's children in reverse order, then the seed.""" if seed.children: tree, handle = handle, handle["handle"] @@ -508,15 +508,15 @@ async def _clean_up(seed: Seed, handle: wire.Handle) -> None: for child in reversed(seed.children): if child.name in children: child.parent = shared - await _clean_up(child, children[child.name]) - await _call(seed.cleanup, handle) + _clean_up(child, children[child.name]) + _call(seed.cleanup, handle) -def _seed_handles(case: Case, handles: dict[str, wire.Handle]) -> dict[str, wire.Handle]: +def _seed_handles(case: Case, handles: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: """Flatten the handle trees into one handle per seed name.""" - out: dict[str, wire.Handle] = {} + out: dict[str, dict[str, Any]] = {} - def add(seed: Seed, handle: wire.Handle) -> None: + def add(seed: Seed, handle: dict[str, Any]) -> None: if not seed.children: out[seed.name] = handle return @@ -551,8 +551,6 @@ def _credentials(credentials: Iterable[Credential]) -> list[wire.Credential]: sent: wire.Credential = {"path": _class_ref(cls), "name": name} if fields: sent["fields"] = fields - if credential.setup_instructions: - sent["setup_instructions"] = credential.setup_instructions if cls.authenticate is Credential.authenticate: sent["manual"] = True out.setdefault(json.dumps([sent["path"], fields], sort_keys=True), sent) @@ -565,13 +563,14 @@ def _built_with(credential: Credential) -> dict[str, Any]: 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", ((), {}))) + args, kwargs = getattr(credential, "_eac_built_with", ((), {})) + fields = _keyword_arguments(cls, args, kwargs) 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]: +def _keyword_arguments(cls: type[Any], 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: @@ -634,23 +633,25 @@ def _credential(sent: wire.Credential) -> Credential: raise WorkerError(f"can't build {sent['path']}: {exc}") from None -async def _check_credentials(sent: list[wire.Credential]) -> wire.CredentialsCheckResult: - """Check every credential at once. One that fails to check isn't set up.""" +def _check_credentials(sent: list[wire.Credential]) -> wire.CredentialsCheckResult: + """Check every credential at once, each in a thread, since checks wait on + things like HTTP calls. One that fails to check isn't set up.""" env = dict(os.environ) - async def check(credential: wire.Credential) -> bool: + def check(credential: wire.Credential) -> bool: try: - return bool(await _call(_credential(credential).is_authenticated, env)) + return bool(_call(_credential(credential).is_authenticated, env)) except Exception as exc: _warn(f"checking {credential['name']}", exc) return False - return {"authenticated": list(await asyncio.gather(*(check(c) for c in sent)))} + with ThreadPoolExecutor() as pool: + return {"authenticated": list(pool.map(check, sent))} -async def _log_in(sent: wire.Credential) -> wire.CredentialsLoginResult: +def _log_in(sent: wire.Credential) -> wire.CredentialsLoginResult: credential = _credential(sent) - env = await _call(credential.authenticate) or {} + env = _call(credential.authenticate) or {} if not isinstance(env, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in env.items()): raise WorkerError(f"{type(credential).__qualname__}.authenticate() must return a dict of strings") return {"env": env} @@ -659,13 +660,11 @@ async def _log_in(sent: wire.Credential) -> wire.CredentialsLoginResult: # Helpers. -async def _call(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: - """Run a coroutine function on the worker's event loop and anything else - in a thread, so sync user code can block or call asyncio.run().""" +def _call(fn: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + """Call user code, which must be a def.""" if inspect.iscoroutinefunction(fn): - return await fn(*args, **kwargs) - result = await asyncio.to_thread(fn, *args, **kwargs) - return await result if inspect.isawaitable(result) else result + raise WorkerError(f"{fn.__qualname__} must be a def, not an async def") + return fn(*args, **kwargs) def _json_dict(value: Any, what: str) -> dict[str, Any]: @@ -697,14 +696,10 @@ def _warn(doing: str, exc: Exception) -> None: print(f"{doing}: {type(exc).__name__}: {exc}", file=sys.stderr) -async def run() -> None: +def run() -> None: """Serve the CLI on fd 3 and fd 4 until it closes fd 3.""" - reader = asyncio.StreamReader(limit=STREAM_LIMIT) - loop = asyncio.get_running_loop() - requests = os.fdopen(REQUEST_FD, "rb", buffering=0) - await loop.connect_read_pipe(lambda: asyncio.StreamReaderProtocol(reader), requests) - with os.fdopen(RESPONSE_FD, "wb") as out: - await Worker(reader, out).serve() + with os.fdopen(REQUEST_FD, "rb") as requests, os.fdopen(RESPONSE_FD, "wb") as out: + Worker(requests, out).serve() def main() -> None: @@ -712,7 +707,7 @@ def main() -> None: print("eac.worker must be started by the eac CLI", file=sys.stderr) raise SystemExit(2) try: - asyncio.run(run()) + run() except KeyboardInterrupt: pass diff --git a/sdks/python/pyproject.toml b/sdks/python/pyproject.toml index 19e898f..75fed4e 100644 --- a/sdks/python/pyproject.toml +++ b/sdks/python/pyproject.toml @@ -20,3 +20,9 @@ path = "eac/_version.py" [tool.hatch.build.targets.wheel] packages = ["eac"] + +# `make typecheck` at the repo root. +[tool.mypy] +files = ["eac"] +python_version = "3.11" +strict = true