Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install agent-platform-autorater-customization@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin agent-platform-autorater-customization v1.0.0 follows the Agent Plugins spec.
gh skills-hub install agent-platform-autorater-customization Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/agent-platform-autorater-customization/ Extract the ZIP to .github/skills/ in your repo. The folder name must match agent-platform-autorater-customization for Copilot to auto-discover it.
Skill Files (12)
SKILL.md 14.2 KB
---
name: agent-platform-autorater-customization
metadata:
version: "1.0.1"
category: AiAndMachineLearning
description: >-
Customizes an autorater (evaluation metric) for an AI agent so its grades
match the user's own judgment, starting from the agent's real trajectories.
Use when a user wants a metric tailored to their agent, wants to turn failing
trajectories into rubrics, says an existing autorater grades their agent
wrong, or wants an autorater to agree with human labels (autorater
hillclimbing, judge calibration). Don't use for quick evals with built-in
metrics or for improving the agent itself (use agent-platform-eval-flywheel).
---
# Agent Platform Autorater Customization
This skill helps a user build graders for their agent that judge the way they
do. You do the reading, writing and testing; the user makes the judgment calls.
The result is a set of metrics registered in the Agent Platform evaluation
service, one or more for each criterion the user cares about.
Carry out the steps below in order. Don't summarize them to the user.
## Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command, you
MUST read and follow the instructions in
[Usage Attribution](references/attribution.md).
## Setup
Check each item before the first evaluation call, and ask the user to fix what
is missing. Ask before installing anything, because it changes the user's
environment.
1. **Python SDK.** Install or upgrade the Agent Platform SDK with the
evaluation extra:
```bash
pip install --upgrade 'google-cloud-aiplatform[evaluation]>=2.8.0,<3'
```
Keep the quotes; unquoted, the shell reads `>=` as a redirect. The
`gcloud` CLI is also needed for authentication; if it is missing, point the
user to https://cloud.google.com/sdk/docs/install instead of installing it.
2. **Project and billing.** Use the project the user names, or ask for one
(`gcloud config set project {project_id}`). The project needs an active
billing account: evaluation calls are billed as model usage. See
https://cloud.google.com/pricing for current prices; don't quote numbers.
3. **API.** Enable the Agent Platform API:
`gcloud services enable aiplatform.googleapis.com`.
4. **Authentication.** Run `gcloud auth login` for the CLI and
`gcloud auth application-default login` for the SDK and scripts, or set
`GOOGLE_APPLICATION_CREDENTIALS` to a service account key file.
5. **IAM.** The user or service account needs `roles/aiplatform.user` to run
evaluations and register metrics. Don't grant broader roles such as
`roles/aiplatform.admin`; ask the user to request the narrower role if it
is missing.
6. **Region.** Use `us-central1` unless the user needs another region (use
`global` for `gemini-4-hydrogen` judge models unless
`allow_cross_region_model` is enabled; see
https://cloud.google.com/about/locations).
## Working with the user
- At each **Approval** point, show the proposal and ask: "Would you like to
change anything, or go ahead with this version?" Wait for a clear yes;
silence is not approval.
- For setup choices (project, region, storage), suggest a default.
- Everything the user reviews (cases, grades, metric definitions) goes in a
review page, not in chat; see [Review pages](#review-pages). Chat updates
say what you did, the numbers, and what you need.
- When you ask about a trajectory in chat, quote the relevant lines.
## Inputs
The user brings a folder of trajectories: the ones they think went wrong, plus
some good ones. Optional: a note or rating per trajectory (thumbs, human score,
an old autorater's verdict), an existing rubric, or reference answers.
- Use all of them unless grading them would be slow or costly in the
evaluation service. Then agree a sample with the user that covers the
failures and a few good cases, and say what was left out.
- AgentData JSONL is best; see
[Converting trajectories](references/converting_trajectories.md). If you
can't map a format to AgentData with confidence, don't guess: say you need
to convert it to AgentData, and ask the user for a schema, a converter, or
one example mapped by hand. Then check every converted case.
- Building a dataset is not this skill's job. If the user has no folder yet,
help them pick and convert trajectories, then continue.
## Terms
- **Criterion:** one thing the user cares about in the agent's behavior: the
answer is correct, the right tool is called, the system instructions are
followed throughout. A criterion holds for the whole dataset; every
trajectory, or every turn, is graded on it, and it can be N/A for some.
- **Rubric:** one yes/no check.
- **Metric:** what grades a criterion in the evaluation service: code, one
rubric, or several weighted rubrics. A criterion gets as many metrics as it
needs, for example a code check for the tool call plus a judge for the
answer.
The predefined multi-turn metrics also turn intents into rubrics with an
importance, but they score the unweighted share of rubrics that pass. Custom
metrics add rubrics written for the user's agent, weights, must-pass rubrics,
and a pass threshold.
## Steps
### 1. Confirm the inputs
Ask where the folder is and whether any trajectories have a note or rating.
### 2. Propose criteria (Approval)
Read the trajectories and the user's notes, and propose the criteria the data
supports, as few as cover the problems the user cares about. They can cover any
part of the trajectory: the final answer, tool calls and arguments, following
the system instructions, handling of errors or clarifications. In a multi-agent
system, a criterion can be about the whole system (routing, the final answer) or
about one sub-agent; say which. For each, give:
- a one-line statement and why it matters for this agent;
- how many cases show a problem, with one quoted example;
- the metrics you plan to build for it (see step 4), with one line on why.
Never propose a criterion you can't point to in the data or the user's notes.
Flag any criterion you doubt, with the reason (for example, it can't be graded
where tool results were trimmed). Also note problems in any existing grading: a
judge that never saw data the agent had, evidence trimmed from the trajectory,
golden answers that were never run.
This step makes no evaluation-service calls. If the user wants help finding
patterns in ten or more failing cases, you can grade them with
`MULTI_TURN_TASK_SUCCESS` and run `client.evals.generate_loss_clusters` after
step 3. Loss clusters only work in the `global` region and for
`multi_turn_task_success` and `multi_turn_tool_use_quality`, not for custom
metrics.
Save the approved criteria as `criteria.md`.
### 3. Agree data rules and spend (Approval)
Ask whether the trajectories may be sent to the evaluation service, which
project to bill, and where outputs may be stored. Show the number of calls
(cases × metrics × samples × rounds, with one call per step for step-based
metrics) and point to https://cloud.google.com/pricing for the cost. Ask again
before any run beyond that.
### 4. Build the metrics
Use the simplest form that grades the criterion: simpler forms cost less, give
the same answer every time, and are easier to trust.
Criterion can be graded by | Form | SDK
--------------------------------------------------------------------------- | ----------------------- | ---
An exact rule on the output or trajectory (a tool name, a format, a number) | Code | `types.CodeExecutionMetric` (runs in the service; can be registered)
One judgment that is the same for every case | LLM, one rubric | `types.LLMMetric` with a yes/no check and a reference
Several checks, some more important than others | LLM, weighted rubrics | `types.StepBasedLLMMetric`: one judge step; code computes the weighted score
Checks that differ per case, with no good reference | Generated checklist | `types.StepBasedLLMMetric`: one step writes checks from the conversation, one grades them
Long or multi-turn traces, per-turn verdicts, or several judging stages | Step-based, multi-stage | `types.StepBasedLLMMetric`
One sub-agent of a multi-agent system | Step-based, one agent | `types.StepBasedLLMMetric` with a code preprocessor that keeps that agent's events
Start each metric from its template in
[Metric templates](references/metric_templates.md); each template says what it
doesn't catch. For weighted rubrics, propose the rubrics, a weight for each, the
must-pass rubrics and a pass threshold, and keep the weights in the parser code
so the judge grades each rubric on its own. Write checks as described in
[Writing LLM checks](references/writing_checks.md). For multi-turn
conversations, decide per criterion whether to grade each turn or the whole
conversation; see [Multi-turn conversations](references/multi_turn.md).
### 5. Grade and show the results
Grade the cases through the evaluation service with `scripts/run_metrics.py`,
then build a review page with `scripts/build_review_page.py`. Pass each metric's
pass threshold as `--threshold`, so PASS and FAIL on the page match the metric.
Optional: if the user has an existing autorater, or wants to compare with a
built-in metric such as `MULTI_TURN_TASK_SUCCESS`, grade with it too and show it
as a baseline. It adds calls, and a built-in metric grades overall task success
rather than the user's criteria.
### 6. Optional: align the metrics with the user's ratings
Ask whether the user wants to mark the grades and have you improve the metrics,
at about a minute per case. Skip to step 7 if not.
1. Set aside about 20% of the cases as held back. Build the review page without
them.
2. The user marks each verdict Agree or Disagree on the review page, with a
reason when they disagree, and gives you `labels.json`. If the user already
has human ratings, use them and ask only about the cases where a metric
disagrees.
3. Compute agreement per metric and per rubric with `scripts/agreement.py`.
Measure judge noise before trusting a change; see
[Noise and agreement](references/noise_and_agreement.md).
4. Revise the metrics yourself (rubric wording, weights, must-pass rubrics,
threshold, reference, code), save each round as a new version, grade again,
and show the user what changed and the new agreement. When a label
contradicts the trajectory, quote the lines and ask the user.
5. Stop when agreement stops improving by more than the noise, or when the user
is satisfied. Grade the held-back cases once. Don't revise on them; if a
held-back case breaks, report overfitting and suggest more labeled cases.
### 7. Review and register (Approval)
Registering the metrics is the goal of this skill. Add to the review page, for
each metric: its criterion, the final definition (rubrics, weights, must-pass
rubrics, threshold, judge model, sample count), its grades, agreement on labeled
and held-back cases if step 6 ran, and open questions. After approval, register
each metric with `create_evaluation_metric`; it creates a shared resource.
Hand over an output folder with:
- `criteria.md`: the approved criteria, each listing the metrics that grade
it;
- `metrics/`: the final definition of every metric, as the file the evaluation
service ran (the metrics file passed to `scripts/run_metrics.py`), with its
registered name;
- `metrics.md`: one entry per metric with its criterion, form, rubrics,
weights, must-pass rubrics, threshold, judge model and sample count, and a
code snippet that runs it by registered name;
- `labels.json` and earlier versions, if step 6 ran;
- `report.md`: the numbers and open questions.
To run the metrics on a full dataset, point to `agent-platform-eval-flywheel`.
## Review pages
Build one self-contained HTML page per round with
`scripts/build_review_page.py`, and give the user its path (or serve it where
the user's browser can reach it). For each case it shows the user's note or
rating, each metric's PASS/FAIL, score, explanation and rubric verdicts, the
baseline if one ran, and the trajectory with tool results collapsed. The user
marks Agree or Disagree on each verdict with a reason; marks are saved in the
browser, and "Download labels.json" exports them in the format
`scripts/agreement.py` reads. Never ask the user to type labels in chat.
## Rules
- All grading goes through the evaluation service. Labels come only from the
user: don't grade trajectories or draft labels with your own model calls or
subagents, because tuning a metric to another model's labels only teaches
one model to agree with another.
- Grade only the cases in the folder while building; the full dataset is for
after registration.
- Every number you report comes from a result file. Report a range when runs
differ.
- Keep proprietary trajectories and outputs, including review pages, where the
user said. Never paste them into shared docs, bugs or chats.
- Read the installed SDK source before using a name; versions differ.
## Cleanup
Registered metrics stay in the project until deleted. When the user wants to
remove a metric they no longer use, or one registered by mistake, confirm the
name with them, then run
`client.evals.delete_evaluation_metric(metric_resource_name={name})`. List them
with `client.evals.list_evaluation_metrics()`. Local outputs (results, review
pages, labels) stay where the user chose; offer to delete them at the end.
## Scripts
All have `--help`.
- `scripts/render_agent_data.py`: trajectories as readable text.
- `scripts/run_metrics.py`: runs SDK metrics with `client.evals.evaluate()`.
- `scripts/build_review_page.py`: the review page and labels export.
- `scripts/agreement.py`: agreement, Cohen's kappa and disagreements, per
metric, per rubric or per turn.
## References
- [Converting trajectories](references/converting_trajectories.md)
- [Metric templates](references/metric_templates.md)
- [Writing LLM checks](references/writing_checks.md)
- [Multi-turn conversations](references/multi_turn.md)
- [Noise and agreement](references/noise_and_agreement.md)
- [SDK gotchas](references/sdk_gotchas.md)
attribution.md 1.9 KB
# Usage Attribution
**MUST READ**: Before executing any `gcloud`, REST API, or MCP command with
this skill, follow these usage attribution instructions. Tag every command you
execute directly in the terminal so usage can be attributed. The tag identifies
only the skill and its version; it carries no user data.
- **`gcloud` CLI Commands**: Prefix every `gcloud` invocation, whatever the
subcommand, with the metrics environment variable. Set it inline on each
command because shell state may not persist between commands:
```bash
CLOUDSDK_METRICS_REQUEST_ATTRIBUTION="agent-skills/1.0 (skill:agent-platform-autorater-customization)" \
gcloud <command> [flags]
```
Do not use `gcloud config set` for this: it would persist beyond the current
task and mislabel unrelated usage.
- **Direct HTTP, REST, and MCP Requests**: On direct HTTP calls to Google
Cloud APIs (for example with `curl`) or HTTP requests to a remote MCP
server, include
`agent-skills/1.0 (skill:agent-platform-autorater-customization)` in the
`User-Agent` header. If a `User-Agent` header is already specified, append
this string to the end of it rather than overwriting existing `User-Agent`
data — the collection pipeline parses the `agent-skills/<version>` and
`skill:<name>` tokens, so any rewording breaks attribution:
```
User-Agent: <existing_user_agent> agent-skills/1.0 (skill:agent-platform-autorater-customization)
```
- **Constraint for Generated Code**: The tracking prefix is strictly for
commands you execute directly in the terminal. Do NOT include this tracking
prefix in generated scripts, Terraform templates, or code provided to the
user for their own repositories.
- **User Opt-Out**: If the user asks to disable or remove tracking or
attribution tags, omit the `CLOUDSDK_METRICS_REQUEST_ATTRIBUTION` variable
and custom `User-Agent` suffix from all commands.
converting_trajectories.md 1.9 KB
# Converting trajectories
Convert every source to the evaluation service's `AgentData` shape, so the
metrics and scripts work the same way for all sources.
## Sources
Source | How to load
---------------------------- | -----------
Local or Cloud Storage files | Read JSONL directly; ADK eval sets with `types.EvaluationDataset.load_from_adk_eval_set`
Cloud Trace | `client.evals.import_evaluation_set` with `cloud_trace_source` (filter with `trace_ids` or `session_ids`)
Interactions | `types.InteractionsDataSource`
Reading trajectories is read-only. Importing them into an evaluation set creates
a resource, so ask first.
## Shape
- One `ConversationTurn` per agent call. When a user (real or simulated)
answers a clarifying question, that is a new turn of the same user request.
Keep the request-to-turn mapping in `turn_id`.
- Tool calls become `function_call` parts. Their outputs become
`function_response` parts with the rows or payload. When truncating, keep
the start and the end, not only the start: time series keep their newest
points at the end.
- Mark internal reasoning as `thought=True`, so judges and preprocessors can
drop it.
- Convert typed values (for example timestamps stored as epoch numbers) to a
readable form.
- Put the golden answer, golden query and golden result rows in `reference`.
- Keep extra fields a code metric or `--trajectory_response` needs (a
rendered trajectory, the intended tool) as extra `EvalCase` attributes.
Judge templates can't rely on them after registration (see
`sdk_gotchas.md`).
## Check the conversion
Check with code, for every case:
- every tool call and result is present;
- text, queries and answers match the source exactly;
- for multi-turn: user text, turn ids, and one reference section per user
turn;
- `types.EvalCase(**case)` validates.
metric_templates.md 24.0 KB
# Metric templates
Working templates for each metric form, each adapted from a published recipe.
Every template here was run against the evaluation service on test trajectories
before it was added.
- [How to use these templates](#how-to-use-these-templates) (line 20)
- [Shared setup](#shared-setup) (line 39)
- [Code metric: expected tool call](#code-metric-expected-tool-call) (line 55)
- [LLM metric, static rubric: reference-guided checks](#llm-metric-static-rubric-reference-guided-checks)
(line 143)
- [Step-based metric: generated checklists](#step-based-metric-generated-checklists)
(line 189)
- [Step-based metric: weighted rubrics](#step-based-metric-weighted-rubrics)
(line 311)
- [Step-based metric: claim faithfulness](#step-based-metric-claim-faithfulness)
(line 419)
- [Sources](#sources) (line 574)
## How to use these templates
1. Copy the template for the metric type chosen in step 4 of SKILL.md into a
metrics file (for example `metrics.py`) that defines
`METRICS = {"name": callable}`.
2. Change only the lines marked `EDIT`, filling them from the approved criteria
and rubrics.
3. Run every metric with `scripts/run_metrics.py`. Its results file is what
`scripts/build_review_page.py` and `scripts/agreement.py` read.
4. Version each change (`answer_checks_v2`, ...) and keep old results.
5. Keep each template's variable names distinct when several share one
metrics file: the `METRICS` lambdas read them when the metric runs, so a
later template that reuses a name replaces the earlier one's value.
Each recipe also says what it does not catch. Check that against the approved
criteria. When one form leaves a gap, split the criterion or add a check from
another form (for example generated checklists for "did it do what was asked"
plus faithfulness for "is what it said true").
## Shared setup
```python
from agentplatform import types
PROJECT = "my-project" # EDIT: your project ID
LOCATION = "global"
# LLMMetric needs the full resource name; short names fail with 400.
JUDGE = f"projects/{PROJECT}/locations/{LOCATION}/publishers/google/models/gemini-4-hydrogen"
```
Cases are EvalCase-shaped JSONL lines with `eval_case_id`, `prompt`,
`responses`, `reference` and `agent_data`. Templates read the trajectory from
`{agent_data}`: extra case attributes reach the judge only in inline runs, not
when a registered metric runs by name.
## Code metric: expected tool call
**Use when** the label is an exact rule on the trajectory: the right tool, the
right arguments, a required format.
**Recipe:** function-call checking as in the Berkeley Function Calling
Leaderboard, which compares the called function and its arguments with the
expected call. Here the expected call is written in the reference as one line,
`EXPECTED_TOOL_CALL: {"name": ..., "args": {...}}`, and extra arguments are
allowed.
Save as `tool_call_match.py`. It runs in the evaluation service's code
sandbox, and the same source can run locally while you debug:
```python
import json
import re
def _text(field):
if isinstance(field, str):
return field
if not isinstance(field, dict):
return ""
if isinstance(field.get("response"), dict):
field = field["response"]
if "contents" in field: # remote sandbox shape
contents = field.get("contents") or {}
if isinstance(contents, dict):
contents = contents.get("gemini_contents") or contents.get("contents") or []
return "".join(p.get("text", "") for c in contents for p in (c.get("parts") or []))
return "".join(p.get("text", "") for p in (field.get("parts") or []))
def _get(d, *names):
for n in names:
if isinstance(d, dict) and d.get(n) is not None:
return d[n]
return None
def _tool_calls(agent_data):
calls = []
for turn in _get(agent_data, "turns") or []:
for event in _get(turn, "events") or []:
for part in (_get(event, "content") or {}).get("parts") or []:
fc = _get(part, "function_call", "functionCall")
if fc:
calls.append((fc.get("name"), fc.get("args") or {}))
return calls
def evaluate(instance: dict) -> float:
m = re.search(r"EXPECTED_TOOL_CALL:\s*(\{.*\})", _text(instance.get("reference")))
if not m:
return 0.0
want = json.loads(m.group(1))
# A local callable gets agent_data; the remote sandbox gets agent_eval_data.
agent_data = instance.get("agent_data") or instance.get("agent_eval_data") or {}
for name, args in _tool_calls(agent_data): # EDIT: your rule
if name == want["name"] and all(
str(args.get(k)).lower() == str(v).lower() for k, v in want.get("args", {}).items()):
return 1.0
return 0.0
def evaluate_local(instance: dict) -> dict:
score = evaluate(instance)
return {"score": score, "explanation": "expected tool call found" if score else "expected tool call missing"}
```
Use the remote version in `METRICS`. It grades cases that have only
`agent_data`, and it can be registered:
```python
METRICS = {
"tool_match": lambda: types.CodeExecutionMetric(
name="tool_match", custom_function=open("tool_call_match.py").read()),
}
```
To debug the rule on your machine, call `evaluate_local(case)` directly, or use
`types.Metric(custom_function=evaluate_local)`. That local form needs
`responses` on every case and can't be registered (see
[SDK gotchas](sdk_gotchas.md)), so don't hand it over as the final metric.
**Doesn't catch:** whether the answer built on the tool result is right.
## LLM metric, static rubric: reference-guided checks
**Use when** the same criteria apply to every case and need judgment, and a
reference answer exists.
**Recipe:** reference-guided single-answer grading from MT-Bench, where the
judge sees a reference answer before grading. Adapted to yes/no checks instead
of a 1-10 score, with tolerated differences listed and the checks answered
before the score.
```python
ANSWER_CHECKS = """You grade an AI agent's answer to a user's request. Judge content only, not style.
# User request
{prompt}
# Agent trajectory (tool calls, tool results, final answer)
{agent_data}
# Reference (one correct answer; a different answer can also be correct)
{reference}
# Checks
1. The final answer addresses every part of the request.
2. Every fact in the final answer is supported by a tool result in the trajectory.
3. The final answer agrees with the reference on the key facts. Tolerated: wording, units written
differently, rounding.
4. The agent used the information it was asked about (for example the requested day or place).
# Output
Answer each check YES or NO with one sentence of evidence, then give the score: 1 only if all
checks are YES, else 0. Return only JSON:
{{"checks": {{"1": "YES|NO: ...", "2": "...", "3": "...", "4": "..."}}, "explanation": "<short>", "score": <1 or 0>}}
"""
# EDIT: replace the checks and tolerated differences with the approved ones.
METRICS["answer_checks"] = lambda: types.LLMMetric(
name="answer_checks", prompt_template=ANSWER_CHECKS, judge_model=JUDGE,
judge_model_sampling_count=1) # use 3 or more for the final check
```
Double the braces of literal JSON in the template (`{{ }}`); single braces are
template variables.
**Doesn't catch:** requirements that differ per case and aren't in the checks.
## Step-based metric: generated checklists
**Use when** each conversation has its own requirements and there is no good
reference: what the user asked for changes from case to case, including in
later turns.
**Recipe:** TICK (Targeted Instruct-evaluation with ChecKlists), which has an
LLM turn each instruction into YES/NO questions and then judges a response
against them. Here both stages read the whole conversation: `generate` writes
the checklist from every user turn and the agent's instructions, `grade` checks
the conversation against it, and a code parser computes a score weighted by
each check's importance.
```python
CHECKLIST_GENERATE = """Write a checklist for judging how well an AI agent handled this conversation.
# Conversation (agent instructions, user messages, tool calls, tool results, agent answers)
{agent_eval_data}
Write 3 to 8 YES/NO checks. Each check is one requirement that a user message or the agent's
instructions states or clearly implies, including requirements added in later turns. Write each as
a statement about the agent's behavior. Don't add requirements about style or length unless the
user asked for them. Rate each check's importance:
- HIGH: failing it makes the answer wrong or unusable for what the user asked (for example the wrong
place, a fact contradicting the tool results, ignoring an explicit request). Use it sparingly.
- MEDIUM: failing it makes the answer worse but still usable.
- LOW: a detail the user would barely notice.
Return only JSON:
{{"checks": [{{"id": "C1", "check": "<statement>", "importance": "HIGH|MEDIUM|LOW"}}]}}
"""
CHECKLIST_GRADE = """Grade an AI agent's conversation against a checklist. Judge each check on its own.
# Conversation (agent instructions, user messages, tool calls, tool results, agent answers)
{agent_eval_data}
# Checklist
{step.generate.output}
For each check answer YES if the conversation meets it, NO if it does not, or NA if it does not
apply. Copy the check's id, text and importance, and give one sentence of evidence quoted from the
conversation.
Return only JSON:
{{"verdicts": [{{"id": "C1", "check": "<text>", "importance": "HIGH|MEDIUM|LOW", "verdict": "YES|NO|NA", "evidence": "<quote or reason>"}}]}}
"""
CHECKLIST_PARSE = r'''
import collections, json
WEIGHTS = {"HIGH": 10, "MEDIUM": 5, "LOW": 2} # EDIT: weight per importance
HIGH_MUST_PASS = False # EDIT: True scores a case 0 when any HIGH check fails
def first_verdicts(text):
# Judges often wrap JSON in Markdown code fences or quote braces in explanations,
# so decode the first object that has "verdicts" instead of matching braces.
decoder = json.JSONDecoder()
for i, ch in enumerate(text):
if ch == "{":
try:
d, _ = decoder.raw_decode(text[i:])
except ValueError:
continue
if isinstance(d, dict) and "verdicts" in d:
return d["verdicts"]
return None
def parse_results(responses):
votes, info = collections.defaultdict(list), {}
for text in responses:
verdicts = first_verdicts(text)
if verdicts is None:
continue
for v in verdicts:
cid, verdict = str(v.get("id", "")).strip(), str(v.get("verdict", "")).upper()
if cid and verdict in ("YES", "NO", "NA"):
votes[cid].append(verdict)
info.setdefault(cid, (v.get("check", ""), str(v.get("importance", "MEDIUM")).upper()))
if not votes:
raise ValueError("no parsable verdicts")
final = {c: collections.Counter(vs).most_common(1)[0][0] for c, vs in votes.items()}
weight = {c: WEIGHTS.get(info[c][1], WEIGHTS["MEDIUM"]) for c in final}
scored = [c for c, v in final.items() if v != "NA"]
total = sum(weight[c] for c in scored)
score = sum(weight[c] for c in scored if final[c] == "YES") / total if total else 1.0
if HIGH_MUST_PASS and any(final[c] == "NO" and info[c][1] == "HIGH" for c in final):
score = 0.0
notes = [f"{c} {info[c][1]} {final[c]}: {info[c][0]}" for c in sorted(final)]
return {"score": score, "explanation": "; ".join(notes)}
'''
METRICS["generated_checklist"] = lambda: types.StepBasedLLMMetric(
name="generated_checklist",
steps=[
{"step_id": "generate", "prompt_template": CHECKLIST_GENERATE,
"autorater_config": {"autorater_model": JUDGE, "sampling_count": 1}},
{"step_id": "grade", "prompt_template": CHECKLIST_GRADE,
"autorater_config": {"autorater_model": JUDGE, "sampling_count": 3},
"response_parser_config": {"custom_code_parser_config": {"parsing_function": CHECKLIST_PARSE}}},
],
)
```
- The checklist is generated once per case (`sampling_count` 1), so every
grading sample votes on the same check ids. With more generation samples
the ids would not line up across samples.
- Generators rate most checks HIGH on short conversations, which flattens the
weights. Set `HIGH_MUST_PASS = True` when one failed core requirement should
fail the case, or use a pass threshold near 1.0.
- The checklist changes between runs (4 to 8 checks on the same case in
testing). To keep it fixed while revising, save the `generate` output from
one run and use it as a static rubric list (see the weighted-rubrics
template).
- In testing on a two-turn conversation where the second turn asked for
Fahrenheit, the checklist included that request and failed the answer
given in Celsius; a checklist generated from the first user message alone
can't see it.
**Doesn't catch reliably:** wrong facts. It failed an answer that invented the
weather only when the generated checklist happened to include a check against
the tool results. Pair it with a grounding check such as claim faithfulness.
## Step-based metric: weighted rubrics
**Use when** one criterion needs several checks and some matter more than
others, for example answer correctness where a wrong fact should fail the case
but a missing detail should only lower the score.
**Recipe:** the checklist scoring of the predefined rubric metrics (one verdict
per rubric, majority vote across samples, N/A rubrics left out), with weights,
must-pass rubrics and a threshold added. The judge sees only the rubrics; the
parser holds the weights, so the judge grades each rubric on its own.
```python
WEIGHTED_RUBRICS = """R1. Every fact in the final answer (numbers, conditions, dates) is stated in a tool result or follows directly from one.
R2. The final answer gives a direct recommendation for the decision the user asked about.
R3. The final answer is about the place and day the user asked about.
R4. The final answer states the temperature."""
# EDIT: the approved rubrics for this criterion, one per line with an id.
WEIGHTED_GRADE = """You grade an AI agent's conversation against a list of rubrics. Judge each rubric on its own.
# Conversation (user messages, tool calls, tool results, agent answers)
{agent_eval_data}
# Rubrics
""" + WEIGHTED_RUBRICS + """
For each rubric answer YES if the conversation meets it, NO if it does not, or NA if the rubric does
not apply to this conversation. Give one sentence of evidence quoted from the conversation.
Return only JSON:
{{"verdicts": [{{"id": "R1", "verdict": "YES|NO|NA", "evidence": "<quote or reason>"}}]}}
"""
WEIGHTED_PARSE = r'''
import collections, json
WEIGHTS = {"R1": 10, "R2": 5, "R3": 5, "R4": 2} # EDIT: HIGH 10, MEDIUM 5, LOW 2
MUST_PASS = {"R1"} # EDIT: a NO on any of these scores the case 0
THRESHOLD = 0.9 # EDIT: score needed to pass
def first_verdicts(text):
# Judges often wrap JSON in Markdown code fences or quote braces in explanations,
# so decode the first object that has "verdicts" instead of matching braces.
decoder = json.JSONDecoder()
for i, ch in enumerate(text):
if ch == "{":
try:
d, _ = decoder.raw_decode(text[i:])
except ValueError:
continue
if isinstance(d, dict) and "verdicts" in d:
return d["verdicts"]
return None
def parse_results(responses):
votes, evidence = collections.defaultdict(list), {}
for text in responses:
verdicts = first_verdicts(text)
if verdicts is None:
continue
for v in verdicts:
rid, verdict = str(v.get("id", "")).strip(), str(v.get("verdict", "")).upper()
if rid in WEIGHTS and verdict in ("YES", "NO", "NA"):
votes[rid].append(verdict)
evidence.setdefault((rid, verdict), v.get("evidence", ""))
if not votes:
raise ValueError("no parsable verdicts")
final = {r: collections.Counter(vs).most_common(1)[0][0] for r, vs in votes.items()}
scored = {r: v for r, v in final.items() if v != "NA"}
total = sum(WEIGHTS[r] for r in scored)
score = sum(WEIGHTS[r] for r, v in scored.items() if v == "YES") / total if total else 1.0
failed_must = sorted(r for r in MUST_PASS if final.get(r) == "NO")
if failed_must:
score = 0.0
notes = [f"{r}={final[r]}: {evidence.get((r, final[r]), '')}" for r in sorted(final)]
head = f"{'PASS' if score >= THRESHOLD else 'FAIL'} ({score:.2f})"
if failed_must:
head += f", must-pass failed: {', '.join(failed_must)}"
return {"score": score, "explanation": head + "; " + "; ".join(notes)}
'''
METRICS["answer_correctness"] = lambda: types.StepBasedLLMMetric(
name="answer_correctness",
steps=[{
"step_id": "grade",
"prompt_template": WEIGHTED_GRADE,
"autorater_config": {"autorater_model": JUDGE, "sampling_count": 3},
"response_parser_config": {"custom_code_parser_config": {"parsing_function": WEIGHTED_PARSE}},
}],
)
```
Run it with `scripts/run_metrics.py` like any other metric. Add the
preprocessor from the next template when traces are long.
- The score is the weight of passing rubrics divided by the weight of
applicable ones. A rubric missing from every sample counts as not
applicable, so check the explanation lists every rubric.
- Count a case as passing when the score reaches the threshold. Report the
threshold with the metric, since it decides the pass rate.
- In testing, a wrong-weather answer passed R2 to R4 and would have scored
0.55 without the must-pass rule; failing R1 set it to 0.
- For rubrics that differ per case, put them in each case's reference and read
them with `{reference}`; ask the judge to copy each rubric's importance into
its verdict, and weight by that in the parser.
**Doesn't catch:** anything outside the listed rubrics. Weights only rank what
the rubrics already check.
## Step-based metric: claim faithfulness
**Use when** the question is whether the agent's answer is supported by what its
tools returned, or when grading needs several stages.
**Recipe:** the Ragas faithfulness metric: split the answer into claims, check
each claim against the retrieved context, and score supported claims divided by
all claims. Here the context is the agent's tool results, and each stage is one
step: `claims` lists the claims, `verify` checks them, and a code parser
computes the score.
```python
PREPROCESS = r'''
def preprocess(agent_data):
keep = 20 # rows from the start and from the end of each tool result
turns = []
for t in agent_data.get("turns", []):
events = []
for e in t.get("events", []):
parts = []
for p in (e.get("content") or {}).get("parts", []):
if p.get("thought"):
continue
fr = p.get("function_response")
if fr:
r = dict(fr.get("response") or {})
rows = r.get("rows")
if isinstance(rows, list) and len(rows) > 2 * keep:
r["rows"] = rows[:keep] + rows[-keep:]
parts.append({"function_response": {"name": fr.get("name"), "response": r}})
elif p.get("function_call") or "text" in p:
parts.append(p)
if parts:
events.append({"author": e.get("author"), "content": {"role": (e.get("content") or {}).get("role"), "parts": parts}})
turns.append({"turn_index": t.get("turn_index"), "turn_id": t.get("turn_id"), "events": events})
return {"agents": agent_data.get("agents", {}), "turns": turns}
'''
CLAIMS = """List the factual claims in the agent's final answer to the user.
# Conversation (user messages, tool calls, tool results, agent answers)
{agent_eval_data}
A claim is one checkable statement of fact (a number, a date, a name, a condition). Split
sentences that state several facts. Skip advice, opinions, and restatements of the question.
Return only JSON: {{"claims": ["<claim>", ...]}}
"""
VERIFY = """Check each claim against the tool results in the conversation.
# Conversation (user messages, tool calls, tool results, agent answers)
{agent_eval_data}
# Claims from the agent's final answer
{step.claims.output}
A claim is SUPPORTED if a tool result states it or it follows directly from a tool result
(simple arithmetic and unit changes count). It is NOT supported if no tool result covers it or
a tool result contradicts it. Use only the tool results, not your own knowledge.
Return only JSON:
{{"verdicts": [{{"claim": "<claim>", "supported": true or false, "evidence": "<tool result or why not>"}}]}}
"""
FAITHFULNESS_PARSE = r'''
import json
def first_verdicts(text):
# Judges often wrap JSON in Markdown code fences or quote braces in explanations,
# so decode the first object that has "verdicts" instead of matching braces.
decoder = json.JSONDecoder()
for i, ch in enumerate(text):
if ch == "{":
try:
d, _ = decoder.raw_decode(text[i:])
except ValueError:
continue
if isinstance(d, dict) and "verdicts" in d:
return d["verdicts"]
return None
def parse_results(responses):
scores, notes = [], []
for text in responses:
verdicts = first_verdicts(text)
if verdicts is None:
continue
if not verdicts:
scores.append(1.0)
notes.append("no factual claims")
continue
ok = [v for v in verdicts if v.get("supported") is True]
scores.append(len(ok) / len(verdicts))
notes.append("; ".join(
f"{'SUPPORTED' if v.get('supported') is True else 'UNSUPPORTED'}: {v.get('claim')}"
for v in verdicts))
if not scores:
raise ValueError("no parsable verdicts")
return {"score": sum(scores) / len(scores), "explanation": notes[0]}
'''
METRICS["faithfulness"] = lambda: types.StepBasedLLMMetric(
name="faithfulness",
preprocessor={"code_config": {"code": PREPROCESS}},
steps=[
{"step_id": "claims", "prompt_template": CLAIMS,
"autorater_config": {"autorater_model": JUDGE, "sampling_count": 1}},
{"step_id": "verify", "prompt_template": VERIFY,
"autorater_config": {"autorater_model": JUDGE, "sampling_count": 1},
"response_parser_config": {"custom_code_parser_config": {"parsing_function": FAITHFULNESS_PARSE}}},
],
)
```
```shell
python3 scripts/run_metrics.py --cases cases.jsonl --metrics_file metrics.py \
--metrics faithfulness --project my-project --location global \
--out results/faithfulness_v1.json
```
How the parts fit:
- The preprocessor keeps what the judge needs and trims long tool results from
both ends.
- To grade one sub-agent, keep the user's messages, the hand-offs to it and
the events whose `author` is that agent. Keep the hand-offs: without them
the judge can't tell whether the agent was called at all. In `preprocess`,
filter each turn's events before anything else:
```python
AGENT = "my_sub_agent" # EDIT: the sub-agent to grade
def is_handoff(e):
parts = (e.get("content") or {}).get("parts") or [{}]
return (parts[0].get("function_call") or {}).get("name") == "transfer_to_agent"
events = [e for e in t.get("events", [])
if e.get("author") in ("user", AGENT) or is_handoff(e)]
```
Tell the judge what to do when the agent wasn't called (score 1, or NA in
a rubric), or it may fail those cases.
- An intermediate step needs no parser; the next step reads its raw output as
`{step.<step_id>.output}`.
- The last step's parser must return a number or
`{"score": ..., "explanation": ...}`. With `sampling_count` above 1 it
receives every sample; this one averages them.
**Doesn't catch:** answers that are true but don't do what was asked, or
mistakes in which tool was called.
**Other stage patterns:** generate evaluation steps first and then grade against
them (G-Eval); extract each turn's request and what it carries over, then judge
each turn (see [Multi-turn conversations](multi_turn.md)).
## Sources
- Berkeley Function Calling Leaderboard (BFCL), in the Gorilla project (Apache
2.0): https://github.com/ShishirPatil/gorilla
- MT-Bench and LLM-as-a-judge (Zheng et al., 2023,
https://arxiv.org/abs/2306.05685), judge prompts in FastChat (Apache 2.0):
https://github.com/lm-sys/FastChat/tree/main/fastchat/llm_judge
- TICK, "TICKing All the Boxes: Generated Checklists Improve LLM Evaluation
and Generation" (Cook et al., 2024): https://arxiv.org/abs/2410.03608
- Ragas faithfulness metric (Apache 2.0):
https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/faithfulness/
- G-Eval (Liu et al., 2023): https://arxiv.org/abs/2303.16634
Prompts here are written for this skill; they follow the methods above and don't
copy their text.
multi_turn.md 2.0 KB
# Multi-turn conversations
## Agree two policies before labeling
Ask the user, with a recommendation:
- **Carry-over:** "If a turn reuses an earlier turn's result instead of
recomputing it, is that correct?" Code metrics need this answer.
- **Mistakes carried forward:** "If a turn builds on an earlier wrong result,
does that turn fail too?" LLM checks need this answer.
Without these answers, labels and metrics disagree on turns that are really
policy questions.
## Grade per user turn
- One verdict per conversation can't be compared with per-turn labels. Use a
step-based metric that returns a verdict per turn, or split the dataset into
one case per turn (earlier turns condensed as context, only that turn's
reference). A step-based metric needs one call per conversation instead of
one per turn.
- Make turn identity explicit. Mark each user message (`[USER TURN k]`) in a
preprocessor and ask the judge to use that number. Line up the turn numbers
across samples before voting; otherwise the vote can mix verdicts of
different turns.
- Try one judge step first. A two-step spec (notes per turn, then judge) did
not do better in practice.
- Predefined rubric metrics given generated rubrics did not work well on long
conversations (parse failures, low agreement per turn). For per-case checks,
use the generated-checklists template, which writes checks from every user
turn, and trim long traces with a preprocessor.
## Look for two kinds of repeated failure
- An early mistake carried into later turns.
- The same mistake made fresh in each turn.
Both show up as several failing turns, but they need different fixes in the
agent.
## Check label consistency
Before tuning, check that the same situation is labeled the same way in
single-turn and multi-turn cases. If it isn't, no metric can match both; ask the
user which is right.
## Checking per-turn agreement
`scripts/agreement.py --turn_map metric=label_key` compares a per-turn label
list with per-turn verdicts parsed from the metric's explanation.
noise_and_agreement.md 1.2 KB
# Noise and agreement
## Measure noise first
LLM judges don't give the same verdict every time. With one judge sample, a few
verdicts in a set of 15 to 20 cases can flip between identical runs, which can
move agreement by over 10 points with no change at all.
- Before comparing two versions, run the current version twice.
- Treat differences of one or two cases as noise.
- Use 3 or more samples for the final check.
## Agreement
`scripts/agreement.py` compares metric scores with labels. A score and a label
agree when both are on the same side of the threshold. Use the metric's own
pass threshold everywhere: build the review page with it, and `agreement.py`
reads it from `labels.json` (default 0.5 only when the labels don't say). It
reports accuracy, Cohen's kappa (agreement corrected for chance), a confusion
table, results per pattern, and the list of disagreements.
## Label sets
When labels come from an existing autorater instead of people, keep two sets:
- the verdicts as given;
- a corrected set where the trajectory clearly contradicts a verdict, each
change with a written reason.
Report agreement against both, and list every case that still needs a human
decision. Agreement with another autorater is not agreement with people.
sdk_gotchas.md 2.7 KB
# SDK gotchas
## LLM metrics
- `LLMMetric` needs `judge_model` as a full resource name
(`projects/{project}/locations/{location}/publishers/google/models/{model}`).
- `LLMMetric` needs `responses` even when `agent_data` is set.
- Template variables `prompt`, `response`, `reference` and `agent_data` come
from the case. Other variables come from extra `EvalCase` attributes with
the same name, but only in inline runs: a registered metric run by name
sends none of them, so the judge gets an empty value.
- Judges sometimes return JSON that can't be parsed; rerun failed cases once.
## Code metrics
- Use `CodeExecutionMetric` (code runs in the service's sandbox) for any code
metric you hand over. A local callable (`types.Metric(custom_function=...)`)
errors with "No response found" on cases without `responses`, and
`create_evaluation_metric` rejects it as an unsupported metric type.
- `CodeExecutionMetric` must return a float.
- The remote sandbox gets the trajectory as `instance["agent_eval_data"]`; a
local callable gets `instance["agent_data"]`. Read both, or every remote
score is 0.0.
- `prompt`, `response` and `reference` arrive as `Content`-like dicts, not
strings.
## Rubric metrics
- Single-turn predefined metrics (for example `FINAL_RESPONSE_REFERENCE_FREE`)
reject multi-turn `agent_data` and grade only `response`. To grade a
trajectory with them, pass the rendered trajectory as `response` and drop
`agent_data`.
- Predefined rubric metrics use your rubrics when the case has one
`rubric_groups` entry. A custom `LLMMetric` with `rubric_group_name` puts
the rubrics in `{question_block}` and expects `STEP 1:` / `Property:` /
`Rationale:` / `Verdict: yes|no` blocks back; prefer the predefined metric.
- Predefined rubric metrics with your rubrics often fail on long inputs
("Rubric results could not be reliably computed").
- `return_raw_output` is rejected, so you can't see the raw judge output
through the SDK. In a step-based metric, put what you need in the
explanation the parser returns.
## Step-based metrics
- `types.StepBasedLLMMetric` needs `google-cloud-aiplatform` 2.8.0 or later.
- Prompt templates read the trace as `{agent_eval_data}`, not
`{agent_data}`.
- Code preprocessors define `preprocess(agent_data)` and return an AgentData
dict. Code parsers define `parse_results(responses)`.
- With `sampling_count` above 1, the parser gets every sample. Line up item
ids across samples before voting, and take the explanation from a sample
that agrees with the majority.
## Other
- `run_inference` overwrites existing responses; don't call it when the
trajectories already have them.
writing_checks.md 1.4 KB
# Writing LLM checks
- Write checks as yes/no statements, never scales ("every number in the answer
appears in a query result", not "rate accuracy 1-5"). Score 1 only if all
checks pass.
- Copy the label owner's definition when one exists: their checks, their
tolerated differences, and which source wins when two disagree. Matching the
owner's definition, and giving the judge the same evidence, are usually the
biggest gains.
- Give the judge the evidence the labels were made with. If labelers saw
golden result rows, the judge needs them too, not only the golden query.
- List tolerated differences explicitly: ordering, rounding, IDs vs names,
extra columns, and outputs of steps that change between runs (such as LLM
calls inside the agent).
- Judges tend to side with the agent when the request is ambiguous. A blanket
rule such as "treat the reference as the intended reading" fixes some cases
but fails correct answers over small differences. What holds up better: the
reference wins on facts (which table or column, the real date range) and on
outcomes it computed; small method choices the user did not specify are
tolerated.
- Ask for JSON output with the checks first and the score last, so the judge
reasons before it scores.
- Don't mix concepts that have separate labels in one check (for example tool
choice inside a "result is correct" check).
agreement.py 6.9 KB
#!/usr/bin/env python3
"""Computes agreement between metric scores and labels, overall and per pattern.
Inputs:
--labels JSON list of label records, one per case:
{"case": "id", "split": "dev", "patterns": ["P1"], "<label_key>": 1
| 0 | 0.4 | null, ...}
null means not applicable; those cases are skipped for that label.
--results One or more results JSON files shaped like
{"cases": {"<case>": {"<metric>": {"score": 0.8, "error": null,
"explanation": "..."}}}}
(run_eval-style output; later files override earlier ones per case
and metric).
--map metric=label_key pairs, e.g. routing_any_local=routing_provisional.
A score and a label agree when both are on the same side of the threshold
(score >= threshold means PASS). The threshold is --threshold if given, else
the "threshold" field the review page writes into labels.json, else 0.5.
Labels made on the review page are only valid at the page's threshold.
Fractional labels (per-turn rates in
multi-turn cases) also report the mean absolute difference.
Output (stdout, JSON): per metric: n, agree, accuracy, cohen_kappa, confusion
(label x prediction), errors, mean_abs_diff, per_pattern, disagreements.
Per-turn mode (multi-turn): --turn_map metric=per_turn_label_key compares a
label list ([1, 0, null, ...], one entry per user turn) with per-turn verdicts
parsed from the metric's explanation by --turn_regex (default matches
"turn 3: ... PASS" / "turn 3: FAIL"). Turns the metric did not report count as
missing, not as disagreements.
Example:
agreement.py --labels labels.json --results r1.json --map
data_v1=data_provisional --split dev
"""
import argparse
import json
import re
import sys
def kappa(tp, tn, fp, fn):
n = tp + tn + fp + fn
if not n:
return None
po = (tp + tn) / n
pe = ((tp + fp) * (tp + fn) + (tn + fn) * (tn + fp)) / (n * n)
return None if pe == 1 else round((po - pe) / (1 - pe), 3)
def main():
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument("--labels", required=True)
ap.add_argument("--results", required=True, nargs="+")
ap.add_argument("--map", default=[], nargs="*", help="metric=label_key")
ap.add_argument(
"--turn_map", default=[], nargs="*", help="metric=per_turn_label_key"
)
ap.add_argument("--turn_regex", default=r"turn (\d+)\b[^;]*?\b(PASS|FAIL)\b")
ap.add_argument(
"--threshold",
type=float,
default=None,
help="default: the labels' threshold field, else 0.5",
)
ap.add_argument(
"--split", default="", help="only cases with this split value"
)
ap.add_argument("--pattern_key", default="patterns")
a = ap.parse_args()
labels = {l["case"]: l for l in json.load(open(a.labels))}
if a.threshold is None:
found = {l["threshold"] for l in labels.values() if "threshold" in l}
if len(found) > 1:
sys.exit(
f"labels have different thresholds {sorted(found)}; pass --threshold"
)
a.threshold = found.pop() if found else 0.5
scores = {}
for path in a.results:
for case, per in json.load(open(path))["cases"].items():
scores.setdefault(case, {}).update(per)
report = {"threshold": a.threshold, "split": a.split or "all", "metrics": {}}
for pair in a.map:
metric, key = pair.split("=", 1)
tp = tn = fp = fn = errors = 0
diffs, dis, per_pattern = [], [], {}
for case, lab in labels.items():
if a.split and lab.get("split") != a.split:
continue
y = lab.get(key)
if y is None:
continue
res = scores.get(case, {}).get(metric)
if res is None:
continue
if res.get("error") or res.get("score") is None:
errors += 1
dis.append({
"case": case,
"label": y,
"score": None,
"error": str(res.get("error"))[:200],
})
continue
s = float(res["score"])
yb, sb = y >= a.threshold, s >= a.threshold
tp += yb and sb
tn += (not yb) and (not sb)
fp += (not yb) and sb
fn += yb and (not sb)
diffs.append(abs(s - y))
for p in lab.get(a.pattern_key) or ["(none)"]:
pp = per_pattern.setdefault(p, {"n": 0, "agree": 0})
pp["n"] += 1
pp["agree"] += yb == sb
if yb != sb:
dis.append({
"case": case,
"label": y,
"score": s,
"patterns": lab.get(a.pattern_key),
"explanation": (res.get("explanation") or "")[:300],
})
n = tp + tn + fp + fn
report["metrics"][metric] = {
"label_key": key,
"n": n,
"agree": tp + tn,
"accuracy": round((tp + tn) / n, 3) if n else None,
"cohen_kappa": kappa(tp, tn, fp, fn),
"confusion": {
"label_pass_pred_pass": tp,
"label_pass_pred_fail": fn,
"label_fail_pred_pass": fp,
"label_fail_pred_fail": tn,
},
"errors": errors,
"mean_abs_diff": round(sum(diffs) / len(diffs), 3) if diffs else None,
"per_pattern": per_pattern,
"disagreements": dis,
}
for pair in a.turn_map:
metric, key = pair.split("=", 1)
tp = tn = fp = fn = missing = shifted = 0
dis = []
for case, lab in labels.items():
if a.split and lab.get("split") != a.split:
continue
ys = lab.get(key)
res = scores.get(case, {}).get(metric)
if not ys or not res or res.get("error"):
continue
got = {
int(k): v.upper() == "PASS"
for k, v in re.findall(
a.turn_regex, res.get("explanation") or "", re.I
)
}
if (
got and min(got) == 1 and max(got) == len(ys)
): # judge numbered turns from 1
got = {k - 1: v for k, v in got.items()}
shifted += 1
for k, y in enumerate(ys):
if y is None:
continue
if k not in got:
missing += 1
continue
yb, sb = y >= a.threshold, got[k]
tp += yb and sb
tn += (not yb) and (not sb)
fp += (not yb) and sb
fn += yb and (not sb)
if yb != sb:
dis.append({
"case": case,
"turn": k,
"label": y,
"pred": "PASS" if sb else "FAIL",
})
n = tp + tn + fp + fn
report["metrics"][metric + " (per turn)"] = {
"label_key": key,
"n": n,
"agree": tp + tn,
"accuracy": round((tp + tn) / n, 3) if n else None,
"cohen_kappa": kappa(tp, tn, fp, fn),
"confusion": {
"label_pass_pred_pass": tp,
"label_pass_pred_fail": fn,
"label_fail_pred_pass": fp,
"label_fail_pred_fail": tn,
},
"missing_turns": missing,
"cases_renumbered_from_1": shifted,
"disagreements": dis,
}
json.dump(report, sys.stdout, indent=1)
print()
if __name__ == "__main__":
main()
build_review_page.py 10.2 KB
#!/usr/bin/env python3
r"""Builds one self-contained HTML page for the user to review metric grades.
For each case the page shows the user's note or rating (if any), each metric's
score, PASS/FAIL, explanation and per-rubric verdicts, and the trajectory with
tool results collapsed. The user marks each metric verdict Agree or Disagree,
with a reason, and downloads labels.json. Marks are kept in the browser's
local storage, so the page can be closed and reopened.
Inputs:
--cases JSONL of EvalCase-shaped dicts (eval_case_id, agent_data, and
optionally note / rating). Only these cases are shown, so leave
held-back cases out.
--results One or more results JSON files from run_metrics.py
({"cases": {"<id>": {"<metric>": {...}}}}).
--metrics Optional comma-separated metric names to show (default: all).
--baseline Optional comma-separated metric names shown as baseline, without
Agree/Disagree buttons.
Use the metric's own pass threshold for --threshold (for example THRESHOLD in
a weighted-rubrics parser), so PASS and FAIL on the page match the metric.
Output: --out HTML file. The downloaded labels.json is a list of
{"case", "split": "dev", "threshold", "<metric>": 1 | 0, "<metric>_reason"},
where the label is the metric's verdict at that threshold when the user agrees
and the opposite when they disagree. agreement.py reads the threshold from the
file, so pass it only --map <metric>=<metric>.
Example:
build_review_page.py --cases dev.jsonl --results results/v1.json \
--threshold 0.9 --out review_v1.html
"""
import argparse
import html
import json
import os
TOOL_MAX = 6000
def esc(x):
return html.escape(str(x))
def clip(t):
if len(t) <= TOOL_MAX:
return t
return (
t[: TOOL_MAX // 2]
+ f"\n… [{len(t) - TOOL_MAX} chars cut] …\n"
+ t[-TOOL_MAX // 2 :]
)
def get(d, *names):
for n in names:
if isinstance(d, dict) and d.get(n) is not None:
return d[n]
return None
def render_trajectory(agent_data):
"""Returns the trajectory as HTML, with tool results and thoughts collapsed."""
out = []
for i, turn in enumerate(get(agent_data, "turns") or []):
out.append(f'<div class="turn"><div class="th">Turn {i + 1}</div>')
for ev in get(turn, "events") or []:
au = esc(get(ev, "author") or "")
for p in (get(ev, "content") or {}).get("parts") or []:
fc = get(p, "function_call", "functionCall")
fr = get(p, "function_response", "functionResponse")
if fc:
args = clip(json.dumps(fc.get("args") or {}, ensure_ascii=False))
out.append(
f'<div class="call">{au} called <b>{esc(fc.get("name"))}'
f"</b> <code>{esc(args)}</code></div>"
)
elif fr:
body = clip(
json.dumps(fr.get("response") or {}, ensure_ascii=False, indent=1)
)
out.append(
f'<details class="res"><summary>{au}: result of '
f'{esc(fr.get("name"))} ({len(body)} chars)</summary>'
f"<pre>{esc(body)}</pre></details>"
)
elif p.get("thought"):
out.append(
f'<details class="res"><summary>{au}: thinking'
f'</summary><pre>{esc(p.get("text", ""))}</pre></details>'
)
elif p.get("text"):
cls = "user" if au == "user" else "ans"
out.append(
f'<div class="{cls}"><b>{au}</b><pre>{esc(p["text"])}</pre></div>'
)
out.append("</div>")
return "\n".join(out)
def render_rubrics(verdicts):
if not verdicts:
return ""
rows = []
for v in verdicts:
if isinstance(v, dict):
text = get(v, "rubric", "property", "text", "id") or ""
verdict = get(v, "verdict", "passed", "score")
rows.append(f"<li>{esc(verdict)}: {esc(text)}</li>")
else:
rows.append(f"<li>{esc(v)}</li>")
return f"<ul class=rub>{''.join(rows)}</ul>"
def main():
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument("--cases", required=True)
ap.add_argument("--results", required=True, nargs="+")
ap.add_argument("--metrics", default="")
ap.add_argument("--baseline", default="")
ap.add_argument(
"--threshold", type=float, default=0.5, help="score >= threshold is PASS"
)
ap.add_argument("--title", default="Metric review")
ap.add_argument("--out", required=True)
a = ap.parse_args()
cases = [json.loads(l) for l in open(a.cases) if l.strip()]
res = {}
for path in a.results:
for cid, ms in json.load(open(path)).get("cases", {}).items():
res.setdefault(cid, {}).update(ms)
baseline = [m for m in a.baseline.split(",") if m]
graded = set()
for ms in res.values():
graded.update(ms)
metrics = [m for m in a.metrics.split(",") if m] or sorted(
graded - set(baseline)
)
toc, body = [], []
for c in cases:
cid = str(c.get("eval_case_id"))
r = res.get(cid, {})
chips, blocks = [], []
for m in metrics + baseline:
x = r.get(m) or {}
score = x.get("score")
if x.get("error") or score is None:
verdict, cls = "ERROR", "err"
else:
verdict = "PASS" if score >= a.threshold else "FAIL"
cls = verdict.lower()
chips.append(f'<span class="chip {cls}">{esc(m)}: {verdict}</span>')
buttons = ""
if m in metrics and cls != "err":
pred = 1 if verdict == "PASS" else 0
key = esc(f"{cid}|{m}")
buttons = (
f'<div class="mark" data-key="{key}" data-pred="{pred}">'
f'<label><input type=radio name="{key}" value=agree> Agree</label>'
f'<label><input type=radio name="{key}" value=disagree> Disagree'
"</label><input class=why placeholder='Why? (needed when you "
"disagree)'></div>"
)
tag = " (baseline)" if m in baseline else ""
blocks.append(
f'<div class="metric {cls}"><b>{esc(m)}{tag}</b>: {verdict} '
"(score"
f' {esc(score)})<p>{esc(x.get("explanation") or x.get("error") or "")}'
f'</p>{render_rubrics(x.get("rubric_verdicts"))}{buttons}</div>'
)
note = " · ".join(
f"<b>{k}:</b> {esc(c[k])}" for k in ("rating", "note") if c.get(k)
)
toc.append(
f'<tr><td><a href="#{esc(cid)}">{esc(cid)}</a></td>'
f'<td>{"".join(chips)}</td><td class=done data-case="{esc(cid)}">'
"</td></tr>"
)
body.append(
f'<section id="{esc(cid)}"><h2>{esc(cid)}</h2>'
f'{f"<p>{note}</p>" if note else ""}{"".join(blocks)}'
"<details class=traj><summary>Trajectory</summary>"
f'{render_trajectory(c.get("agent_data") or {})}</details>'
'<p><a href="#top">Back to top</a></p></section>'
)
page = f"""<!doctype html><meta charset="utf-8"><title>{esc(a.title)}</title>
<style>
body{{font:14px/1.45 system-ui,sans-serif;max-width:1100px;margin:auto;padding:16px}}
pre{{white-space:pre-wrap;word-break:break-word;margin:4px 0}}
code{{font-size:12px;word-break:break-all}}
section{{border-top:2px solid #444;margin-top:28px}}
.turn{{border-left:3px solid #ccc;padding-left:10px;margin:10px 0}}
.th{{font-weight:bold;color:#555}} .user{{background:#eef4ff;padding:4px 8px}}
.ans{{background:#f1fff0;padding:4px 8px}} .call{{color:#7a4a00}} .res{{color:#555}}
.metric{{border:1px solid #ddd;padding:6px 10px;margin:8px 0}}
.pass{{background:#efe}} .fail{{background:#fee}} .err{{background:#eee}}
.chip{{display:inline-block;padding:1px 6px;margin:1px;border-radius:3px}}
.mark{{margin-top:6px}} .why{{width:60%;margin-left:8px}}
#bar{{position:sticky;top:0;background:#fff;padding:6px 0;border-bottom:1px solid #ccc}}
table td{{padding:2px 8px;vertical-align:top}}
</style><a id="top"></a><div id="bar"><b>{esc(a.title)}</b> ·
<span id="progress"></span> · <button id="dl">Download labels.json</button></div>
<p>For each metric verdict, choose Agree or Disagree, and say why when you
disagree. Your marks are saved in this browser. When you are done, download
labels.json and give it back.</p>
<table>{"".join(toc)}</table>{"".join(body)}
<script>
const KEY = "review:" + document.title + ":" + location.pathname;
const saved = JSON.parse(localStorage.getItem(KEY) || "{{}}");
const marks = [...document.querySelectorAll(".mark")];
function save() {{
const s = {{}};
let done = 0;
for (const m of marks) {{
const v = m.querySelector("input[type=radio]:checked");
const why = m.querySelector(".why").value;
if (v || why) s[m.dataset.key] = {{v: v ? v.value : null, why}};
if (v && (v.value === "agree" || why)) done++;
}}
localStorage.setItem(KEY, JSON.stringify(s));
document.getElementById("progress").textContent = done + " of " + marks.length + " verdicts marked";
for (const td of document.querySelectorAll("td.done")) {{
const mine = marks.filter(m => m.dataset.key.startsWith(td.dataset.case + "|"));
const ok = mine.filter(m => {{ const v = s[m.dataset.key]; return v && v.v && (v.v === "agree" || v.why); }});
td.textContent = mine.length && ok.length === mine.length ? "done" : "";
}}
return s;
}}
for (const m of marks) {{
const s = saved[m.dataset.key];
if (s) {{
if (s.v) m.querySelector(`input[value=${{s.v}}]`).checked = true;
m.querySelector(".why").value = s.why || "";
}}
m.addEventListener("input", save);
}}
document.getElementById("dl").onclick = () => {{
const s = save(), out = {{}};
for (const m of marks) {{
const v = s[m.dataset.key];
if (!v || !v.v) continue;
const [cid, metric] = m.dataset.key.split("|");
const pred = Number(m.dataset.pred);
const rec = out[cid] || (out[cid] = {{case: cid, split: "dev", threshold: {a.threshold}}});
rec[metric] = v.v === "agree" ? pred : 1 - pred;
rec[metric + "_reason"] = v.why;
}}
const blob = new Blob([JSON.stringify(Object.values(out), null, 1)], {{type: "application/json"}});
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = "labels.json";
a.click();
}};
save();
</script>"""
os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
open(a.out, "w").write(page)
print(
json.dumps({
"out": a.out,
"cases": len(cases),
"metrics": metrics,
"baseline": baseline,
"verdicts_to_mark": page.count('class="mark"'),
})
)
if __name__ == "__main__":
main()
render_agent_data.py 3.3 KB
#!/usr/bin/env python3
"""Renders AgentData trajectories as plain text for reading, labeling, or judging.
Input: JSONL where each line is an EvalCase-shaped dict with `agent_data`
(and optionally `eval_case_id`), or a bare AgentData dict ({"turns": [...]}).
Uses: read trajectories to find failure patterns; give labelers a readable
view; pass the text as a template variable (or as `response`) to metrics that
do not read agent_data themselves (single-turn predefined metrics, LLMMetric).
Output (stdout, JSON): {"cases": [{"id": ..., "chars": N, "text": "..."}]}
With --out_dir, also writes <id>.txt per case.
Example:
render_agent_data.py cases.jsonl --skip_thoughts --max_tool_chars 4000
"""
import argparse
import json
import os
import sys
def get(d, *names):
for n in names:
if isinstance(d, dict) and d.get(n) is not None:
return d[n]
return None
def render(agent_data, skip_thoughts, max_tool_chars):
"""Returns AgentData as readable text, one block per turn."""
lines = []
for i, turn in enumerate(get(agent_data, "turns") or []):
tid = get(turn, "turn_id", "turnId")
lines.append(
"--- Turn"
f" {get(turn, 'turn_index', 'turnIndex') if get(turn, 'turn_index', 'turnIndex') is not None else i}"
+ (f" ({tid})" if tid else "")
+ " ---"
)
for e in get(turn, "events") or []:
author = get(e, "author") or "?"
for p in (get(e, "content") or {}).get("parts") or []:
if p.get("thought"):
if not skip_thoughts:
lines.append(f"{author} (thought): {p.get('text', '')}")
continue
fc = get(p, "function_call", "functionCall")
fr = get(p, "function_response", "functionResponse")
if fc:
lines.append(
f"{author} CALL {fc.get('name')}: "
+ json.dumps(fc.get("args"), ensure_ascii=False)
)
elif fr:
body = json.dumps(fr.get("response"), ensure_ascii=False, default=str)
if len(body) > max_tool_chars:
body = (
body[:max_tool_chars]
+ f"... [{len(body) - max_tool_chars} chars cut]"
)
lines.append(f"{author} RESULT {fr.get('name')}: {body}")
elif "text" in p:
lines.append(f"{author}: {p['text']}")
return "\n".join(lines)
def main():
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument("inp", help="JSONL of eval cases or AgentData dicts")
ap.add_argument("--skip_thoughts", action="store_true")
ap.add_argument("--max_tool_chars", type=int, default=4000)
ap.add_argument("--out_dir", default="")
a = ap.parse_args()
out = []
with open(a.inp) as f:
for n, line in enumerate(f):
if not line.strip():
continue
rec = json.loads(line)
ad = rec.get("agent_data") or rec.get("agent_eval_data") or rec
cid = rec.get("eval_case_id") or f"case_{n}"
text = render(ad, a.skip_thoughts, a.max_tool_chars)
out.append({"id": cid, "chars": len(text), "text": text})
if a.out_dir:
os.makedirs(a.out_dir, exist_ok=True)
with open(os.path.join(a.out_dir, f"{cid}.txt"), "w") as o:
o.write(text)
json.dump({"cases": out}, sys.stdout, ensure_ascii=False)
print()
if __name__ == "__main__":
main()
run_metrics.py 6.3 KB
#!/usr/bin/env python3
r"""Runs SDK metrics on eval cases with client.evals.evaluate() and saves per-case results.
Inputs:
--cases JSONL; each line is an EvalCase-shaped dict (eval_case_id,
prompt, responses, reference, agent_data, plus any extra
attributes your code metrics or --trajectory_response use,
such as trajectory).
--metrics_file Python file defining METRICS = {"name": callable}; each
callable returns an SDK metric (see
references/metric_templates.md).
--metrics Comma-separated names from METRICS to run.
--rubrics Optional JSON {"<case id>": [rubric, ...]}, for example the
user's existing rubrics; attached as
rubric_groups[--rubric_group] for predefined rubric metrics.
--trajectory_response Put the case's `trajectory` text in `responses` and
drop `agent_data`, for metrics that grade only the response.
Output: --out JSON {"cases": {"<id>": {"<metric>": {"score", "explanation",
"error", "rubric_verdicts"}}}}, which agreement.py reads. A one-line JSON
summary goes to stdout.
Example:
run_metrics.py --cases cases.jsonl --metrics_file my_metrics.py \
--metrics tool_match,answer_checks --project my-project --location us-central1 \
--out results/v1.json
"""
import argparse
import importlib.util
import json
import os
import sys
import time
import agentplatform
from agentplatform import types
def load_metrics(path, names):
spec = importlib.util.spec_from_file_location("user_metrics", path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
missing = [n for n in names if n not in mod.METRICS]
if missing:
sys.exit(f"unknown metrics {missing}; METRICS has {sorted(mod.METRICS)}")
return [mod.METRICS[n]() for n in names]
def load_cases(path, ids, rubrics, rubric_group, trajectory_response):
"""Reads EvalCase dicts from JSONL, applying rubrics and response options."""
cases = []
for line in open(path):
if not line.strip():
continue
c = json.loads(line)
if ids and c["eval_case_id"] not in ids:
continue
if trajectory_response:
c["responses"] = [
{"response": {"role": "model", "parts": [{"text": c["trajectory"]}]}}
]
c.pop("agent_data", None)
if c["eval_case_id"] in rubrics:
c["rubric_groups"] = {
rubric_group: {"rubrics": rubrics[c["eval_case_id"]]}
}
cases.append(types.EvalCase(**c))
return cases
def collect(cases, result, names):
"""Returns {case id: {metric: result dict}} from an EvaluationResult."""
# The SDK omits cases that produced no result, so match on eval_case_index.
by_index = {r.eval_case_index: r for r in result.eval_case_results or []}
missing = {
"score": None,
"explanation": None,
"error": "no result returned for this case",
"rubric_verdicts": [],
}
out = {}
for i, case in enumerate(cases):
res = by_index.get(i)
per = {}
for cand in (res.response_candidate_results if res else None) or []:
for name, mr in (cand.metric_results or {}).items():
verdicts = []
for v in mr.rubric_verdicts or []:
rubric = v.evaluated_rubric
prop = rubric.content.property if rubric and rubric.content else None
verdicts.append({
"rubric": prop.description if prop else None,
"verdict": v.verdict,
"reasoning": v.reasoning,
})
per[name] = {
"score": mr.score,
"explanation": mr.explanation,
"error": mr.error_message,
"rubric_verdicts": verdicts,
}
if not per:
per = {name: dict(missing) for name in names}
out[case.eval_case_id] = per
return out
def main():
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument("--cases", required=True)
ap.add_argument("--metrics_file", required=True)
ap.add_argument("--metrics", required=True)
ap.add_argument("--project", required=True)
ap.add_argument("--location", default="us-central1")
ap.add_argument("--out", required=True)
ap.add_argument("--ids", default="", help="comma-separated case ids to run")
ap.add_argument("--rubrics", default="")
ap.add_argument("--rubric_group", default="custom_rubrics")
ap.add_argument("--trajectory_response", action="store_true")
ap.add_argument(
"--retry_errors", action="store_true", help="rerun failed cases once"
)
a = ap.parse_args()
names = [n for n in a.metrics.split(",") if n]
metrics = load_metrics(a.metrics_file, names)
rubrics = json.load(open(a.rubrics)) if a.rubrics else {}
ids = set(filter(None, a.ids.split(",")))
cases = load_cases(
a.cases, ids, rubrics, a.rubric_group, a.trajectory_response
)
client = agentplatform.Client(project=a.project, location=a.location)
t0 = time.time()
result = client.evals.evaluate(
dataset=types.EvaluationDataset(eval_cases=cases),
metrics=metrics,
config={"allow_cross_region_model": True},
)
result_names = [getattr(m, "name", None) or n for m, n in zip(metrics, names)]
per_case = collect(cases, result, result_names)
if a.retry_errors:
failed = [
c
for c in cases
if any(m["error"] for m in per_case[c.eval_case_id].values())
]
if failed:
again = client.evals.evaluate(
dataset=types.EvaluationDataset(eval_cases=failed),
metrics=metrics,
config={"allow_cross_region_model": True},
)
for cid, per in collect(failed, again, result_names).items():
for name, m in per.items():
if per_case[cid].get(name, {}).get("error") and not m["error"]:
per_case[cid][name] = dict(m, retried=True)
out = {
"metrics": names,
"seconds": round(time.time() - t0, 1),
"cases": per_case,
}
os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
json.dump(out, open(a.out, "w"), indent=1, default=str)
errors = 0
for per in per_case.values():
errors += sum(1 for m in per.values() if m["error"])
json.dump(
{
"out": a.out,
"cases": len(cases),
"errors": errors,
"seconds": out["seconds"],
},
sys.stdout,
)
print()
if __name__ == "__main__":
main()
License (Apache-2.0)
View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/google/skills/blob/main/LICENSE