synth-ai 0.2.0__py3-none-any.whl → 0.2.1.dev0__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.
- synth_ai/__init__.py +28 -2
- synth_ai/core/system.py +4 -0
- synth_ai/environments/__init__.py +35 -0
- synth_ai/environments/environment/__init__.py +1 -0
- synth_ai/environments/environment/artifacts/__init__.py +1 -0
- synth_ai/environments/environment/artifacts/base.py +50 -0
- synth_ai/environments/environment/core.py +22 -0
- synth_ai/environments/environment/db/__init__.py +1 -0
- synth_ai/environments/environment/db/sqlite.py +45 -0
- synth_ai/environments/environment/registry.py +24 -0
- synth_ai/environments/environment/resources/sqlite.py +46 -0
- synth_ai/environments/environment/results.py +1 -0
- synth_ai/environments/environment/rewards/__init__.py +1 -0
- synth_ai/environments/environment/rewards/core.py +28 -0
- synth_ai/environments/environment/shared_engine.py +26 -0
- synth_ai/environments/environment/tools/__init__.py +34 -0
- synth_ai/environments/examples/__init__.py +1 -0
- synth_ai/environments/examples/crafter_classic/__init__.py +8 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_comprehensive_evaluation.py +58 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_evaluation_browser.py +152 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_evaluation_framework.py +1194 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_quick_evaluation.py +51 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_react_agent.py +872 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/crafter_trace_evaluation.py +1412 -0
- synth_ai/environments/examples/crafter_classic/agent_demos/test_crafter_react_agent.py +1110 -0
- synth_ai/environments/examples/crafter_classic/config_logging.py +111 -0
- synth_ai/environments/examples/crafter_classic/engine.py +502 -0
- synth_ai/environments/examples/crafter_classic/engine_deterministic_patch.py +63 -0
- synth_ai/environments/examples/crafter_classic/engine_helpers/action_map.py +5 -0
- synth_ai/environments/examples/crafter_classic/engine_helpers/serialization.py +74 -0
- synth_ai/environments/examples/crafter_classic/environment.py +255 -0
- synth_ai/environments/examples/crafter_classic/taskset.py +228 -0
- synth_ai/environments/examples/enron/agent_demos/test_synth_react.py +535 -0
- synth_ai/environments/examples/enron/art_helpers/email_search_tools.py +156 -0
- synth_ai/environments/examples/enron/art_helpers/local_email_db.py +280 -0
- synth_ai/environments/examples/enron/art_helpers/types_enron.py +24 -0
- synth_ai/environments/examples/enron/engine.py +291 -0
- synth_ai/environments/examples/enron/environment.py +165 -0
- synth_ai/environments/examples/enron/taskset.py +112 -0
- synth_ai/environments/examples/enron/units/keyword_stats.py +111 -0
- synth_ai/environments/examples/enron/units/test_email_index.py +8 -0
- synth_ai/environments/examples/minigrid/__init__.py +48 -0
- synth_ai/environments/examples/minigrid/agent_demos/minigrid_evaluation_framework.py +1188 -0
- synth_ai/environments/examples/minigrid/agent_demos/minigrid_quick_evaluation.py +47 -0
- synth_ai/environments/examples/minigrid/agent_demos/minigrid_react_agent.py +562 -0
- synth_ai/environments/examples/minigrid/agent_demos/minigrid_trace_evaluation.py +220 -0
- synth_ai/environments/examples/minigrid/agent_demos/test_minigrid_react_agent.py +393 -0
- synth_ai/environments/examples/minigrid/engine.py +589 -0
- synth_ai/environments/examples/minigrid/environment.py +274 -0
- synth_ai/environments/examples/minigrid/environment_mapping.py +242 -0
- synth_ai/environments/examples/minigrid/puzzle_loader.py +416 -0
- synth_ai/environments/examples/minigrid/taskset.py +583 -0
- synth_ai/environments/examples/minigrid/units/test_action_behavior.py +226 -0
- synth_ai/environments/examples/minigrid/units/test_debug_messages.py +83 -0
- synth_ai/environments/examples/minigrid/units/test_exploration.py +120 -0
- synth_ai/environments/examples/minigrid/units/test_minigrid_engine.py +214 -0
- synth_ai/environments/examples/minigrid/units/test_minigrid_environment.py +238 -0
- synth_ai/environments/examples/minigrid/units/test_minigrid_environment_mapping.py +301 -0
- synth_ai/environments/examples/minigrid/units/test_minigrid_taskset.py +210 -0
- synth_ai/environments/examples/nethack/__init__.py +7 -0
- synth_ai/environments/examples/nethack/achievements.py +337 -0
- synth_ai/environments/examples/nethack/agent_demos/nethack_evaluation_framework.py +981 -0
- synth_ai/environments/examples/nethack/agent_demos/nethack_quick_evaluation.py +74 -0
- synth_ai/environments/examples/nethack/agent_demos/nethack_react_agent.py +832 -0
- synth_ai/environments/examples/nethack/agent_demos/test_nethack_react_agent.py +1112 -0
- synth_ai/environments/examples/nethack/engine.py +738 -0
- synth_ai/environments/examples/nethack/environment.py +255 -0
- synth_ai/environments/examples/nethack/helpers/__init__.py +42 -0
- synth_ai/environments/examples/nethack/helpers/action_mapping.py +301 -0
- synth_ai/environments/examples/nethack/helpers/nle_wrapper.py +401 -0
- synth_ai/environments/examples/nethack/helpers/observation_utils.py +433 -0
- synth_ai/environments/examples/nethack/helpers/recording_wrapper.py +201 -0
- synth_ai/environments/examples/nethack/helpers/trajectory_recorder.py +268 -0
- synth_ai/environments/examples/nethack/helpers/visualization/replay_viewer.py +308 -0
- synth_ai/environments/examples/nethack/helpers/visualization/visualizer.py +430 -0
- synth_ai/environments/examples/nethack/taskset.py +323 -0
- synth_ai/environments/examples/nethack/units/test_nethack_engine.py +277 -0
- synth_ai/environments/examples/nethack/units/test_nethack_environment.py +281 -0
- synth_ai/environments/examples/nethack/units/test_nethack_taskset.py +213 -0
- synth_ai/environments/examples/nethack/units/test_recording.py +307 -0
- synth_ai/environments/examples/red/__init__.py +7 -0
- synth_ai/environments/examples/red/agent_demos/__init__.py +1 -0
- synth_ai/environments/examples/red/agent_demos/test_synth_react.py +1471 -0
- synth_ai/environments/examples/red/config_logging.py +110 -0
- synth_ai/environments/examples/red/engine.py +693 -0
- synth_ai/environments/examples/red/engine_helpers/__init__.py +1 -0
- synth_ai/environments/examples/red/engine_helpers/memory_map.py +28 -0
- synth_ai/environments/examples/red/engine_helpers/reward_components.py +275 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/__init__.py +142 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/adaptive_rewards.py +56 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/battle_rewards.py +283 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/composite_rewards.py +149 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/economy_rewards.py +137 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/efficiency_rewards.py +56 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/exploration_rewards.py +330 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/novelty_rewards.py +120 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/pallet_town_rewards.py +558 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/pokemon_rewards.py +312 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/social_rewards.py +147 -0
- synth_ai/environments/examples/red/engine_helpers/reward_library/story_rewards.py +246 -0
- synth_ai/environments/examples/red/engine_helpers/screen_analysis.py +367 -0
- synth_ai/environments/examples/red/engine_helpers/state_extraction.py +139 -0
- synth_ai/environments/examples/red/environment.py +235 -0
- synth_ai/environments/examples/red/taskset.py +77 -0
- synth_ai/environments/examples/red/test_fixes.py +125 -0
- synth_ai/environments/examples/red/test_fixes_mock.py +148 -0
- synth_ai/environments/examples/red/units/__init__.py +1 -0
- synth_ai/environments/examples/red/units/test_basic_functionality.py +97 -0
- synth_ai/environments/examples/red/units/test_button_press_requirements.py +217 -0
- synth_ai/environments/examples/red/units/test_engine.py +192 -0
- synth_ai/environments/examples/red/units/test_environment.py +455 -0
- synth_ai/environments/examples/red/units/test_exploration_strategy.py +227 -0
- synth_ai/environments/examples/red/units/test_integration.py +217 -0
- synth_ai/environments/examples/red/units/test_memory_extraction.py +111 -0
- synth_ai/environments/examples/red/units/test_menu_bug_reproduction.py +1100 -0
- synth_ai/environments/examples/red/units/test_movement_debug.py +255 -0
- synth_ai/environments/examples/red/units/test_pokemon_mcts_debug.py +163 -0
- synth_ai/environments/examples/red/units/test_pokemon_mcts_verbose.py +117 -0
- synth_ai/environments/examples/red/units/test_red_basic.py +145 -0
- synth_ai/environments/examples/red/units/test_red_comprehensive.py +323 -0
- synth_ai/environments/examples/red/units/test_retry_movement.py +195 -0
- synth_ai/environments/examples/red/units/test_reward_components.py +186 -0
- synth_ai/environments/examples/red/units/test_rom_integration.py +260 -0
- synth_ai/environments/examples/red/units/test_taskset.py +116 -0
- synth_ai/environments/examples/red/units/test_tree.py +448 -0
- synth_ai/environments/examples/sokoban/__init__.py +1 -0
- synth_ai/environments/examples/sokoban/agent_demos/sokoban_full_eval.py +900 -0
- synth_ai/environments/examples/sokoban/agent_demos/test_dspy_react.py +1 -0
- synth_ai/environments/examples/sokoban/agent_demos/test_sokoban_react_agent.py +498 -0
- synth_ai/environments/examples/sokoban/agent_demos/test_synth_lats.py +1 -0
- synth_ai/environments/examples/sokoban/agent_demos/test_synth_react_locally.py +748 -0
- synth_ai/environments/examples/sokoban/agent_demos/test_synth_react_service.py +296 -0
- synth_ai/environments/examples/sokoban/engine.py +675 -0
- synth_ai/environments/examples/sokoban/engine_helpers/__init__.py +1 -0
- synth_ai/environments/examples/sokoban/engine_helpers/room_utils.py +656 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/__init__.py +17 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/__init__.py +3 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/boxoban_env.py +129 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/render_utils.py +370 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/room_utils.py +331 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env.py +305 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_fixed_targets.py +66 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_pull.py +114 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_two_player.py +122 -0
- synth_ai/environments/examples/sokoban/engine_helpers/vendored/envs/sokoban_env_variations.py +394 -0
- synth_ai/environments/examples/sokoban/environment.py +228 -0
- synth_ai/environments/examples/sokoban/generate_verified_puzzles.py +438 -0
- synth_ai/environments/examples/sokoban/puzzle_loader.py +311 -0
- synth_ai/environments/examples/sokoban/taskset.py +425 -0
- synth_ai/environments/examples/sokoban/units/astar_common.py +94 -0
- synth_ai/environments/examples/sokoban/units/test_building_task_set.py +49 -0
- synth_ai/environments/examples/sokoban/units/test_false_positive.py +120 -0
- synth_ai/environments/examples/sokoban/units/test_simple_run_through_environment.py +119 -0
- synth_ai/environments/examples/sokoban/units/test_sokoban_environment.py +98 -0
- synth_ai/environments/examples/sokoban/units/test_tree.py +364 -0
- synth_ai/environments/examples/tictactoe/__init__.py +1 -0
- synth_ai/environments/examples/tictactoe/agent_demos/test_synth_react.py +266 -0
- synth_ai/environments/examples/tictactoe/agent_demos/test_tictactoe_react_agent.py +470 -0
- synth_ai/environments/examples/tictactoe/engine.py +368 -0
- synth_ai/environments/examples/tictactoe/environment.py +239 -0
- synth_ai/environments/examples/tictactoe/taskset.py +214 -0
- synth_ai/environments/examples/tictactoe/units/test_tictactoe_engine.py +393 -0
- synth_ai/environments/examples/tictactoe/units/test_tictactoe_environment.py +493 -0
- synth_ai/environments/examples/tictactoe/units/test_tictactoe_taskset.py +191 -0
- synth_ai/environments/examples/verilog/__init__.py +10 -0
- synth_ai/environments/examples/verilog/agent_demos/test_synth_react.py +520 -0
- synth_ai/environments/examples/verilog/engine.py +328 -0
- synth_ai/environments/examples/verilog/environment.py +349 -0
- synth_ai/environments/examples/verilog/taskset.py +418 -0
- synth_ai/environments/examples/verilog/units/test_verilog_engine.py +466 -0
- synth_ai/environments/examples/verilog/units/test_verilog_environment.py +585 -0
- synth_ai/environments/examples/verilog/units/test_verilog_integration.py +383 -0
- synth_ai/environments/examples/verilog/units/test_verilog_taskset.py +457 -0
- synth_ai/environments/reproducibility/core.py +42 -0
- synth_ai/environments/reproducibility/tree.py +364 -0
- synth_ai/environments/service/app.py +78 -0
- synth_ai/environments/service/core_routes.py +775 -0
- synth_ai/environments/service/external_registry.py +57 -0
- synth_ai/environments/service/registry.py +9 -0
- synth_ai/environments/stateful/__init__.py +1 -0
- synth_ai/environments/stateful/core.py +28 -0
- synth_ai/environments/stateful/engine.py +21 -0
- synth_ai/environments/stateful/state.py +7 -0
- synth_ai/environments/tasks/api.py +19 -0
- synth_ai/environments/tasks/core.py +78 -0
- synth_ai/environments/tasks/filters.py +39 -0
- synth_ai/environments/tasks/utils.py +89 -0
- synth_ai/environments/v0_observability/history.py +3 -0
- synth_ai/environments/v0_observability/log.py +2 -0
- synth_ai/lm/caching/constants.py +1 -0
- synth_ai/{zyk/lms → lm}/caching/ephemeral.py +4 -8
- synth_ai/{zyk/lms → lm}/caching/handler.py +15 -15
- synth_ai/{zyk/lms → lm}/caching/initialize.py +2 -4
- synth_ai/{zyk/lms → lm}/caching/persistent.py +4 -10
- synth_ai/{zyk/lms → lm}/config.py +2 -1
- synth_ai/{zyk/lms → lm}/constants.py +2 -2
- synth_ai/{zyk/lms → lm}/core/all.py +10 -10
- synth_ai/{zyk/lms → lm}/core/main.py +57 -33
- synth_ai/{zyk/lms → lm}/core/vendor_clients.py +12 -10
- synth_ai/lm/cost/monitor.py +1 -0
- synth_ai/lm/cost/statefulness.py +1 -0
- synth_ai/lm/provider_support/__init__.py +8 -0
- synth_ai/lm/provider_support/anthropic.py +945 -0
- synth_ai/lm/provider_support/openai.py +1115 -0
- synth_ai/lm/provider_support/suppress_logging.py +31 -0
- synth_ai/{zyk/lms → lm}/structured_outputs/handler.py +58 -80
- synth_ai/{zyk/lms → lm}/structured_outputs/inject.py +6 -20
- synth_ai/{zyk/lms → lm}/structured_outputs/rehabilitate.py +6 -12
- synth_ai/{zyk/lms → lm}/vendors/core/anthropic_api.py +21 -30
- synth_ai/{zyk/lms → lm}/vendors/core/gemini_api.py +35 -32
- synth_ai/{zyk/lms → lm}/vendors/core/mistral_api.py +19 -28
- synth_ai/{zyk/lms → lm}/vendors/core/openai_api.py +26 -36
- synth_ai/{zyk/lms → lm}/vendors/openai_standard.py +29 -33
- synth_ai/{zyk/lms → lm}/vendors/retries.py +1 -1
- synth_ai/lm/vendors/supported/__init__.py +0 -0
- synth_ai/{zyk/lms → lm}/vendors/supported/custom_endpoint.py +131 -118
- synth_ai/{zyk/lms → lm}/vendors/supported/deepseek.py +4 -8
- synth_ai/{zyk/lms → lm}/vendors/supported/grok.py +6 -8
- synth_ai/{zyk/lms → lm}/vendors/supported/groq.py +1 -1
- synth_ai/{zyk/lms → lm}/vendors/supported/ollama.py +2 -2
- synth_ai/{zyk/lms → lm}/vendors/supported/openrouter.py +18 -16
- synth_ai/{zyk/lms → lm}/vendors/supported/together.py +1 -1
- synth_ai/tracing/__init__.py +0 -0
- synth_ai/tracing/abstractions.py +224 -0
- synth_ai/tracing/base_client.py +91 -0
- synth_ai/tracing/client_manager.py +131 -0
- synth_ai/tracing/config.py +140 -0
- synth_ai/tracing/context.py +146 -0
- synth_ai/tracing/decorators.py +679 -0
- synth_ai/tracing/events/__init__.py +0 -0
- synth_ai/tracing/events/manage.py +147 -0
- synth_ai/tracing/events/scope.py +86 -0
- synth_ai/tracing/events/store.py +227 -0
- synth_ai/tracing/immediate_client.py +152 -0
- synth_ai/tracing/local.py +18 -0
- synth_ai/tracing/log_client_base.py +74 -0
- synth_ai/tracing/retry_queue.py +187 -0
- synth_ai/tracing/trackers.py +515 -0
- synth_ai/tracing/upload.py +504 -0
- synth_ai/tracing/utils.py +9 -0
- synth_ai/zyk/__init__.py +28 -2
- synth_ai-0.2.1.dev0.dist-info/METADATA +349 -0
- synth_ai-0.2.1.dev0.dist-info/RECORD +261 -0
- {synth_ai-0.2.0.dist-info → synth_ai-0.2.1.dev0.dist-info}/WHEEL +1 -1
- synth_ai/zyk/lms/caching/constants.py +0 -1
- synth_ai/zyk/lms/cost/monitor.py +0 -1
- synth_ai/zyk/lms/cost/statefulness.py +0 -1
- synth_ai-0.2.0.dist-info/METADATA +0 -36
- synth_ai-0.2.0.dist-info/RECORD +0 -50
- /synth_ai/{zyk/lms/__init__.py → environments/reproducibility/helpers.py} +0 -0
- /synth_ai/{zyk/lms/caching → lm}/__init__.py +0 -0
- /synth_ai/{zyk/lms/core → lm/caching}/__init__.py +0 -0
- /synth_ai/{zyk/lms → lm}/caching/dbs.py +0 -0
- /synth_ai/{zyk/lms/cost → lm/core}/__init__.py +0 -0
- /synth_ai/{zyk/lms → lm}/core/exceptions.py +0 -0
- /synth_ai/{zyk/lms/structured_outputs → lm/cost}/__init__.py +0 -0
- /synth_ai/{zyk/lms/vendors → lm/structured_outputs}/__init__.py +0 -0
- /synth_ai/{zyk/lms → lm}/tools/__init__.py +0 -0
- /synth_ai/{zyk/lms → lm}/tools/base.py +0 -0
- /synth_ai/{zyk/lms/vendors/core → lm/vendors}/__init__.py +0 -0
- /synth_ai/{zyk/lms → lm}/vendors/base.py +0 -0
- /synth_ai/{zyk/lms/vendors/local → lm/vendors/core}/__init__.py +0 -0
- /synth_ai/{zyk/lms/vendors/supported → lm/vendors/local}/__init__.py +0 -0
- /synth_ai/{zyk/lms → lm}/vendors/local/ollama.py +0 -0
- {synth_ai-0.2.0.dist-info → synth_ai-0.2.1.dev0.dist-info/licenses}/LICENSE +0 -0
- {synth_ai-0.2.0.dist-info → synth_ai-0.2.1.dev0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,266 @@
|
|
1
|
+
from __future__ import annotations
|
2
|
+
|
3
|
+
import asyncio
|
4
|
+
import json
|
5
|
+
from typing import Dict, Any, List, Optional
|
6
|
+
from pydantic import BaseModel
|
7
|
+
|
8
|
+
from synth_ai.zyk import LM
|
9
|
+
from synth_ai.environments.examples.tictactoe.environment import TicTacToeEnvironment
|
10
|
+
from synth_ai.environments.examples.tictactoe.taskset import create_tictactoe_taskset
|
11
|
+
|
12
|
+
|
13
|
+
class TicTacToeActionInput(BaseModel):
|
14
|
+
action: str # "A1", "B2", etc.
|
15
|
+
|
16
|
+
|
17
|
+
class TerminateArgs(BaseModel):
|
18
|
+
reason: Optional[str] = None
|
19
|
+
|
20
|
+
|
21
|
+
class TicTacToeReActAgent:
|
22
|
+
def __init__(self, llm, max_turns: int = 9):
|
23
|
+
self.llm = llm
|
24
|
+
self.max_turns = max_turns
|
25
|
+
self.history = []
|
26
|
+
self.system_name = "tictactoe-react"
|
27
|
+
|
28
|
+
self.tools = [
|
29
|
+
{
|
30
|
+
"type": "function",
|
31
|
+
"function": {
|
32
|
+
"name": "tictactoe_interact",
|
33
|
+
"description": "Place your mark in a cell. Valid cells are A1-A3, B1-B3, C1-C3.",
|
34
|
+
"parameters": {
|
35
|
+
"type": "object",
|
36
|
+
"properties": {
|
37
|
+
"action": {
|
38
|
+
"type": "string",
|
39
|
+
"description": "The cell coordinate (e.g. A1, B2, C3)",
|
40
|
+
}
|
41
|
+
},
|
42
|
+
"required": ["action"],
|
43
|
+
},
|
44
|
+
},
|
45
|
+
},
|
46
|
+
{
|
47
|
+
"type": "function",
|
48
|
+
"function": {
|
49
|
+
"name": "terminate",
|
50
|
+
"description": "End the game if it's completed (win/draw/loss) or no valid moves remain.",
|
51
|
+
"parameters": {
|
52
|
+
"type": "object",
|
53
|
+
"properties": {
|
54
|
+
"reason": {
|
55
|
+
"type": "string",
|
56
|
+
"description": "Reason for terminating",
|
57
|
+
}
|
58
|
+
},
|
59
|
+
},
|
60
|
+
},
|
61
|
+
},
|
62
|
+
]
|
63
|
+
|
64
|
+
def _format_observation(self, obs: Dict[str, Any]) -> str:
|
65
|
+
"""Format observation for LLM consumption"""
|
66
|
+
lines = []
|
67
|
+
|
68
|
+
if "board_text" in obs:
|
69
|
+
lines.append("Current Board:")
|
70
|
+
lines.append(obs["board_text"])
|
71
|
+
|
72
|
+
if "current_player" in obs:
|
73
|
+
lines.append(f"\nCurrent Player: {obs['current_player']}")
|
74
|
+
|
75
|
+
if "last_move" in obs and obs["last_move"]:
|
76
|
+
lines.append(f"Last Move: {obs['last_move']}")
|
77
|
+
|
78
|
+
if "move_count" in obs:
|
79
|
+
lines.append(f"Move Count: {obs['move_count']}/9")
|
80
|
+
|
81
|
+
if "winner" in obs and obs["winner"]:
|
82
|
+
lines.append(f"\nGame Result: {obs['winner']}")
|
83
|
+
|
84
|
+
if "reward_last" in obs and obs["reward_last"] != 0:
|
85
|
+
lines.append(f"Reward: {obs['reward_last']}")
|
86
|
+
|
87
|
+
if "error" in obs:
|
88
|
+
lines.append(f"\nError: {obs['error']}")
|
89
|
+
|
90
|
+
return "\n".join(lines)
|
91
|
+
|
92
|
+
async def decide(self, obs: str) -> Dict[str, Any]:
|
93
|
+
"""Get LLM decision based on observation"""
|
94
|
+
# Add observation to history
|
95
|
+
self.history.append({"role": "user", "content": obs})
|
96
|
+
|
97
|
+
# Create prompt
|
98
|
+
messages = [
|
99
|
+
{
|
100
|
+
"role": "system",
|
101
|
+
"content": (
|
102
|
+
"You are playing TicTacToe. Analyze the board state and make strategic moves. "
|
103
|
+
"Use tictactoe_interact to place your mark, and terminate when the game ends."
|
104
|
+
),
|
105
|
+
}
|
106
|
+
] + self.history
|
107
|
+
|
108
|
+
# Get LLM response
|
109
|
+
response = await self.llm.respond_async(
|
110
|
+
system_message=messages[0]["content"], user_message=obs, tools=self.tools
|
111
|
+
)
|
112
|
+
|
113
|
+
# Parse tool calls
|
114
|
+
if hasattr(response, "tool_calls") and response.tool_calls:
|
115
|
+
tool_call = response.tool_calls[0]
|
116
|
+
|
117
|
+
# Handle different response structures
|
118
|
+
if hasattr(tool_call, "function"):
|
119
|
+
tool_name = tool_call.function.name
|
120
|
+
tool_args = tool_call.function.arguments
|
121
|
+
elif isinstance(tool_call, dict):
|
122
|
+
if "function" in tool_call:
|
123
|
+
tool_name = tool_call["function"]["name"]
|
124
|
+
tool_args = tool_call["function"]["arguments"]
|
125
|
+
else:
|
126
|
+
tool_name = tool_call.get("name", "unknown")
|
127
|
+
tool_args = tool_call.get("arguments", {})
|
128
|
+
else:
|
129
|
+
return {
|
130
|
+
"name": "terminate",
|
131
|
+
"parameters": {"reason": "Unexpected tool call format"},
|
132
|
+
}
|
133
|
+
|
134
|
+
if isinstance(tool_args, str):
|
135
|
+
tool_args = json.loads(tool_args)
|
136
|
+
|
137
|
+
return {"name": tool_name, "parameters": tool_args}
|
138
|
+
else:
|
139
|
+
# Default to a terminate if no tool call
|
140
|
+
return {"name": "terminate", "parameters": {"reason": "No valid action"}}
|
141
|
+
|
142
|
+
async def run_episode(self, env: TicTacToeEnvironment) -> Dict[str, Any]:
|
143
|
+
"""Run a single episode"""
|
144
|
+
# Initialize
|
145
|
+
obs = await env.initialize()
|
146
|
+
formatted_obs = self._format_observation(obs)
|
147
|
+
|
148
|
+
# Reset history
|
149
|
+
self.history = []
|
150
|
+
|
151
|
+
# Track episode data
|
152
|
+
episode_data = {
|
153
|
+
"turns": 0,
|
154
|
+
"winner": None,
|
155
|
+
"final_reward": 0.0,
|
156
|
+
"terminated_correctly": False,
|
157
|
+
"moves": [],
|
158
|
+
}
|
159
|
+
|
160
|
+
# Main game loop
|
161
|
+
for turn in range(self.max_turns):
|
162
|
+
episode_data["turns"] = turn + 1
|
163
|
+
|
164
|
+
# Get agent decision
|
165
|
+
action = await self.decide(formatted_obs)
|
166
|
+
|
167
|
+
# Check for termination
|
168
|
+
if action["name"] == "terminate":
|
169
|
+
final_obs = await env.checkpoint()
|
170
|
+
episode_data["terminated_correctly"] = True
|
171
|
+
episode_data["winner"] = final_obs.get("winner_final")
|
172
|
+
episode_data["final_reward"] = final_obs.get("total_reward", 0.0)
|
173
|
+
break
|
174
|
+
|
175
|
+
# Execute action
|
176
|
+
tool_call = {"name": "interact", "parameters": action["parameters"]}
|
177
|
+
|
178
|
+
obs = await env.step(tool_call)
|
179
|
+
formatted_obs = self._format_observation(obs)
|
180
|
+
|
181
|
+
# Track move
|
182
|
+
if "last_move" in obs:
|
183
|
+
episode_data["moves"].append(obs["last_move"])
|
184
|
+
|
185
|
+
# Check if game ended
|
186
|
+
if obs.get("terminated", False) or obs.get("winner"):
|
187
|
+
episode_data["winner"] = obs.get("winner")
|
188
|
+
episode_data["final_reward"] = obs.get("total_reward", 0.0)
|
189
|
+
episode_data["terminated_correctly"] = False # Should have used terminate
|
190
|
+
break
|
191
|
+
|
192
|
+
return episode_data
|
193
|
+
|
194
|
+
|
195
|
+
async def eval_react_tictactoe(
|
196
|
+
model_name: str = "gpt-4.1-mini", num_episodes: int = 10
|
197
|
+
) -> List[Dict[str, Any]]:
|
198
|
+
"""Run ReAct agent evaluation on TicTacToe taskset"""
|
199
|
+
|
200
|
+
# Load taskset
|
201
|
+
taskset = await create_tictactoe_taskset()
|
202
|
+
|
203
|
+
# Initialize LLM and agent
|
204
|
+
llm = LM(model_name=model_name, formatting_model_name=model_name, temperature=0.7)
|
205
|
+
agent = TicTacToeReActAgent(llm)
|
206
|
+
|
207
|
+
# Run episodes
|
208
|
+
results = []
|
209
|
+
for i, instance in enumerate(taskset.instances[:num_episodes]):
|
210
|
+
print(f"\nRunning episode {i + 1}/{num_episodes}...")
|
211
|
+
|
212
|
+
# Create environment
|
213
|
+
env = TicTacToeEnvironment(instance)
|
214
|
+
|
215
|
+
# Run episode
|
216
|
+
result = await agent.run_episode(env)
|
217
|
+
result["task_metadata"] = {
|
218
|
+
"starting_player": instance.metadata.starting_player,
|
219
|
+
"opening_moves": instance.metadata.opening_moves,
|
220
|
+
"optimal_outcome": instance.metadata.optimal_outcome,
|
221
|
+
"position_complexity": instance.metadata.position_complexity,
|
222
|
+
}
|
223
|
+
|
224
|
+
results.append(result)
|
225
|
+
|
226
|
+
# Print result
|
227
|
+
print(
|
228
|
+
f" Result: {result['winner']}, Moves: {len(result['moves'])}, Reward: {result['final_reward']}"
|
229
|
+
)
|
230
|
+
|
231
|
+
return results
|
232
|
+
|
233
|
+
|
234
|
+
async def test_react_agent_tictactoe():
|
235
|
+
"""Test function for pytest compatibility"""
|
236
|
+
results = await eval_react_tictactoe(num_episodes=5)
|
237
|
+
|
238
|
+
# Basic assertions
|
239
|
+
assert len(results) > 0
|
240
|
+
assert all("winner" in r for r in results)
|
241
|
+
assert all("turns" in r for r in results)
|
242
|
+
|
243
|
+
# Calculate statistics
|
244
|
+
total_games = len(results)
|
245
|
+
wins = sum(1 for r in results if r["winner"] == "X")
|
246
|
+
draws = sum(1 for r in results if r["winner"] == "draw")
|
247
|
+
losses = sum(1 for r in results if r["winner"] == "O")
|
248
|
+
|
249
|
+
win_rate = wins / total_games if total_games > 0 else 0
|
250
|
+
|
251
|
+
print(f"\n=== TicTacToe ReAct Agent Results ===")
|
252
|
+
print(f"Total Games: {total_games}")
|
253
|
+
print(f"Wins (X): {wins} ({win_rate:.1%})")
|
254
|
+
print(f"Draws: {draws} ({draws / total_games:.1%})")
|
255
|
+
print(f"Losses (O): {losses} ({losses / total_games:.1%})")
|
256
|
+
print(f"Average Moves: {sum(len(r['moves']) for r in results) / total_games:.1f}")
|
257
|
+
|
258
|
+
# Check that agent can at least draw in simple positions
|
259
|
+
simple_games = [r for r in results if r["task_metadata"]["position_complexity"] == 0]
|
260
|
+
if simple_games:
|
261
|
+
simple_non_losses = sum(1 for r in simple_games if r["winner"] != "O")
|
262
|
+
print(f"Non-loss rate in fresh games: {simple_non_losses / len(simple_games):.1%}")
|
263
|
+
|
264
|
+
|
265
|
+
if __name__ == "__main__":
|
266
|
+
asyncio.run(test_react_agent_tictactoe())
|