Files
aji/tools/eval/ajieval/context.py
T

212 lines
9.1 KiB
Python

"""Context metrics (protocol §16), the same for both tracks.
provider_input_tokens what the model provider counted: input,
cached and uncached separately
cumulative_context_tokens the text returned to the agent through its
tool loop (every tool output, plus the task
message), counted each time it was returned
unique_reference_tokens the distinct documentation text the agent
actually saw: distinct lines in the outputs
of tool calls that touched /docs
reference_coverage for a single-file reference (the Aji Agent
Reference Bundle): the fraction of its
non-empty lines that appeared in those outputs
docs for a directory of documentation (the Source
Reference Bundle), per file and per group of
the profile's `doc_groups`:
<group>_tokens size of the group (e.g. quick_reference_tokens,
source_docs_tokens, air_docs_tokens)
full_source_docs_tokens every group except air_docs
read_tokens_by_group tokens of the group's lines the agent saw
coverage_by_section per file: fraction of its distinctive lines
(in no other file of the mount) seen
files_opened files named in a tool input: by /docs path, by
path relative to /docs, or by file name as a
whole token (`cd /docs/language; cat syntax.md`)
unique_docs_read how many files were opened
The gap between them shows where context is amplified: rereading the same
documentation, verbose tool output, or the provider resending history.
Tokens are counted with tiktoken `cl100k_base` when it is installed,
otherwise estimated as bytes / 4; the record says which.
"""
import json
import os
import re
from . import util
_PREFIX = re.compile(r"^\s*\d+\s*[:\t→│|]\s?")
# grep/ripgrep output and the agents' grep tools: `path:12:text`, context
# lines `path-12-text`, and `path:text` when several files are searched.
_GREP = re.compile(r"^(?:/docs/\S+?|\S+\.md)(?::\d+[:-]|-\d+-|:)")
def _tokenizer():
try:
import tiktoken
enc = tiktoken.get_encoding("cl100k_base")
return "cl100k_base", lambda s: len(enc.encode(s, disallowed_special=()))
except Exception:
return "estimate(bytes/4)", lambda s: util.estimate_tokens(len(s.encode()))
def _norm(line):
return _PREFIX.sub("", _GREP.sub("", line, count=1)).strip()
def tool_events_track_a(events_path):
"""(input text, output text) per tool call from a Track A event log."""
out = []
for line in open(events_path, encoding="utf-8"):
e = json.loads(line)
if e["event"] == "command":
out.append((e["command"], e.get("output") or ""))
elif e["event"] == "tool" and e["name"] != "run":
out.append((json.dumps(e.get("input")), e.get("output") or ""))
return out
def tool_events_native(agent_name, transcript_path):
"""(input text, output text) per tool call from a native CLI transcript."""
out = []
pending = {}
for line in open(transcript_path, encoding="utf-8", errors="replace"):
line = line.strip()
if not line.startswith("{"):
continue
try:
e = json.loads(line)
except json.JSONDecodeError:
continue
if agent_name == "codex":
item = e.get("item") or {}
if e.get("type") == "item.completed" and item.get("type") == "command_execution":
out.append((item.get("command") or "", item.get("aggregated_output") or ""))
elif agent_name == "claude":
msg = e.get("message") or {}
for b in msg.get("content", []) if isinstance(msg.get("content"), list) else []:
if b.get("type") == "tool_use":
pending[b.get("id")] = json.dumps(b.get("input"))
elif b.get("type") == "tool_result":
c = b.get("content")
text = c if isinstance(c, str) else "\n".join(x.get("text", "") for x in (c or []) if isinstance(x, dict))
out.append((pending.pop(b.get("tool_use_id"), ""), text))
elif agent_name == "opencode":
part = e.get("part") or {}
if e.get("type") == "tool_use":
st = part.get("state") or {}
out.append((json.dumps(st.get("input")), st.get("output") or ""))
return out
def _doc_files(docs):
"""[(path under /docs, host path)] of every file in the mounts."""
out = []
for name, p in docs:
if os.path.isfile(p):
out.append((name or os.path.basename(p), p))
continue
for d, _, files in os.walk(p):
for f in sorted(files):
hp = os.path.join(d, f)
rel = os.path.relpath(hp, p)
out.append((os.path.join(name, rel) if name else rel, hp))
return sorted(out)
def _named(rel, inputs):
"""Whether a tool input names the file: `/docs/<rel>`, `<rel>`, or its
file name as a whole token."""
for name in {rel, os.path.basename(rel)}:
if re.search(r"(?<![\w.-])" + re.escape(name) + r"(?![\w.-])", inputs):
return True
return False
def _group_of(rel, groups):
for g, prefixes in groups.items():
for pre in prefixes:
if rel == pre or (pre.endswith("/") and rel.startswith(pre)):
return g
return "other"
def doc_metrics(tool_events, docs, groups, seen, count):
"""Per-file and per-group reading of a documentation directory.
Only distinctive lines count: a line contributes to a file's coverage
only if no other file in the mount contains it, and to a group's read
tokens only if every file containing it is in that group. Table rules,
fences and sections copied into several files (the error-code table is
in diagnostics/ and in air/) would otherwise be credited to files the
agent never opened."""
files = _doc_files(docs)
inputs = "\n".join(i for i, _ in tool_events)
texts, owners = {}, {}
for rel, hp in files:
with open(hp, encoding="utf-8", errors="replace") as f:
texts[rel] = f.read()
for x in {_norm(x) for x in texts[rel].splitlines() if _norm(x)}:
owners.setdefault(x, set()).add(rel)
own = {}
for x, fs in owners.items():
if len(fs) == 1:
own.setdefault(next(iter(fs)), set()).add(x)
coverage, opened, size, read_lines = {}, [], {}, {}
for rel, _ in files:
mine = own.get(rel, set())
coverage[rel] = round(len(mine & seen) / len(mine), 4) if mine else 0.0
if _named(rel, inputs):
opened.append(rel)
g = _group_of(rel, groups)
size[g] = size.get(g, 0) + count(texts[rel])
read_lines.setdefault(g, set())
for x in seen:
gs = {_group_of(f, groups) for f in owners.get(x, ())}
if len(gs) == 1:
read_lines[gs.pop()].add(x)
out = {f"{g}_tokens": n for g, n in sorted(size.items())}
out["full_source_docs_tokens"] = sum(n for g, n in size.items() if g != "air_docs")
out["read_tokens_by_group"] = {g: (count("\n".join(sorted(ls))) if ls else 0) for g, ls in sorted(read_lines.items())}
out["coverage_by_section"] = coverage
out["files_opened"] = opened
out["unique_docs_read"] = len(opened)
return out
def metrics(tool_events, task_message, docs, provider, groups=None):
"""`docs` is [(mount name, host path)]; `provider` holds input, output,
cached_input as counted by the provider (None when unknown); `groups` is
the profile's `doc_groups` ({name: [file or "dir/" prefix]})."""
name, count = _tokenizer()
cumulative = count(task_message) + sum(count(o) for _, o in tool_events)
seen = set()
for inp, outp in tool_events:
if "/docs" in inp:
for line in outp.splitlines():
n = _norm(line)
if n:
seen.add(n)
unique = count("\n".join(sorted(seen)))
coverage = None
files = [p for _, p in docs if os.path.isfile(p)]
if len(files) == 1 and len(docs) == 1:
with open(files[0], encoding="utf-8", errors="replace") as f:
ref = {_norm(x) for x in f.read().splitlines() if _norm(x)}
coverage = round(len(ref & seen) / len(ref), 4) if ref else None
inp, cached = provider.get("input"), provider.get("cached_input")
dirs = [p for _, p in docs if os.path.isdir(p)]
extra = {"docs": doc_metrics(tool_events, docs, groups or {}, seen, count)} if dirs else {}
return {
"tokenizer": name,
"provider_input_tokens": {"total": inp, "cached": cached, "uncached": None if inp is None or cached is None else inp - cached, "output": provider.get("output")},
"cumulative_context_tokens": cumulative,
"unique_reference_tokens": unique,
"reference_coverage": coverage,
"tool_outputs": len(tool_events),
**extra,
}