Skip to content

First-time tool-calling lab

Run a fake local model through the real harness, diagnose failures, and replay conversations without provider keys.

Source: examples/first-time-onboarding. Read the guide for the concepts behind it.

apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: first-tool-calling-run
spec:
dataset:
path: tasks.jsonl
target:
connector: openai-compatible
base_url: http://127.0.0.1:8765/v1
model: bad-arguments
max_tokens: 256
harness:
builtin:
max_steps: 6
tools:
sandbox: false
mocks:
- name: lookup_order
description: Look up an order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"status":"paid","refundable":true}'
- name: refund
description: Refund an eligible order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"refunded":true}'
evaluators:
- ref: tool-call-accuracy
- ref: tool-errors
- ref: loop-detection
- ref: contains
params:
substring: Refunded order
trials: 1
gates:
- metric: tool-call-accuracy.recall
min: 1.0
- metric: tool-call-accuracy.precision
min: 1.0
- metric: contains
min: 1.0
- metric: tool-errors
max: 0.0
- metric: contains
stat: GATE_STAT_ERROR_RATE
max: 0.0
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: first-tool-calling-run
spec:
dataset:
path: tasks.jsonl
target:
connector: openai-compatible
base_url: http://127.0.0.1:8765/v1
model: careful
max_tokens: 256
harness:
builtin:
max_steps: 6
tools:
sandbox: false
evaluators:
- ref: tool-call-accuracy
- ref: tool-errors
- ref: loop-detection
- ref: contains
params:
substring: Refunded order
- ref: task-success
trials: 1
gates:
- metric: tool-call-accuracy.recall
min: 1.0
- metric: tool-call-accuracy.precision
min: 1.0
- metric: contains
min: 1.0
- metric: tool-errors
max: 0.0
- metric: contains
stat: GATE_STAT_ERROR_RATE
max: 0.0
- metric: task-success
min: 1.0
environment:
database:
schema: CREATE TABLE orders (id INTEGER PRIMARY KEY, refunded INTEGER NOT NULL);
seed: INSERT INTO orders VALUES (42,0),(7,0),(99,0);
tools:
- name: lookup_order
description: Look up order
sql: SELECT id, refunded FROM orders WHERE id = :id
parameters:
type: object
properties:
id:
type: integer
required:
- id
- name: refund
description: Refund order
mode: write
sql: UPDATE orders SET refunded = 1 WHERE id = :id
min_rows: 1
max_rows: 1
parameters:
type: object
properties:
id:
type: integer
required:
- id
assertions:
- name: one-refund
sql: SELECT SUM(refunded) FROM orders
expect:
- - 1
"""Local, deterministic chat-completions model for the onboarding lab.
This simulates autoregressive conversation turns, not neural token generation.
No model weights, provider credentials or third-party services are used.
"""
from __future__ import annotations
import argparse
import json
import re
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any
def reply(body: dict[str, Any]) -> dict[str, Any]:
"""Choose the next assistant message from the entire conversation prefix."""
messages = body["messages"]
mode = body.get("model", "careful")
user = next(m["content"] for m in messages if m["role"] == "user")
order = int(re.search(r"order (\d+)", user)[1])
observations = [m for m in messages if m["role"] == "tool"]
names = [m.get("name", "") for m in observations]
# Chat-completions tool messages need not carry a name: recover it by ID.
calls = {c["id"]: c["function"]["name"] for m in messages for c in m.get("tool_calls", [])}
names = [
n or calls.get(m.get("tool_call_id"), "") for n, m in zip(names, observations, strict=True)
]
def call(name: str, arguments: Any) -> dict[str, Any]:
return {
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": f"call_{len(observations)}",
"type": "function",
"function": {"name": name, "arguments": json.dumps(arguments)},
}
],
}
if mode == "loop":
return call("lookup_order", {"id": order})
if not observations:
return call("lookup_order", {} if mode == "bad-arguments" else {"id": order})
if mode in {"bad-arguments", "skip-refund"}:
return {"role": "assistant", "content": f"Refunded order {order}."}
# One retry following a tool error; a persistent fault then ends the task.
if observations[-1]["content"].startswith("ERROR:"):
if sum(m["content"].startswith("ERROR:") for m in observations) < 2:
return call(names[-1], {"id": order})
return {"role": "assistant", "content": "Could not complete the refund."}
if names[-1] == "lookup_order":
return call("refund", {"id": order})
return {"role": "assistant", "content": f"Refunded order {order}."}
class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
self.send_json(200 if self.path == "/health" else 404, {"status": "ok"})
def do_POST(self) -> None:
if self.path != "/v1/chat/completions":
self.send_json(404, {"error": "Use /v1/chat/completions"})
return
try:
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if body.get("stream"):
self.send_json(400, {"error": "This tutorial implements non-streaming only"})
return
message = reply(body)
if self.server.log_path:
# Only synthetic tutorial content. Never log Authorization headers.
with self.server.log_path.open("a") as log:
log.write(json.dumps({"request": body, "message": message}) + "\n")
self.send_json(
200,
{
"id": "tutorial-completion",
"object": "chat.completion",
"model": body.get("model", "careful"),
"choices": [
{
"index": 0,
"message": message,
"finish_reason": "tool_calls" if message.get("tool_calls") else "stop",
}
],
"usage": {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120},
},
)
except (KeyError, ValueError, TypeError) as exc:
self.send_json(400, {"error": str(exc)})
def send_json(self, status: int, value: Any) -> None:
data = json.dumps(value).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *_: Any) -> None:
pass
class Server(ThreadingHTTPServer):
log_path: Path | None = None
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--port", type=int, default=8765)
parser.add_argument("--log", type=Path)
args = parser.parse_args()
server = Server(("127.0.0.1", args.port), Handler)
server.log_path = args.log
print(f"Fake model listening at http://127.0.0.1:{server.server_port}/v1", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
if __name__ == "__main__":
main()
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: first-tool-calling-run
spec:
dataset:
path: tasks.jsonl
target:
connector: openai-compatible
base_url: http://127.0.0.1:8765/v1
model: careful
max_tokens: 256
harness:
builtin:
max_steps: 6
tools:
sandbox: false
mocks:
- name: lookup_order
description: Look up an order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"status":"paid","refundable":true}'
- name: refund
description: Refund an eligible order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"refunded":true}'
faults:
- tool: refund
kind: error
rate: 1.0
evaluators:
- ref: tool-call-accuracy
- ref: tool-errors
- ref: loop-detection
- ref: contains
params:
substring: Refunded order
trials: 1
gates:
- metric: tool-call-accuracy.recall
min: 1.0
- metric: tool-call-accuracy.precision
min: 1.0
- metric: contains
min: 1.0
- metric: tool-errors
max: 0.0
- metric: contains
stat: GATE_STAT_ERROR_RATE
max: 0.0
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: onboarding-agent
labels:
evalsi.dev/project: onboarding
spec:
target:
agent:
cli:
command: [sh, -c, "cat >/dev/null; printf done > out.txt"]
environment:
sandbox:
min_isolation: namespaced
checker:
command: [sh, -c, 'test "$(cat out.txt)" = done']
dataset:
inline:
records:
- id: write-file
input: {text: "Write done to out.txt."}
evaluators:
- ref: task-success
gates:
- metric: task-success
min: 1.0
apiVersion: apps/v1
kind: Deployment
metadata:
name: onboarding-model
spec:
replicas: 1
selector:
matchLabels: {app: onboarding-model}
template:
metadata:
labels: {app: onboarding-model}
spec:
automountServiceAccountToken: false
containers:
- name: model
image: evalsi:onboarding
imagePullPolicy: IfNotPresent
command: [python3, /model/tinylm.py, --host, "0.0.0.0", --port, "8765"]
ports:
- containerPort: 8765
readinessProbe:
httpGet: {path: /healthz, port: 8765}
volumeMounts:
- {name: model, mountPath: /model, readOnly: true}
volumes:
- name: model
configMap: {name: onboarding-model}
---
apiVersion: v1
kind: Service
metadata:
name: onboarding-model
spec:
selector: {app: onboarding-model}
ports:
- {port: 8765, targetPort: 8765}
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: onboarding-recorded
labels:
evalsi.dev/project: onboarding
spec:
dataset:
inline:
records:
- id: correct
input: {text: "2+2"}
output: {text: "4"}
reference: {text: "4"}
- id: incorrect
input: {text: "3+3"}
output: {text: "7"}
reference: {text: "6"}
evaluators:
- ref: exact-match
gates:
- metric: exact-match
min: 0.5
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: onboarding-support
labels: {evalsi.dev/project: onboarding}
spec:
target:
connector: openai-compatible
model: tinylm-support
base_url: http://onboarding-model.onboarding.svc:8765/v1
api_key_env: none
stream: true
dataset:
inline:
records:
- id: refund-paid
input: {text: "Customer asks: please refund order 42."}
reference:
json:
tool_calls:
- {name: lookup_order, arguments: {id: 42}}
- {name: refund, arguments: {id: 42}}
harness:
builtin:
max_steps: 6
tools:
sandbox: false
mocks:
- name: lookup_order
description: Look up an order by id.
input_schema: {type: object, properties: {id: {type: integer}}, required: [id]}
response: "order 42: status paid, total $30.00"
- name: refund
description: Refund an order in full.
input_schema: {type: object, properties: {id: {type: integer}}, required: [id]}
response: "ok: refund issued"
evaluators:
- ref: tool-call-accuracy
- ref: tool-errors
- ref: run-completed
gates:
- {metric: tool-call-accuracy.recall, min: 1.0}
- {metric: tool-call-accuracy.precision, min: 1.0}
- {metric: tool-errors, max: 0.0}
- {metric: run-completed, min: 1.0}
image:
repository: evalsi
tag: onboarding
pullPolicy: IfNotPresent
server:
persistence:
enabled: true
sandbox:
pool:
enabled: true
pod:
defaultImage: evalsi:onboarding
networkPolicyEnforced: false
bootstrap:
enabled: true
projects:
- name: onboarding
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: first-tool-calling-run
spec:
dataset:
path: tasks.jsonl
target:
connector: openai-compatible
base_url: http://127.0.0.1:8765/v1
model: loop
max_tokens: 256
harness:
builtin:
max_steps: 6
tools:
sandbox: false
mocks:
- name: lookup_order
description: Look up an order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"status":"paid","refundable":true}'
- name: refund
description: Refund an eligible order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"refunded":true}'
evaluators:
- ref: tool-call-accuracy
- ref: tool-errors
- ref: loop-detection
- ref: contains
params:
substring: Refunded order
trials: 1
gates:
- metric: tool-call-accuracy.recall
min: 1.0
- metric: tool-call-accuracy.precision
min: 1.0
- metric: contains
min: 1.0
- metric: tool-errors
max: 0.0
- metric: contains
stat: GATE_STAT_ERROR_RATE
max: 0.0
# First-time onboarding lab
A local fake chat-completions model drives the **real evalsi-harness tool loop**.
All tasks are synthetic. No provider key, weights or paid model is required.
Read the [complete course](../../docs/tutorials/README.md) for explanations,
installation diagnostics, exercises and interpretation.
## Published-release quick run
From the repository root, create and activate a fresh environment:
```bash
python3 -m venv .venv-onboarding
. .venv-onboarding/bin/activate
python -m pip install 'evalsi[server]==0.3.1' 'evalsi-harness==0.3.1'
cd examples/first-time-onboarding
python verify.py
```
The verifier starts and stops its own loopback server on a free port. It checks
seven scenarios; expected exits are `0,3,3,3,3,0,0`. Failures of its assertions
exit nonzero. Results/tapes are temporary. For manual exploration:
```bash
python fake_model.py --log requests.jsonl
# In a second activated terminal, in this directory:
evalsi run -f run.yaml --output results.json
evalsi report results.json -o report.html
```
| Spec | Model behavior | Expected exit |
|---|---|---:|
| `run.yaml` | Lookup, refund, answer | 0 |
| `regressed.yaml` | Lookup and false success claim | 3 |
| `loop.yaml` | Repeated lookup, bounded at six turns | 3 |
| `bad-arguments.yaml` | Lookup without the required order ID | 3 |
| `fault.yaml` | Every refund fails; retry once, then stop | 3 |
| `record.yaml` | Record a successful run to tapes | 0 |
| `replay.yaml` | Replay those tapes without the model | 0 |
| `database.yaml` | Real per-trial SQL writes/assertions, **source only** | 0 |
`fake_model.py` simulates the next conversation turn from its prefix, not token
sampling. It supports non-streaming chat completions only. Its usage values are
synthetic. Mock tools do not change business state. The source-only database
extension is described in [lesson 5](../../docs/tutorials/05-state-and-handoff.md).
After installing the Python workspace, run `python verify.py --database` with
that environment active to exercise all nine scenarios.
Stop the manual server with Ctrl-C. Delete generated results and `tapes/` after
inspection. Request logs contain the entire synthetic conversation; do not log
real customer data this way.
## Optional live provider and Kubernetes paths
The [Haiku lesson](../../docs/tutorials/10-real-haiku.md) uses
`verify_live.py --allow-paid` for non-streaming, streaming and provider-free
replay, with `--database` reserved for source installs. Credentials come only
from the environment; no provider calls run in the offline verifier or CI tests.
The [kind lesson](../../docs/tutorials/11-local-kind.md) uses `kind-values.yaml`
and the `kind-*.yaml` resources for recorded scoring, a checked pod-sandbox
agent and a cluster-local TinyLM tool loop, including three negative controls.
Read the networking, persistence and cleanup limitations before applying them.
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: first-tool-calling-run
spec:
dataset:
path: tasks.jsonl
target:
connector: openai-compatible
base_url: http://127.0.0.1:8765/v1
model: careful
max_tokens: 256
harness:
builtin:
max_steps: 6
tools:
sandbox: false
mocks:
- name: lookup_order
description: Look up an order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"status":"paid","refundable":true}'
- name: refund
description: Refund an eligible order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"refunded":true}'
recording:
mode: record
dir: tapes
evaluators:
- ref: tool-call-accuracy
- ref: tool-errors
- ref: loop-detection
- ref: contains
params:
substring: Refunded order
trials: 1
gates:
- metric: tool-call-accuracy.recall
min: 1.0
- metric: tool-call-accuracy.precision
min: 1.0
- metric: contains
min: 1.0
- metric: tool-errors
max: 0.0
- metric: contains
stat: GATE_STAT_ERROR_RATE
max: 0.0
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: first-tool-calling-run
spec:
dataset:
path: tasks.jsonl
target:
connector: openai-compatible
base_url: http://127.0.0.1:8765/v1
model: skip-refund
max_tokens: 256
harness:
builtin:
max_steps: 6
tools:
sandbox: false
mocks:
- name: lookup_order
description: Look up an order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"status":"paid","refundable":true}'
- name: refund
description: Refund an eligible order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"refunded":true}'
evaluators:
- ref: tool-call-accuracy
- ref: tool-errors
- ref: loop-detection
- ref: contains
params:
substring: Refunded order
trials: 1
gates:
- metric: tool-call-accuracy.recall
min: 1.0
- metric: tool-call-accuracy.precision
min: 1.0
- metric: contains
min: 1.0
- metric: tool-errors
max: 0.0
- metric: contains
stat: GATE_STAT_ERROR_RATE
max: 0.0
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: first-tool-calling-run
spec:
dataset:
path: tasks.jsonl
target:
connector: openai-compatible
base_url: http://127.0.0.1:8765/v1
model: careful
max_tokens: 256
harness:
builtin:
max_steps: 6
tools:
sandbox: false
mocks:
- name: lookup_order
description: Look up an order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"status":"paid","refundable":true}'
- name: refund
description: Refund an eligible order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"refunded":true}'
recording:
mode: replay
dir: tapes
evaluators:
- ref: tool-call-accuracy
- ref: tool-errors
- ref: loop-detection
- ref: contains
params:
substring: Refunded order
trials: 1
gates:
- metric: tool-call-accuracy.recall
min: 1.0
- metric: tool-call-accuracy.precision
min: 1.0
- metric: contains
min: 1.0
- metric: tool-errors
max: 0.0
- metric: contains
stat: GATE_STAT_ERROR_RATE
max: 0.0
apiVersion: evalsi.dev/v1alpha1
kind: EvalRun
metadata:
name: first-tool-calling-run
spec:
dataset:
path: tasks.jsonl
target:
connector: openai-compatible
base_url: http://127.0.0.1:8765/v1
model: careful
max_tokens: 256
harness:
builtin:
max_steps: 6
tools:
sandbox: false
mocks:
- name: lookup_order
description: Look up an order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"status":"paid","refundable":true}'
- name: refund
description: Refund an eligible order by numeric id.
input_schema:
type: object
properties:
id:
type: integer
required:
- id
response: '{"refunded":true}'
evaluators:
- ref: tool-call-accuracy
- ref: tool-errors
- ref: loop-detection
- ref: contains
params:
substring: Refunded order
trials: 1
gates:
- metric: tool-call-accuracy.recall
min: 1.0
- metric: tool-call-accuracy.precision
min: 1.0
- metric: contains
min: 1.0
- metric: tool-errors
max: 0.0
- metric: contains
stat: GATE_STAT_ERROR_RATE
max: 0.0
{"id": "refund-42", "input": "Refund order 42.", "reference": {"tool_calls": [{"name": "lookup_order", "arguments": {"id": 42}}, {"name": "refund", "arguments": {"id": 42}}]}}
{"id": "refund-7", "input": "Refund order 7.", "reference": {"tool_calls": [{"name": "lookup_order", "arguments": {"id": 7}}, {"name": "refund", "arguments": {"id": 7}}]}}
{"id": "refund-99", "input": "Refund order 99.", "reference": {"tool_calls": [{"name": "lookup_order", "arguments": {"id": 99}}, {"name": "refund", "arguments": {"id": 99}}]}}
from __future__ import annotations
from pathlib import Path
import pytest
import yaml
from verify_live import ROOT, build_spec, check_result, configuration
from evalsi.runspec import load_spec
def test_live_configuration_requires_explicit_model(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("ANTHROPIC_DEFAULT_HAIKU_MODEL", raising=False)
with pytest.raises(ValueError, match="no model is billed by default"):
configuration()
def test_live_configuration_names_credentials_without_copying_them(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("ANTHROPIC_DEFAULT_HAIKU_MODEL", "haiku-test")
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
monkeypatch.setenv("ANTHROPIC_AUTH_TOKEN", "test-secret")
monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://localhost:1234/")
assert configuration() == ("haiku-test", "ANTHROPIC_AUTH_TOKEN", "http://localhost:1234")
@pytest.mark.parametrize("database", [False, True])
def test_live_spec_needs_no_sandbox_and_preserves_reference_calls(
database: bool, tmp_path: Path
) -> None:
document = build_spec(
"haiku-test", "TEST_KEY", "http://localhost:1234", stream=True, database=database
)
path = tmp_path / "run.yaml"
path.write_text(yaml.safe_dump(document))
load_spec(path)
spec = document["spec"]
assert spec["target"]["stream"] is True
assert spec["harness"]["builtin"]["tools"]["sandbox"] is False
assert len(spec["dataset"]["inline"]["records"]) == 3
assert all(r["reference"]["json"]["tool_calls"] for r in spec["dataset"]["inline"]["records"])
assert ("environment" in spec) is database
assert "test-secret" not in repr(spec)
def test_live_result_rejects_success_shaped_missing_metrics() -> None:
with pytest.raises(AssertionError, match=r"tool-call-accuracy\.recall"):
check_result({"records": [{}, {}, {}], "summaries": []})
def test_live_result_rejects_evaluator_errors() -> None:
with pytest.raises(AssertionError, match="Evaluator errors"):
check_result({"records": [{}, {}, {}], "summaries": [{"errors": 1}]})
@pytest.mark.parametrize("name", ["recorded", "agent", "support"])
def test_kind_run_examples_parse(name: str) -> None:
load_spec(ROOT / f"kind-{name}.yaml")
"""Opt-in paid Haiku onboarding: business tools, streaming, replay and optional SQL."""
from __future__ import annotations
import argparse
import copy
import json
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import Any
import yaml
ROOT = Path(__file__).resolve().parent
POLICY = (
"First call lookup_order for the requested numeric id. Refund exactly once only if "
"the order is paid and not already refunded. Do not call any other tools. "
"After a successful refund answer 'Refunded order <id>' with the numeric id. "
)
SQL_POLICY = (
"First call lookup_order for the requested numeric id. If refunded is 0, call refund "
"exactly once with that id. Do not call any other tools. After success answer "
"'Refunded order <id>' with the numeric id. "
)
def configuration() -> tuple[str, str, str]:
model = os.environ.get("ANTHROPIC_DEFAULT_HAIKU_MODEL")
if not model:
raise ValueError(
"Set ANTHROPIC_DEFAULT_HAIKU_MODEL explicitly; no model is billed by default"
)
key_env = next(
(name for name in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN") if os.environ.get(name)),
None,
)
if key_env is None:
raise ValueError("Set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN in the environment")
base = os.environ.get("ANTHROPIC_BASE_URL", "https://api.anthropic.com").rstrip("/")
return model, key_env, base
def build_spec(
model: str, key_env: str, base: str, *, stream: bool, database: bool = False
) -> dict[str, Any]:
source = ROOT / "database.yaml" if database else ROOT.parent / "tinylm" / "support.yaml"
document: dict[str, Any] = yaml.safe_load(source.read_text())
spec = document["spec"]
spec["target"] = {
"connector": "anthropic",
"model": model,
"api_key_env": key_env,
"base_url": base,
"stream": stream,
"max_tokens": 512,
}
dataset = ROOT / "tasks.jsonl" if database else ROOT.parent / "tinylm" / "support.jsonl"
records = [json.loads(line) for line in dataset.read_text().splitlines() if line.strip()]
for record in records:
record["input"] = {"text": (SQL_POLICY if database else POLICY) + record["input"]}
record["reference"] = {"json": record["reference"]}
spec["dataset"] = {"inline": {"records": records}}
spec["harness"]["builtin"]["tools"]["sandbox"] = False
spec["harness"]["builtin"]["budget"] = {"tokens": 20000, "wall_clock": "90s"}
if not database:
spec.pop("environment", None)
spec["gates"].append({"metric": "run-completed", "min": 1.0})
spec["gates"].append(
{"metric": "tool-call-accuracy.recall", "stat": "GATE_STAT_ERROR_RATE", "max": 0.0}
)
return document
def check_result(data: dict[str, Any], *, database: bool = False) -> dict[str, float]:
if len(data["records"]) != 3:
raise AssertionError("Expected exactly three records")
if any(summary["errors"] for summary in data["summaries"]):
raise AssertionError("Evaluator errors are not model failures")
means = {summary["metric"]: summary["mean"] for summary in data["summaries"]}
required = ["tool-call-accuracy.recall", "tool-call-accuracy.precision"]
required += ["task-success", "contains"] if database else ["run-completed"]
for metric in required:
if means.get(metric) != 1.0:
raise AssertionError(f"Expected {metric}=1, got {means.get(metric)}")
if means.get("tool-errors") != 0.0:
raise AssertionError(f"Expected tool-errors=0, got {means.get('tool-errors')}")
return means
def run_case(
cli: str, name: str, document: dict[str, Any], work: Path, *, database: bool = False
) -> dict[str, float]:
path, output = work / f"{name}.yaml", work / f"{name}.json"
path.write_text(yaml.safe_dump(document))
result = subprocess.run(
[cli, "run", "-f", str(path), "--output", str(output), "--quiet"],
capture_output=True,
text=True,
timeout=180,
check=False,
)
if result.returncode:
detail = result.stdout + result.stderr
target = document["spec"]["target"]
for value in (target["base_url"], os.environ.get(target["api_key_env"], "")):
if value:
detail = detail.replace(value, "[redacted]")
raise RuntimeError(f"{name}: CLI exit {result.returncode}\n{detail}")
means = check_result(json.loads(output.read_text()), database=database)
print(json.dumps({"case": name, "exit": result.returncode, "records": 3, "means": means}))
return means
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--allow-paid", action="store_true", help="Explicitly permit provider calls"
)
parser.add_argument("--database", action="store_true", help="Also test source-only SQL state")
args = parser.parse_args()
if not args.allow_paid:
parser.error("Provider calls cost money; pass --allow-paid to opt in")
model, key_env, base = configuration()
cli = shutil.which("evalsi")
if cli is None:
parser.error("evalsi is not on PATH; activate the environment being tested")
with tempfile.TemporaryDirectory(prefix="evalsi-live-onboarding-") as tmp:
work = Path(tmp)
run_case(cli, "haiku-nonstream", build_spec(model, key_env, base, stream=False), work)
streamed = build_spec(model, key_env, base, stream=True)
streamed["spec"]["harness"]["builtin"]["recording"] = {
"mode": "record",
"dir": str(work / "tapes"),
}
recorded = run_case(cli, "haiku-stream-record", streamed, work)
replay = copy.deepcopy(streamed)
replay["spec"]["target"]["base_url"] = "http://127.0.0.1:1"
replay["spec"]["harness"]["builtin"]["recording"]["mode"] = "replay"
if run_case(cli, "haiku-offline-replay", replay, work) != recorded:
raise AssertionError("Recorded and replayed metric means differ")
if args.database:
run_case(
cli,
"haiku-sql-state",
build_spec(model, key_env, base, stream=False, database=True),
work,
database=True,
)
if __name__ == "__main__":
main()
"""Run the tutorial matrix against the installed evalsi CLI, with no external API."""
from __future__ import annotations
import argparse
import json
import subprocess
import tempfile
import threading
from pathlib import Path
import yaml
from fake_model import Handler, Server
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--database", action="store_true", help="Also test source-only SQL tasks")
args = parser.parse_args()
root = Path(__file__).resolve().parent
server = Server(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
cases = [
("run", 0),
("regressed", 3),
("loop", 3),
("bad-arguments", 3),
("fault", 3),
("record", 0),
("replay", 0),
]
if args.database:
cases += [("database", 0), ("database-regressed", 3)]
try:
with tempfile.TemporaryDirectory(prefix="evalsi-onboarding-") as tmp:
work = Path(tmp)
for name, expected in cases:
source = "database" if name == "database-regressed" else name
spec = yaml.safe_load((root / f"{source}.yaml").read_text())
spec["spec"]["dataset"]["path"] = str(root / "tasks.jsonl")
spec["spec"]["target"]["base_url"] = f"http://127.0.0.1:{server.server_port}/v1"
if name == "database-regressed":
spec["spec"]["target"]["model"] = "skip-refund"
if name == "replay":
# Make model access impossible: replay must use the tape.
spec["spec"]["target"]["base_url"] = "http://127.0.0.1:1/v1"
path = work / f"{name}.yaml"
path.write_text(yaml.safe_dump(spec))
output = work / f"{name}.json"
result = subprocess.run(
["evalsi", "run", "-f", str(path), "--output", str(output)],
capture_output=True,
text=True,
timeout=60,
check=False,
)
if result.returncode != expected:
raise AssertionError(
f"{name}: expected {expected}, got {result.returncode}\n"
f"{result.stdout}\n{result.stderr}"
)
data = json.loads(output.read_text())
assert len(data["records"]) == 3, (name, "missing records")
assert all(s["errors"] == 0 for s in data["summaries"]), name
means = {s["metric"]: s["mean"] for s in data["summaries"]}
if name in {"run", "record", "replay", "database"}:
assert means["tool-call-accuracy.recall"] == 1, name
if name == "regressed":
assert means["tool-call-accuracy.recall"] == 0.5
assert means["contains"] == 1, (
"The false success claim must still pass text check"
)
if name == "database-regressed":
assert means["task-success"] == 0
if name == "loop":
assert means["loop-detection"] == 0
print(json.dumps({"case": name, "exit": result.returncode, "means": means}))
finally:
server.shutdown()
server.server_close()
thread.join()
if __name__ == "__main__":
main()