-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext_adventure_agent_demo.py
More file actions
226 lines (191 loc) · 7.61 KB
/
Copy pathtext_adventure_agent_demo.py
File metadata and controls
226 lines (191 loc) · 7.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"""
text_adventure_agent_demo.py
Demo: Text Adventure Agent – an LLM-driven agent that plays a simple
text-based game by generating actions and interpreting environment
descriptions. Text adventures (e.g. Zork, AI Dungeon) are a classic and
popular use case for generative agents, demonstrating planning, world
modeling, and long-term memory.
Flow:
1. Environment represents rooms, objects, and state
2. Agent receives observation text from environment
3. LLM produces an action (e.g., "go north", "take key")
4. Simulator updates state, returns new description
5. Repeat until goal reached or max steps
This pattern is widely used in research on LLM decision-making, open
ended play, and embodied agents (TextWorld, Jericho).
Usage:
- pip install requests
- Set OLLAMA_HOST, OLLAMA_MODEL or OPENAI_API_KEY
- python text_adventure_agent_demo.py
"""
import os
import random
from typing import Dict, Tuple
try:
import requests
OLLAMA_AVAILABLE = True
except ImportError:
OLLAMA_AVAILABLE = False
try:
from openai import OpenAI
OPENAI_AVAILABLE = False
except ImportError:
OPENAI_AVAILABLE = False
# ---------------------------------------------------------------------------
# Simple text world environment
# ---------------------------------------------------------------------------
class Room:
def __init__(self, description: str, items: list = None, exits: dict = None):
self.description = description
self.items = items or []
self.exits = exits or {}
class TextWorld:
def __init__(self):
# define few connected rooms
self.rooms: Dict[str, Room] = {
"hall": Room(
"You are in a grand hall. There is a door to the north.",
items=["key"],
exits={"north": "study"},
),
"study": Room(
"You are in a cozy study. There's a locked chest here.",
items=[],
exits={"south": "hall", "east": "garden"},
),
"garden": Room(
"You are in a sunny garden. A fountain lies in the center.",
items=["flower"],
exits={"west": "study"},
),
}
self.current_room = "hall"
self.inventory = []
self.chest_locked = True
def observe(self) -> str:
room = self.rooms[self.current_room]
obs = room.description
if room.items:
obs += " You see " + ", ".join(room.items) + "."
if self.inventory:
obs += " You have " + ", ".join(self.inventory) + "."
return obs
def step(self, action: str) -> Tuple[str, bool]:
# returns (observation, done)
action = action.lower().strip()
room = self.rooms[self.current_room]
# movement
if action.startswith("go "):
direction = action.split(" ")[1]
if direction in room.exits:
self.current_room = room.exits[direction]
return self.observe(), False
else:
return "You can't go that way.", False
# take item
if action.startswith("take "):
item = action.split(" ")[1]
if item in room.items:
room.items.remove(item)
self.inventory.append(item)
return f"You pick up the {item}.", False
else:
return f"There is no {item} here.", False
# unlock chest
if action == "open chest":
if self.current_room == "study":
if "key" in self.inventory:
if self.chest_locked:
self.chest_locked = False
return "You open the chest and find treasure! You win!", True
else:
return "The chest is already open.", False
else:
return "The chest is locked. You need a key.", False
else:
return "There is no chest here.", False
return "I don't understand that action.", False
# ---------------------------------------------------------------------------
# Agent using LLM to choose actions
# ---------------------------------------------------------------------------
class TextAdventureAgent:
def __init__(self, llm_provider: str = "ollama"):
self.llm_provider = llm_provider
def choose_action(self, observation: str) -> str:
prompt = (
"You are playing a text adventure game. Based on the current "
"observation, choose one simple action (e.g., 'go north', 'take key', "
"'open chest'). Provide only the action text.\n\n"
f"Observation: {observation}\n\nAction:"
)
action = call_llm(prompt, self.llm_provider)
# take first line as action
return action.split("\n")[0]
# ---------------------------------------------------------------------------
# LLM helpers
# ---------------------------------------------------------------------------
def call_llm(prompt: str, provider: str = "ollama", system_prompt: str = None) -> str:
if provider.lower() == "openai":
return call_openai(prompt, system_prompt)
else:
return call_ollama(prompt, system_prompt)
def call_ollama(prompt: str, system_prompt: str = None) -> str:
if not OLLAMA_AVAILABLE:
return "(Ollama not available)"
host = os.getenv("OLLAMA_HOST", "http://localhost:11434")
model = os.getenv("OLLAMA_MODEL", "phi3")
url = f"{host.rstrip('/')}/chat?model={model}"
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
try:
resp = requests.post(url, json={"messages": messages}, headers={"Content-Type": "application/json"}, timeout=30)
resp.raise_for_status()
data = resp.json()
if isinstance(data, dict):
choices = data.get("choices", [])
if choices and isinstance(choices[0], dict):
return choices[0].get("message", {}).get("content", "").strip()
return str(data)
except Exception as e:
return f"(Error: {e})"
def call_openai(prompt: str, system_prompt: str = None) -> str:
if not OPENAI_AVAILABLE:
return "(OpenAI not available)"
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
return "(No API key)"
try:
client = OpenAI(api_key=api_key)
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
response = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages, max_tokens=500)
return response.choices[0].message.content.strip()
except Exception as e:
return f"(Error: {e})"
# ---------------------------------------------------------------------------
# Demo execution
# ---------------------------------------------------------------------------
if __name__ == "__main__":
env = TextWorld()
agent = TextAdventureAgent(llm_provider="ollama")
done = False
steps = 0
print("Starting text adventure. Type 'quit' to exit early.\n")
while not done and steps < 20:
obs = env.observe()
print(f"Observation: {obs}")
action = agent.choose_action(obs)
print(f"Agent action: {action}")
if action.lower() == "quit":
break
obs, done = env.step(action)
print(f"Result: {obs}\n")
steps += 1
if done:
print("Game ended: success!")
else:
print("Game ended: max steps reached or quit.")