|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +import os |
| 4 | + |
| 5 | +from agents import Agent as OpenAIAgent |
| 6 | +from agents import ModelSettings, OpenAIProvider, RunConfig, SQLiteSession |
| 7 | +from agents import Runner as OpenAIRunner |
| 8 | +from terminal.env import TerminalEnv |
| 9 | +from terminal.judge_agent import JudgeAgent, judge_from_env |
| 10 | +from terminal.prompt import SYSTEM_PROMPT |
| 11 | +from transformers import PreTrainedTokenizerFast |
| 12 | + |
| 13 | +from areal.api.cli_args import GenerationHyperparameters |
| 14 | +from areal.api.workflow_api import RolloutWorkflow |
| 15 | +from areal.experimental.openai import ArealOpenAI |
| 16 | +from areal.utils import stats_tracker |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +class TerminalAgent: |
| 22 | + def __init__( |
| 23 | + self, |
| 24 | + tokenizer: PreTrainedTokenizerFast, |
| 25 | + max_tokens_per_turn: int = 1024, |
| 26 | + max_turns: int = 8, |
| 27 | + max_total_tokens: int = 32768, |
| 28 | + dump_dir: str | None = None, |
| 29 | + rollout_stat_scope: str = "rollout", |
| 30 | + ): |
| 31 | + self.tokenizer = tokenizer |
| 32 | + self.max_tokens_per_turn = max_tokens_per_turn |
| 33 | + self.max_turns = max_turns |
| 34 | + self.max_total_tokens = max_total_tokens |
| 35 | + self.dump_dir = dump_dir |
| 36 | + self.rollout_stat_scope = rollout_stat_scope |
| 37 | + |
| 38 | + async def run_agent(self, data, client: ArealOpenAI, judge_agent: JudgeAgent): |
| 39 | + """Run the agent workflow for terminal task execution.""" |
| 40 | + run_config = RunConfig( |
| 41 | + model_provider=OpenAIProvider( |
| 42 | + openai_client=client, |
| 43 | + use_responses=True, |
| 44 | + ), |
| 45 | + tracing_disabled=True, |
| 46 | + model_settings=ModelSettings( |
| 47 | + temperature=1.0, |
| 48 | + extra_args={"max_completion_tokens": self.max_tokens_per_turn}, |
| 49 | + tool_choice="auto", |
| 50 | + store=True, |
| 51 | + ), |
| 52 | + ) |
| 53 | + |
| 54 | + async with TerminalEnv( |
| 55 | + task_name=data["task_name"], |
| 56 | + dump_dir=self.dump_dir, |
| 57 | + rollout_stat_scope=self.rollout_stat_scope, |
| 58 | + ) as env: |
| 59 | + # Create agent workflow with terminal tools |
| 60 | + agent = OpenAIAgent( |
| 61 | + name="Terminal Task Agent", |
| 62 | + instructions=SYSTEM_PROMPT, |
| 63 | + tools=env.get_tools(), |
| 64 | + ) |
| 65 | + session = SQLiteSession("terminal") |
| 66 | + content = data["instruction"] |
| 67 | + |
| 68 | + max_attempts = self.max_turns |
| 69 | + reward = 0 |
| 70 | + judge_reward = 0 |
| 71 | + tracker = stats_tracker.get(self.rollout_stat_scope) |
| 72 | + |
| 73 | + with tracker.record_timing("run_agent_total"): |
| 74 | + error_count = 0.0 |
| 75 | + attempts_used = 0.0 |
| 76 | + for attempt in range(max_attempts): |
| 77 | + attempts_used = float(attempt + 1) |
| 78 | + try: |
| 79 | + with tracker.record_timing("openai_runner_run"): |
| 80 | + result = await OpenAIRunner.run( |
| 81 | + agent, |
| 82 | + input=content, |
| 83 | + session=session, |
| 84 | + run_config=run_config, |
| 85 | + max_turns=30, |
| 86 | + ) |
| 87 | + except Exception as e: |
| 88 | + logger.error(f"Error running agent: {e}") |
| 89 | + error_count += 1.0 |
| 90 | + break |
| 91 | + |
| 92 | + with tracker.record_timing("env_validate_reward"): |
| 93 | + reward = env.reward() |
| 94 | + if judge_agent: |
| 95 | + with tracker.record_timing("judge_agent_reward"): |
| 96 | + judge_reward = await judge_agent.get_reward_from_judge( |
| 97 | + session=session, |
| 98 | + dockerfile_contents=data["dockerfile_contents"], |
| 99 | + ) |
| 100 | + if judge_reward >= 0 and reward < 0.99: |
| 101 | + reward = reward * 0.65 + judge_reward * 0.35 |
| 102 | + |
| 103 | + tracker.scalar( |
| 104 | + reward=reward, |
| 105 | + judge_reward=judge_reward, |
| 106 | + attempt_index=float(attempt), |
| 107 | + input_chars=float(len(content) if content else 0.0), |
| 108 | + output_chars=float( |
| 109 | + len(getattr(result, "final_output", "") or "") |
| 110 | + ), |
| 111 | + ) |
| 112 | + |
| 113 | + if isinstance(reward, float) and reward >= 0.99: |
| 114 | + tracker.scalar(success=1.0) |
| 115 | + break |
| 116 | + |
| 117 | + if attempt < max_attempts - 1: |
| 118 | + content = f"""The previous attempt didn't complete the task successfully. |
| 119 | + Please try a different approach. |
| 120 | + Original task: {data["instruction"]} |
| 121 | +
|
| 122 | + Previous attempt result: {result.final_output} |
| 123 | +
|
| 124 | + Please analyze what went wrong and try again with a corrected approach.""" |
| 125 | + else: |
| 126 | + content = f"""This is your final attempt. Please be extremely careful. |
| 127 | + Original task: {data["instruction"]} |
| 128 | +
|
| 129 | + Previous attempts: {result.final_output} |
| 130 | +
|
| 131 | + Please provide a final, carefully executed solution.""" |
| 132 | + tracker.scalar(success=0.0) |
| 133 | + |
| 134 | + tracker.scalar( |
| 135 | + final_reward=reward, attempts_used=attempts_used, errors=error_count |
| 136 | + ) |
| 137 | + |
| 138 | + client.set_final_reward(reward) |
| 139 | + |
| 140 | + return reward |
| 141 | + |
| 142 | + |
| 143 | +class TerminalAgentWorkflow(RolloutWorkflow): |
| 144 | + def __init__( |
| 145 | + self, |
| 146 | + gconfig: GenerationHyperparameters, |
| 147 | + tokenizer: PreTrainedTokenizerFast, |
| 148 | + dump_dir: str | None = None, |
| 149 | + rollout_stat_scope: str = "rollout", |
| 150 | + n_trajs: int = 1, |
| 151 | + max_tokens: int = 32768, |
| 152 | + max_turns: int = 8, |
| 153 | + ): |
| 154 | + self.gconfig = gconfig |
| 155 | + self.gconfig.n_samples = 1 |
| 156 | + self.tokenizer = tokenizer |
| 157 | + self.dump_dir = dump_dir |
| 158 | + self.max_tokens = max_tokens |
| 159 | + self.rollout_stat_scope = rollout_stat_scope |
| 160 | + if self.dump_dir is not None and not os.path.exists(self.dump_dir): |
| 161 | + os.makedirs(self.dump_dir, exist_ok=True) |
| 162 | + |
| 163 | + # Search hyper-parameters |
| 164 | + self.n_trajs = n_trajs |
| 165 | + self.agent = TerminalAgent( |
| 166 | + tokenizer=self.tokenizer, |
| 167 | + max_tokens_per_turn=self.gconfig.max_new_tokens, |
| 168 | + max_turns=max_turns, |
| 169 | + max_total_tokens=max_tokens, |
| 170 | + dump_dir=self.dump_dir, |
| 171 | + rollout_stat_scope=self.rollout_stat_scope, |
| 172 | + ) |
| 173 | + self.judge_agent = judge_from_env() |
| 174 | + |
| 175 | + async def arun_episode(self, engine, data): |
| 176 | + clients = [ |
| 177 | + ArealOpenAI( |
| 178 | + engine=engine, tokenizer=self.tokenizer, tool_call_parser="qwen25" |
| 179 | + ) |
| 180 | + for _ in range(self.n_trajs) |
| 181 | + ] |
| 182 | + |
| 183 | + # Collect trajectories |
| 184 | + rewards = await asyncio.gather( |
| 185 | + *[ |
| 186 | + self.agent.run_agent( |
| 187 | + data=data, |
| 188 | + client=clients[i], |
| 189 | + judge_agent=self.judge_agent, |
| 190 | + ) |
| 191 | + for i in range(self.n_trajs) |
| 192 | + ] |
| 193 | + ) |
| 194 | + for reward in rewards: |
| 195 | + stats_tracker.get(self.rollout_stat_scope).scalar(reward=reward) |
| 196 | + |
| 197 | + interactions_with_reward = {} |
| 198 | + for client in clients: |
| 199 | + client.apply_reward_discount(turn_discount=0.9) |
| 200 | + interactions = client.export_interactions(style="individual") |
| 201 | + interactions_with_reward.update(interactions) |
| 202 | + return interactions_with_reward |
0 commit comments