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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -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)
Expand All @@ -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

Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
1 change: 0 additions & 1 deletion core/PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions core/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 2 additions & 6 deletions core/src/eac/phases/credentials.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,13 +218,9 @@ fn confirm(question: &str) -> Result<bool> {
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
Expand Down
6 changes: 1 addition & 5 deletions core/src/schema/protocol.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand All @@ -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": [
Expand Down
6 changes: 1 addition & 5 deletions core/src/schema/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand Down
11 changes: 4 additions & 7 deletions core/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down Expand Up @@ -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"];
Expand All @@ -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"]);
Expand Down
1 change: 0 additions & 1 deletion core/tests/fixtures/project/evals/chat_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 3 additions & 9 deletions docs/app/cases-and-runners/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -60,18 +60,16 @@ Prefer keeping cases in data files? `from_jsonl("cases/*.jsonl", judges=[...])`
<CodeFile filename="evals/triage/runners/offline.py" source="examples/sentry-assistant-python/evals/triage/runners/offline.py">

```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)
```

</CodeFile>
Expand All @@ -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).

<Callout type="tip">
Runners, judges and seeds can be sync or async. Use whichever fits your code.
</Callout>

To run the same cases against two models or agents, see [Comparing variants](/comparing-variants).
12 changes: 3 additions & 9 deletions docs/app/credentials/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,18 @@ If your evals need a token or a login, declare it as a credential. eac checks th
<CodeFile filename="evals/triage/credentials/openrouter.py" source="examples/sentry-assistant-python/evals/triage/credentials/openrouter.py">

```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."
```

</CodeFile>
Expand All @@ -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.

Expand Down
4 changes: 2 additions & 2 deletions docs/app/introduction/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
22 changes: 11 additions & 11 deletions docs/app/judges/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ A judge looks at one case's output and gives it a score between 0 and 1. Judges
<CodeFile filename="evals/triage/judges/found_issue_judge.py" source="examples/sentry-assistant-python/evals/triage/judges/found_issue_judge.py">

```python
from eac import Judge, Score
from eac import Case, Judge, Score


class FoundIssueJudge(Judge):
Expand All @@ -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")
Expand All @@ -45,13 +45,13 @@ Some judges need more than the final output, like the agent's full conversation
<CodeFile filename="evals/triage/judges/triage_llm_judge.py" source="examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py">

```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
Expand All @@ -73,11 +73,11 @@ An LLM judge asks a model to grade the trace. This one asks two true-or-false qu
<CodeFile filename="evals/triage/judges/triage_llm_judge.py" source="examples/sentry-assistant-python/evals/triage/judges/triage_llm_judge.py">

```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},
Expand All @@ -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)),
)
Expand Down
4 changes: 2 additions & 2 deletions docs/app/online-evals/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ The runner's `collect_cases` returns what happened in a time window, as cases wi
<CodeFile filename="evals/triage/runners/online.py" source="examples/sentry-assistant-python/evals/triage/runners/online.py">

```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"])]

Expand Down
12 changes: 6 additions & 6 deletions docs/app/seeds/page.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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}")
```
Expand All @@ -61,7 +61,7 @@ If instances of a seed differ by their constructor arguments, add those to the k
<LanguageCode>

```python
def key(self):
def key(self) -> str:
return stable_hash([super().key(), self.slug])
```

Expand All @@ -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}")
```

Expand Down
4 changes: 2 additions & 2 deletions docs/components/landing.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading