mirror of
https://github.com/block/buzz.git
synced 2026-11-30 05:02:57 +00:00
bench: emit submittable trajectories and parse current usage
Co-authored-by: Codex <noreply@openai.com> Signed-off-by: Atish Patel <atishpatel2012@gmail.com>
This commit is contained in:
@@ -84,8 +84,11 @@ _ANSI_RE = re.compile(r"\x1b\[[0-9;]*[a-zA-Z]")
|
||||
# fields) degrades to "no samples" rather than a wrong number.
|
||||
USAGE_MARKER = "goose usage update"
|
||||
_SESSION_RE = re.compile(r"\bsession_id=(\S+)")
|
||||
_INPUT_RE = re.compile(r"\binput=(\d+)\b")
|
||||
_OUTPUT_RE = re.compile(r"\boutput=(\d+)\b")
|
||||
# ACP serializes optional counters as ``Some(123)`` in current builds and older
|
||||
# builds emitted bare ``123``. Accept both so an instrumentation formatting
|
||||
# change cannot silently turn a paid trial into a zero-token result.
|
||||
_INPUT_RE = re.compile(r"\binput=(?:Some\()?(\d+)\)?\b")
|
||||
_OUTPUT_RE = re.compile(r"\boutput=(?:Some\()?(\d+)\)?\b")
|
||||
# The cache-served subset of `input`, added to the usage line by buzz-acp. Absent
|
||||
# in logs written by an agent build that predates it, which is why a missing
|
||||
# field must read as "unknown" (fall back to the modelled rate) and never as 0 —
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from harbor.agents.base import BaseAgent
|
||||
from harbor.environments.base import BaseEnvironment
|
||||
from harbor.models.agent.context import AgentContext
|
||||
from harbor.models.trajectories import Agent, FinalMetrics, Step, Trajectory
|
||||
from harbor.utils.trajectory_utils import format_trajectory_json
|
||||
|
||||
from .container_runtime import BuzzContainerRuntime, EndpointLaunchConfig
|
||||
from .manifest import ExperimentManifest
|
||||
@@ -18,8 +22,7 @@ from .runtime import OrchestraRuntime
|
||||
class BuzzOrchestraAgent(BaseAgent):
|
||||
"""Coordinate an arbitrary manifest-defined team through a Buzz trial."""
|
||||
|
||||
# Set True only once the runtime writes a validated agent/trajectory.json.
|
||||
SUPPORTS_ATIF = False
|
||||
SUPPORTS_ATIF = True
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -77,6 +80,94 @@ class BuzzOrchestraAgent(BaseAgent):
|
||||
def version(self) -> str:
|
||||
return "0.1.0"
|
||||
|
||||
def _write_trajectory(
|
||||
self,
|
||||
*,
|
||||
instruction: str,
|
||||
trial_id: str,
|
||||
result: Any,
|
||||
) -> None:
|
||||
"""Write the ATIF artifact required by Harbor leaderboard submissions.
|
||||
|
||||
Buzz is a composite runtime, so its canonical cross-agent record is the
|
||||
relay transcript. Detailed ACP streaming and tool events remain beside
|
||||
it in ``buzz/<agent>.stdout.log``; the ATIF file captures the complete
|
||||
user/agent message history without inventing tool outputs that Buzz does
|
||||
not currently persist in a structured form.
|
||||
"""
|
||||
transcript_path = self.logs_dir / "buzz" / "transcript.json"
|
||||
messages: list[dict[str, Any]] = []
|
||||
if transcript_path.is_file():
|
||||
payload = json.loads(transcript_path.read_text(encoding="utf-8"))
|
||||
raw_messages = payload.get("messages", [])
|
||||
if isinstance(raw_messages, list):
|
||||
messages = [
|
||||
message for message in raw_messages if isinstance(message, dict)
|
||||
]
|
||||
|
||||
steps: list[Step] = []
|
||||
for message in messages:
|
||||
content = message.get("content")
|
||||
if not isinstance(content, str):
|
||||
continue
|
||||
author = str(message.get("author") or "unknown")
|
||||
created_at = message.get("created_at")
|
||||
timestamp = None
|
||||
if isinstance(created_at, (int, float)):
|
||||
timestamp = (
|
||||
datetime.fromtimestamp(created_at, UTC)
|
||||
.isoformat()
|
||||
.replace("+00:00", "Z")
|
||||
)
|
||||
steps.append(
|
||||
Step(
|
||||
step_id=len(steps) + 1,
|
||||
timestamp=timestamp,
|
||||
source="user" if author == "user" else "agent",
|
||||
message=content,
|
||||
extra={"buzz_author": author},
|
||||
)
|
||||
)
|
||||
|
||||
if not steps:
|
||||
steps.append(Step(step_id=1, source="user", message=instruction))
|
||||
completion = result.metadata.get("completion_message")
|
||||
if isinstance(completion, str) and completion:
|
||||
steps.append(Step(step_id=2, source="agent", message=completion))
|
||||
|
||||
model_revisions = sorted(
|
||||
{entry.model_revision or entry.endpoint for entry in self.manifest.roster}
|
||||
)
|
||||
trajectory = Trajectory(
|
||||
schema_version="ATIF-v1.7",
|
||||
session_id=trial_id,
|
||||
agent=Agent(
|
||||
name=self.name(),
|
||||
version=self.version(),
|
||||
model_name=model_revisions[0] if len(model_revisions) == 1 else None,
|
||||
extra={
|
||||
"condition": self.manifest.condition,
|
||||
"model_revisions": model_revisions,
|
||||
},
|
||||
),
|
||||
steps=steps,
|
||||
notes=(
|
||||
"Composite Buzz relay transcript. Detailed ACP streaming and tool "
|
||||
"events are preserved in buzz/<agent>.stdout.log."
|
||||
),
|
||||
final_metrics=FinalMetrics(
|
||||
total_prompt_tokens=result.input_tokens,
|
||||
total_cached_tokens=result.cached_input_tokens,
|
||||
total_completion_tokens=result.output_tokens,
|
||||
total_cost_usd=result.cost_usd,
|
||||
total_steps=len(steps),
|
||||
),
|
||||
)
|
||||
(self.logs_dir / "trajectory.json").write_text(
|
||||
format_trajectory_json(trajectory.to_json_dict()) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _load_mapping(
|
||||
source: str | Path | dict[str, Any] | None,
|
||||
@@ -211,6 +302,12 @@ class BuzzOrchestraAgent(BaseAgent):
|
||||
finally:
|
||||
self.provisioner.teardown(handle)
|
||||
|
||||
self._write_trajectory(
|
||||
instruction=instruction,
|
||||
trial_id=trial_id,
|
||||
result=result,
|
||||
)
|
||||
|
||||
context.n_input_tokens = result.input_tokens
|
||||
context.n_cache_tokens = result.cached_input_tokens
|
||||
context.n_output_tokens = result.output_tokens
|
||||
|
||||
@@ -64,6 +64,16 @@ def test_parse_usage_log_reads_the_coloured_lines_a_real_trial_produces():
|
||||
)
|
||||
|
||||
|
||||
def test_parse_usage_log_reads_current_optional_counter_format():
|
||||
text = (
|
||||
"2026-08-20T20:37:07Z DEBUG acp::usage: goose usage update "
|
||||
"session_id=ses-current input=Some(7474) output=Some(701) cached=4608"
|
||||
)
|
||||
assert accounting.parse_usage_log(text) == (
|
||||
accounting.SessionUsage("ses-current", 7474, 701, 4608),
|
||||
)
|
||||
|
||||
|
||||
def test_parse_handoffs_reads_coloured_lines_too():
|
||||
"""Same formatter, same escapes — the compaction bound must not silently zero."""
|
||||
text = (
|
||||
@@ -370,9 +380,7 @@ def test_collect_keeps_the_handoff_bound_out_of_the_metered_cost(
|
||||
assert "floor" in result.reconciliation_note
|
||||
|
||||
|
||||
def test_collect_warns_when_an_agent_truncated_its_own_history(
|
||||
tmp_path, solo_manifest
|
||||
):
|
||||
def test_collect_warns_when_an_agent_truncated_its_own_history(tmp_path, solo_manifest):
|
||||
write_log(
|
||||
tmp_path,
|
||||
"opus-orchestrator-1",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
|
||||
@@ -101,6 +102,47 @@ async def test_agent_lifecycle_and_context(tmp_path, manifest_data):
|
||||
) == (10, 2, 3, 0.25)
|
||||
assert context.metadata["manifest_sha256"] == agent.manifest.sha256
|
||||
assert context.metadata["trial_id"] == str(context_id)
|
||||
assert agent.SUPPORTS_ATIF is True
|
||||
trajectory = json.loads((tmp_path / "trajectory.json").read_text())
|
||||
assert trajectory["schema_version"] == "ATIF-v1.7"
|
||||
assert trajectory["session_id"] == str(context_id)
|
||||
assert trajectory["steps"] == [
|
||||
{"step_id": 1, "source": "user", "message": "solve it"}
|
||||
]
|
||||
assert trajectory["final_metrics"]["total_prompt_tokens"] == 10
|
||||
assert trajectory["final_metrics"]["total_cached_tokens"] == 2
|
||||
assert trajectory["final_metrics"]["total_completion_tokens"] == 3
|
||||
|
||||
|
||||
async def test_agent_trajectory_uses_the_relay_transcript(tmp_path, manifest_data):
|
||||
transcript_dir = tmp_path / "buzz"
|
||||
transcript_dir.mkdir()
|
||||
(transcript_dir / "transcript.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"messages": [
|
||||
{"author": "user", "content": "@meli solve it", "created_at": 1},
|
||||
{"author": "meli", "content": "done", "created_at": 2},
|
||||
]
|
||||
}
|
||||
)
|
||||
)
|
||||
provisioner, runtime, context_id = Provisioner(), Runtime(), uuid4()
|
||||
agent = BuzzOrchestraAgent(
|
||||
logs_dir=tmp_path,
|
||||
manifest=manifest_data,
|
||||
provisioner=provisioner,
|
||||
runtime=runtime,
|
||||
)
|
||||
agent.context_id = context_id
|
||||
await agent.run("solve it", SimpleNamespace(context_id=context_id), AgentContext())
|
||||
|
||||
trajectory = json.loads((tmp_path / "trajectory.json").read_text())
|
||||
assert [step["source"] for step in trajectory["steps"]] == ["user", "agent"]
|
||||
assert [step["message"] for step in trajectory["steps"]] == [
|
||||
"@meli solve it",
|
||||
"done",
|
||||
]
|
||||
|
||||
|
||||
async def test_teardown_runs_when_runtime_fails(tmp_path, manifest_data):
|
||||
|
||||
Reference in New Issue
Block a user