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,514 @@
|
|
|
1
|
+
"""Compact OTel trajectory filtering for judge evaluation.
|
|
2
|
+
|
|
3
|
+
Uses standard OpenTelemetry GenAI semantic conventions (gen_ai.*) to identify
|
|
4
|
+
span types — no vendor-specific attributes (e.g. LangSmith) are required.
|
|
5
|
+
|
|
6
|
+
Tool call results that exceed _TOOL_RESULT_MAX_INLINE_SIZE or contain base64
|
|
7
|
+
images are externalized to JSON files under _TOOL_RESULT_FILES_DIR.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
import logging
|
|
14
|
+
import re
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from enum import Enum
|
|
17
|
+
from typing import Iterable, Optional
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
_TOOL_RESULT_MAX_INLINE_SIZE = 1024
|
|
22
|
+
_TOOL_RESULT_FILES_DIR = "/tmp/tool_call_results"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
# Upper bound on attached screenshots — a sanity cap so a misconfigured filter can't
|
|
26
|
+
# attach dozens of full-resolution frames to a single judge call.
|
|
27
|
+
_MAX_SCREENSHOT_LAST_N = 50
|
|
28
|
+
# PER_CRITERION frame budget (``frame_budget``); lives here because ``frame_selection`` imports this module.
|
|
29
|
+
# The cap keeps under the ~100-image limit of multimodal endpoints; the floor leaves the rest of the run
|
|
30
|
+
# at least as many frames as the final-frame reservation.
|
|
31
|
+
MAX_FRAME_BUDGET = 95
|
|
32
|
+
DEFAULT_FRAME_BUDGET = 90
|
|
33
|
+
FINAL_FRAMES_RESERVED = 3
|
|
34
|
+
MIN_FRAME_BUDGET = 2 * FINAL_FRAMES_RESERVED
|
|
35
|
+
# ACTION_LOG line cap (``action_log_max_lines``, see ``frame_selection.action_log``).
|
|
36
|
+
DEFAULT_ACTION_LOG_MAX_LINES = 120
|
|
37
|
+
MIN_ACTION_LOG_MAX_LINES = 10
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class CompactionType(str, Enum):
|
|
41
|
+
"""How a trajectory is compacted for a judge.
|
|
42
|
+
|
|
43
|
+
DEFAULT — reduce raw spans to a compact event list and externalize tool-result
|
|
44
|
+
images to side-files (the agent judge opens them with tools). This is the only
|
|
45
|
+
behavior that ever existed before screenshot grading.
|
|
46
|
+
SCREENSHOT — for a direct multimodal LLM judge: strip ALL base64 out of the
|
|
47
|
+
trajectory text and attach frames as images — the last N (``frame_strategy=final_frames``,
|
|
48
|
+
see ``compact_screenshot_trajectory``) or frames chosen per criterion across the whole run
|
|
49
|
+
(``per_criterion``, see ``frame_selection``).
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
DEFAULT = "default"
|
|
53
|
+
SCREENSHOT = "screenshot"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class FrameStrategy(str, Enum):
|
|
57
|
+
"""Which frames the SCREENSHOT compaction attaches: the final ``screenshot_last_n`` frames, or up to
|
|
58
|
+
``frame_budget`` frames chosen across the whole run for the criteria being graded (``frame_selection``)."""
|
|
59
|
+
|
|
60
|
+
FINAL_FRAMES = "final_frames"
|
|
61
|
+
PER_CRITERION = "per_criterion"
|
|
62
|
+
|
|
63
|
+
@classmethod
|
|
64
|
+
def _missing_(cls, value: object) -> Optional[FrameStrategy]:
|
|
65
|
+
return cls.FINAL_FRAMES if value == "last_n" else None # earlier spelling of FINAL_FRAMES
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class TrajectoryText(str, Enum):
|
|
69
|
+
"""What text accompanies the frames on the SCREENSHOT compaction: the whole trajectory with images
|
|
70
|
+
stripped, or one line per tool call / agent message (``frame_selection.action_log``) — what lets a
|
|
71
|
+
~90-frame call fit, the full text being up to 2.4M chars."""
|
|
72
|
+
|
|
73
|
+
FULL = "full"
|
|
74
|
+
ACTION_LOG = "action_log"
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _compile_or_raise(pattern: object, what: str) -> None:
|
|
78
|
+
"""Reject a non-string or invalid regex at construction rather than at judge time."""
|
|
79
|
+
if not isinstance(pattern, str):
|
|
80
|
+
raise ValueError(f"{what} must be a regex string, got {pattern!r}")
|
|
81
|
+
try:
|
|
82
|
+
re.compile(pattern)
|
|
83
|
+
except re.error as e:
|
|
84
|
+
raise ValueError(f"{what} is not a valid regex: {e}") from e
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@dataclass
|
|
88
|
+
class TrajectoryFilter:
|
|
89
|
+
"""Configures how an OTel trajectory is compacted for judge evaluation.
|
|
90
|
+
|
|
91
|
+
``compaction_type`` selects the variant: the ``include_*`` flags drive the DEFAULT event-reduction;
|
|
92
|
+
the remaining fields drive the SCREENSHOT variant. The two regex knobs are matched case-insensitively
|
|
93
|
+
against ``frame_selection.rendered_action`` (``"<tool> <args json>"``). The per_criterion knobs
|
|
94
|
+
(``frame_budget``, ``evidence_exclude_pattern``, ``always_show_actions``) are validated whatever the
|
|
95
|
+
strategy — a task document may set them while toggling it — and ignored unless it is per_criterion.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
include_tool_calls: bool = True
|
|
99
|
+
include_tool_call_results: bool = True
|
|
100
|
+
include_response: bool = True
|
|
101
|
+
include_thinking: bool = False
|
|
102
|
+
compaction_type: CompactionType = CompactionType.DEFAULT
|
|
103
|
+
screenshot_last_n: int = 3
|
|
104
|
+
frame_strategy: FrameStrategy = FrameStrategy.FINAL_FRAMES
|
|
105
|
+
frame_budget: int = DEFAULT_FRAME_BUDGET # MIN_FRAME_BUDGET..MAX_FRAME_BUDGET
|
|
106
|
+
# What text accompanies the frames. None (the default) resolves in ``__post_init__`` to ACTION_LOG when the
|
|
107
|
+
# strategy is per_criterion (the full text next to ~90 frames is never what that caller wants) and to FULL
|
|
108
|
+
# otherwise; an explicit value always wins, and ``to_dict`` writes the resolved value.
|
|
109
|
+
trajectory_text: Optional[TrajectoryText] = None
|
|
110
|
+
# Actions whose rendering matches are not used as criterion evidence (e.g. navigation mechanics).
|
|
111
|
+
evidence_exclude_pattern: Optional[str] = None
|
|
112
|
+
# {label: regex}: the frame after every matching action is reserved and labelled "<label> action K"
|
|
113
|
+
# (e.g. {"submitted": "^submit_form\\b"}); see ``frame_selection`` for the cap.
|
|
114
|
+
always_show_actions: Optional[dict[str, str]] = None
|
|
115
|
+
action_log_max_lines: int = DEFAULT_ACTION_LOG_MAX_LINES # >= MIN_ACTION_LOG_MAX_LINES
|
|
116
|
+
|
|
117
|
+
def __post_init__(self) -> None:
|
|
118
|
+
# Accept plain strings (e.g. constructed from JSON) and coerce to the enums.
|
|
119
|
+
if isinstance(self.compaction_type, str):
|
|
120
|
+
self.compaction_type = CompactionType(self.compaction_type)
|
|
121
|
+
if isinstance(self.frame_strategy, str):
|
|
122
|
+
self.frame_strategy = FrameStrategy(self.frame_strategy)
|
|
123
|
+
if self.trajectory_text is None:
|
|
124
|
+
self.trajectory_text = (TrajectoryText.ACTION_LOG if self.frame_strategy == FrameStrategy.PER_CRITERION
|
|
125
|
+
else TrajectoryText.FULL)
|
|
126
|
+
elif isinstance(self.trajectory_text, str):
|
|
127
|
+
self.trajectory_text = TrajectoryText(self.trajectory_text)
|
|
128
|
+
if (self.compaction_type == CompactionType.SCREENSHOT
|
|
129
|
+
and self.frame_strategy == FrameStrategy.FINAL_FRAMES
|
|
130
|
+
and not 1 <= self.screenshot_last_n <= _MAX_SCREENSHOT_LAST_N):
|
|
131
|
+
raise ValueError(
|
|
132
|
+
f"screenshot_last_n must be between 1 and {_MAX_SCREENSHOT_LAST_N}, "
|
|
133
|
+
f"got {self.screenshot_last_n}"
|
|
134
|
+
)
|
|
135
|
+
# Strict ints: JSON can hand over 90.0, which a range test alone accepts and a slice then rejects.
|
|
136
|
+
frames = self.frame_budget
|
|
137
|
+
if (isinstance(frames, bool) or not isinstance(frames, int)
|
|
138
|
+
or not (MIN_FRAME_BUDGET <= frames <= MAX_FRAME_BUDGET)):
|
|
139
|
+
raise ValueError(
|
|
140
|
+
f"frame_budget must be an integer between {MIN_FRAME_BUDGET} and "
|
|
141
|
+
f"{MAX_FRAME_BUDGET}, got {frames!r}"
|
|
142
|
+
)
|
|
143
|
+
if self.evidence_exclude_pattern is not None:
|
|
144
|
+
_compile_or_raise(self.evidence_exclude_pattern, "evidence_exclude_pattern")
|
|
145
|
+
if self.always_show_actions is not None:
|
|
146
|
+
if not isinstance(self.always_show_actions, dict) or not all(
|
|
147
|
+
isinstance(label, str) and label for label in self.always_show_actions
|
|
148
|
+
):
|
|
149
|
+
raise ValueError(
|
|
150
|
+
"always_show_actions must map non-empty labels to regexes, "
|
|
151
|
+
'e.g. {"submitted": "^submit_form\\\\b"}; got ' + repr(self.always_show_actions)
|
|
152
|
+
)
|
|
153
|
+
for label, pattern in self.always_show_actions.items():
|
|
154
|
+
_compile_or_raise(pattern, f"always_show_actions[{label!r}]")
|
|
155
|
+
lines = self.action_log_max_lines
|
|
156
|
+
if isinstance(lines, bool) or not isinstance(lines, int) or lines < MIN_ACTION_LOG_MAX_LINES:
|
|
157
|
+
raise ValueError(
|
|
158
|
+
f"action_log_max_lines must be an integer >= {MIN_ACTION_LOG_MAX_LINES}, got {lines!r}"
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
def to_dict(self) -> dict:
|
|
162
|
+
return {
|
|
163
|
+
"include_tool_calls": self.include_tool_calls,
|
|
164
|
+
"include_tool_call_results": self.include_tool_call_results,
|
|
165
|
+
"include_response": self.include_response,
|
|
166
|
+
"include_thinking": self.include_thinking,
|
|
167
|
+
"compaction_type": self.compaction_type.value,
|
|
168
|
+
"screenshot_last_n": self.screenshot_last_n,
|
|
169
|
+
"frame_strategy": self.frame_strategy.value,
|
|
170
|
+
"frame_budget": self.frame_budget,
|
|
171
|
+
"trajectory_text": TrajectoryText(self.trajectory_text).value, # resolved in __post_init__
|
|
172
|
+
"evidence_exclude_pattern": self.evidence_exclude_pattern,
|
|
173
|
+
"always_show_actions": dict(self.always_show_actions) if self.always_show_actions is not None else None,
|
|
174
|
+
"action_log_max_lines": self.action_log_max_lines,
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
@classmethod
|
|
178
|
+
def from_dict(cls, data: dict) -> TrajectoryFilter:
|
|
179
|
+
return cls(
|
|
180
|
+
include_tool_calls=data.get("include_tool_calls", True),
|
|
181
|
+
include_tool_call_results=data.get("include_tool_call_results", True),
|
|
182
|
+
include_response=data.get("include_response", True),
|
|
183
|
+
include_thinking=data.get("include_thinking", False),
|
|
184
|
+
compaction_type=CompactionType(data.get("compaction_type", "default")),
|
|
185
|
+
screenshot_last_n=data.get("screenshot_last_n", 3),
|
|
186
|
+
frame_strategy=FrameStrategy(data.get("frame_strategy", "final_frames")),
|
|
187
|
+
frame_budget=data.get("frame_budget", DEFAULT_FRAME_BUDGET),
|
|
188
|
+
trajectory_text=data.get("trajectory_text"), # absent -> the strategy's default (__post_init__)
|
|
189
|
+
evidence_exclude_pattern=data.get("evidence_exclude_pattern"),
|
|
190
|
+
always_show_actions=data.get("always_show_actions"),
|
|
191
|
+
action_log_max_lines=data.get("action_log_max_lines", DEFAULT_ACTION_LOG_MAX_LINES),
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
def compact_otel_trajectory(
|
|
195
|
+
spans: list[dict], trajectory_filter: TrajectoryFilter, result_file_prefix: str = ""
|
|
196
|
+
) -> tuple[list[dict], list[tuple[str, str]]]:
|
|
197
|
+
"""Filter raw OTel spans into a compact list of events.
|
|
198
|
+
|
|
199
|
+
``result_file_prefix`` is prepended to externalized tool-result filenames so a caller
|
|
200
|
+
compacting several trajectories into one dir (e.g. per-turn files) avoids collisions.
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
(events, externalized_files) where externalized_files is a list of
|
|
204
|
+
(file_path, content_json) pairs for tool results externalized to files.
|
|
205
|
+
"""
|
|
206
|
+
if not any("gen_ai.operation.name" in s.get("attributes", {}) for s in spans):
|
|
207
|
+
logger.warning(f"No OTel GenAI attributes found, returning {len(spans)} spans unfiltered")
|
|
208
|
+
return spans, []
|
|
209
|
+
|
|
210
|
+
events: list[dict] = []
|
|
211
|
+
externalized_files: list[tuple[str, str]] = []
|
|
212
|
+
if trajectory_filter.include_thinking:
|
|
213
|
+
events.extend(_extract_thinking_blocks(spans))
|
|
214
|
+
if trajectory_filter.include_tool_calls or trajectory_filter.include_tool_call_results:
|
|
215
|
+
tool_events, result_files = _extract_tool_events(
|
|
216
|
+
spans,
|
|
217
|
+
include_calls=trajectory_filter.include_tool_calls,
|
|
218
|
+
include_results=trajectory_filter.include_tool_call_results,
|
|
219
|
+
result_file_prefix=result_file_prefix,
|
|
220
|
+
)
|
|
221
|
+
events.extend(tool_events)
|
|
222
|
+
externalized_files.extend(result_files)
|
|
223
|
+
if trajectory_filter.include_response:
|
|
224
|
+
events.extend(_extract_final_response(spans))
|
|
225
|
+
events.sort(key=lambda e: e.get("timestamp", ""))
|
|
226
|
+
|
|
227
|
+
logger.info(
|
|
228
|
+
f"Compacted {len(spans)} OTel spans into {len(events)} events "
|
|
229
|
+
f"(tool_calls={trajectory_filter.include_tool_calls}, "
|
|
230
|
+
f"tool_results={trajectory_filter.include_tool_call_results}, "
|
|
231
|
+
f"response={trajectory_filter.include_response}, "
|
|
232
|
+
f"thinking={trajectory_filter.include_thinking}, "
|
|
233
|
+
f"externalized_files={len(externalized_files)})"
|
|
234
|
+
)
|
|
235
|
+
return events, externalized_files
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _extract_thinking_blocks(spans: list[dict]) -> list[dict]:
|
|
239
|
+
"""Extract thinking blocks from assistant turn spans (gen_ai.operation.name == 'chat')."""
|
|
240
|
+
events = []
|
|
241
|
+
for span in spans:
|
|
242
|
+
attrs = span.get("attributes", {})
|
|
243
|
+
if attrs.get("gen_ai.operation.name") != "chat":
|
|
244
|
+
continue
|
|
245
|
+
completion_raw = attrs.get("gen_ai.completion", "")
|
|
246
|
+
completion = parse_json_attr(completion_raw)
|
|
247
|
+
if not isinstance(completion, dict):
|
|
248
|
+
continue
|
|
249
|
+
content = completion.get("content", [])
|
|
250
|
+
if not isinstance(content, list):
|
|
251
|
+
continue
|
|
252
|
+
for block in content:
|
|
253
|
+
if isinstance(block, dict) and block.get("type") == "thinking":
|
|
254
|
+
thinking_text = block.get("thinking", "")
|
|
255
|
+
if thinking_text:
|
|
256
|
+
events.append({
|
|
257
|
+
"type": "thinking",
|
|
258
|
+
"text": thinking_text,
|
|
259
|
+
"timestamp": span.get("start_time", ""),
|
|
260
|
+
})
|
|
261
|
+
return events
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _output_contains_image(tool_output: dict | list | str) -> bool:
|
|
265
|
+
"""Check whether a tool output structure contains any base64 image blocks."""
|
|
266
|
+
blocks: list = []
|
|
267
|
+
if isinstance(tool_output, dict):
|
|
268
|
+
blocks = tool_output.get("content", [])
|
|
269
|
+
if not isinstance(blocks, list):
|
|
270
|
+
blocks = [tool_output]
|
|
271
|
+
elif isinstance(tool_output, list):
|
|
272
|
+
blocks = tool_output
|
|
273
|
+
elif isinstance(tool_output, str):
|
|
274
|
+
try:
|
|
275
|
+
parsed = json.loads(tool_output)
|
|
276
|
+
return _output_contains_image(parsed)
|
|
277
|
+
except (json.JSONDecodeError, TypeError):
|
|
278
|
+
return False
|
|
279
|
+
else:
|
|
280
|
+
return False
|
|
281
|
+
|
|
282
|
+
for block in blocks:
|
|
283
|
+
if not isinstance(block, dict):
|
|
284
|
+
continue
|
|
285
|
+
if block.get("type") == "image" and block.get("source", {}).get("data"):
|
|
286
|
+
return True
|
|
287
|
+
if "content" in block and isinstance(block["content"], list):
|
|
288
|
+
if _output_contains_image(block["content"]):
|
|
289
|
+
return True
|
|
290
|
+
return False
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
# Matches a base64 image payload: an optional data:image/...;base64, prefix, then a
|
|
294
|
+
# JPEG (/9j/) or PNG (iVBORw0KGgo) magic header, then a long base64 run. The {200,}
|
|
295
|
+
# floor keeps it off ordinary short tokens.
|
|
296
|
+
_BASE64_IMAGE_RE = re.compile(
|
|
297
|
+
r"(?:data:image/[a-z]+;base64,)?(?:/9j/|iVBORw0KGgo)[A-Za-z0-9+/=\r\n]{200,}"
|
|
298
|
+
)
|
|
299
|
+
# Truncate backstop for the text fed to a direct judge (after base64 stripping the
|
|
300
|
+
# text is far smaller). Sized for a ~1M-token judge (gemini-pro-latest): ~2.4M chars
|
|
301
|
+
# ≈ 600-700k tokens, leaving the rest of the window for criteria, frames, and verdict.
|
|
302
|
+
MAX_JUDGE_TRAJECTORY_CHARS = 2_400_000
|
|
303
|
+
# base64 magic-byte prefixes of the screenshot formats agent harnesses emit. We set the
|
|
304
|
+
# data-URI media type from this because some multimodal APIs validate it against the payload.
|
|
305
|
+
_B64_MAGIC_MEDIA_TYPES = (("iVBORw0KGgo", "image/png"), ("/9j/", "image/jpeg"))
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def media_type_for_b64(b64: str) -> str:
|
|
309
|
+
"""Infer an image media type from a base64 payload's magic-byte prefix.
|
|
310
|
+
Defaults to image/png when no JPEG header is seen."""
|
|
311
|
+
for prefix, media_type in _B64_MAGIC_MEDIA_TYPES:
|
|
312
|
+
if b64.startswith(prefix):
|
|
313
|
+
return media_type
|
|
314
|
+
return "image/png"
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
@dataclass(frozen=True)
|
|
318
|
+
class ImageFrame:
|
|
319
|
+
"""A single image extracted from a trajectory — transport-agnostic. Callers adapt
|
|
320
|
+
it to whatever the judge expects (e.g. a litellm image_url block); this module
|
|
321
|
+
stays free of any judge/message-shape concerns."""
|
|
322
|
+
|
|
323
|
+
media_type: str
|
|
324
|
+
data: str # base64-encoded image bytes, no `data:` prefix
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def strip_base64_images(text: str, placeholder: str = "<image omitted>") -> str:
|
|
328
|
+
"""Replace every base64 image payload in a serialized trajectory with a placeholder.
|
|
329
|
+
|
|
330
|
+
Text-level companion to the structured externalization above: `_output_contains_image`
|
|
331
|
+
+ `_extract_tool_events` externalize TOOL-RESULT images to side files during
|
|
332
|
+
compaction, but base64 also rides along in chat/prompt-history spans (not
|
|
333
|
+
externalized) and in the RAW trajectory when no compaction runs. For callers that
|
|
334
|
+
feed trajectory TEXT to a model (e.g. a direct LLM judge, which can't open
|
|
335
|
+
externalized files), this strips ALL of it — data: URIs and bare JPEG (/9j/) / PNG
|
|
336
|
+
(iVBORw0KGgo) blobs alike, wherever they appear. The {200,} floor avoids touching
|
|
337
|
+
ordinary short tokens.
|
|
338
|
+
"""
|
|
339
|
+
return _BASE64_IMAGE_RE.sub(placeholder, text)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def final_frames_from_raw(raw_text: str, last_n: int) -> list[str]:
|
|
343
|
+
"""Return the last ``last_n`` base64 image frames from a RAW OTel trajectory.
|
|
344
|
+
|
|
345
|
+
Screenshots are stored on each ``execute_tool`` span at
|
|
346
|
+
``attributes["gen_ai.completion"]`` (a JSON string) under ``"screenshot"``. Read
|
|
347
|
+
these from the RAW trajectory on purpose: compaction externalizes every
|
|
348
|
+
screenshot to a side file, so the compacted text no longer contains them —
|
|
349
|
+
running this on the compacted trajectory would silently find zero frames.
|
|
350
|
+
|
|
351
|
+
Returns raw base64 (no ``data:`` prefix). On a parse failure, a non-list payload,
|
|
352
|
+
or a screenshot-less trajectory returns ``[]``. The caller is expected to release
|
|
353
|
+
``raw_text`` (it can be ~MBs) right after calling.
|
|
354
|
+
"""
|
|
355
|
+
try:
|
|
356
|
+
spans = json.loads(raw_text)
|
|
357
|
+
except Exception:
|
|
358
|
+
return []
|
|
359
|
+
if not isinstance(spans, list):
|
|
360
|
+
return []
|
|
361
|
+
frames: list[str] = []
|
|
362
|
+
for span in spans:
|
|
363
|
+
attrs = span.get("attributes") if isinstance(span, dict) else None
|
|
364
|
+
if not isinstance(attrs, dict):
|
|
365
|
+
continue
|
|
366
|
+
comp = attrs.get("gen_ai.completion")
|
|
367
|
+
if isinstance(comp, str):
|
|
368
|
+
try:
|
|
369
|
+
comp_obj = json.loads(comp)
|
|
370
|
+
except Exception:
|
|
371
|
+
continue
|
|
372
|
+
elif isinstance(comp, dict):
|
|
373
|
+
comp_obj = comp
|
|
374
|
+
else:
|
|
375
|
+
continue
|
|
376
|
+
if isinstance(comp_obj, dict) and comp_obj.get("screenshot"):
|
|
377
|
+
frames.append(comp_obj["screenshot"])
|
|
378
|
+
# last_n must be a positive count; non-positive returns nothing (never "all" — a
|
|
379
|
+
# silent "attach every screenshot" is a footgun for long trajectories).
|
|
380
|
+
return frames[-last_n:] if last_n > 0 else []
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def final_image_frames(raw_text: str, last_n: int) -> list[ImageFrame]:
|
|
384
|
+
"""The last ``last_n`` screenshots of a RAW trajectory as ``ImageFrame``s (media type + base64)."""
|
|
385
|
+
return [ImageFrame(media_type=media_type_for_b64(b64), data=b64)
|
|
386
|
+
for b64 in final_frames_from_raw(raw_text, last_n)]
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def strip_trajectory_images(
|
|
390
|
+
raw_text: str, *, attached: Iterable[str] = (), max_chars: Optional[int] = None,
|
|
391
|
+
) -> str:
|
|
392
|
+
"""The trajectory text with every base64 image stripped, truncated to its final ``max_chars``
|
|
393
|
+
(default ``MAX_JUDGE_TRAJECTORY_CHARS``; the tail is kept because final-state outcomes live there).
|
|
394
|
+
``attached`` are the payloads the caller attaches as images: only then does the placeholder say frames
|
|
395
|
+
are attached — a trajectory can carry prompt-history images without any screenshot to attach, and
|
|
396
|
+
telling the judge to look for absent images would mislead it."""
|
|
397
|
+
if max_chars is None:
|
|
398
|
+
max_chars = MAX_JUDGE_TRAJECTORY_CHARS
|
|
399
|
+
attached = list(attached)
|
|
400
|
+
placeholder = "<image omitted; final frames attached separately>" if attached else "<image omitted>"
|
|
401
|
+
text = raw_text
|
|
402
|
+
for b64 in attached:
|
|
403
|
+
text = text.replace(b64, placeholder)
|
|
404
|
+
text = strip_base64_images(text, placeholder)
|
|
405
|
+
if len(text) > max_chars:
|
|
406
|
+
text = "<trajectory truncated; showing the final portion>\n" + text[-max_chars:]
|
|
407
|
+
return text
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def compact_screenshot_trajectory(
|
|
411
|
+
raw_text: str,
|
|
412
|
+
*,
|
|
413
|
+
last_n: int,
|
|
414
|
+
max_chars: Optional[int] = None,
|
|
415
|
+
) -> tuple[str, list[ImageFrame]]:
|
|
416
|
+
"""``CompactionType.SCREENSHOT`` compaction of a RAW trajectory for a direct judge: the base64-free
|
|
417
|
+
text and the last ``last_n`` screenshots as attachable frames (the default compaction externalizes
|
|
418
|
+
images to side-files only the agent judge can open)."""
|
|
419
|
+
frames = final_image_frames(raw_text, last_n)
|
|
420
|
+
text = strip_trajectory_images(raw_text, attached=[f.data for f in frames], max_chars=max_chars)
|
|
421
|
+
return text, frames
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _extract_tool_events(
|
|
425
|
+
spans: list[dict], include_calls: bool, include_results: bool, result_file_prefix: str = ""
|
|
426
|
+
) -> tuple[list[dict], list[tuple[str, str]]]:
|
|
427
|
+
"""Extract tool call and/or result events from tool spans.
|
|
428
|
+
|
|
429
|
+
Returns:
|
|
430
|
+
(events, externalized_files) where externalized_files contains
|
|
431
|
+
(path, content_json) for tool results externalized to files.
|
|
432
|
+
"""
|
|
433
|
+
events = []
|
|
434
|
+
externalized_files: list[tuple[str, str]] = []
|
|
435
|
+
result_file_counter = 0
|
|
436
|
+
|
|
437
|
+
for span in spans:
|
|
438
|
+
attrs = span.get("attributes", {})
|
|
439
|
+
if attrs.get("gen_ai.operation.name") != "execute_tool":
|
|
440
|
+
continue
|
|
441
|
+
|
|
442
|
+
tool_name = span.get("name", "")
|
|
443
|
+
prompt_raw = attrs.get("gen_ai.prompt", "{}")
|
|
444
|
+
prompt = parse_json_attr(prompt_raw)
|
|
445
|
+
tool_input = prompt.get("input", {}) if isinstance(prompt, dict) else prompt
|
|
446
|
+
|
|
447
|
+
completion_raw = attrs.get("gen_ai.completion", "{}")
|
|
448
|
+
completion = parse_json_attr(completion_raw)
|
|
449
|
+
tool_output = completion.get("output", completion) if isinstance(completion, dict) else completion
|
|
450
|
+
|
|
451
|
+
if include_calls:
|
|
452
|
+
events.append({
|
|
453
|
+
"type": "tool_call",
|
|
454
|
+
"tool": tool_name,
|
|
455
|
+
"input": tool_input,
|
|
456
|
+
"timestamp": span.get("start_time", ""),
|
|
457
|
+
})
|
|
458
|
+
|
|
459
|
+
if include_results:
|
|
460
|
+
output_json = json.dumps(tool_output)
|
|
461
|
+
if len(output_json) > _TOOL_RESULT_MAX_INLINE_SIZE or _output_contains_image(tool_output):
|
|
462
|
+
result_file_counter += 1
|
|
463
|
+
file_path = f"{_TOOL_RESULT_FILES_DIR}/{result_file_prefix}tool_call_result_{result_file_counter}.json"
|
|
464
|
+
externalized_files.append((file_path, output_json))
|
|
465
|
+
event = {
|
|
466
|
+
"type": "tool_result",
|
|
467
|
+
"tool": tool_name,
|
|
468
|
+
"output_file": file_path,
|
|
469
|
+
"timestamp": span.get("end_time", ""),
|
|
470
|
+
}
|
|
471
|
+
else:
|
|
472
|
+
event = {
|
|
473
|
+
"type": "tool_result",
|
|
474
|
+
"tool": tool_name,
|
|
475
|
+
"output": tool_output,
|
|
476
|
+
"timestamp": span.get("end_time", ""),
|
|
477
|
+
}
|
|
478
|
+
events.append(event)
|
|
479
|
+
|
|
480
|
+
return events, externalized_files
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _extract_final_response(spans: list[dict]) -> list[dict]:
|
|
484
|
+
"""Extract the final response from the conversation root span (gen_ai.operation.name == 'chain')."""
|
|
485
|
+
for span in spans:
|
|
486
|
+
attrs = span.get("attributes", {})
|
|
487
|
+
if attrs.get("gen_ai.operation.name") != "chain":
|
|
488
|
+
continue
|
|
489
|
+
completion_raw = attrs.get("gen_ai.completion", "")
|
|
490
|
+
completion = parse_json_attr(completion_raw)
|
|
491
|
+
if not isinstance(completion, dict):
|
|
492
|
+
continue
|
|
493
|
+
content = completion.get("content", [])
|
|
494
|
+
if not isinstance(content, list):
|
|
495
|
+
continue
|
|
496
|
+
text_parts = [
|
|
497
|
+
block.get("text", "")
|
|
498
|
+
for block in content
|
|
499
|
+
if isinstance(block, dict) and block.get("type") == "text"
|
|
500
|
+
]
|
|
501
|
+
if text_parts:
|
|
502
|
+
return [{
|
|
503
|
+
"type": "final_response",
|
|
504
|
+
"text": "\n".join(text_parts),
|
|
505
|
+
"timestamp": span.get("end_time", ""),
|
|
506
|
+
}]
|
|
507
|
+
return []
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def parse_json_attr(value: str) -> dict | list | str:
|
|
511
|
+
try:
|
|
512
|
+
return json.loads(value)
|
|
513
|
+
except (json.JSONDecodeError, TypeError):
|
|
514
|
+
return value
|