Skip to content
Open
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
83 changes: 67 additions & 16 deletions benchmarks/agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ the same model on the same questions under two conditions:
| `baseline` | `list_documents`, `read_document`, and `search_documents` (plain text or regex search over lines). |
| `graph` | The same document tools, plus every read-only tool of the SelfGraph MCP server, over a graph of the same documents. |

It reports accuracy, wall time, tokens, cost, and tool calls for each condition.
Every question runs `--repeats` times (3 by default) under each condition. The
benchmark reports accuracy with a 95% interval, accuracy per question kind, a
paired comparison with `baseline`, wall time, tokens, cost, and tool calls.

The graph tools come from the MCP server itself (`src/selfgraph/mcp/server.py`):
the benchmark builds it in process with `build_server()`, keeps every tool
Expand All @@ -25,15 +27,17 @@ adds the server's own instructions to the shared system prompt.
```bash
pip install -e ".[llm,kuzu,mcp]"
export <PROVIDER>_API_KEY=...
python benchmarks/agent/run.py --model provider/model
python benchmarks/agent/run.py --model provider/model --judge provider/other-model --audit 30
```

| Flag | Default | Effect |
|------|---------|--------|
| `--model` | required | The agent model, in litellm form (`provider/model`). |
| `--judge` | `--model` | The judge model, in the same form. |
| `--judge` | `--model` | The judge model, in the same form. Use a different model; see Scoring. |
| `--conditions` | `baseline,graph` | Which conditions to run. |
| `--questions N` | all | Run the first N questions. |
| `--repeats N` | 3 | Run every question N times per condition. |
| `--audit N` | off | Write N judged runs, drawn at random, to grade by hand. |
| `--price IN,OUT` | litellm's cost data | USD per million input and output tokens for `--model`. |
| `--judge-price IN,OUT` | `--price` for the same model, else litellm's cost data | The same for `--judge`. |
| `--estimate` | off | Print the cost estimate and stop, with no model call. |
Expand All @@ -52,8 +56,8 @@ later team or account change retires the earlier one.
Every run first prints an estimate per condition and for the judge, then starts.
Use `--estimate` to see it without running. The estimate counts about four
characters per token over the system prompt, the tool specs, the questions, and
the average document, and assumes five model calls per question, each resending
the conversation so far. Treat it as an order of magnitude. Prices come from
the average document, and assumes five model calls per run, each resending
the conversation so far. It grows linearly with `--repeats`. Treat it as an order of magnitude. Prices come from
`--price` and `--judge-price`, or from litellm's own cost data for the model;
a row with no price shows `n/a`.

Expand All @@ -66,14 +70,45 @@ could not find the information. A run that times out, hits the step limit, or
fails gives no answer and counts as `wrong`. A judge reply with no valid verdict
counts as `unscored`. Accuracy is `correct / runs`.

The runs of one question are not independent samples of the benchmark, so the
95% interval comes from a bootstrap that resamples questions, not runs: it draws
the questions with replacement 2,000 times with a fixed seed and takes the 2.5th
and 97.5th percentiles of the accuracy. With about 40 questions the interval is
wide; read a gap between conditions as real only when the paired interval below
leaves out zero.

The paired comparison scores each question by its mean over its runs (correct
1, partial 0.5, wrong 0) and counts the questions where a condition does better,
worse, or the same as `baseline`. The accuracy difference is the mean of the
per question differences in accuracy, with a bootstrap interval over the same
paired questions.

### Judge choice and audit

The judge defaults to the agent model, which then grades its own answers. The
run allows it but prints a warning, since a model can favour answers in its own
style. Pass `--judge` with a model from a different provider or family.

`--audit N` writes `<timestamp>-audit.md` next to the results JSON with N runs
the judge graded, drawn with a fixed seed: the question, the gold answer, the
answer, the judge verdict and reason, and an empty human verdict column. Fill in
the human column by the rubric, then report the agreement as the share of rows
where the human and the judge give the same verdict, with the count (for example
`27 of 30, 90%`), and list every row where they differ. 30 rows is a reasonable
minimum; agreement below about 85% means the accuracy numbers need a better
judge or rubric before anyone reads them.

## Output

The run prints a markdown table of totals per condition and one line each for
the judge's usage and the graph build. It writes `results/<timestamp>.json`
with the options, the graph build (counts, warnings, seconds, tool names), one
record per run (answer, verdict, judge reason, wall seconds, model calls,
tokens, cost, failure, and every tool call with its arguments, status, and
seconds), and the totals per condition. Cost covers the calls with a known
The run prints a markdown table of totals per condition with the accuracy
interval, a table of accuracy per question kind, the paired comparison with
`baseline`, and one line each for the judge's usage and the graph build. It
writes `results/<timestamp>.json` with the options, the graph build (counts,
warnings, seconds, tool names), one record per run (attempt number, answer,
verdict, judge reason, wall seconds, model calls, tokens, cost, failure, and
every tool call with its arguments, status, and seconds), the totals per
condition (`summary`, with `accuracy_ci` and `kinds`), and the paired comparison
(`paired`). Cost covers the calls with a known
price; the table marks it `(partial)` when some call had none. Judge tokens and
cost are reported apart from the conditions.

