|
| 1 | +# Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import os |
| 7 | +from typing import Any, Dict |
| 8 | + |
| 9 | +import numpy as np |
| 10 | +from add_instruction import add_chat_instruction, add_single_instruction |
| 11 | +from agl_envs import make_env_manager |
| 12 | +from autogen_agentchat.agents import AssistantAgent |
| 13 | +from autogen_core.models import ModelFamily |
| 14 | +from autogen_ext.models.openai import OpenAIChatCompletionClient |
| 15 | + |
| 16 | +from agentlightning import LLM, LitAgent, NamedResources, Rollout, configure_logger, emit_object, emit_reward, operation |
| 17 | +from agentlightning.utils.otel import make_link_attributes |
| 18 | +from contrib.recipes.envs.prompt_builder import HistoryPromptBuilder |
| 19 | + |
| 20 | +logger = configure_logger(name=__name__, level=logging.ERROR) |
| 21 | + |
| 22 | + |
| 23 | +class EnvAgent(LitAgent): |
| 24 | + def __init__(self, config, trained_agents: str | None = None) -> None: |
| 25 | + super().__init__(trained_agents=trained_agents) |
| 26 | + self.config = config |
| 27 | + self.env = None |
| 28 | + |
| 29 | + def _build_agent(self, llm: LLM, temperature: float): |
| 30 | + model_client = OpenAIChatCompletionClient( |
| 31 | + model=llm.model, |
| 32 | + base_url=llm.endpoint, |
| 33 | + api_key=os.environ.get("OPENAI_API_KEY", "token-abc123"), |
| 34 | + model_info={ |
| 35 | + "vision": False, |
| 36 | + "function_calling": True, |
| 37 | + "json_output": False, |
| 38 | + "family": ModelFamily.UNKNOWN, |
| 39 | + "structured_output": False, |
| 40 | + }, |
| 41 | + temperature=temperature, |
| 42 | + ) |
| 43 | + |
| 44 | + return AssistantAgent( |
| 45 | + name="envs", |
| 46 | + model_client=model_client, |
| 47 | + ) |
| 48 | + |
| 49 | + def _get_instructed_prompt(self, prompt, sep="\n\n"): |
| 50 | + """Return instructed observation based on prompt_type and captioner type.""" |
| 51 | + prompt_type = self.config.captioner.prompt_type |
| 52 | + cap_type = self.config.captioner.type |
| 53 | + |
| 54 | + if prompt_type == "chat": |
| 55 | + if cap_type == "cot": |
| 56 | + return add_chat_instruction(prompt, "cot", sep, self.config.env_name) |
| 57 | + elif cap_type == "naive": |
| 58 | + return add_chat_instruction(prompt, "naive", sep) |
| 59 | + |
| 60 | + elif prompt_type == "single": |
| 61 | + if cap_type == "cot": |
| 62 | + return add_single_instruction(prompt, "cot", sep, self.config.env_name) |
| 63 | + elif cap_type == "naive": |
| 64 | + return add_single_instruction(prompt, "naive", sep, self.config.env_name) |
| 65 | + |
| 66 | + raise ValueError(f"Unsupported prompt_type={prompt_type}, type={cap_type}") |
| 67 | + |
| 68 | + async def rollout_async( |
| 69 | + self, |
| 70 | + task: Dict[str, Any], |
| 71 | + resources: NamedResources, |
| 72 | + rollout: Rollout, |
| 73 | + ) -> float | None: |
| 74 | + rollout_id = rollout.rollout_id |
| 75 | + logger.info(f"[Rollout {rollout_id}] Task: {task}") |
| 76 | + |
| 77 | + format_penalty = float(self.config["format_penalty"]) |
| 78 | + reward_scale = float(self.config["reawrd_scale"]) |
| 79 | + |
| 80 | + # Setup agent |
| 81 | + llm: LLM = resources.get("main_llm") |
| 82 | + print("Training with model:", llm.model, "on endpoint:", llm.endpoint) |
| 83 | + self.agent = self._build_agent(llm, 1.0 if rollout.mode == "train" else 0.4) |
| 84 | + if "max_tokens" in self.config and self.config["max_tokens"] > -1: |
| 85 | + self.agent._model_client.max_tokens = self.config["max_tokens"] |
| 86 | + |
| 87 | + try: |
| 88 | + # Setup environment |
| 89 | + prompt_builder = HistoryPromptBuilder( |
| 90 | + max_history=self.config.captioner.max_history, prompt_type=self.config.captioner.prompt_type |
| 91 | + ) |
| 92 | + |
| 93 | + self.env = make_env_manager(self.config.env_name, task, self.config) |
| 94 | + env_obs, infos, available_actions_hint = self.env.reset() |
| 95 | + |
| 96 | + prompt_builder.init(self.env) |
| 97 | + prompt_builder.update_observation(env_obs) |
| 98 | + prompt_builder.update_admissible_actions(available_actions_hint) |
| 99 | + |
| 100 | + prompt = prompt_builder.get_prompt() |
| 101 | + |
| 102 | + episode_reward, done = 0.0, False |
| 103 | + |
| 104 | + step_count = 0 |
| 105 | + while not done: |
| 106 | + try: |
| 107 | + instructed_prompt = self._get_instructed_prompt(prompt) |
| 108 | + |
| 109 | + # Main agent step |
| 110 | + with operation(step_count=step_count): |
| 111 | + result = await self.agent._model_client.create(instructed_prompt) |
| 112 | + output = result.content |
| 113 | + logger.info(f"[LLM output]: {output}") |
| 114 | + |
| 115 | + except Exception as e: |
| 116 | + logger.error(f"[Rollout {rollout_id}] Error during training rollout: {e}", exc_info=True) |
| 117 | + break |
| 118 | + |
| 119 | + if self.config.log_env_obs: |
| 120 | + emit_object(env_obs, attributes=make_link_attributes({"step_count": str(step_count)})) |
| 121 | + |
| 122 | + env_obs, executed_action, is_valid, step_reward, terminated, truncated, info, available_actions_hint = ( |
| 123 | + self.env.step( |
| 124 | + output, |
| 125 | + use_reasoning=self.config.captioner.type == "cot", |
| 126 | + use_success_rate=self.config.use_success_rate, |
| 127 | + ) |
| 128 | + ) |
| 129 | + |
| 130 | + prompt_builder.update_step_count() |
| 131 | + prompt_builder.update_action(executed_action) |
| 132 | + prompt_builder.update_observation(env_obs) |
| 133 | + prompt_builder.update_admissible_actions(available_actions_hint) |
| 134 | + |
| 135 | + prompt = prompt_builder.get_prompt() |
| 136 | + |
| 137 | + if rollout.mode == "train": |
| 138 | + step_reward *= reward_scale |
| 139 | + |
| 140 | + if format_penalty != 0.0: |
| 141 | + emit_reward( |
| 142 | + { |
| 143 | + "extrinsic_reward": step_reward, |
| 144 | + "intrinsic_reward": 0.0 if is_valid else -1.0 * format_penalty, |
| 145 | + }, |
| 146 | + primary_key="extrinsic_reward", |
| 147 | + attributes=make_link_attributes({"step_count": str(step_count)}), |
| 148 | + ) |
| 149 | + else: |
| 150 | + emit_reward(step_reward, attributes=make_link_attributes({"step_count": str(step_count)})) |
| 151 | + |
| 152 | + episode_reward += float(step_reward) |
| 153 | + done = np.logical_or(terminated, truncated) |
| 154 | + |
| 155 | + step_count += 1 |
| 156 | + |
| 157 | + return episode_reward |
| 158 | + |
| 159 | + finally: |
| 160 | + if self.env is not None: |
| 161 | + self.env.close() |
0 commit comments