gbl1357 commited on
Commit
d86f7b8
·
verified ·
1 Parent(s): 574e8f2

Update agent.py

Browse files
Files changed (1) hide show
  1. agent.py +333 -0
agent.py CHANGED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Optimized MCP ReAct Agent for Generalized Text Adventures
3
+ Designed to maximize score across 51 Jericho games.
4
+ """
5
+
6
+ import json
7
+ import os
8
+ import re
9
+ import sys
10
+ from dataclasses import dataclass, field
11
+ from pathlib import Path
12
+ from typing import Optional, Any
13
+
14
+ from dotenv import load_dotenv
15
+ from huggingface_hub import InferenceClient
16
+
17
+ load_dotenv()
18
+
19
+ LLM_MODEL = "Qwen/Qwen2.5-72B-Instruct"
20
+
21
+ _hf_token = os.getenv("HF_TOKEN")
22
+ if not _hf_token:
23
+ raise ValueError("HF_TOKEN not found. Set it in your .env file.")
24
+
25
+ LLM_CLIENT = InferenceClient(token=_hf_token)
26
+
27
+ def call_llm(prompt: str, system_prompt: str, seed: int, max_tokens: int = 300) -> str:
28
+ messages = [
29
+ {"role": "system", "content": system_prompt},
30
+ {"role": "user", "content": prompt},
31
+ ]
32
+ response = LLM_CLIENT.chat.completions.create(
33
+ model=LLM_MODEL,
34
+ messages=messages,
35
+ temperature=0.0,
36
+ max_tokens=max_tokens,
37
+ seed=seed,
38
+ )
39
+ return response.choices[0].message.content
40
+
41
+ @dataclass
42
+ class RunResult:
43
+ final_score: int
44
+ max_score: int
45
+ moves: int
46
+ locations_visited: set[str]
47
+ game_completed: bool
48
+ error: Optional[str] = None
49
+ history: list[tuple[str, str, str]] = field(default_factory=list)
50
+
51
+ # Highly optimized, generalized prompt for text adventure heuristics
52
+ SYSTEM_PROMPT = """You are an expert AI agent playing a classic text adventure game. Your ultimate goal is to MAXIMIZE YOUR SCORE. To get points, you must explore, interact with objects, solve puzzles, and collect treasures.
53
+
54
+ AVAILABLE TOOLS:
55
+ 1. play_action - Execute game commands (e.g., 'north', 'take lamp', 'examine door')
56
+ 2. memory - Get current game state, score, and recent history
57
+ 3. get_map - See explored locations and connections
58
+ 4. inventory - Check what you're carrying
59
+
60
+ UNIVERSAL HEURISTICS FOR SCORING POINTS:
61
+ 1. TAKE EVERYTHING: If a room description mentions an item, your FIRST action should be "take <item>" or "take all".
62
+ 2. EXAMINE NOUNS: If you enter a room and see an object (e.g., a rug, a tree, a button), "examine <object>" to find hidden clues.
63
+ 3. OPEN CONTAINERS: If you see a door, window, box, chest, or mailbox, try to "open <object>".
64
+ 4. EXPLORE UNMAPPED AREAS: Try compass directions (n, s, e, w, u, d, ne, nw, se, sw) to find new rooms.
65
+ 5. NEVER PING-PONG: Do not walk back and forth between two rooms (e.g., going East, then immediately West) unless you hit a dead end.
66
+ 6. LEARN FROM FAILURE: If a command says "You can't do that" or "I don't understand", NEVER try that exact command again.
67
+ 7. USE INVENTORY: If you are stuck, check your inventory. Try to "wear", "eat", "turn on", or "unlock <object> with <item>".
68
+
69
+ RESPOND IN THIS EXACT FORMAT:
70
+ THOUGHT: <Identify nouns/objects in the room description to interact with, OR decide which unexplored direction to take>
71
+ TOOL: <tool_name>
72
+ ARGS: <JSON arguments>
73
+
74
+ Example of excellent gameplay:
75
+ THOUGHT: The description mentions a mailbox. I should open it to see if there is a treasure or clue inside.
76
+ TOOL: play_action
77
+ ARGS: {"action": "open mailbox"}
78
+ """
79
+
80
+ class StudentAgent:
81
+ def __init__(self, logger: Any = None, enable_logging: bool = False):
82
+ self.history: list[dict] = []
83
+ self.recent_actions: list[str] = []
84
+ self.score: int = 0
85
+ self.failed_actions: dict[str, int] = {}
86
+ self.locations_explored: set[str] = set()
87
+ self.unexplored_directions: list[str] = []
88
+ self.steps_since_map_check: int = 0
89
+ self.steps_since_progress: int = 0
90
+ self.current_map: Optional[str] = None
91
+ self.walkthrough_hints: Optional[list[str]] = None
92
+ self.logger = None
93
+ self.current_inventory: list[str] = []
94
+ self.last_direction_moved: Optional[str] = None
95
+
96
+ async def run(
97
+ self, client, game: str, max_steps: int, seed: int, verbose: bool = False, walkthrough: Optional[list[str]] = None
98
+ ) -> RunResult:
99
+ locations_visited = set()
100
+ history = []
101
+ moves = 0
102
+ self.walkthrough_hints = walkthrough
103
+
104
+ tools = await client.list_tools()
105
+ tool_names = [t.name for t in tools]
106
+
107
+ inv_result = await client.call_tool("inventory", {})
108
+ self.current_inventory = self._parse_inventory(self._extract_result(inv_result))
109
+
110
+ result = await client.call_tool("play_action", {"action": "look"})
111
+ observation = self._extract_result(result)
112
+
113
+ location = "Start"
114
+ location = self._extract_location(observation, location)
115
+ locations_visited.add(location)
116
+ self.locations_explored.add(location)
117
+ self.unexplored_directions = ["north", "south", "east", "west", "up", "down", "ne", "nw", "se", "sw"]
118
+
119
+ if verbose: print(f"\n{observation}")
120
+
121
+ for step in range(1, max_steps + 1):
122
+ self.steps_since_map_check += 1
123
+ if self.steps_since_map_check >= 6 or self.steps_since_progress > 3:
124
+ map_result = await client.call_tool("get_map", {})
125
+ self.current_map = self._extract_result(map_result)
126
+ self.steps_since_map_check = 0
127
+
128
+ prompt = self._build_prompt(observation)
129
+ response = call_llm(prompt, SYSTEM_PROMPT, seed + step)
130
+ thought, tool_name, tool_args = self._parse_response(response, tool_names)
131
+
132
+ if verbose:
133
+ print(f"\n--- Step {step} ---")
134
+ print(f"[THOUGHT] {thought}")
135
+ print(f"[TOOL] {tool_name}({tool_args})")
136
+
137
+ tool_name, tool_args = self._validate_tool_call(tool_name, tool_args, tool_names)
138
+
139
+ if tool_name == "play_action":
140
+ action = tool_args.get("action", "look")
141
+ self.recent_actions.append(action)
142
+ if len(self.recent_actions) > 5: self.recent_actions = self.recent_actions[-5:]
143
+
144
+ # Severe anti-loop detection
145
+ if len(self.recent_actions) >= 3 and len(set(self.recent_actions[-3:])) == 1:
146
+ if self.unexplored_directions:
147
+ action = self.unexplored_directions.pop(0)
148
+ tool_args = {"action": action}
149
+ else:
150
+ tool_args = {"action": "look"}
151
+ self.recent_actions[-1] = tool_args["action"]
152
+
153
+ # Track last movement to prevent immediate backtracking
154
+ move_cmds = {"north":"south", "south":"north", "east":"west", "west":"east", "up":"down", "down":"up"}
155
+ if action in move_cmds:
156
+ self.last_direction_moved = action
157
+ elif action not in move_cmds.values():
158
+ self.last_direction_moved = None
159
+
160
+ moves += 1
161
+
162
+ try:
163
+ result = await client.call_tool(tool_name, tool_args)
164
+ observation = self._extract_result(result)
165
+ if tool_name == "inventory":
166
+ self.current_inventory = self._parse_inventory(observation)
167
+ except Exception as e:
168
+ observation = f"Error: {e}"
169
+
170
+ new_location = self._extract_location(observation, location)
171
+ old_score = self.score
172
+ self._update_score(observation)
173
+
174
+ # Check for TRUE progress (New room or more points)
175
+ is_new_room = new_location not in self.locations_explored
176
+
177
+ if is_new_room or self.score > old_score:
178
+ self.steps_since_progress = 0 # Only reset if we actually achieve something new!
179
+ else:
180
+ self.steps_since_progress += 1
181
+
182
+ # Always update location tracking
183
+ if new_location != location:
184
+ location = new_location
185
+ locations_visited.add(location)
186
+ if is_new_room:
187
+ self.locations_explored.add(location)
188
+ # Reset unexplored directions for the new room
189
+ self.unexplored_directions = ["north", "south", "east", "west", "up", "down", "ne", "nw", "se", "sw"]
190
+
191
+ # Track failed actions to avoid repeating them
192
+ if tool_name == "play_action":
193
+ action = tool_args.get("action", "look")
194
+ failure_phrases = ["can't", "cannot", "don't", "not", "fail", "impossible", "doesn't work", "not allowed", "look dark", "i don't understand", "no such"]
195
+ if any(phrase in observation.lower() for phrase in failure_phrases):
196
+ self.failed_actions[action] = self.failed_actions.get(action, 0) + 1
197
+
198
+ if verbose: print(f"[LOCATION] {location} | Score: {self.score} | Explored: {len(self.locations_explored)} | Progress Steps: {self.steps_since_progress}")
199
+
200
+ self.history.append({
201
+ "step": step, "thought": thought, "tool": tool_name, "args": tool_args,
202
+ "result": observation[:200], "location": location, "score": self.score
203
+ })
204
+ if len(self.history) > 10: self.history = self.history[-10:]
205
+ history.append((thought, f"{tool_name}({tool_args})", observation[:100]))
206
+
207
+ if self._is_game_over(observation):
208
+ if verbose: print("\n*** GAME OVER ***")
209
+ break
210
+
211
+ return RunResult(
212
+ final_score=self.score, max_score=350, moves=moves,
213
+ locations_visited=locations_visited, game_completed=self._is_game_over(observation), history=history
214
+ )
215
+
216
+ def _extract_location(self, observation: str, current_location: str = "Unknown") -> str:
217
+ if not observation: return current_location
218
+ ignore_phrases = ["you can't go", "you cannot go", "impenetrable", "nothing special", "doesn't seem to work", "i don't understand", "it's pitch black", "locked", "closed", "inventory:", "valid actions:", "there is no", "you hear", "you are empty-handed", "already", "that's not", "what do you want to", "i see no", "failed"]
219
+ lines = observation.strip().split('\n')
220
+ for line in lines:
221
+ line = line.strip()
222
+ line_lower = line.lower()
223
+ if not line or line.startswith('['): continue
224
+ if any(phrase in line_lower for phrase in ignore_phrases): continue
225
+ if line.endswith('.') and len(line.split()) > 3: continue
226
+ return line
227
+ return current_location
228
+
229
+ def _build_prompt(self, observation: str) -> str:
230
+ parts = [f"Current Score: {self.score}", f"Locations explored: {len(self.locations_explored)}"]
231
+
232
+ if self.history:
233
+ parts.append("\nRecent actions:")
234
+ for entry in self.history[-3:]:
235
+ action = entry.get("args", {}).get("action", entry["tool"])
236
+ res = entry["result"].replace('\n', ' ')
237
+ res_short = res[:80] + "..." if len(res) > 80 else res
238
+ parts.append(f" > {action} -> {res_short}")
239
+
240
+ # Dynamic State Injection
241
+ if self.steps_since_progress == 0 and observation != "Unknown" and len(self.history) > 0:
242
+ parts.append("\n[TACTICAL ADVICE: You just discovered a new area!]")
243
+ parts.append("1. DO NOT move to another room yet.")
244
+ parts.append("2. Look closely at the description below. Are there any objects mentioned? (e.g., mailbox, chest, sword)")
245
+ parts.append("3. If yes, you MUST try to 'take', 'open', or 'examine' them right now.")
246
+ elif self.steps_since_progress > 3:
247
+ parts.append(f"\n[CRITICAL WARNING: You have made {self.steps_since_progress} moves with NO score increase and NO NEW ROOMS.]")
248
+ parts.append("You are walking in circles through already-explored areas. STOP WANDERING.")
249
+ parts.append("To break out of this loop, you MUST do one of the following:")
250
+ parts.append(" 1. Call the 'get_map' tool to see which directions you haven't tried yet.")
251
+ parts.append(" 2. Move in a completely unexplored direction (n, s, e, w, u, d).")
252
+ parts.append(" 3. Examine or interact with an object you previously ignored.")
253
+
254
+ # Warn about failed actions
255
+ if self.failed_actions:
256
+ failed_list = [f"'{k}'" for k, v in self.failed_actions.items() if v >= 2]
257
+ if failed_list: parts.append(f"\n[AVOID: These actions do not work here: {', '.join(failed_list)}]")
258
+
259
+ parts.append(f"\nCurrent situation:\n{observation}\n\nWhat do you do next?")
260
+ return "\n".join(parts)
261
+
262
+ def _parse_response(self, response: str, valid_tools: list[str]) -> tuple[str, str, dict]:
263
+ thought, tool_name, tool_args = "No reasoning provided", "play_action", {"action": "look"}
264
+ for line in response.strip().split("\n"):
265
+ line_clean = line.strip()
266
+ line_upper = line_clean.upper()
267
+ if line_upper.startswith("THOUGHT:"): thought = line_clean.split(":", 1)[1].strip()
268
+ elif line_upper.startswith("TOOL:"):
269
+ raw = line_clean.split(":", 1)[1].strip().lower().replace("**", "").replace("*", "").replace("`", "")
270
+ tool_name = raw.split()[0] if raw else "play_action"
271
+ elif line_upper.startswith("ARGS:"):
272
+ args_part = line_clean.split(":", 1)[1].strip()
273
+ try: tool_args = json.loads(args_part.replace("'", '"'))
274
+ except:
275
+ match = re.search(r'"action"\s*:\s*"([^"]+)"', args_part)
276
+ tool_args = {"action": match.group(1)} if match else {"action": "look"}
277
+ return thought, tool_name, tool_args
278
+
279
+ def _validate_tool_call(self, tool_name: str, tool_args: dict, valid_tools: list[str]) -> tuple[str, dict]:
280
+ if tool_name not in valid_tools: tool_name = "play_action"
281
+
282
+ if tool_name == "play_action":
283
+ action = tool_args.get("action", "look").lower().strip().replace("**", "")
284
+
285
+ # Map bad verbs to Z-Machine standard verbs
286
+ verb_map = {"check": "examine", "inspect": "examine", "investigate": "examine", "grab": "take", "pick up": "take"}
287
+ words = action.split()
288
+ if words and words[0] in verb_map:
289
+ words[0] = verb_map[words[0]]
290
+ action = " ".join(words)
291
+
292
+ # Prevent immediate backtracking (ping-ponging)
293
+ reverse_dirs = {"north":"south", "south":"north", "east":"west", "west":"east", "up":"down", "down":"up"}
294
+ if self.last_direction_moved and action == reverse_dirs.get(self.last_direction_moved):
295
+ if self.unexplored_directions:
296
+ action = self.unexplored_directions.pop(0) # Force a different direction
297
+
298
+ # Prevent repeating failed actions
299
+ if action in self.failed_actions and self.failed_actions[action] >= 2:
300
+ action = self.unexplored_directions.pop(0) if self.unexplored_directions else "look"
301
+
302
+ tool_args["action"] = action
303
+
304
+ return tool_name, tool_args
305
+
306
+ def _extract_result(self, result) -> str:
307
+ if hasattr(result, 'content') and result.content: return result.content[0].text
308
+ if isinstance(result, list) and result: return result[0].text if hasattr(result[0], 'text') else str(result[0])
309
+ return str(result)
310
+
311
+ def _update_score(self, text: str) -> None:
312
+ for pattern in [r'Score:\s*(\d+)', r'score[:\s]+(\d+)', r'\[Score:\s*(\d+)']:
313
+ match = re.search(pattern, text, re.IGNORECASE)
314
+ if match: self.score = max(self.score, int(match.group(1)))
315
+
316
+ def _is_game_over(self, text: str) -> bool:
317
+ return any(phrase in text.lower() for phrase in ["game over", "you have died", "you are dead", "*** you have died ***"])
318
+
319
+ def _parse_inventory(self, inv_text: str) -> list[str]:
320
+ if "empty-handed" in inv_text.lower() or "nothing" in inv_text.lower(): return []
321
+ if ":" in inv_text: return [item.strip() for item in inv_text.split(":", 1)[1].strip().split(",") if item.strip()]
322
+ return []
323
+
324
+ async def test_agent():
325
+ from fastmcp import Client
326
+ agent = StudentAgent()
327
+ async with Client("mcp_server.py") as client:
328
+ result = await agent.run(client=client, game="zork1", max_steps=40, seed=42, verbose=True)
329
+ print(f"\n{'=' * 50}\nFinal Score: {result.final_score}\nMoves: {result.moves}\nLocations: {len(result.locations_visited)}")
330
+
331
+ if __name__ == "__main__":
332
+ import asyncio
333
+ asyncio.run(test_agent())