Expand Down Expand Up @@ -118,8 +153,24 @@ Fill this in after the first run.
| SelfGraph version | |
| Model | |
| Judge | |

| Condition | Runs | Accuracy | Correct | Partial | Wrong | Mean s | p95 s | Input tokens | Output tokens | Cost (USD) | Tool calls |
|-----------|------|----------|---------|---------|-------|--------|-------|--------------|---------------|------------|------------|
| `baseline` | | | | | | | | | | | |
| `graph` | | | | | | | | | | | |
| Repeats | |
| Judge and human agreement | |

| Condition | Runs | Accuracy | 95% CI | Correct | Partial | Wrong | Mean s | p95 s | Input tokens | Output tokens | Cost (USD) | Tool calls |
|-----------|------|----------|--------|---------|---------|-------|--------|-------|--------------|---------------|------------|------------|
| `baseline` | | | | | | | | | | | | |
| `graph` | | | | | | | | | | | | |

| Kind | `baseline` | `graph` |
|------|------------|---------|
| lookup | | |
| multi_hop | | |
| connection | | |
| impact | | |
| temporal | | |
| aggregation | | |
| unanswerable | | |

| Versus `baseline` | Questions | Better | Worse | Tied | Accuracy difference | 95% CI |
|-------------------|-----------|--------|-------|------|---------------------|--------|
| `graph` | | | | | | |
30 changes: 21 additions & 9 deletions benchmarks/agent/harness.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ class Run:
condition: str
question_id: str
kind: str
attempt: int = 1
answer: str = ""
failure: str | None = None
seconds: float = 0.0
Expand All @@ -116,6 +117,7 @@ class Options:
judge: str
conditions: tuple[str, ...] = CONDITIONS
questions: int | None = None
repeats: int = 3
price: Price | None = None
judge_price: Price | None = None
concurrency: int = 4
Expand Down Expand Up @@ -329,17 +331,21 @@ def estimate(setup: Setup, options: Options) -> dict[str, dict[str, Any]]:
@param options (Options): the run options, for the conditions and prices.
@return (dict[str, dict[str, Any]]): per condition and for the judge: input tokens, output tokens, and cost.
"""
count, steps, out = len(setup.questions), ESTIMATE_STEPS, ESTIMATE_OUTPUT
count, steps, out = len(setup.questions) * options.repeats, ESTIMATE_STEPS, ESTIMATE_OUTPUT
asked = sum(len(q["question"]) for q in setup.questions) / CHARS_PER_TOKEN
gold = sum(len(q["answer"]) for q in setup.questions) / CHARS_PER_TOKEN
document = sum(len(d.text) for d in setup.documents) / max(1, len(setup.documents)) / CHARS_PER_TOKEN
totals = {}
for condition in options.conditions:
fixed = len(setup.prompts[condition] + json.dumps(setup.toolboxes[condition].specs)) / CHARS_PER_TOKEN
grown = steps * (steps - 1) / 2 * (document + out)
totals[condition] = (count * (steps * fixed + grown) + steps * asked, count * steps * out, options.price)
totals[condition] = (
count * (steps * fixed + grown) + options.repeats * steps * asked,
count * steps * out,
options.price,
)
runs = len(options.conditions)
judged = runs * (count * (len(JUDGE_PROMPT) / CHARS_PER_TOKEN + out) + asked + gold)
judged = runs * (count * (len(JUDGE_PROMPT) / CHARS_PER_TOKEN + out) + options.repeats * (asked + gold))
totals["judge"] = (judged, runs * count * out, options.judge_price)
return {
name: {"input_tokens": round(i), "output_tokens": round(o), "cost": cost_of(round(i), round(o), price)}
Expand Down Expand Up @@ -396,17 +402,20 @@ async def build_graph(folder: Path) -> dict[str, Any]:
return {"seconds": seconds, "counts": counts, "warnings": len(result.get("warnings") or [])}


async def _attempt(client: Any, options: Options, setup: Setup, question: dict[str, Any], condition: str) -> Run:
async def _attempt(
client: Any, options: Options, setup: Setup, question: dict[str, Any], condition: str, attempt: int
) -> Run:
"""Answer and score one question under one condition.

