|
| 1 | +import copy |
| 2 | +import re |
| 3 | +from typing import List, Optional |
| 4 | + |
| 5 | +from balrog.agents.base import BaseAgent |
| 6 | + |
| 7 | +from .dummy import make_dummy_action |
| 8 | + |
| 9 | + |
| 10 | +class Message: |
| 11 | + def __init__(self, role: str, content: str, attachment: Optional[object] = None): |
| 12 | + self.role = role # 'system', 'user', 'assistant' |
| 13 | + self.content = content # String content of the message |
| 14 | + self.attachment = attachment |
| 15 | + |
| 16 | + def __repr__(self): |
| 17 | + return f"Message(role={self.role}, content={self.content}, attachment={self.attachment})" |
| 18 | + |
| 19 | + |
| 20 | +class FewShotAgent(BaseAgent): |
| 21 | + def __init__(self, client_factory, prompt_builder): |
| 22 | + """Initialize the FewShotAgent with a client and prompt builder.""" |
| 23 | + super().__init__(client_factory, prompt_builder) |
| 24 | + # self.client = client_factory() |
| 25 | + self.icl_episodes = [] |
| 26 | + self.icl_events = [] |
| 27 | + self.cached_icl = False |
| 28 | + |
| 29 | + def update_icl_observation(self, obs: dict): |
| 30 | + long_term_context = obs["text"].get("long_term_context", "") |
| 31 | + self.icl_events.append( |
| 32 | + { |
| 33 | + "type": "icl_observation", |
| 34 | + "text": long_term_context, |
| 35 | + } |
| 36 | + ) |
| 37 | + |
| 38 | + def update_icl_action(self, action: str): |
| 39 | + self.icl_events.append( |
| 40 | + { |
| 41 | + "type": "icl_action", |
| 42 | + "action": action, |
| 43 | + } |
| 44 | + ) |
| 45 | + |
| 46 | + def cache_icl(self): |
| 47 | + self.client.cache_icl_demo(self.get_icl_prompt()) |
| 48 | + self.cached_icl = True |
| 49 | + |
| 50 | + def wrap_episode(self): |
| 51 | + icl_episode = [] |
| 52 | + icl_episode.append( |
| 53 | + Message(role="user", content=f"****** START OF DEMONSTRATION EPISODE {len(self.icl_episodes) + 1} ******") |
| 54 | + ) |
| 55 | + for event in self.icl_events: |
| 56 | + if event["type"] == "icl_observation": |
| 57 | + content = "Obesrvation:\n" + event["text"] |
| 58 | + message = Message(role="user", content=content) |
| 59 | + elif event["type"] == "icl_action": |
| 60 | + content = event["action"] |
| 61 | + message = Message(role="assistant", content=content) |
| 62 | + icl_episode.append(message) |
| 63 | + icl_episode.append( |
| 64 | + Message(role="user", content=f"****** END OF DEMONSTRATION EPISODE {len(self.icl_episodes) + 1} ******") |
| 65 | + ) |
| 66 | + |
| 67 | + self.icl_episodes.append(icl_episode) |
| 68 | + self.icl_events = [] |
| 69 | + |
| 70 | + def get_icl_prompt(self) -> List[Message]: |
| 71 | + icl_instruction = Message( |
| 72 | + role="user", |
| 73 | + content=self.prompt_builder.system_prompt.replace( |
| 74 | + "PLAY", |
| 75 | + "First, observe the demonstrations provided and learn from them!", |
| 76 | + ), |
| 77 | + ) |
| 78 | + |
| 79 | + # unroll the wrapped icl episodes messages |
| 80 | + icl_messages = [icl_instruction] |
| 81 | + for icl_episode in self.icl_episodes: |
| 82 | + icl_messages.extend(icl_episode) |
| 83 | + |
| 84 | + end_demo_message = Message( |
| 85 | + role="user", |
| 86 | + content="****** Now it's your turn to play the game! ******", |
| 87 | + ) |
| 88 | + icl_messages.append(end_demo_message) |
| 89 | + |
| 90 | + return icl_messages |
| 91 | + |
| 92 | + def act(self, obs, prev_action=None): |
| 93 | + """Generate the next action based on the observation and previous action. |
| 94 | +
|
| 95 | + Args: |
| 96 | + obs (dict): The current observation in the environment. |
| 97 | + prev_action (str, optional): The previous action taken. |
| 98 | +
|
| 99 | + Returns: |
| 100 | + str: The selected action from the LLM response. |
| 101 | + """ |
| 102 | + if prev_action: |
| 103 | + self.prompt_builder.update_action(prev_action) |
| 104 | + |
| 105 | + self.prompt_builder.update_observation(obs) |
| 106 | + |
| 107 | + if not self.cached_icl: |
| 108 | + messages = self.get_icl_prompt() |
| 109 | + else: |
| 110 | + messages = [] |
| 111 | + |
| 112 | + messages.extend(self.prompt_builder.get_prompt(icl_episodes=True)) |
| 113 | + |
| 114 | + naive_instruction = """ |
| 115 | +You always have to output one of the above actions at a time and no other text. You always have to output an action until the episode terminates. |
| 116 | + """.strip() |
| 117 | + |
| 118 | + if messages and messages[-1].role == "user": |
| 119 | + messages[-1].content += "\n\n" + naive_instruction |
| 120 | + |
| 121 | + response = make_dummy_action(messages) |
| 122 | + # response = self.client.generate(messages) |
| 123 | + |
| 124 | + final_answer = self._extract_final_answer(response) |
| 125 | + |
| 126 | + return final_answer |
| 127 | + |
| 128 | + def _extract_final_answer(self, answer): |
| 129 | + """Sanitize the final answer, keeping only alphabetic characters. |
| 130 | +
|
| 131 | + Args: |
| 132 | + answer (LLMResponse): The response from the LLM. |
| 133 | +
|
| 134 | + Returns: |
| 135 | + LLMResponse: The sanitized response. |
| 136 | + """ |
| 137 | + |
| 138 | + def filter_letters(input_string): |
| 139 | + return re.sub(r"[^a-zA-Z\s:]", "", input_string) |
| 140 | + |
| 141 | + final_answer = copy.deepcopy(answer) |
| 142 | + final_answer = final_answer._replace(completion=filter_letters(final_answer.completion)) |
| 143 | + |
| 144 | + return final_answer |
0 commit comments