agentenv-framework 0.9.1254__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_env/__init__.py +0 -0
- agent_env/a2a_agent/__init__.py +23 -0
- agent_env/a2a_agent/a2a_agent.py +600 -0
- agent_env/a2a_agent/conversation_store.py +356 -0
- agent_env/a2a_agent/object_transfer.py +609 -0
- agent_env/a2a_agent/protocol.py +238 -0
- agent_env/a2a_agent/store.py +201 -0
- agent_env/a2a_agent/validator.py +901 -0
- agent_env/artifact/__init__.py +48 -0
- agent_env/artifact/artifact.py +74 -0
- agent_env/artifact/artifacts/__init__.py +0 -0
- agent_env/artifact/artifacts/cli.py +83 -0
- agent_env/artifact/artifacts/docker_image.py +457 -0
- agent_env/artifact/artifacts/environment.py +89 -0
- agent_env/artifact/artifacts/environment_universe.py +156 -0
- agent_env/artifact/artifacts/file.py +214 -0
- agent_env/artifact/artifacts/file_artifact_universe.py +206 -0
- agent_env/artifact/artifacts/skill.py +206 -0
- agent_env/artifact/artifacts/vm_image.py +95 -0
- agent_env/artifact/ref.py +15 -0
- agent_env/artifact/registry.py +251 -0
- agent_env/artifact/store.py +295 -0
- agent_env/artifact/universe.py +38 -0
- agent_env/attribution.py +41 -0
- agent_env/bundle/__init__.py +4 -0
- agent_env/bundle/_fs.py +128 -0
- agent_env/bundle/authoring.py +239 -0
- agent_env/bundle/installed.py +175 -0
- agent_env/bundle/ledger.py +269 -0
- agent_env/bundle/materialize.py +204 -0
- agent_env/bundle/parse.py +594 -0
- agent_env/bundle/plan.py +414 -0
- agent_env/bundle/resolve.py +404 -0
- agent_env/bundle/run.py +361 -0
- agent_env/cli/__init__.py +69 -0
- agent_env/cli/__main__.py +10 -0
- agent_env/cli/_installers.py +576 -0
- agent_env/cli/_plugin_changes.py +947 -0
- agent_env/cli/a2a_agent/__init__.py +22 -0
- agent_env/cli/a2a_agent/add_skill.py +97 -0
- agent_env/cli/a2a_agent/deploy.py +60 -0
- agent_env/cli/a2a_agent/get.py +15 -0
- agent_env/cli/a2a_agent/get_instance.py +26 -0
- agent_env/cli/a2a_agent/put.py +78 -0
- agent_env/cli/a2a_agent/validate.py +56 -0
- agent_env/cli/artifact/__init__.py +20 -0
- agent_env/cli/artifact/cli.py +83 -0
- agent_env/cli/artifact/environment.py +44 -0
- agent_env/cli/artifact/environment_universe.py +163 -0
- agent_env/cli/artifact/file_artifact_universe.py +281 -0
- agent_env/cli/artifact/skill.py +128 -0
- agent_env/cli/banner.py +25 -0
- agent_env/cli/config.py +263 -0
- agent_env/cli/env/__init__.py +31 -0
- agent_env/cli/env/deploy.py +112 -0
- agent_env/cli/env/gateway.py +57 -0
- agent_env/cli/env/get_instance.py +40 -0
- agent_env/cli/env/mcp_server.py +410 -0
- agent_env/cli/env/multi.py +282 -0
- agent_env/cli/env/service_db.py +99 -0
- agent_env/cli/env/snapshot.py +35 -0
- agent_env/cli/env/state/__init__.py +6 -0
- agent_env/cli/env/state/init.py +108 -0
- agent_env/cli/env/state/teardown.py +44 -0
- agent_env/cli/env/website.py +216 -0
- agent_env/cli/env/website_browser.py +67 -0
- agent_env/cli/eval/__init__.py +16 -0
- agent_env/cli/eval/add_tasks.py +63 -0
- agent_env/cli/eval/create.py +49 -0
- agent_env/cli/eval/run.py +194 -0
- agent_env/cli/identity/__init__.py +5 -0
- agent_env/cli/identity/client_identity.py +37 -0
- agent_env/cli/plugin.py +438 -0
- agent_env/cli/run.py +285 -0
- agent_env/cli/task/__init__.py +21 -0
- agent_env/cli/task/create.py +109 -0
- agent_env/cli/task/get.py +17 -0
- agent_env/cli/task/get_instance.py +34 -0
- agent_env/cli/task/run.py +615 -0
- agent_env/cli/task/validate.py +31 -0
- agent_env/cli/up.py +123 -0
- agent_env/cli/utils.py +183 -0
- agent_env/config/__init__.py +50 -0
- agent_env/config/describe.py +1067 -0
- agent_env/config/errors.py +13 -0
- agent_env/config/loader.py +245 -0
- agent_env/config/model.py +154 -0
- agent_env/config/paths.py +25 -0
- agent_env/config/plugin_tables.py +101 -0
- agent_env/config/provenance.py +134 -0
- agent_env/config/runtime.py +1064 -0
- agent_env/config/snapshot.py +81 -0
- agent_env/entity_refs.py +186 -0
- agent_env/env/__init__.py +49 -0
- agent_env/env/env.py +433 -0
- agent_env/env/env_artifact_store.py +87 -0
- agent_env/env/envs/__init__.py +7 -0
- agent_env/env/envs/_deployment.py +281 -0
- agent_env/env/envs/gateway_server.py +32 -0
- agent_env/env/envs/mcp_server.py +387 -0
- agent_env/env/envs/multi_env.py +780 -0
- agent_env/env/envs/service_db/Dockerfile +20 -0
- agent_env/env/envs/service_db/Dockerfile.db-mcp +42 -0
- agent_env/env/envs/service_db/Dockerfile.db-web +8 -0
- agent_env/env/envs/service_db.py +92 -0
- agent_env/env/envs/website.py +294 -0
- agent_env/env/envs/website_browser/Dockerfile +40 -0
- agent_env/env/envs/website_browser/__init__.py +17 -0
- agent_env/env/envs/website_browser/entrypoint.sh +13 -0
- agent_env/env/gateway/Dockerfile +14 -0
- agent_env/env/gateway/__init__.py +37 -0
- agent_env/env/gateway/clock.py +184 -0
- agent_env/env/gateway/constants.py +190 -0
- agent_env/env/gateway/entrypoint.py +156 -0
- agent_env/env/gateway/gateway.py +1095 -0
- agent_env/env/gateway/get_time.py +60 -0
- agent_env/env/gateway/requirements.txt +4 -0
- agent_env/env/gateway/triggers.py +1193 -0
- agent_env/env/legacy_protocol.py +146 -0
- agent_env/env/registry.py +93 -0
- agent_env/env/snapshot_store.py +372 -0
- agent_env/env/store.py +411 -0
- agent_env/eval/__init__.py +14 -0
- agent_env/eval/eval.py +68 -0
- agent_env/eval/store.py +116 -0
- agent_env/examples/hello/README.md +9 -0
- agent_env/examples/hello/artifacts/greeting/check.sh +1 -0
- agent_env/examples/hello/artifacts/greeting/hello.txt +1 -0
- agent_env/examples/hello/tasks/hello.json +10 -0
- agent_env/explorer/__init__.py +12 -0
- agent_env/explorer/app.py +277 -0
- agent_env/explorer/openapi_docs.py +242 -0
- agent_env/explorer/plugin.py +95 -0
- agent_env/explorer/routers/__init__.py +1 -0
- agent_env/explorer/routers/common.py +174 -0
- agent_env/explorer/routers/conversations.py +25 -0
- agent_env/explorer/routers/objects.py +112 -0
- agent_env/explorer/routers/runs.py +475 -0
- agent_env/plugins/__init__.py +59 -0
- agent_env/plugins/_cli.py +244 -0
- agent_env/plugins/_discovery.py +97 -0
- agent_env/plugins/_inventory.py +262 -0
- agent_env/plugins/_registration.py +268 -0
- agent_env/plugins/_report.py +47 -0
- agent_env/plugins/_requirements.py +55 -0
- agent_env/providers/__init__.py +37 -0
- agent_env/providers/env_providers/__init__.py +12 -0
- agent_env/providers/env_providers/constants.py +13 -0
- agent_env/providers/env_providers/env_gateway_provider.py +1354 -0
- agent_env/providers/env_providers/env_provider.py +237 -0
- agent_env/providers/env_providers/env_server_provider.py +133 -0
- agent_env/providers/env_state/__init__.py +49 -0
- agent_env/providers/env_state/env_state_provider.py +554 -0
- agent_env/providers/env_state/local_postgres.py +390 -0
- agent_env/providers/env_state/store.py +112 -0
- agent_env/providers/sandbox_providers/__init__.py +29 -0
- agent_env/providers/sandbox_providers/chained_sandbox_provider.py +93 -0
- agent_env/providers/sandbox_providers/e2b/__init__.py +6 -0
- agent_env/providers/sandbox_providers/e2b/provider.py +376 -0
- agent_env/providers/sandbox_providers/e2b/sandbox.py +342 -0
- agent_env/providers/sandbox_providers/e2b/template.py +158 -0
- agent_env/providers/sandbox_providers/local_sandbox.py +408 -0
- agent_env/providers/sandbox_providers/modal_sandbox.py +500 -0
- agent_env/providers/sandbox_providers/modal_vm_sandbox.py +466 -0
- agent_env/providers/sandbox_providers/sandbox.py +387 -0
- agent_env/providers/sandbox_providers/sandbox_provider.py +614 -0
- agent_env/py.typed +0 -0
- agent_env/runner/__init__.py +16 -0
- agent_env/runner/local_runner.py +190 -0
- agent_env/runner/runner.py +127 -0
- agent_env/runner/store.py +94 -0
- agent_env/store/__init__.py +126 -0
- agent_env/store/_google.py +68 -0
- agent_env/store/base.py +33 -0
- agent_env/store/document_store/__init__.py +60 -0
- agent_env/store/document_store/document_store.py +519 -0
- agent_env/store/document_store/dynamodb_document_store.py +306 -0
- agent_env/store/document_store/evaluation.py +199 -0
- agent_env/store/document_store/firestore_mongo_document_store.py +242 -0
- agent_env/store/document_store/mongo_document_store.py +259 -0
- agent_env/store/document_store/sqlite_document_store.py +314 -0
- agent_env/store/ids.py +123 -0
- agent_env/store/image_store/__init__.py +34 -0
- agent_env/store/image_store/ecr_image_store.py +131 -0
- agent_env/store/image_store/google_credentials.py +113 -0
- agent_env/store/image_store/image_store.py +113 -0
- agent_env/store/image_store/local_registry_image_store.py +106 -0
- agent_env/store/image_store/oci_registry_credentials.py +196 -0
- agent_env/store/local_state.py +27 -0
- agent_env/store/object_store/__init__.py +24 -0
- agent_env/store/object_store/gcs_object_store.py +415 -0
- agent_env/store/object_store/local_object_store.py +143 -0
- agent_env/store/object_store/object_store.py +198 -0
- agent_env/store/object_store/s3_object_store.py +354 -0
- agent_env/store/query.py +112 -0
- agent_env/store/routing.py +609 -0
- agent_env/store/secret_store/__init__.py +19 -0
- agent_env/store/secret_store/aws_secrets_manager_secret_store.py +293 -0
- agent_env/store/secret_store/gcp_secret_manager_secret_store.py +319 -0
- agent_env/store/secret_store/local_secret_store.py +47 -0
- agent_env/store/secret_store/secret_store.py +19 -0
- agent_env/task/__init__.py +27 -0
- agent_env/task/interrupts.py +109 -0
- agent_env/task/registry.py +27 -0
- agent_env/task/step_journal.py +99 -0
- agent_env/task/store.py +940 -0
- agent_env/task/task.py +815 -0
- agent_env/task/teardown.py +142 -0
- agent_env/task_step/__init__.py +47 -0
- agent_env/task_step/context.py +195 -0
- agent_env/task_step/context_ops.py +224 -0
- agent_env/task_step/registry.py +182 -0
- agent_env/task_step/review_store.py +118 -0
- agent_env/task_step/snapshot_utils/__init__.py +2 -0
- agent_env/task_step/snapshot_utils/agent_state_capture.py +261 -0
- agent_env/task_step/snapshot_utils/snapshot_series.py +631 -0
- agent_env/task_step/store.py +129 -0
- agent_env/task_step/task_step.py +173 -0
- agent_env/task_step/task_steps/__init__.py +27 -0
- agent_env/task_step/task_steps/a2a_agent_validator/__init__.py +31 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/README.md +158 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.m4a +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp3 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.mp4 +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.ogg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/clip.wav +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/document.pdf +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.gif +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.jpg +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/fixtures/red.png +0 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_card.py +103 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_config_identity.py +69 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_agent_mcp.py +178 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_core_protocol.py +67 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_install.py +115 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution.py +124 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_litellm_attribution_runtime.py +173 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_modalities.py +270 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_peer_agents.py +102 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_role.py +151 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_skill_config.py +194 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_snapshot.py +111 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_system_prompt.py +215 -0
- agent_env/task_step/task_steps/a2a_agent_validator/verify_a2a_trajectory.py +164 -0
- agent_env/task_step/task_steps/add_skills.py +240 -0
- agent_env/task_step/task_steps/apply_server_config.py +288 -0
- agent_env/task_step/task_steps/collect_artifacts.py +940 -0
- agent_env/task_step/task_steps/deploy_agent.py +626 -0
- agent_env/task_step/task_steps/deploy_env.py +197 -0
- agent_env/task_step/task_steps/deploy_human_agent.py +100 -0
- agent_env/task_step/task_steps/deploy_sandbox.py +170 -0
- agent_env/task_step/task_steps/env_card_validator/__init__.py +4 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_card.py +109 -0
- agent_env/task_step/task_steps/env_card_validator/verify_env_core_protocol.py +108 -0
- agent_env/task_step/task_steps/install_agent.py +376 -0
- agent_env/task_step/task_steps/load_artifact.py +775 -0
- agent_env/task_step/task_steps/mcp_cli_builder/__init__.py +4 -0
- agent_env/task_step/task_steps/mcp_cli_builder/build_mcp_cli.py +201 -0
- agent_env/task_step/task_steps/mcp_cli_builder/codegen.py +627 -0
- agent_env/task_step/task_steps/mcp_env_validator/__init__.py +44 -0
- agent_env/task_step/task_steps/mcp_env_validator/validation_gate_aggregator.py +102 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_env_assessment.py +78 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_mcp_tool_schema.py +152 -0
- agent_env/task_step/task_steps/mcp_env_validator/verify_spec_conformance.py +486 -0
- agent_env/task_step/task_steps/modify_env_tool_access.py +80 -0
- agent_env/task_step/task_steps/multienv_validator/__init__.py +3 -0
- agent_env/task_step/task_steps/multienv_validator/combine_universe_verdicts.py +107 -0
- agent_env/task_step/task_steps/multienv_validator/universe_comparison.py +253 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_agent_judge.py +180 -0
- agent_env/task_step/task_steps/multienv_validator/verify_universe_roundtrip.py +241 -0
- agent_env/task_step/task_steps/peer_agents.py +92 -0
- agent_env/task_step/task_steps/prompt_agent.py +900 -0
- agent_env/task_step/task_steps/register_agent_triggers.py +113 -0
- agent_env/task_step/task_steps/register_env_triggers.py +97 -0
- agent_env/task_step/task_steps/reset_env.py +71 -0
- agent_env/task_step/task_steps/review.py +152 -0
- agent_env/task_step/task_steps/run_code.py +461 -0
- agent_env/task_step/task_steps/run_code_runner.py +52 -0
- agent_env/task_step/task_steps/run_docker_container.py +380 -0
- agent_env/task_step/task_steps/sandbox_utils/__init__.py +0 -0
- agent_env/task_step/task_steps/sandbox_utils/sandbox_utils.py +79 -0
- agent_env/task_step/task_steps/snapshot_agent_state.py +205 -0
- agent_env/task_step/task_steps/snapshot_env.py +637 -0
- agent_env/task_step/task_steps/sync_env_clock.py +132 -0
- agent_env/task_step/task_steps/teardown_sandboxes.py +170 -0
- agent_env/task_step/task_steps/verifiers/__init__.py +23 -0
- agent_env/task_step/task_steps/verifiers/agent_prompt_response_verifier.py +166 -0
- agent_env/task_step/task_steps/verifiers/aggregate_verifiers.py +90 -0
- agent_env/task_step/task_steps/verifiers/env_outcome_verifier.py +127 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/__init__.py +2 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/frame_selection.py +377 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/judge_output_format.py +1293 -0
- agent_env/task_step/task_steps/verifiers/judge_utils/trajectory_filter.py +514 -0
- agent_env/task_step/task_steps/verifiers/rubrics_verifier.py +1318 -0
- agent_env/task_step/task_steps/verifiers/run_container_unit_tests_verifier.py +434 -0
- agent_env/task_step/task_steps/verifiers/scoring.py +40 -0
- agent_env/task_step/task_steps/verifiers/verify_sandbox.py +308 -0
- agent_env/task_step/thread_work.py +61 -0
- agent_env/utils/__init__.py +0 -0
- agent_env/utils/card_naming.py +108 -0
- agent_env/utils/deprecation.py +109 -0
- agent_env/utils/docker_build.py +29 -0
- agent_env/utils/exec_retry.py +77 -0
- agent_env/utils/litellm_attribution.py +59 -0
- agent_env/utils/paths.py +20 -0
- agentenv_framework-0.9.1254.dist-info/METADATA +394 -0
- agentenv_framework-0.9.1254.dist-info/RECORD +312 -0
- agentenv_framework-0.9.1254.dist-info/WHEEL +4 -0
- agentenv_framework-0.9.1254.dist-info/entry_points.txt +5 -0
- agentenv_framework-0.9.1254.dist-info/licenses/LICENSE +202 -0
- agentenv_framework-0.9.1254.dist-info/licenses/NOTICE +4 -0
- agentenv_framework-0.9.1254.dist-info/licenses/THIRD_PARTY_NOTICES.md +7665 -0
|
@@ -0,0 +1,1318 @@
|
|
|
1
|
+
"""Verify agent output against rubric criteria using an LLM judge."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
import uuid
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from typing import ClassVar, Optional
|
|
12
|
+
|
|
13
|
+
from agent_env.a2a_agent.object_transfer import (
|
|
14
|
+
TrajectoryUpload,
|
|
15
|
+
fetch_trajectory,
|
|
16
|
+
trajectory_mode,
|
|
17
|
+
)
|
|
18
|
+
from agent_env.config import get_config
|
|
19
|
+
from agent_env.config.model import ModelParam
|
|
20
|
+
from agent_env.task_step.context import TaskStepContext
|
|
21
|
+
from agent_env.task_step.task_steps.verifiers.judge_utils.judge_output_format import (
|
|
22
|
+
SCREENSHOT_GROUNDING,
|
|
23
|
+
JudgeOutputFormat,
|
|
24
|
+
JudgeOutputFormatSpec,
|
|
25
|
+
ResultRows,
|
|
26
|
+
evidence_checks_instruction,
|
|
27
|
+
get_judge_output_format_spec,
|
|
28
|
+
per_criterion_grounding,
|
|
29
|
+
trajectory_mistakes_rows_from_evidence,
|
|
30
|
+
)
|
|
31
|
+
from agent_env.task_step.snapshot_utils.agent_state_capture import (
|
|
32
|
+
store_trajectory,
|
|
33
|
+
trajectory_object_url,
|
|
34
|
+
)
|
|
35
|
+
from agent_env.entity_refs import EntityRef
|
|
36
|
+
from agent_env.task_step.task_step import TaskStep, TaskStepDependency
|
|
37
|
+
from agent_env.task_step.task_steps.verifiers.scoring import ScoreAggregator, aggregate_score
|
|
38
|
+
from agent_env.task_step.task_steps.sandbox_utils.sandbox_utils import (
|
|
39
|
+
agent_error_text,
|
|
40
|
+
fetch_container_logs,
|
|
41
|
+
)
|
|
42
|
+
from agent_env.task_step.task_steps.verifiers.judge_utils.frame_selection import (
|
|
43
|
+
LabeledFrame,
|
|
44
|
+
Transcript,
|
|
45
|
+
action_log,
|
|
46
|
+
select_frames_per_criterion,
|
|
47
|
+
transcript_from_raw,
|
|
48
|
+
)
|
|
49
|
+
from agent_env.task_step.task_steps.verifiers.judge_utils.trajectory_filter import (
|
|
50
|
+
CompactionType,
|
|
51
|
+
FrameStrategy,
|
|
52
|
+
ImageFrame,
|
|
53
|
+
TrajectoryFilter,
|
|
54
|
+
TrajectoryText,
|
|
55
|
+
compact_otel_trajectory,
|
|
56
|
+
final_image_frames,
|
|
57
|
+
strip_trajectory_images,
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
logger = logging.getLogger(__name__)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# The judge echoes each criterion's id back and results are matched by exact string.
|
|
64
|
+
# Models drop or transpose a character when copying a 36-char UUID, and one mismatched
|
|
65
|
+
# id discards the whole judge response. Short positional keys (c1..cN) remove that
|
|
66
|
+
# transcription surface; the real ids stay the source of truth and are restored on
|
|
67
|
+
# the graded rows.
|
|
68
|
+
def _to_short_keyed_criteria(criteria: list[dict]) -> tuple[list[dict], dict[str, str]]:
|
|
69
|
+
"""Return (criteria re-keyed as c1..cN, {short_id: real_id}). Does not mutate the input.
|
|
70
|
+
|
|
71
|
+
Raises ValueError if the criterion ids are not unique non-empty strings — a
|
|
72
|
+
malformed rubric that generated keys would otherwise mask.
|
|
73
|
+
"""
|
|
74
|
+
ids = [c.get("id") for c in criteria]
|
|
75
|
+
if not all(isinstance(i, str) and i for i in ids) or len(set(ids)) != len(ids):
|
|
76
|
+
raise ValueError("rubric criteria must have unique, non-empty string ids")
|
|
77
|
+
short_criteria: list[dict] = []
|
|
78
|
+
real_by_short: dict[str, str] = {}
|
|
79
|
+
for index, criterion in enumerate(criteria, start=1):
|
|
80
|
+
short_id = f"c{index}"
|
|
81
|
+
real_by_short[short_id] = criterion.get("id")
|
|
82
|
+
short_criteria.append({**criterion, "id": short_id})
|
|
83
|
+
return short_criteria, real_by_short
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _restore_criterion_ids(results: list[dict], real_by_short: dict[str, str]) -> None:
|
|
87
|
+
"""Rewrite each row's short id (c1..cN) back to its real criterion id, in place.
|
|
88
|
+
|
|
89
|
+
Rows whose id is not a known short key are left untouched, so this is safe to run
|
|
90
|
+
over default/failure rows or an already-real id.
|
|
91
|
+
"""
|
|
92
|
+
for row in results:
|
|
93
|
+
real_id = real_by_short.get(row.get("id"))
|
|
94
|
+
if real_id is not None:
|
|
95
|
+
row["id"] = real_id
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
_FRAME_LABEL_ID = re.compile(r"\[(c\d+)\]")
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _restore_frame_labels(rows: list[dict], real_by_short: dict[str, str]) -> None:
|
|
102
|
+
"""Rewrite the short criterion keys inside cited frame labels ("[c1][c3] action 17") to the real ids, in place."""
|
|
103
|
+
for row in rows:
|
|
104
|
+
frame = row.get("frame")
|
|
105
|
+
if isinstance(frame, str) and frame:
|
|
106
|
+
row["frame"] = _FRAME_LABEL_ID.sub(lambda m: f"[{real_by_short.get(m.group(1), m.group(1))}]", frame)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# A rubric_evidence_with_mistakes step writes its trajectory-mistakes entry under its own verifier_id plus this
|
|
110
|
+
# suffix (``trajectory_mistakes_key``).
|
|
111
|
+
TRAJECTORY_MISTAKES_SUFFIX = "-trajectory-mistakes"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def trajectory_mistakes_key(verifier_id: str) -> str:
|
|
115
|
+
"""The ``verifications`` key a ``rubric_evidence_with_mistakes`` step writes its second (trajectory_mistakes-
|
|
116
|
+
shaped) entry under: the step's own ``verifier_id`` + ``TRAJECTORY_MISTAKES_SUFFIX``. A reader that knows
|
|
117
|
+
the verifier id rebuilds the key from it; the entry also carries ``source_verifier_id``."""
|
|
118
|
+
return f"{verifier_id}{TRAJECTORY_MISTAKES_SUFFIX}"
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# A context_facts_for_judge path: dotted segments of letters, digits, `_` and `-` (dict keys, or a list index).
|
|
122
|
+
_CONTEXT_FACT_PATH = re.compile(r"^[\w-]+(\.[\w-]+)*$")
|
|
123
|
+
CONTEXT_FACT_MAX_CHARS = 600 # longer rendered values are cut and end in "…"
|
|
124
|
+
CONTEXT_FACT_NOT_AVAILABLE = "(not available)" # rendered for a path that does not resolve
|
|
125
|
+
_MISSING = object()
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _lookup_dotted_path(root: object, path: str) -> object:
|
|
129
|
+
node = root
|
|
130
|
+
for segment in path.split("."):
|
|
131
|
+
if isinstance(node, dict):
|
|
132
|
+
if segment not in node:
|
|
133
|
+
return _MISSING
|
|
134
|
+
node = node[segment]
|
|
135
|
+
elif isinstance(node, list) and segment.isdigit() and int(segment) < len(node):
|
|
136
|
+
node = node[int(segment)]
|
|
137
|
+
else:
|
|
138
|
+
return _MISSING
|
|
139
|
+
return node
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _render_fact(value: object) -> str:
|
|
143
|
+
"""Compact JSON with sorted keys; stored key order when the keys cannot be sorted; ``str`` when not JSON."""
|
|
144
|
+
try:
|
|
145
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
|
|
146
|
+
except (TypeError, ValueError):
|
|
147
|
+
pass
|
|
148
|
+
try:
|
|
149
|
+
return json.dumps(value, ensure_ascii=False, default=str)
|
|
150
|
+
except (TypeError, ValueError):
|
|
151
|
+
return str(value)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def resolve_context_facts(facts: dict[str, str], metadata: dict) -> list[tuple[str, str]]:
|
|
155
|
+
"""Resolve ``{label: dotted path}`` against ``metadata`` into ``[(label, rendered value)]``, in order.
|
|
156
|
+
A path walks dicts by key and lists by index; one that does not resolve renders as
|
|
157
|
+
``CONTEXT_FACT_NOT_AVAILABLE`` so the judge sees the fact was requested. Never raises."""
|
|
158
|
+
rendered: list[tuple[str, str]] = []
|
|
159
|
+
for label, path in facts.items():
|
|
160
|
+
value = _lookup_dotted_path(metadata, path)
|
|
161
|
+
if value is _MISSING:
|
|
162
|
+
text = CONTEXT_FACT_NOT_AVAILABLE
|
|
163
|
+
else:
|
|
164
|
+
text = _render_fact(value)
|
|
165
|
+
if len(text) > CONTEXT_FACT_MAX_CHARS:
|
|
166
|
+
text = text[:CONTEXT_FACT_MAX_CHARS] + "…"
|
|
167
|
+
rendered.append((label, text))
|
|
168
|
+
return rendered
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
# Only fall back from structured output when the error clearly says the response
|
|
172
|
+
# format itself is unsupported. Image/provider/transient failures should retry as-is.
|
|
173
|
+
_SCHEMA_TERMS = (
|
|
174
|
+
"response_format",
|
|
175
|
+
"response format",
|
|
176
|
+
"json_schema",
|
|
177
|
+
"json schema",
|
|
178
|
+
"response schema",
|
|
179
|
+
"structured output",
|
|
180
|
+
)
|
|
181
|
+
_UNSUPPORTED_TERMS = (
|
|
182
|
+
"not supported",
|
|
183
|
+
"unsupported",
|
|
184
|
+
"not allowed",
|
|
185
|
+
"does not support",
|
|
186
|
+
"cannot be used",
|
|
187
|
+
"incompatible",
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _looks_like_response_format_error(exc: Exception) -> bool:
|
|
192
|
+
msg = str(exc).lower()
|
|
193
|
+
return any(s in msg for s in _SCHEMA_TERMS) and any(u in msg for u in _UNSUPPORTED_TERMS)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _image_url_block(frame: ImageFrame) -> dict:
|
|
197
|
+
"""Adapt a neutral trajectory image to LiteLLM's image block shape."""
|
|
198
|
+
return {
|
|
199
|
+
"type": "image_url",
|
|
200
|
+
"image_url": {"url": f"data:{frame.media_type};base64,{frame.data}"},
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@dataclass
|
|
205
|
+
class _CompactedTrajectory:
|
|
206
|
+
"""Every representation the filter produced; the caller picks what its judge consumes."""
|
|
207
|
+
|
|
208
|
+
container_s3_uri: Optional[str] = None # trajectory file (loaded into an agent-judge container)
|
|
209
|
+
tool_result_files: list[tuple[str, str]] = field(default_factory=list)
|
|
210
|
+
inline_text: Optional[str] = None # pre-rendered text (screenshot); None for DEFAULT (read lazily)
|
|
211
|
+
image_blocks: list[dict] = field(default_factory=list) # frame images (screenshot); a label text block before each per-criterion
|
|
212
|
+
compact_s3_uri: Optional[str] = None # compacted URI, if produced; recorded on the result only
|
|
213
|
+
per_criterion: bool = False # labelled per-criterion frames were attached (False when that selection found none)
|
|
214
|
+
|
|
215
|
+
@classmethod
|
|
216
|
+
def empty(cls) -> "_CompactedTrajectory":
|
|
217
|
+
return cls()
|
|
218
|
+
|
|
219
|
+
@classmethod
|
|
220
|
+
def for_default(
|
|
221
|
+
cls, container_s3_uri: Optional[str], tool_result_files: list[tuple[str, str]],
|
|
222
|
+
compact_s3_uri: Optional[str] = None,
|
|
223
|
+
) -> "_CompactedTrajectory":
|
|
224
|
+
return cls(container_s3_uri=container_s3_uri, tool_result_files=tool_result_files,
|
|
225
|
+
compact_s3_uri=compact_s3_uri)
|
|
226
|
+
|
|
227
|
+
@classmethod
|
|
228
|
+
def for_screenshot(
|
|
229
|
+
cls, inline_text: Optional[str], image_blocks: list[dict],
|
|
230
|
+
container_s3_uri: Optional[str] = None, per_criterion: bool = False,
|
|
231
|
+
) -> "_CompactedTrajectory":
|
|
232
|
+
# container_s3_uri = raw file, kept so an agent judge (no inline frames) can still load it.
|
|
233
|
+
return cls(inline_text=inline_text, image_blocks=image_blocks or [], container_s3_uri=container_s3_uri,
|
|
234
|
+
per_criterion=per_criterion)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _image_count(blocks: list[dict]) -> int:
|
|
238
|
+
"""Images among judge message blocks (per-criterion frames interleave a ``FRAME:`` text block before each)."""
|
|
239
|
+
return sum(1 for b in blocks if b.get("type") == "image_url")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _labeled_image_blocks(frames: list[LabeledFrame]) -> list[dict]:
|
|
243
|
+
"""``FRAME: <label>`` text block, then the image — the judge cites the label in each row's ``frame``."""
|
|
244
|
+
blocks: list[dict] = []
|
|
245
|
+
for f in frames:
|
|
246
|
+
blocks.append({"type": "text", "text": f"FRAME: {f.label}"})
|
|
247
|
+
blocks.append(_image_url_block(f.frame))
|
|
248
|
+
return blocks
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _is_per_criterion(tf: TrajectoryFilter | None) -> bool:
|
|
252
|
+
return (tf is not None and tf.compaction_type == CompactionType.SCREENSHOT
|
|
253
|
+
and tf.frame_strategy == FrameStrategy.PER_CRITERION)
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
class RubricsVerifierTaskStep(TaskStep):
|
|
257
|
+
type: ClassVar[str] = "rubrics_verifier"
|
|
258
|
+
entity_refs = (EntityRef.agent("judge_a2a_agent_id"),)
|
|
259
|
+
DEFAULT_JUDGE_TIMEOUT_SECONDS: ClassVar[int] = 1000
|
|
260
|
+
DEFAULT_MAX_RETRIES: ClassVar[int] = 3
|
|
261
|
+
DEFAULT_POLL_INTERVAL_SECONDS: ClassVar[int] = 10
|
|
262
|
+
TRAJECTORY_CONTAINER_PATH: ClassVar[str] = "/tmp/prompt_trajectory.json"
|
|
263
|
+
# Multi-turn agent judge: base for a per-run subdir holding turn_NN.json files.
|
|
264
|
+
TRAJECTORY_CONTAINER_DIR: ClassVar[str] = "/tmp/prompt_trajectory_turns"
|
|
265
|
+
_MULTITURN_DIR_NOTE: ClassVar[str] = (
|
|
266
|
+
"\n\nNOTE: This is a multi-turn conversation. The trajectory path above is a "
|
|
267
|
+
"DIRECTORY containing {n} files named turn_01.json, turn_02.json, … — one per "
|
|
268
|
+
"conversation turn, in chronological order. Read every file, in order, to judge the "
|
|
269
|
+
"full conversation; actions the agent took in earlier turns count."
|
|
270
|
+
)
|
|
271
|
+
_CONTEXT_FACTS_LEAD: ClassVar[str] = (
|
|
272
|
+
"These values were measured from the run's record. Rely on them over what the screenshots or "
|
|
273
|
+
"trajectory text appear to show."
|
|
274
|
+
)
|
|
275
|
+
|
|
276
|
+
def __init__(
|
|
277
|
+
self,
|
|
278
|
+
id: str,
|
|
279
|
+
version: Optional[int],
|
|
280
|
+
criteria: list[dict],
|
|
281
|
+
prompt_id: str,
|
|
282
|
+
default_model: str = "claude-sonnet-4-6",
|
|
283
|
+
default_model_api_base: Optional[str] = None,
|
|
284
|
+
score_aggregator: Optional[ScoreAggregator] = None,
|
|
285
|
+
verifier_id: Optional[str] = None,
|
|
286
|
+
agent_name: Optional[str] = None,
|
|
287
|
+
trajectory_filter: Optional[TrajectoryFilter] = None,
|
|
288
|
+
max_thinking_tokens: Optional[int] = None,
|
|
289
|
+
effort: Optional[str] = None,
|
|
290
|
+
use_agent_judge: bool = True,
|
|
291
|
+
use_trajectory: bool = True,
|
|
292
|
+
judge_a2a_agent_id: Optional[str] = None,
|
|
293
|
+
judge_sandbox_type: Optional[str] = None,
|
|
294
|
+
judge_priority: Optional[int] = None,
|
|
295
|
+
judge_timeout_seconds: Optional[int] = None,
|
|
296
|
+
output_format: JudgeOutputFormat | str = JudgeOutputFormat.RUBRIC_BINARY,
|
|
297
|
+
grading_policy_prompt: Optional[str] = None,
|
|
298
|
+
context_facts_for_judge: Optional[dict[str, str]] = None,
|
|
299
|
+
depends_on: Optional[list[TaskStepDependency]] = None,
|
|
300
|
+
fail_task_on_error: bool = True,
|
|
301
|
+
):
|
|
302
|
+
super().__init__(id, version, depends_on=depends_on, fail_task_on_error=fail_task_on_error)
|
|
303
|
+
# Task-authored rules the criteria alone do not state, appended as a "## Grading policy" section;
|
|
304
|
+
# with rubric_evidence its findings come back as `checks`.
|
|
305
|
+
self.grading_policy_prompt = grading_policy_prompt
|
|
306
|
+
# {label: dotted path into context.metadata}, resolved at execute time (``resolve_context_facts``)
|
|
307
|
+
# and shown as a "## Context facts" section the judge trusts over the pixels.
|
|
308
|
+
if context_facts_for_judge is not None:
|
|
309
|
+
if not isinstance(context_facts_for_judge, dict) or not all(
|
|
310
|
+
isinstance(label, str) and label and isinstance(path, str) and _CONTEXT_FACT_PATH.match(path)
|
|
311
|
+
for label, path in context_facts_for_judge.items()
|
|
312
|
+
):
|
|
313
|
+
raise ValueError(
|
|
314
|
+
"context_facts_for_judge must map non-empty labels to dotted paths of identifiers "
|
|
315
|
+
"(letters, digits, '_' and '-' per segment), e.g. "
|
|
316
|
+
'{"items in cart": "verifications.cart-check.count"}.'
|
|
317
|
+
)
|
|
318
|
+
self.context_facts_for_judge = context_facts_for_judge
|
|
319
|
+
if isinstance(output_format, str):
|
|
320
|
+
output_format = JudgeOutputFormat(output_format)
|
|
321
|
+
self.output_format = output_format
|
|
322
|
+
self.verifier_id = verifier_id or uuid.uuid4().hex
|
|
323
|
+
self.criteria = criteria
|
|
324
|
+
self.prompt_id = prompt_id
|
|
325
|
+
self.default_model = default_model
|
|
326
|
+
self.default_model_api_base = default_model_api_base
|
|
327
|
+
if isinstance(score_aggregator, str):
|
|
328
|
+
score_aggregator = ScoreAggregator(score_aggregator)
|
|
329
|
+
self.score_aggregator = score_aggregator or ScoreAggregator.ALL_PASS
|
|
330
|
+
self.agent_name = agent_name
|
|
331
|
+
if isinstance(trajectory_filter, dict):
|
|
332
|
+
trajectory_filter = TrajectoryFilter.from_dict(trajectory_filter)
|
|
333
|
+
self.trajectory_filter = trajectory_filter
|
|
334
|
+
self.max_thinking_tokens = max_thinking_tokens
|
|
335
|
+
self.effort = effort
|
|
336
|
+
self.use_agent_judge = use_agent_judge
|
|
337
|
+
self.use_trajectory = use_trajectory
|
|
338
|
+
self.judge_a2a_agent_id = judge_a2a_agent_id
|
|
339
|
+
self.judge_sandbox_type = judge_sandbox_type
|
|
340
|
+
self.judge_priority = judge_priority
|
|
341
|
+
self.judge_timeout_seconds = judge_timeout_seconds or self.DEFAULT_JUDGE_TIMEOUT_SECONDS
|
|
342
|
+
if self.default_model_api_base and self.use_agent_judge:
|
|
343
|
+
# Agent judges route through their deployed runtime, so this direct-judge
|
|
344
|
+
# default would otherwise be silently ignored.
|
|
345
|
+
raise ValueError(
|
|
346
|
+
"default_model_api_base only applies to the direct LLM judge "
|
|
347
|
+
"(use_agent_judge=False); it is ignored by the agent judge."
|
|
348
|
+
)
|
|
349
|
+
if self._spec().cites_evidence and not (
|
|
350
|
+
not self.use_agent_judge and self.use_trajectory and _is_per_criterion(self.trajectory_filter)
|
|
351
|
+
):
|
|
352
|
+
# rubric_evidence / rubric_evidence_with_mistakes: the rows cite labelled per-criterion frames; only
|
|
353
|
+
# the direct judge gets them.
|
|
354
|
+
raise ValueError(
|
|
355
|
+
f"output_format={self.output_format.value} requires the direct LLM judge (use_agent_judge=False) "
|
|
356
|
+
"with use_trajectory=True and a trajectory_filter with compaction_type=screenshot and "
|
|
357
|
+
"frame_strategy=per_criterion."
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
def _spec(self) -> JudgeOutputFormatSpec:
|
|
361
|
+
return get_judge_output_format_spec(self.output_format)
|
|
362
|
+
|
|
363
|
+
@property
|
|
364
|
+
def _writes_mistakes_entry(self) -> bool:
|
|
365
|
+
"""rubric_evidence_with_mistakes: the same judge call also detects trajectory mistakes and a second entry,
|
|
366
|
+
shaped and scored as a standalone trajectory_mistakes step's, is written under
|
|
367
|
+
``trajectory_mistakes_key(self.verifier_id)`` (see ``_write_entries``)."""
|
|
368
|
+
return self.output_format is JudgeOutputFormat.RUBRIC_EVIDENCE_WITH_MISTAKES
|
|
369
|
+
|
|
370
|
+
def _entry_format_fields(self) -> dict:
|
|
371
|
+
"""``format`` on the verification entry — the shape of its rows (``JudgeOutputFormatSpec.stored_format``)
|
|
372
|
+
— plus ``judge_output_format``, the format the judge actually ran, when the two differ."""
|
|
373
|
+
stored = self._spec().stored_format
|
|
374
|
+
if stored is None:
|
|
375
|
+
return {"format": self.output_format.value}
|
|
376
|
+
return {"format": stored, "judge_output_format": self.output_format.value}
|
|
377
|
+
|
|
378
|
+
def _mistakes_entry_fields(self) -> dict:
|
|
379
|
+
"""``format`` / ``source_verifier_id`` of the second entry written under ``trajectory_mistakes_key``."""
|
|
380
|
+
return {"format": JudgeOutputFormat.TRAJECTORY_MISTAKES.value, "source_verifier_id": self.verifier_id}
|
|
381
|
+
|
|
382
|
+
def _write_skipped_entries(self, context: TaskStepContext, row_id: str, message: str) -> None:
|
|
383
|
+
"""Store a zero-score entry with one row saying why the run was not judged — under ``verifier_id``
|
|
384
|
+
and, for rubric_evidence_with_mistakes, ``trajectory_mistakes_key(verifier_id)``."""
|
|
385
|
+
def skipped(fields: dict) -> dict:
|
|
386
|
+
return {
|
|
387
|
+
**fields,
|
|
388
|
+
"results": [{"id": row_id, "score": 0, "result": False, "message": message}],
|
|
389
|
+
"score": 0,
|
|
390
|
+
}
|
|
391
|
+
verifications = context.metadata.setdefault("verifications", {})
|
|
392
|
+
verifications[self.verifier_id] = skipped(self._entry_format_fields())
|
|
393
|
+
if self._writes_mistakes_entry:
|
|
394
|
+
verifications[trajectory_mistakes_key(self.verifier_id)] = skipped(self._mistakes_entry_fields())
|
|
395
|
+
|
|
396
|
+
def to_dict(self) -> dict:
|
|
397
|
+
base = super().to_dict()
|
|
398
|
+
base["verifier_id"] = self.verifier_id
|
|
399
|
+
base["criteria"] = self.criteria
|
|
400
|
+
base["prompt_id"] = self.prompt_id
|
|
401
|
+
base["default_model"] = self.default_model
|
|
402
|
+
base["default_model_api_base"] = self.default_model_api_base
|
|
403
|
+
base["score_aggregator"] = self.score_aggregator.value
|
|
404
|
+
base["agent_name"] = self.agent_name
|
|
405
|
+
base["trajectory_filter"] = self.trajectory_filter.to_dict() if self.trajectory_filter else None
|
|
406
|
+
base["max_thinking_tokens"] = self.max_thinking_tokens
|
|
407
|
+
base["effort"] = self.effort
|
|
408
|
+
base["use_agent_judge"] = self.use_agent_judge
|
|
409
|
+
base["use_trajectory"] = self.use_trajectory
|
|
410
|
+
base["judge_a2a_agent_id"] = self.judge_a2a_agent_id
|
|
411
|
+
base["judge_sandbox_type"] = self.judge_sandbox_type
|
|
412
|
+
base["judge_priority"] = self.judge_priority
|
|
413
|
+
base["judge_timeout_seconds"] = self.judge_timeout_seconds
|
|
414
|
+
base["output_format"] = self.output_format.value
|
|
415
|
+
base["grading_policy_prompt"] = self.grading_policy_prompt
|
|
416
|
+
base["context_facts_for_judge"] = self.context_facts_for_judge
|
|
417
|
+
return base
|
|
418
|
+
|
|
419
|
+
@classmethod
|
|
420
|
+
def from_dict(cls, data: dict) -> RubricsVerifierTaskStep:
|
|
421
|
+
from agent_env.config import get_config
|
|
422
|
+
|
|
423
|
+
raw_agg = data.get("score_aggregator")
|
|
424
|
+
raw_tf = data.get("trajectory_filter")
|
|
425
|
+
return cls(
|
|
426
|
+
**cls._base_from_dict(data),
|
|
427
|
+
criteria=data["criteria"],
|
|
428
|
+
prompt_id=data["prompt_id"],
|
|
429
|
+
default_model=data.get("default_model") or get_config().get_model_for_role("judge") or "claude-sonnet-4-6",
|
|
430
|
+
default_model_api_base=data.get("default_model_api_base"),
|
|
431
|
+
score_aggregator=ScoreAggregator(raw_agg) if raw_agg else None,
|
|
432
|
+
verifier_id=data.get("verifier_id"),
|
|
433
|
+
agent_name=data.get("agent_name"),
|
|
434
|
+
trajectory_filter=TrajectoryFilter.from_dict(raw_tf) if raw_tf else None,
|
|
435
|
+
max_thinking_tokens=data.get("max_thinking_tokens"),
|
|
436
|
+
effort=data.get("effort"),
|
|
437
|
+
use_agent_judge=data.get("use_agent_judge", True),
|
|
438
|
+
use_trajectory=data.get("use_trajectory", True),
|
|
439
|
+
judge_a2a_agent_id=data.get("judge_a2a_agent_id"),
|
|
440
|
+
judge_sandbox_type=data.get("judge_sandbox_type"),
|
|
441
|
+
judge_priority=data.get("judge_priority"),
|
|
442
|
+
judge_timeout_seconds=data.get("judge_timeout_seconds"),
|
|
443
|
+
output_format=data.get("output_format", "rubric_binary"),
|
|
444
|
+
grading_policy_prompt=data.get("grading_policy_prompt"),
|
|
445
|
+
context_facts_for_judge=data.get("context_facts_for_judge"),
|
|
446
|
+
)
|
|
447
|
+
|
|
448
|
+
def _resolved_criteria(self, context: TaskStepContext) -> list[dict]:
|
|
449
|
+
"""Criteria for this run: a per-run ``step_params`` override replaces the stored list.
|
|
450
|
+
|
|
451
|
+
Replace-on-presence, like ``load_artifact`` — an explicit ``[]`` replaces rather
|
|
452
|
+
than reverting (presence check, not truthiness). Returns a copy; never mutates
|
|
453
|
+
``self``, which is shared across concurrent rollouts.
|
|
454
|
+
"""
|
|
455
|
+
step_overrides = self.step_param_overrides(context)
|
|
456
|
+
return list(step_overrides["criteria"]) if "criteria" in step_overrides else self.criteria
|
|
457
|
+
|
|
458
|
+
async def execute(self, context: TaskStepContext) -> TaskStepContext:
|
|
459
|
+
prompt_response = next((pr for pr in context.prompt_responses if pr.prompt_id == self.prompt_id), None)
|
|
460
|
+
if prompt_response is None:
|
|
461
|
+
raise RuntimeError(f"PromptResponse with prompt_id='{self.prompt_id}' not found in context")
|
|
462
|
+
|
|
463
|
+
if prompt_response.error_type:
|
|
464
|
+
logger.warning(f"Skipping verification '{self.verifier_id}': prompt had error_type={prompt_response.error_type}")
|
|
465
|
+
self._write_skipped_entries(
|
|
466
|
+
context, "prompt_error", f"Skipped: prompt had error_type={prompt_response.error_type}")
|
|
467
|
+
return context
|
|
468
|
+
|
|
469
|
+
per_turn_uris = [u for u in (prompt_response.target_agent_per_turn_trajectory_s3_uris or []) if u]
|
|
470
|
+
if self.use_trajectory and not (per_turn_uris or prompt_response.agent_trajectory_s3_uri):
|
|
471
|
+
raise RuntimeError(f"No trajectory available for prompt_id='{self.prompt_id}'")
|
|
472
|
+
|
|
473
|
+
overrides = context.metadata.get("user_overrides", {})
|
|
474
|
+
# Resolved into a local, not onto self: one step instance is shared across
|
|
475
|
+
# concurrent rollouts, so mutating self would leak the override between them.
|
|
476
|
+
use_agent_judge_override = overrides.get("use_agent_judge")
|
|
477
|
+
use_agent_judge = use_agent_judge_override if use_agent_judge_override is not None else self.use_agent_judge
|
|
478
|
+
criteria = self._resolved_criteria(context)
|
|
479
|
+
# The judge sees/echoes short keys (c1..cN), not UUIDs; frame labels use them too, hence before compaction.
|
|
480
|
+
criteria_for_judge, real_by_short = _to_short_keyed_criteria(criteria)
|
|
481
|
+
apply_filter_override = overrides.get("apply_trajectory_filter")
|
|
482
|
+
if apply_filter_override is False:
|
|
483
|
+
filter_to_apply = None
|
|
484
|
+
elif apply_filter_override is True:
|
|
485
|
+
filter_to_apply = self.trajectory_filter or TrajectoryFilter()
|
|
486
|
+
else:
|
|
487
|
+
filter_to_apply = self.trajectory_filter
|
|
488
|
+
|
|
489
|
+
# Multi-turn: judge every turn (fed from the per-turn URIs already on the
|
|
490
|
+
# PromptResponse), not just the last. DEFAULT compaction runs per turn; SCREENSHOT
|
|
491
|
+
# across turns isn't supported yet — fail fast rather than silently judging only the
|
|
492
|
+
# last turn and producing misleading results.
|
|
493
|
+
multiturn = self.use_trajectory and len(per_turn_uris) >= 2
|
|
494
|
+
if multiturn and filter_to_apply is not None and filter_to_apply.compaction_type == CompactionType.SCREENSHOT:
|
|
495
|
+
raise RuntimeError(
|
|
496
|
+
f"Verifier '{self.verifier_id}': SCREENSHOT compaction is not supported on a "
|
|
497
|
+
f"multi-turn run ({len(per_turn_uris)} turns) — it would silently judge only the "
|
|
498
|
+
"last turn. Use the DEFAULT filter (compacted per turn) or no filter."
|
|
499
|
+
)
|
|
500
|
+
|
|
501
|
+
per_criterion_filter = _is_per_criterion(filter_to_apply)
|
|
502
|
+
# Per-criterion frames are image attachments for a direct judge; the agent judge loads the raw file.
|
|
503
|
+
if use_agent_judge and per_criterion_filter:
|
|
504
|
+
raise RuntimeError(
|
|
505
|
+
f"Verifier '{self.verifier_id}': frame_strategy=per_criterion only applies to the "
|
|
506
|
+
"direct LLM judge (use_agent_judge=False)."
|
|
507
|
+
)
|
|
508
|
+
|
|
509
|
+
# Per-run dir so per-turn files can't collide with a prior run's on a reused (agent_name)
|
|
510
|
+
# judge sandbox — a shorter run would otherwise leave stale later-turn files behind.
|
|
511
|
+
multiturn_dir = f"{self.TRAJECTORY_CONTAINER_DIR}/{uuid.uuid4().hex[:12]}" if multiturn else None
|
|
512
|
+
|
|
513
|
+
# Single-file compaction is only needed off the multi-turn path. It reads the trajectory,
|
|
514
|
+
# and for the DEFAULT filter writes a compacted copy back, so it runs on a thread.
|
|
515
|
+
compacted = _CompactedTrajectory.empty() if multiturn else await asyncio.to_thread(
|
|
516
|
+
self._compact_trajectory, prompt_response, filter_to_apply, criteria=criteria,
|
|
517
|
+
label_ids={real: short for short, real in real_by_short.items()})
|
|
518
|
+
if not use_agent_judge:
|
|
519
|
+
compacted.tool_result_files = [] # only an agent judge's container reads them; they can be large
|
|
520
|
+
if self._spec().cites_evidence and not compacted.per_criterion:
|
|
521
|
+
fmt = self.output_format.value
|
|
522
|
+
if per_criterion_filter:
|
|
523
|
+
# The selection found no screenshots (none recorded, or malformed): a fact about the run,
|
|
524
|
+
# not the configuration — a skipped entry, as for a prompt error.
|
|
525
|
+
logger.warning(
|
|
526
|
+
f"Skipping verification '{self.verifier_id}': output_format={fmt} needs "
|
|
527
|
+
"per-criterion frames, but the trajectory holds no screenshots."
|
|
528
|
+
)
|
|
529
|
+
self._write_skipped_entries(
|
|
530
|
+
context, "no_screenshots",
|
|
531
|
+
f"Skipped: {fmt} needs per-criterion frames, but the trajectory holds no screenshots")
|
|
532
|
+
return context
|
|
533
|
+
# The constructor checked the stored filter; a run-time override can still drop it, leaving a
|
|
534
|
+
# prompt that demands `frame` / `evidence_status` with nothing to cite.
|
|
535
|
+
raise RuntimeError(
|
|
536
|
+
f"Verifier '{self.verifier_id}': output_format={fmt} needs per-criterion frames, "
|
|
537
|
+
"but this run's trajectory filter attached none (user_overrides.apply_trajectory_filter=False?)."
|
|
538
|
+
)
|
|
539
|
+
|
|
540
|
+
auto_deployed_judge = None
|
|
541
|
+
judge_agent = None
|
|
542
|
+
judge_a2a_url: Optional[str] = None
|
|
543
|
+
judge_sandbox_id: Optional[str] = None
|
|
544
|
+
judge_agent_card: dict = {}
|
|
545
|
+
if use_agent_judge:
|
|
546
|
+
if self.agent_name is not None:
|
|
547
|
+
agent = next((a for a in context.deployed_agents if a.agent_name == self.agent_name), None)
|
|
548
|
+
if agent is None:
|
|
549
|
+
raise RuntimeError(f"Agent '{self.agent_name}' not found in context.deployed_agents")
|
|
550
|
+
if not agent.sandbox_id:
|
|
551
|
+
raise RuntimeError(f"Agent '{self.agent_name}' has no sandbox_id")
|
|
552
|
+
judge_a2a_url = agent.a2a_url or agent.api_url
|
|
553
|
+
judge_sandbox_id = agent.sandbox_id
|
|
554
|
+
judge_agent_card = agent.a2a_card or {}
|
|
555
|
+
judge_agent = agent
|
|
556
|
+
else:
|
|
557
|
+
from agent_env.a2a_agent import A2AAgent
|
|
558
|
+
from agent_env.config import get_config
|
|
559
|
+
|
|
560
|
+
config = get_config()
|
|
561
|
+
api_key = (
|
|
562
|
+
overrides.get("judge_litellm_api_key")
|
|
563
|
+
or overrides.get("litellm_api_key")
|
|
564
|
+
or config.get_litellm_api_key()
|
|
565
|
+
)
|
|
566
|
+
litellm_base_url = (
|
|
567
|
+
overrides.get("judge_litellm_base_url")
|
|
568
|
+
or overrides.get("litellm_base_url")
|
|
569
|
+
or config.get_litellm_base_url()
|
|
570
|
+
)
|
|
571
|
+
env_vars = {"LITELLM_API_KEY": api_key, "LITELLM_BASE_URL": litellm_base_url}
|
|
572
|
+
judge_project_id = context.metadata.get("project_id")
|
|
573
|
+
judge_customer = context.metadata.get("customer_id")
|
|
574
|
+
if judge_customer:
|
|
575
|
+
env_vars["LITELLM_USER"] = judge_customer
|
|
576
|
+
if judge_project_id:
|
|
577
|
+
env_vars["LITELLM_PROJECT_ID"] = judge_project_id
|
|
578
|
+
resolved_judge_id = self.judge_a2a_agent_id or config.get_default_a2a_agent_id()
|
|
579
|
+
a2a_agent = A2AAgent.get(resolved_judge_id)
|
|
580
|
+
deploy_kwargs = {
|
|
581
|
+
"env_vars": env_vars,
|
|
582
|
+
"attribution": {
|
|
583
|
+
k: v for k, v in
|
|
584
|
+
(("project_id", judge_project_id), ("customer", judge_customer))
|
|
585
|
+
if v
|
|
586
|
+
},
|
|
587
|
+
}
|
|
588
|
+
resolved_sandbox_type = overrides.get("agent_sandbox") or self.judge_sandbox_type
|
|
589
|
+
if resolved_sandbox_type:
|
|
590
|
+
deploy_kwargs["sandbox_type"] = resolved_sandbox_type
|
|
591
|
+
_priority_override = overrides.get("priority")
|
|
592
|
+
resolved_priority = _priority_override if _priority_override is not None else self.judge_priority
|
|
593
|
+
if resolved_priority is not None:
|
|
594
|
+
deploy_kwargs["priority"] = resolved_priority
|
|
595
|
+
auto_deployed_judge = await a2a_agent.deploy(**deploy_kwargs)
|
|
596
|
+
judge_a2a_url = auto_deployed_judge.a2a_url
|
|
597
|
+
judge_sandbox_id = auto_deployed_judge.sandbox_id
|
|
598
|
+
judge_agent_card = auto_deployed_judge.agent_card
|
|
599
|
+
judge_agent = auto_deployed_judge
|
|
600
|
+
logger.info(f"Auto-deployed judge A2A agent '{resolved_judge_id}' at {judge_a2a_url}")
|
|
601
|
+
if self.use_trajectory:
|
|
602
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_agent_sandbox_provider
|
|
603
|
+
judge_sandbox_type = auto_deployed_judge.sandbox_type if auto_deployed_judge else (agent.sandbox_type if self.agent_name else None)
|
|
604
|
+
provider = build_sandbox_provider(judge_sandbox_type) if judge_sandbox_type else get_agent_sandbox_provider()
|
|
605
|
+
sandbox = await provider.get_sandbox(judge_sandbox_id)
|
|
606
|
+
if multiturn:
|
|
607
|
+
await self._load_per_turn_trajectories(sandbox, per_turn_uris, multiturn_dir, filter_to_apply)
|
|
608
|
+
else:
|
|
609
|
+
await sandbox.write_file_from_s3(compacted.container_s3_uri, self.TRAJECTORY_CONTAINER_PATH)
|
|
610
|
+
if compacted.tool_result_files:
|
|
611
|
+
await self._load_tool_result_files(sandbox, compacted.tool_result_files)
|
|
612
|
+
compacted.tool_result_files = []
|
|
613
|
+
|
|
614
|
+
try:
|
|
615
|
+
model = overrides.get("judge_model") or self.default_model
|
|
616
|
+
criteria_for_prompt = [
|
|
617
|
+
{**c, "negative": True} if (c.get("weight") is not None and c["weight"] < 0) else c
|
|
618
|
+
for c in criteria_for_judge
|
|
619
|
+
]
|
|
620
|
+
criteria_json = json.dumps(criteria_for_prompt, indent=2)
|
|
621
|
+
agent_prompt_text = prompt_response.prompt_text or ""
|
|
622
|
+
judge_trajectory_s3_uri: Optional[str] = None
|
|
623
|
+
judge_effort = overrides.get("judge_effort") or self.effort
|
|
624
|
+
judge_max_thinking_tokens = overrides.get("judge_max_thinking_tokens") or self.max_thinking_tokens
|
|
625
|
+
loaded_for_judge: list[dict] = []
|
|
626
|
+
if use_agent_judge and self.agent_name is not None:
|
|
627
|
+
loaded_for_judge = [
|
|
628
|
+
e for e in (context.metadata.get("loaded_file_artifact_universes") or [])
|
|
629
|
+
if e.get("agent_name") == self.agent_name
|
|
630
|
+
]
|
|
631
|
+
context_facts = (resolve_context_facts(self.context_facts_for_judge, context.metadata)
|
|
632
|
+
if self.context_facts_for_judge else [])
|
|
633
|
+
image_blocks: list[dict] = []
|
|
634
|
+
if use_agent_judge:
|
|
635
|
+
# Agent judge can't use inline screenshot frames; it loads the raw file.
|
|
636
|
+
if filter_to_apply and filter_to_apply.compaction_type == CompactionType.SCREENSHOT:
|
|
637
|
+
logger.warning(
|
|
638
|
+
f"compaction_type=screenshot only applies on the direct-LLM judge; "
|
|
639
|
+
f"verifier '{self.verifier_id}' uses an agent judge — raw trajectory "
|
|
640
|
+
"passed through unchanged."
|
|
641
|
+
)
|
|
642
|
+
trajectory_path = None
|
|
643
|
+
if self.use_trajectory:
|
|
644
|
+
trajectory_path = multiturn_dir if multiturn else self.TRAJECTORY_CONTAINER_PATH
|
|
645
|
+
eval_prompt = self._build_eval_prompt(
|
|
646
|
+
agent_prompt=agent_prompt_text,
|
|
647
|
+
agent_response=prompt_response.response,
|
|
648
|
+
criteria_json=criteria_json,
|
|
649
|
+
trajectory_path=trajectory_path,
|
|
650
|
+
loaded_artifacts=loaded_for_judge,
|
|
651
|
+
context_facts=context_facts,
|
|
652
|
+
)
|
|
653
|
+
if self.use_trajectory and multiturn:
|
|
654
|
+
eval_prompt += self._MULTITURN_DIR_NOTE.format(n=len(per_turn_uris))
|
|
655
|
+
else:
|
|
656
|
+
image_blocks = compacted.image_blocks
|
|
657
|
+
# Direct judge embeds the trajectory inline; DEFAULT has no pre-rendered text.
|
|
658
|
+
if multiturn:
|
|
659
|
+
trajectory_inline = await asyncio.to_thread(self._merge_per_turn_text, per_turn_uris, filter_to_apply)
|
|
660
|
+
else:
|
|
661
|
+
trajectory_inline = compacted.inline_text
|
|
662
|
+
if trajectory_inline is None and compacted.container_s3_uri:
|
|
663
|
+
trajectory_inline = await asyncio.to_thread(self._read_trajectory_text, compacted.container_s3_uri)
|
|
664
|
+
eval_prompt = self._build_eval_prompt(
|
|
665
|
+
agent_prompt=agent_prompt_text,
|
|
666
|
+
agent_response=prompt_response.response,
|
|
667
|
+
criteria_json=criteria_json,
|
|
668
|
+
trajectory_inline=trajectory_inline,
|
|
669
|
+
image_blocks=image_blocks,
|
|
670
|
+
per_criterion_frames=compacted.per_criterion,
|
|
671
|
+
context_facts=context_facts,
|
|
672
|
+
)
|
|
673
|
+
if image_blocks:
|
|
674
|
+
logger.info(
|
|
675
|
+
f"Verifier '{self.verifier_id}': direct judge — {_image_count(image_blocks)} "
|
|
676
|
+
f"image(s){' chosen per criterion' if compacted.per_criterion else ''}, "
|
|
677
|
+
f"eval prompt {len(eval_prompt)} chars (~{len(eval_prompt) // 4} tokens)."
|
|
678
|
+
)
|
|
679
|
+
|
|
680
|
+
verification_results, judge_output_retries, judge_output_discrepancies, judge_trajectory_s3_uri = (
|
|
681
|
+
await self._run_judge_with_output_retries(
|
|
682
|
+
eval_prompt=eval_prompt,
|
|
683
|
+
context=context,
|
|
684
|
+
model=model,
|
|
685
|
+
judge_a2a_url=judge_a2a_url,
|
|
686
|
+
judge_agent_card=judge_agent_card,
|
|
687
|
+
judge_agent=judge_agent,
|
|
688
|
+
judge_effort=judge_effort,
|
|
689
|
+
judge_max_thinking_tokens=judge_max_thinking_tokens,
|
|
690
|
+
use_agent_judge=use_agent_judge,
|
|
691
|
+
criteria=criteria_for_judge,
|
|
692
|
+
image_blocks=image_blocks,
|
|
693
|
+
)
|
|
694
|
+
)
|
|
695
|
+
# Rows come back keyed by c1..cN; restore the real criterion ids, in the cited frame labels too.
|
|
696
|
+
_restore_criterion_ids(verification_results, real_by_short)
|
|
697
|
+
if isinstance(verification_results, ResultRows):
|
|
698
|
+
_restore_frame_labels(verification_results, real_by_short)
|
|
699
|
+
_restore_frame_labels(verification_results.checks, real_by_short)
|
|
700
|
+
finally:
|
|
701
|
+
if auto_deployed_judge is not None:
|
|
702
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_agent_sandbox_provider
|
|
703
|
+
try:
|
|
704
|
+
judge_type = auto_deployed_judge.sandbox_type
|
|
705
|
+
provider = build_sandbox_provider(judge_type) if judge_type else get_agent_sandbox_provider()
|
|
706
|
+
sandbox = await provider.get_sandbox(auto_deployed_judge.sandbox_id)
|
|
707
|
+
await sandbox.terminate()
|
|
708
|
+
logger.info(f"Terminated auto-deployed judge sandbox {auto_deployed_judge.sandbox_id}")
|
|
709
|
+
except Exception as e:
|
|
710
|
+
logger.warning(f"Failed to terminate auto-deployed judge sandbox: {e}")
|
|
711
|
+
|
|
712
|
+
judge_call_fields: dict = {
|
|
713
|
+
"compact_trajectory_s3_uri": compacted.compact_s3_uri,
|
|
714
|
+
"judge_trajectory_s3_uri": judge_trajectory_s3_uri,
|
|
715
|
+
}
|
|
716
|
+
if judge_output_retries:
|
|
717
|
+
judge_call_fields["judge_output_retries"] = judge_output_retries
|
|
718
|
+
if judge_output_discrepancies:
|
|
719
|
+
judge_call_fields["judge_output_discrepancies"] = judge_output_discrepancies
|
|
720
|
+
self._write_entries(context, verification_results, judge_call_fields)
|
|
721
|
+
return context
|
|
722
|
+
|
|
723
|
+
def _write_entries(self, context: TaskStepContext, verification_results: list[dict], judge_call_fields: dict) -> None:
|
|
724
|
+
"""Store the rubric entry under ``verifier_id`` and, for rubric_evidence_with_mistakes, the
|
|
725
|
+
trajectory-mistakes entry under ``trajectory_mistakes_key(verifier_id)``; ``judge_call_fields`` (URIs,
|
|
726
|
+
retries) go on both. The mistake rows are built before either entry is written, so a response they
|
|
727
|
+
cannot be derived from leaves neither behind."""
|
|
728
|
+
score = aggregate_score(verification_results, self.score_aggregator)
|
|
729
|
+
mistake_rows: Optional[list[dict]] = None
|
|
730
|
+
if self._writes_mistakes_entry:
|
|
731
|
+
if not isinstance(verification_results, ResultRows):
|
|
732
|
+
raise RuntimeError(
|
|
733
|
+
f"Verifier '{self.verifier_id}': the judge response carries no mistake findings "
|
|
734
|
+
f"({type(verification_results).__name__})")
|
|
735
|
+
mistake_rows = trajectory_mistakes_rows_from_evidence(verification_results)
|
|
736
|
+
verifications = context.metadata.setdefault("verifications", {})
|
|
737
|
+
verification_entry = {
|
|
738
|
+
**self._entry_format_fields(),
|
|
739
|
+
"results": list(verification_results),
|
|
740
|
+
"score": score,
|
|
741
|
+
**judge_call_fields,
|
|
742
|
+
}
|
|
743
|
+
if isinstance(verification_results, ResultRows):
|
|
744
|
+
# rubric_evidence: the judge's `reasoning` and policy `checks` ride on the entry, not the rows.
|
|
745
|
+
verification_entry["reasoning"] = verification_results.reasoning
|
|
746
|
+
verification_entry["checks"] = verification_results.checks
|
|
747
|
+
verifications[self.verifier_id] = verification_entry
|
|
748
|
+
logger.info(f"Verification '{self.verifier_id}' complete: {len(verification_results)} criteria, score={score}")
|
|
749
|
+
|
|
750
|
+
if mistake_rows is not None:
|
|
751
|
+
mistakes_score = aggregate_score(mistake_rows, ScoreAggregator.WEIGHTED_AVERAGE)
|
|
752
|
+
mistakes_key = trajectory_mistakes_key(self.verifier_id)
|
|
753
|
+
verifications[mistakes_key] = {
|
|
754
|
+
**self._mistakes_entry_fields(),
|
|
755
|
+
"results": mistake_rows,
|
|
756
|
+
"score": mistakes_score,
|
|
757
|
+
**judge_call_fields,
|
|
758
|
+
}
|
|
759
|
+
logger.info(
|
|
760
|
+
f"Verification '{mistakes_key}' complete (from '{self.verifier_id}'): "
|
|
761
|
+
f"{len(mistake_rows)} rows, score={mistakes_score}")
|
|
762
|
+
|
|
763
|
+
def _compact_trajectory(
|
|
764
|
+
self,
|
|
765
|
+
prompt_response: "PromptResponse",
|
|
766
|
+
filter_to_apply: Optional[TrajectoryFilter],
|
|
767
|
+
criteria: Optional[list[dict]] = None,
|
|
768
|
+
label_ids: Optional[dict[str, str]] = None,
|
|
769
|
+
) -> _CompactedTrajectory:
|
|
770
|
+
"""Compact per the filter and return every representation; judge-agnostic — the
|
|
771
|
+
caller picks which one its judge path consumes. ``criteria`` / ``label_ids`` (criterion id ->
|
|
772
|
+
the key the judge sees) only matter to per-criterion frame selection."""
|
|
773
|
+
if not self.use_trajectory:
|
|
774
|
+
return _CompactedTrajectory.empty()
|
|
775
|
+
|
|
776
|
+
# Fall back to the last per-turn URI when agent_trajectory_s3_uri is unset (the value
|
|
777
|
+
# it normally holds). The execute() guard guarantees one source exists; the raise only narrows the type.
|
|
778
|
+
raw_uri = prompt_response.agent_trajectory_s3_uri or next(
|
|
779
|
+
(u for u in reversed(prompt_response.target_agent_per_turn_trajectory_s3_uris or []) if u),
|
|
780
|
+
None,
|
|
781
|
+
)
|
|
782
|
+
if raw_uri is None:
|
|
783
|
+
raise RuntimeError(f"No trajectory available for prompt_id='{self.prompt_id}'")
|
|
784
|
+
ctype = filter_to_apply.compaction_type if filter_to_apply else CompactionType.DEFAULT
|
|
785
|
+
|
|
786
|
+
if filter_to_apply is not None and ctype == CompactionType.SCREENSHOT:
|
|
787
|
+
raw_text = self._read_trajectory_text(raw_uri)
|
|
788
|
+
return self._compact_screenshot(raw_text, raw_uri, filter_to_apply, criteria or [], label_ids or {})
|
|
789
|
+
|
|
790
|
+
s3_uri, tool_files = raw_uri, []
|
|
791
|
+
compact_s3_uri: Optional[str] = None
|
|
792
|
+
if filter_to_apply and ctype == CompactionType.DEFAULT:
|
|
793
|
+
s3_uri, tool_files = self._filter_trajectory(raw_uri, filter_to_apply)
|
|
794
|
+
# Return the URI; never write it back onto prompt_response. It's an appended
|
|
795
|
+
# item in context.prompt_responses ($addToSet, immutable) — mutating it re-adds
|
|
796
|
+
# a duplicate (hub renders the trajectory twice). Recorded on the result instead.
|
|
797
|
+
compact_s3_uri = s3_uri
|
|
798
|
+
return _CompactedTrajectory.for_default(s3_uri, tool_files, compact_s3_uri)
|
|
799
|
+
|
|
800
|
+
def _compact_screenshot(
|
|
801
|
+
self, raw_text: str, raw_uri: str, tf: TrajectoryFilter, criteria: list[dict],
|
|
802
|
+
label_ids: dict[str, str],
|
|
803
|
+
) -> _CompactedTrajectory:
|
|
804
|
+
"""SCREENSHOT compaction for the direct judge: the frames ``frame_strategy`` picks and the text
|
|
805
|
+
``trajectory_text`` selects."""
|
|
806
|
+
per_criterion = tf.frame_strategy == FrameStrategy.PER_CRITERION
|
|
807
|
+
action_log_text = tf.trajectory_text == TrajectoryText.ACTION_LOG
|
|
808
|
+
transcript = transcript_from_raw(raw_text) if per_criterion or action_log_text else Transcript([], [])
|
|
809
|
+
attached: list[str] = [] # frame payloads the FULL text flags as attached (final frames only)
|
|
810
|
+
if per_criterion:
|
|
811
|
+
# The regex knobs are matched case-insensitively (see TrajectoryFilter).
|
|
812
|
+
exclude = re.compile(tf.evidence_exclude_pattern, re.I) if tf.evidence_exclude_pattern else None
|
|
813
|
+
always_show = {label: re.compile(pattern, re.I) for label, pattern in (tf.always_show_actions or {}).items()}
|
|
814
|
+
labeled = select_frames_per_criterion(transcript.actions, criteria, max_frames=tf.frame_budget,
|
|
815
|
+
exclude_pattern=exclude, always_show=always_show, label_ids=label_ids)
|
|
816
|
+
image_blocks = _labeled_image_blocks(labeled)
|
|
817
|
+
else:
|
|
818
|
+
final = final_image_frames(raw_text, tf.screenshot_last_n)
|
|
819
|
+
image_blocks = [_image_url_block(f) for f in final]
|
|
820
|
+
attached = [f.data for f in final]
|
|
821
|
+
if action_log_text:
|
|
822
|
+
inline_text = action_log(transcript.actions, messages=transcript.messages, max_lines=tf.action_log_max_lines)
|
|
823
|
+
else:
|
|
824
|
+
inline_text = strip_trajectory_images(raw_text, attached=attached)
|
|
825
|
+
# A trajectory with no screenshots selects nothing: the judge gets the text alone, with no frame rules.
|
|
826
|
+
return _CompactedTrajectory.for_screenshot(inline_text, image_blocks, container_s3_uri=raw_uri,
|
|
827
|
+
per_criterion=per_criterion and bool(image_blocks))
|
|
828
|
+
|
|
829
|
+
def _filter_trajectory(self, s3_uri: str, trajectory_filter: TrajectoryFilter) -> tuple[str, list[tuple[str, str]]]:
|
|
830
|
+
"""Download trajectory from S3, apply compact filter, re-upload as a compact version.
|
|
831
|
+
|
|
832
|
+
Returns:
|
|
833
|
+
(compact_s3_uri, tool_result_files) where tool_result_files is a list of
|
|
834
|
+
(container_path, content_json) pairs for externalized tool results.
|
|
835
|
+
"""
|
|
836
|
+
from agent_env.config import get_config
|
|
837
|
+
|
|
838
|
+
config = get_config()
|
|
839
|
+
object_store = config.get_object_store()
|
|
840
|
+
spans = json.loads(object_store.get(s3_uri))
|
|
841
|
+
filtered, tool_result_files = compact_otel_trajectory(spans, trajectory_filter)
|
|
842
|
+
compact_key = f"{config.get_artifact_key_prefix()}compacted-trajectories/{uuid.uuid4().hex}.json"
|
|
843
|
+
object_url = object_store.put(compact_key, json.dumps(filtered).encode(), content_type="application/json")
|
|
844
|
+
return object_url, tool_result_files
|
|
845
|
+
|
|
846
|
+
async def _load_tool_result_files(self, sandbox, tool_result_files: list[tuple[str, str]]) -> None:
|
|
847
|
+
"""Write externalized tool result files into the agent container."""
|
|
848
|
+
for container_path, content in tool_result_files:
|
|
849
|
+
await sandbox.write_file_from_text(content, container_path)
|
|
850
|
+
logger.info(f"Loaded {len(tool_result_files)} tool result files into container")
|
|
851
|
+
|
|
852
|
+
async def _load_trajectory_into_container(self, sandbox_id: str, s3_uri: str) -> None:
|
|
853
|
+
"""Load trajectory from S3 into an existing agent's container."""
|
|
854
|
+
from agent_env.providers.sandbox_providers.sandbox_provider import get_agent_sandbox_provider
|
|
855
|
+
sandbox = await get_agent_sandbox_provider().get_sandbox(sandbox_id)
|
|
856
|
+
await sandbox.write_file_from_s3(s3_uri, self.TRAJECTORY_CONTAINER_PATH)
|
|
857
|
+
|
|
858
|
+
def _read_trajectory_text(self, s3_uri: str) -> str:
|
|
859
|
+
from agent_env.config import get_config
|
|
860
|
+
return get_config().get_object_store().get(s3_uri).decode("utf-8", errors="replace")
|
|
861
|
+
|
|
862
|
+
async def _load_per_turn_trajectories(
|
|
863
|
+
self, sandbox, per_turn_uris: list[str], container_dir: str,
|
|
864
|
+
trajectory_filter: Optional[TrajectoryFilter] = None,
|
|
865
|
+
) -> None:
|
|
866
|
+
"""Load each turn into the judge container as turn_NN.json under ``container_dir``.
|
|
867
|
+
|
|
868
|
+
No filter → direct S3 pull per turn. DEFAULT filter → compact each turn in memory and
|
|
869
|
+
write as text, its externalized tool-result files namespaced ``turn_NN_`` to avoid
|
|
870
|
+
collisions, then loaded into the sandbox. The write methods create ``container_dir``
|
|
871
|
+
inside the container, so no separate mkdir is needed.
|
|
872
|
+
"""
|
|
873
|
+
tool_result_files: list[tuple[str, str]] = []
|
|
874
|
+
for i, uri in enumerate(per_turn_uris, start=1):
|
|
875
|
+
dest = f"{container_dir}/turn_{i:02d}.json"
|
|
876
|
+
if trajectory_filter is not None:
|
|
877
|
+
content, turn_files = await asyncio.to_thread(
|
|
878
|
+
self._filter_trajectory_content, uri, trajectory_filter, f"turn_{i:02d}_"
|
|
879
|
+
)
|
|
880
|
+
await sandbox.write_file_from_text(content, dest)
|
|
881
|
+
tool_result_files.extend(turn_files)
|
|
882
|
+
else:
|
|
883
|
+
await sandbox.write_file_from_s3(uri, dest)
|
|
884
|
+
if tool_result_files:
|
|
885
|
+
await self._load_tool_result_files(sandbox, tool_result_files)
|
|
886
|
+
logger.info(
|
|
887
|
+
f"Loaded {len(per_turn_uris)} per-turn trajectories into {container_dir}"
|
|
888
|
+
f"{' (filtered)' if trajectory_filter else ''}, {len(tool_result_files)} tool-result files"
|
|
889
|
+
)
|
|
890
|
+
|
|
891
|
+
def _merge_per_turn_text(
|
|
892
|
+
self, per_turn_uris: list[str], trajectory_filter: Optional[TrajectoryFilter] = None,
|
|
893
|
+
) -> str:
|
|
894
|
+
"""Concatenate every turn's trajectory text, turn-marked, for the direct-LLM judge
|
|
895
|
+
(embedded inline; in-memory, no S3 write). A DEFAULT filter compacts each turn; its
|
|
896
|
+
externalized files are dropped, as on the single-turn direct-judge path (no container)."""
|
|
897
|
+
parts = []
|
|
898
|
+
for i, uri in enumerate(per_turn_uris, start=1):
|
|
899
|
+
if trajectory_filter is not None:
|
|
900
|
+
text, _ = self._filter_trajectory_content(uri, trajectory_filter, f"turn_{i:02d}_")
|
|
901
|
+
else:
|
|
902
|
+
text = self._read_trajectory_text(uri)
|
|
903
|
+
parts.append(f"===== Turn {i} =====\n{text}")
|
|
904
|
+
return "\n\n".join(parts)
|
|
905
|
+
|
|
906
|
+
def _filter_trajectory_content(
|
|
907
|
+
self, s3_uri: str, trajectory_filter: TrajectoryFilter, result_file_prefix: str = "",
|
|
908
|
+
) -> tuple[str, list[tuple[str, str]]]:
|
|
909
|
+
"""DEFAULT-compact one trajectory in memory (no S3 re-upload), returning
|
|
910
|
+
(compacted_json_text, tool_result_files). ``result_file_prefix`` namespaces the
|
|
911
|
+
externalized filenames so per-turn files don't collide. In-memory sibling of
|
|
912
|
+
``_filter_trajectory`` (which re-uploads to S3 for the single-file path)."""
|
|
913
|
+
spans = json.loads(self._read_trajectory_text(s3_uri))
|
|
914
|
+
filtered, tool_result_files = compact_otel_trajectory(
|
|
915
|
+
spans, trajectory_filter, result_file_prefix=result_file_prefix,
|
|
916
|
+
)
|
|
917
|
+
return json.dumps(filtered), tool_result_files
|
|
918
|
+
|
|
919
|
+
async def _prompt_llm_judge(
|
|
920
|
+
self,
|
|
921
|
+
eval_prompt: str,
|
|
922
|
+
*,
|
|
923
|
+
model: str,
|
|
924
|
+
context: TaskStepContext,
|
|
925
|
+
image_blocks: Optional[list[dict]] = None,
|
|
926
|
+
) -> dict:
|
|
927
|
+
"""Direct LiteLLM judge — no agent boot, no tools. Returns {response, trajectory_s3_uri}.
|
|
928
|
+
|
|
929
|
+
When ``image_blocks`` are provided the user message becomes multimodal
|
|
930
|
+
(text + images); otherwise it stays a plain string, identical to before."""
|
|
931
|
+
import litellm
|
|
932
|
+
|
|
933
|
+
from agent_env.config import get_config
|
|
934
|
+
from agent_env.utils.litellm_attribution import build_litellm_cost_attribution_kwargs
|
|
935
|
+
|
|
936
|
+
overrides = context.metadata.get("user_overrides", {})
|
|
937
|
+
config = get_config()
|
|
938
|
+
cost_kwargs = build_litellm_cost_attribution_kwargs(context.metadata)
|
|
939
|
+
call_config = config.resolve_model_call(
|
|
940
|
+
model,
|
|
941
|
+
default_api_key=overrides.get("judge_litellm_api_key") or overrides.get("litellm_api_key"),
|
|
942
|
+
base_override=overrides.get("judge_litellm_base_url")
|
|
943
|
+
or overrides.get("litellm_base_url")
|
|
944
|
+
or self.default_model_api_base,
|
|
945
|
+
)
|
|
946
|
+
user_content = (
|
|
947
|
+
[{"type": "text", "text": eval_prompt}, *image_blocks]
|
|
948
|
+
if image_blocks
|
|
949
|
+
else eval_prompt
|
|
950
|
+
)
|
|
951
|
+
response_format = {
|
|
952
|
+
"type": "json_schema",
|
|
953
|
+
"json_schema": {
|
|
954
|
+
"name": "rubrics_verification",
|
|
955
|
+
"schema": self._spec().output_format["schema"],
|
|
956
|
+
"strict": True,
|
|
957
|
+
},
|
|
958
|
+
}
|
|
959
|
+
# Some endpoints reject json_schema with images. Fall back once on that exact
|
|
960
|
+
# error shape; malformed JSON is handled by the outer output-retry loop.
|
|
961
|
+
use_response_format = True
|
|
962
|
+
|
|
963
|
+
last_exc: Exception | None = None
|
|
964
|
+
for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1):
|
|
965
|
+
try:
|
|
966
|
+
request_kwargs: dict = dict(
|
|
967
|
+
model=model,
|
|
968
|
+
messages=[{"role": "user", "content": user_content}],
|
|
969
|
+
timeout=self.judge_timeout_seconds,
|
|
970
|
+
**call_config.client_kwargs(),
|
|
971
|
+
**cost_kwargs,
|
|
972
|
+
)
|
|
973
|
+
if use_response_format:
|
|
974
|
+
request_kwargs[ModelParam.RESPONSE_FORMAT] = response_format
|
|
975
|
+
response = await litellm.acompletion(**request_kwargs)
|
|
976
|
+
content = response.choices[0].message.content or ""
|
|
977
|
+
return {"response": content, "trajectory_s3_uri": None}
|
|
978
|
+
except Exception as exc:
|
|
979
|
+
last_exc = exc
|
|
980
|
+
if image_blocks and use_response_format and _looks_like_response_format_error(exc):
|
|
981
|
+
logger.warning(
|
|
982
|
+
f"Multimodal judge call with json_schema failed for verifier "
|
|
983
|
+
f"'{self.verifier_id}' ({type(exc).__name__}: {exc}); retrying "
|
|
984
|
+
f"WITHOUT response_format (text-completion + parse)."
|
|
985
|
+
)
|
|
986
|
+
use_response_format = False
|
|
987
|
+
continue
|
|
988
|
+
if attempt < self.DEFAULT_MAX_RETRIES:
|
|
989
|
+
logger.warning(f"LLM judge attempt {attempt}/{self.DEFAULT_MAX_RETRIES} failed ({type(exc).__name__}: {exc}), retrying...")
|
|
990
|
+
else:
|
|
991
|
+
logger.error(f"LLM judge failed after {self.DEFAULT_MAX_RETRIES} attempts ({type(exc).__name__}: {exc})")
|
|
992
|
+
raise RuntimeError(f"LLM judge failed after {self.DEFAULT_MAX_RETRIES} attempts") from last_exc
|
|
993
|
+
|
|
994
|
+
async def _configure_judge_a2a(
|
|
995
|
+
self,
|
|
996
|
+
*,
|
|
997
|
+
judge_a2a_url: str,
|
|
998
|
+
judge_agent_card: dict,
|
|
999
|
+
model: str,
|
|
1000
|
+
judge_effort: Optional[str],
|
|
1001
|
+
judge_max_thinking_tokens: Optional[int],
|
|
1002
|
+
context: TaskStepContext,
|
|
1003
|
+
) -> None:
|
|
1004
|
+
from agent_env.a2a_agent import A2AAgent
|
|
1005
|
+
from agent_env.a2a_agent import protocol
|
|
1006
|
+
|
|
1007
|
+
desired_config: dict = {
|
|
1008
|
+
"model": model,
|
|
1009
|
+
"effort": judge_effort,
|
|
1010
|
+
"max_thinking_tokens": judge_max_thinking_tokens,
|
|
1011
|
+
"output_format": self._spec().output_format,
|
|
1012
|
+
"timeout_seconds": self.judge_timeout_seconds,
|
|
1013
|
+
"project_id": context.metadata.get("project_id"),
|
|
1014
|
+
"task_id": context.metadata.get("task_id"),
|
|
1015
|
+
}
|
|
1016
|
+
desired_config = {k: v for k, v in desired_config.items() if v is not None}
|
|
1017
|
+
config_ext = A2AAgent.find_extension(judge_agent_card, A2AAgent.EXT_AGENT_CONFIG)
|
|
1018
|
+
if config_ext and desired_config:
|
|
1019
|
+
supported = (config_ext.get("params") or {}).get("methods", {}).get("set", {}).get("request", {}).get("supported", [])
|
|
1020
|
+
config_payload = {k: v for k, v in desired_config.items() if k in supported}
|
|
1021
|
+
if config_payload:
|
|
1022
|
+
endpoint = (config_ext.get("params") or {}).get("endpoint", "/ext/agent-config")
|
|
1023
|
+
await protocol.post_agent_config(judge_a2a_url + endpoint, config_payload)
|
|
1024
|
+
logger.info(f"Set judge agent config: {list(config_payload.keys())}")
|
|
1025
|
+
|
|
1026
|
+
async def _invoke_judge_a2a(
|
|
1027
|
+
self,
|
|
1028
|
+
*,
|
|
1029
|
+
eval_prompt: str,
|
|
1030
|
+
judge_a2a_url: str,
|
|
1031
|
+
judge_agent_card: dict,
|
|
1032
|
+
judge_agent,
|
|
1033
|
+
) -> dict:
|
|
1034
|
+
"""Send one evaluation prompt to an A2A judge and return its response."""
|
|
1035
|
+
from agent_env.a2a_agent import protocol
|
|
1036
|
+
|
|
1037
|
+
task_id, _ = await protocol.send_a2a_message(
|
|
1038
|
+
judge_a2a_url,
|
|
1039
|
+
parts=[{"kind": "text", "text": eval_prompt}],
|
|
1040
|
+
message_id=uuid.uuid4().hex,
|
|
1041
|
+
context_id=None,
|
|
1042
|
+
timeout_seconds=self.judge_timeout_seconds,
|
|
1043
|
+
)
|
|
1044
|
+
result = await protocol.poll_a2a_task(
|
|
1045
|
+
judge_a2a_url,
|
|
1046
|
+
task_id,
|
|
1047
|
+
timeout_seconds=self.judge_timeout_seconds,
|
|
1048
|
+
poll_interval_seconds=self.DEFAULT_POLL_INTERVAL_SECONDS,
|
|
1049
|
+
)
|
|
1050
|
+
state = result["status"]["state"]
|
|
1051
|
+
status_msg = (result.get("status") or {}).get("message") or {}
|
|
1052
|
+
tr = protocol.TerminalResponse.from_message(status_msg)
|
|
1053
|
+
if state == "failed":
|
|
1054
|
+
sandbox_id = getattr(judge_agent, "sandbox_id", None)
|
|
1055
|
+
logger.error(
|
|
1056
|
+
"Judge A2A task %s failed (verifier=%s sandbox=%s error_type=%s exception=%s). "
|
|
1057
|
+
"Raw A2A status message: %s",
|
|
1058
|
+
task_id, self.verifier_id, sandbox_id,
|
|
1059
|
+
tr.error_type, tr.error_class, json.dumps(status_msg, default=str)[:4000],
|
|
1060
|
+
)
|
|
1061
|
+
detail = ", ".join(filter(None, [
|
|
1062
|
+
f"error_type={tr.error_type}" if tr.error_type else None,
|
|
1063
|
+
f"exception={tr.error_class}" if tr.error_class else None,
|
|
1064
|
+
f"task_id={task_id}",
|
|
1065
|
+
f"judge_sandbox={sandbox_id}" if sandbox_id else None,
|
|
1066
|
+
]))
|
|
1067
|
+
body = agent_error_text(tr.error_message, tr.response_text)
|
|
1068
|
+
# Fetched here, inside execute()'s try, so it runs before the finally
|
|
1069
|
+
# terminates an auto-deployed judge sandbox.
|
|
1070
|
+
container_logs = await fetch_container_logs(judge_agent)
|
|
1071
|
+
if container_logs:
|
|
1072
|
+
logger.error(
|
|
1073
|
+
"Judge container logs for failed A2A task %s (verifier=%s):\n%s",
|
|
1074
|
+
task_id, self.verifier_id, container_logs,
|
|
1075
|
+
)
|
|
1076
|
+
body = f"{body}\n{container_logs}" if body else container_logs
|
|
1077
|
+
raise RuntimeError(f"Judge A2A task failed ({detail}): {body}")
|
|
1078
|
+
judge_trajectory_s3_uri = await self._fetch_judge_trajectory(
|
|
1079
|
+
judge_a2a_url=judge_a2a_url,
|
|
1080
|
+
judge_agent_card=judge_agent_card,
|
|
1081
|
+
a2a_server_task_id=task_id,
|
|
1082
|
+
)
|
|
1083
|
+
return {"response": tr.response_text, "trajectory_s3_uri": judge_trajectory_s3_uri}
|
|
1084
|
+
|
|
1085
|
+
async def _fetch_judge_trajectory(
|
|
1086
|
+
self,
|
|
1087
|
+
*,
|
|
1088
|
+
judge_a2a_url: str,
|
|
1089
|
+
judge_agent_card: dict,
|
|
1090
|
+
a2a_server_task_id: str,
|
|
1091
|
+
) -> Optional[str]:
|
|
1092
|
+
"""Best-effort capture of the judge's own reasoning trajectory, via the same
|
|
1093
|
+
EXT_TRAJECTORY extension `prompt_agent` uses, keyed by the A2A task id. Retries
|
|
1094
|
+
the fetch up to DEFAULT_MAX_RETRIES times; never raises — a fetch failure is a
|
|
1095
|
+
log line, not a broken run."""
|
|
1096
|
+
from agent_env.a2a_agent import A2AAgent
|
|
1097
|
+
|
|
1098
|
+
traj_ext = A2AAgent.find_extension(judge_agent_card, A2AAgent.EXT_TRAJECTORY)
|
|
1099
|
+
if not traj_ext:
|
|
1100
|
+
return None
|
|
1101
|
+
if not (traj_ext.get("params") or {}).get("endpoint"):
|
|
1102
|
+
# Don't guess a path — the extension is self-describing precisely so callers
|
|
1103
|
+
# never have to assume where it lives (it may differ by judge/version).
|
|
1104
|
+
logger.warning(
|
|
1105
|
+
"Verifier '%s': judge's EXT_TRAJECTORY extension has no params.endpoint — "
|
|
1106
|
+
"skipping trajectory capture", self.verifier_id,
|
|
1107
|
+
)
|
|
1108
|
+
return None
|
|
1109
|
+
get_method, get_path = A2AAgent.operation(traj_ext, "get")
|
|
1110
|
+
config = get_config()
|
|
1111
|
+
store = config.get_object_store()
|
|
1112
|
+
prefix = store.object_url(f"{config.get_artifact_key_prefix()}judge_trajectories/verifier_id={self.verifier_id}/")
|
|
1113
|
+
mode = trajectory_mode(get_method, store, by="task_id")
|
|
1114
|
+
if mode is None:
|
|
1115
|
+
logger.warning(
|
|
1116
|
+
"Verifier '%s': judge advertises no trajectory get form this object store "
|
|
1117
|
+
"can serve — skipping trajectory capture", self.verifier_id,
|
|
1118
|
+
)
|
|
1119
|
+
return None
|
|
1120
|
+
# Named per call rather than by the judge's own task id, which a judge could reuse
|
|
1121
|
+
# to overwrite another run's trajectory.
|
|
1122
|
+
upload = None
|
|
1123
|
+
if mode == "objects":
|
|
1124
|
+
try:
|
|
1125
|
+
upload = await asyncio.to_thread(TrajectoryUpload.to, store, trajectory_object_url(prefix, store=store))
|
|
1126
|
+
except Exception as exc:
|
|
1127
|
+
logger.warning(
|
|
1128
|
+
"Verifier '%s': judge trajectory grant unavailable (continuing without it): %s",
|
|
1129
|
+
self.verifier_id, exc,
|
|
1130
|
+
)
|
|
1131
|
+
return None
|
|
1132
|
+
last_exc: Optional[Exception] = None
|
|
1133
|
+
for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1):
|
|
1134
|
+
try:
|
|
1135
|
+
fetched = await fetch_trajectory(
|
|
1136
|
+
judge_a2a_url + get_path, {"task_id": a2a_server_task_id}, upload=upload
|
|
1137
|
+
)
|
|
1138
|
+
return await asyncio.to_thread(store_trajectory, fetched, prefix)
|
|
1139
|
+
except Exception as exc:
|
|
1140
|
+
last_exc = exc
|
|
1141
|
+
if attempt < self.DEFAULT_MAX_RETRIES:
|
|
1142
|
+
logger.warning(
|
|
1143
|
+
"Verifier '%s': judge trajectory fetch attempt %d/%d failed (%s), retrying...",
|
|
1144
|
+
self.verifier_id, attempt, self.DEFAULT_MAX_RETRIES, exc,
|
|
1145
|
+
)
|
|
1146
|
+
logger.warning(
|
|
1147
|
+
"Verifier '%s': judge trajectory fetch failed after %d attempts (continuing without it): %s",
|
|
1148
|
+
self.verifier_id, self.DEFAULT_MAX_RETRIES, last_exc,
|
|
1149
|
+
)
|
|
1150
|
+
return None
|
|
1151
|
+
|
|
1152
|
+
async def _run_judge_with_output_retries(
|
|
1153
|
+
self,
|
|
1154
|
+
*,
|
|
1155
|
+
eval_prompt: str,
|
|
1156
|
+
context: TaskStepContext,
|
|
1157
|
+
model: str,
|
|
1158
|
+
judge_a2a_url: Optional[str],
|
|
1159
|
+
judge_agent_card: dict,
|
|
1160
|
+
judge_agent,
|
|
1161
|
+
judge_effort: Optional[str],
|
|
1162
|
+
judge_max_thinking_tokens: Optional[int],
|
|
1163
|
+
use_agent_judge: bool,
|
|
1164
|
+
criteria: list[dict],
|
|
1165
|
+
image_blocks: Optional[list[dict]] = None,
|
|
1166
|
+
) -> tuple[list[dict], int, list[dict], Optional[str]]:
|
|
1167
|
+
"""Invoke the judge, retrying with corrective feedback when output ids/count are wrong.
|
|
1168
|
+
|
|
1169
|
+
``use_agent_judge`` is the run-resolved value (passed in, not read off self — see execute()).
|
|
1170
|
+
"""
|
|
1171
|
+
spec = self._spec()
|
|
1172
|
+
prompt = eval_prompt
|
|
1173
|
+
discrepancy_log: list[dict] = []
|
|
1174
|
+
judge_trajectory_s3_uri: Optional[str] = None
|
|
1175
|
+
|
|
1176
|
+
if use_agent_judge:
|
|
1177
|
+
if not judge_a2a_url:
|
|
1178
|
+
raise RuntimeError("Judge A2A URL is required when use_agent_judge=True")
|
|
1179
|
+
await self._configure_judge_a2a(
|
|
1180
|
+
judge_a2a_url=judge_a2a_url,
|
|
1181
|
+
judge_agent_card=judge_agent_card,
|
|
1182
|
+
model=model,
|
|
1183
|
+
judge_effort=judge_effort,
|
|
1184
|
+
judge_max_thinking_tokens=judge_max_thinking_tokens,
|
|
1185
|
+
context=context,
|
|
1186
|
+
)
|
|
1187
|
+
|
|
1188
|
+
for attempt in range(1, self.DEFAULT_MAX_RETRIES + 1):
|
|
1189
|
+
if use_agent_judge:
|
|
1190
|
+
data = await self._invoke_judge_a2a(
|
|
1191
|
+
eval_prompt=prompt,
|
|
1192
|
+
judge_a2a_url=judge_a2a_url,
|
|
1193
|
+
judge_agent_card=judge_agent_card,
|
|
1194
|
+
judge_agent=judge_agent,
|
|
1195
|
+
)
|
|
1196
|
+
elif image_blocks:
|
|
1197
|
+
data = await self._prompt_llm_judge(
|
|
1198
|
+
prompt, model=model, context=context, image_blocks=image_blocks,
|
|
1199
|
+
)
|
|
1200
|
+
else:
|
|
1201
|
+
data = await self._prompt_llm_judge(prompt, model=model, context=context)
|
|
1202
|
+
|
|
1203
|
+
logger.info(f"Judge response: {data['response'][:200]}...")
|
|
1204
|
+
judge_trajectory_s3_uri = data.get("trajectory_s3_uri")
|
|
1205
|
+
|
|
1206
|
+
results, discrepancy = spec.diagnose_response(data["response"], criteria)
|
|
1207
|
+
if discrepancy is None:
|
|
1208
|
+
assert results is not None
|
|
1209
|
+
return results, attempt - 1, discrepancy_log, judge_trajectory_s3_uri
|
|
1210
|
+
|
|
1211
|
+
logger.warning(
|
|
1212
|
+
"Judge rubric output discrepancy (attempt %d/%d, verifier_id=%s): %s",
|
|
1213
|
+
attempt,
|
|
1214
|
+
self.DEFAULT_MAX_RETRIES,
|
|
1215
|
+
self.verifier_id,
|
|
1216
|
+
discrepancy,
|
|
1217
|
+
)
|
|
1218
|
+
discrepancy_log.append(discrepancy.to_dict())
|
|
1219
|
+
if attempt == self.DEFAULT_MAX_RETRIES:
|
|
1220
|
+
raise ValueError(
|
|
1221
|
+
f"Judge returned {discrepancy.returned_count} results but expected "
|
|
1222
|
+
f"{discrepancy.expected_count} criteria"
|
|
1223
|
+
)
|
|
1224
|
+
|
|
1225
|
+
prompt = spec.format_correction_prompt(
|
|
1226
|
+
eval_prompt=eval_prompt,
|
|
1227
|
+
previous_response=data["response"],
|
|
1228
|
+
discrepancy=discrepancy,
|
|
1229
|
+
)
|
|
1230
|
+
|
|
1231
|
+
raise RuntimeError("Judge output retry loop exited unexpectedly")
|
|
1232
|
+
|
|
1233
|
+
def _build_eval_prompt(
|
|
1234
|
+
self,
|
|
1235
|
+
*,
|
|
1236
|
+
agent_prompt: str,
|
|
1237
|
+
agent_response: str,
|
|
1238
|
+
criteria_json: str,
|
|
1239
|
+
trajectory_path: Optional[str] = None,
|
|
1240
|
+
trajectory_inline: Optional[str] = None,
|
|
1241
|
+
loaded_artifacts: Optional[list[dict]] = None,
|
|
1242
|
+
image_blocks: Optional[list[dict]] = None,
|
|
1243
|
+
per_criterion_frames: bool = False,
|
|
1244
|
+
context_facts: Optional[list[tuple[str, str]]] = None,
|
|
1245
|
+
) -> str:
|
|
1246
|
+
"""``context_facts`` are rendered ``(label, value)`` pairs (``resolve_context_facts``); ``image_blocks``
|
|
1247
|
+
are the blocks attached to the judge message, labels included when ``per_criterion_frames``."""
|
|
1248
|
+
spec = self._spec()
|
|
1249
|
+
# Only the rubric_evidence templates have this placeholder; the others ignore the argument.
|
|
1250
|
+
checks_instruction = evidence_checks_instruction(has_policy=bool(self.grading_policy_prompt))
|
|
1251
|
+
if trajectory_path is not None:
|
|
1252
|
+
base = spec.prompt_template_path.substitute(
|
|
1253
|
+
agent_prompt=agent_prompt,
|
|
1254
|
+
agent_response=agent_response,
|
|
1255
|
+
criteria_json=criteria_json,
|
|
1256
|
+
trajectory_path=trajectory_path,
|
|
1257
|
+
checks_instruction=checks_instruction,
|
|
1258
|
+
)
|
|
1259
|
+
elif trajectory_inline is not None:
|
|
1260
|
+
base = spec.prompt_template_inline.substitute(
|
|
1261
|
+
agent_prompt=agent_prompt,
|
|
1262
|
+
agent_response=agent_response,
|
|
1263
|
+
criteria_json=criteria_json,
|
|
1264
|
+
trajectory_content=trajectory_inline,
|
|
1265
|
+
checks_instruction=checks_instruction,
|
|
1266
|
+
)
|
|
1267
|
+
else:
|
|
1268
|
+
base = spec.prompt_template_no_trajectory.substitute(
|
|
1269
|
+
agent_prompt=agent_prompt,
|
|
1270
|
+
agent_response=agent_response,
|
|
1271
|
+
criteria_json=criteria_json,
|
|
1272
|
+
checks_instruction=checks_instruction,
|
|
1273
|
+
)
|
|
1274
|
+
if loaded_artifacts:
|
|
1275
|
+
base += "\n\n" + self._build_loaded_artifacts_block(loaded_artifacts)
|
|
1276
|
+
if context_facts:
|
|
1277
|
+
# Facts before the policy: they are inputs, the policy is how to read them.
|
|
1278
|
+
base += "\n\n## Context facts\n" + self._CONTEXT_FACTS_LEAD + "\n" + "\n".join(
|
|
1279
|
+
f"- {label}: {value}" for label, value in context_facts)
|
|
1280
|
+
if self.grading_policy_prompt:
|
|
1281
|
+
base += "\n\n## Grading policy\n" + self.grading_policy_prompt.strip()
|
|
1282
|
+
if image_blocks:
|
|
1283
|
+
# Images are attached to the judge message separately; tell it how to use them.
|
|
1284
|
+
n = _image_count(image_blocks)
|
|
1285
|
+
if per_criterion_frames:
|
|
1286
|
+
base += per_criterion_grounding(n, cites_evidence=spec.cites_evidence)
|
|
1287
|
+
else:
|
|
1288
|
+
base += SCREENSHOT_GROUNDING.format(n=n)
|
|
1289
|
+
return base
|
|
1290
|
+
|
|
1291
|
+
@staticmethod
|
|
1292
|
+
def _build_loaded_artifacts_block(entries: list[dict]) -> str:
|
|
1293
|
+
lines = [
|
|
1294
|
+
"## Files Available For Inspection",
|
|
1295
|
+
"",
|
|
1296
|
+
"The following file artifacts have been pre-loaded into your container so you can verify the agent's claims about files:",
|
|
1297
|
+
"",
|
|
1298
|
+
]
|
|
1299
|
+
for e in entries:
|
|
1300
|
+
dest = (e.get("destination_path") or "/tmp/file_artifacts").rstrip("/")
|
|
1301
|
+
artifact_id = e.get("id") or "<unknown>"
|
|
1302
|
+
raw_files = e.get("files") or []
|
|
1303
|
+
file_names = list(raw_files.keys()) if isinstance(raw_files, dict) else list(raw_files)
|
|
1304
|
+
if file_names:
|
|
1305
|
+
preview = ", ".join(file_names[:8])
|
|
1306
|
+
if len(file_names) > 8:
|
|
1307
|
+
preview += f", ... ({len(file_names)} files total)"
|
|
1308
|
+
lines.append(f"- `{artifact_id}` at `{dest}/` — contains: {preview}")
|
|
1309
|
+
else:
|
|
1310
|
+
lines.append(f"- `{artifact_id}` at `{dest}/`")
|
|
1311
|
+
lines += [
|
|
1312
|
+
"",
|
|
1313
|
+
"When the criteria reference files the agent produced, claimed to produce, or operates on, "
|
|
1314
|
+
"inspect these locations using Bash (`ls`, `cat`, `find`, `grep`, `wc -c`, `file`) or Read tools. "
|
|
1315
|
+
"The agent may have written files in nested subdirectories — use `find` to search recursively. "
|
|
1316
|
+
"Do not rely solely on the agent's response text — verify against the actual files when possible.",
|
|
1317
|
+
]
|
|
1318
|
+
return "\n".join(lines)
|