@param client (Any): the model client.
@param options (Options): the run options.
@param setup (Setup): the prepared run, for the condition's tools and prompt.
@param question (dict[str, Any]): the question with its gold answer.
@param condition (str): "baseline" or "graph".
@param attempt (int): which repeat of the question this is, from 1.
@return (Run): the scored run; a run with no answer is wrong, a judge failure unscored.
"""
run = Run(condition, question["id"], question["kind"])
run = Run(condition, question["id"], question["kind"], attempt)
started = time.perf_counter()
try:
asked = ask(client, options, question["question"], setup.prompts[condition], setup.toolboxes[condition], run)
Expand All @@ -429,7 +438,7 @@ async def _attempt(client: Any, options: Options, setup: Setup, question: dict[s


async def run_benchmark(setup: Setup, options: Options, client: Any) -> dict[str, Any]:
"""Run every question under every condition and return the raw results.
"""Run every question options.repeats times under every condition and return the raw results.

@param setup (Setup): the prepared run.
@param options (Options): the run options.
Expand All @@ -440,16 +449,19 @@ async def run_benchmark(setup: Setup, options: Options, client: Any) -> dict[str

gate = asyncio.Semaphore(options.concurrency)

async def gated(question: dict[str, Any], condition: str) -> Run:
async def gated(question: dict[str, Any], condition: str, attempt: int) -> Run:
async with gate:
return await _attempt(client, options, setup, question, condition)
return await _attempt(client, options, setup, question, condition, attempt)

graph = None
with tempfile.TemporaryDirectory(prefix="selfgraph-agent-bench-") as folder:
try:
if setup.tools is not None:
graph = {**await build_graph(Path(folder)), "tools": setup.tools}
runs = await asyncio.gather(*(gated(q, c) for c in options.conditions for q in setup.questions))
attempts = range(1, options.repeats + 1)
runs = await asyncio.gather(
*(gated(q, c, a) for c in options.conditions for q in setup.questions for a in attempts)
)
finally:
await srv.close()
runs_json = [asdict(r) for r in runs]
Expand Down
25 changes: 20 additions & 5 deletions benchmarks/agent/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,17 @@
from typing import Any

from harness import CONDITIONS, LiteLLMClient, Options, estimate, litellm_price, prepare, run_benchmark
from scoring import estimate_markdown, markdown, summarize
from scoring import audit_markdown, compare, estimate_markdown, markdown, summarize

from selfgraph import __version__
from selfgraph.errors import SelfGraphError, surface_hint

RESULTS = Path(__file__).parent / "results"
INSTALL = 'pip install "selfgraph[llm,kuzu,mcp]"'
SELF_GRADING = (
"warning: the judge is the agent model, and a model grading its own answers can bias the verdicts; "
"pass --judge with a different model"
)


def _flag(parse: Any, expected: str) -> Any:
Expand Down Expand Up @@ -71,7 +75,10 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument(
"--conditions", type=_flag(_conditions, "baseline, graph, or both"), default=CONDITIONS, help="baseline,graph"
)
parser.add_argument("--questions", type=_flag(lambda t: int(t) if int(t) > 0 else None, "N > 0"), help="first N")
positive = _flag(lambda t: int(t) if int(t) > 0 else None, "N > 0")
parser.add_argument("--questions", type=positive, help="first N")
parser.add_argument("--repeats", type=positive, default=3, help="runs per question and condition (default 3)")
parser.add_argument("--audit", type=positive, help="write N random judged runs to grade by hand")
parser.add_argument("--price", type=price, help="INPUT,OUTPUT USD per million tokens for --model")
parser.add_argument("--judge-price", type=price, help="INPUT,OUTPUT USD per million tokens for --judge")
parser.add_argument("--estimate", action="store_true", help="print the cost estimate and stop")
Expand Down Expand Up @@ -100,7 +107,7 @@ def check_requirements(options: Options, calls_litellm: bool) -> str | None:


def main(argv: list[str] | None = None, client: Any = None) -> int:
"""Print the cost estimate, run the benchmark, write results/<timestamp>.json, and print the totals.
"""Print the cost estimate, run the benchmark, write results/<timestamp>.json (and the audit), and print totals.

@param argv (list[str] | None): the arguments, or None for sys.argv.
@param client (Any): the model client, or None for litellm.
Expand All @@ -110,11 +117,13 @@ def main(argv: list[str] | None = None, client: Any = None) -> int:
judge = args.judge or args.model
price = args.price or litellm_price(args.model)
judge_price = args.judge_price or (price if judge == args.model else litellm_price(judge))
options = Options(args.model, judge, args.conditions, args.questions, price, judge_price)
options = Options(args.model, judge, args.conditions, args.questions, args.repeats, price, judge_price)
problem = check_requirements(options, client is None and not args.estimate)
if problem:
print(f"error: {problem}", file=sys.stderr)
return 2
if judge == args.model:
print(SELF_GRADING, file=sys.stderr)
started = datetime.now(timezone.utc)
try:
setup = asyncio.run(prepare(options))
Expand All @@ -127,10 +136,16 @@ def main(argv: list[str] | None = None, client: Any = None) -> int:
return 1
result = {"started_at": started.isoformat(), "selfgraph": __version__, **result}
result["summary"] = summarize(result["runs"], list(options.conditions))
result["paired"] = compare(result["runs"], list(options.conditions))
args.results.mkdir(parents=True, exist_ok=True)
path = args.results / f"{started.strftime('%Y%m%dT%H%M%SZ')}.json"
stamp = started.strftime("%Y%m%dT%H%M%SZ")
path = args.results / f"{stamp}.json"
path.write_text(json.dumps(result, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"\n{markdown(result)}\n\nresults: {path}")
if args.audit:
audit = args.results / f"{stamp}-audit.md"
audit.write_text(audit_markdown(result["runs"], setup.questions, args.audit), encoding="utf-8")
print(f"audit: {audit}")
return 0


Expand Down
Loading
Loading