-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbot.py
More file actions
438 lines (364 loc) · 15.7 KB
/
Copy pathbot.py
File metadata and controls
438 lines (364 loc) · 15.7 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
"""Core LLM-powered Balatro bot implementation."""
import asyncio
import base64
import json
import logging
import time
from pathlib import Path
from typing import Any
import httpx
from openai.types.chat import ChatCompletion
from .client import BalatroClient, BalatroError
from .collector import (
ChatCompletionError,
ChatCompletionResponse,
Collector,
FinishReason,
Stats,
)
from .config import Config, Task, get_model_config
from .llm import LLMClient, LLMClientError, LLMTimeoutError
from .strategy import StrategyManager
logger = logging.getLogger(__name__)
def _to_wine_path(path: Path) -> str:
"""Convert a Linux path under Wine's drive_c to a Windows-style path.
Balatro (via BalatroBot Lua mod) runs inside Wine/Proton and can only write
to Windows-style paths. This converts e.g.:
/home/user/.../drive_c/users/foo/bar.png
-> C:\\users\\foo\\bar.png
Falls back to the original string if drive_c is not in the path.
"""
parts = path.parts
try:
idx = next(i for i, p in enumerate(parts) if p == "drive_c")
return "C:\\" + "\\".join(parts[idx + 1 :])
except StopIteration:
return str(path)
class BotError(Exception):
"""Base exception for bot errors."""
pass
class Bot:
"""One-shot LLM-powered Balatro bot. Creates clients, plays a single game, returns stats."""
def __init__(self, task: Task, config: Config, port: int | None = None) -> None:
self.task = task
self.config = config
self.port = port if port is not None else config.port
self.model_config = get_model_config(config.model_config)
self.strategy = StrategyManager(task.strategy)
self._balatro: BalatroClient | None = None
self._llm: LLMClient | None = None
self._collector: Collector | None = None
self._last_error_msg: str | None = None
self._last_failed_msg: str | None = None
self._history: list[dict[str, Any]] = []
# Finish reason tracking
self._finish_reason: FinishReason | None = None
# Separate counters for error calls vs failed calls
self._consecutive_errors: int = 0
self._consecutive_faileds: int = 0
async def __aenter__(self) -> "Bot":
"""Initialize all clients."""
self._balatro = BalatroClient(
host=self.config.host,
port=self.port,
)
await self._balatro.__aenter__()
self._llm = LLMClient(
base_url=self.config.base_url,
api_key=self.config.api_key or "",
vision=self.config.vision,
)
await self._llm.__aenter__()
return self
async def __aexit__(self, *_: Any) -> None:
"""Clean up all clients."""
if self._llm is not None:
await self._llm.__aexit__(None, None, None)
self._llm = None
if self._balatro is not None:
await self._balatro.__aexit__(None, None, None)
self._balatro = None
def _setup_file_logging(self) -> None:
"""Redirect logging to file in run directory."""
if self._collector is None:
return
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
log_file = self._collector.run_dir / "run.log"
file_handler = logging.FileHandler(log_file)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(
logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
)
root_logger.addHandler(file_handler)
async def _wait_for_menu(self, timeout: float = 10.0) -> None:
"""Wait for game to be in MENU state."""
assert self._balatro is not None
start = time.time()
while time.time() - start < timeout:
try:
gamestate = await self._balatro.call("gamestate")
if gamestate.get("state", "") == "MENU":
logger.debug("Confirmed MENU state")
return
except Exception as e:
logger.debug(f"Gamestate check failed: {e}")
await asyncio.sleep(0.5)
self._finish_reason = "connection_abort"
raise BotError(f"Timeout waiting for MENU state after {timeout}s")
async def play(self, runs_dir: Path = Path.cwd()) -> Stats:
"""Play a single game run. Returns final Stats."""
if self._balatro is None or self._llm is None:
raise RuntimeError(
"Bot not initialized. Use 'async with Bot(config) as bot:'"
)
# Health check before initializing collector
try:
await self._balatro.call("gamestate")
except (httpx.ConnectError, httpx.TimeoutException) as e:
self._finish_reason = "connection_abort"
raise BotError(
f"Cannot connect to Balatro on {self.config.host}:{self.port}. "
"Make sure Balatro instance started correctly."
) from e
except Exception as e:
self._finish_reason = "connection_abort"
raise BotError(f"Failed to connect to Balatro: {e}") from e
self._collector = Collector(self.task, runs_dir)
self._setup_file_logging()
logger.info("Starting game")
logger.info(f"Run data will be saved to: {self._collector.run_dir}")
try:
await self._balatro.call("menu")
await self._wait_for_menu()
gamestate = await self._balatro.call(
"start",
{
"deck": self.task.deck,
"stake": self.task.stake,
"seed": self.task.seed,
},
)
await self._run_game_loop(gamestate)
except BotError:
logger.error("Game ended due to bot error")
raise
except Exception as e:
self._finish_reason = "unexpected_error"
logger.exception("Unexpected error occurred during gameplay")
raise BotError(f"Unexpected error: {e}") from e
finally:
if self._collector:
try:
reason: FinishReason = self._finish_reason or "unexpected_error"
self._collector.write_stats(reason)
logger.info("Stats written")
except Exception as e:
logger.debug(
f"Could not write stats (normal if run failed early): {e}"
)
return self._collector._calculate_stats(
self._finish_reason or "unexpected_error"
)
async def _run_game_loop(self, gamestate: dict[str, Any]) -> None:
"""Main game loop."""
assert self._balatro is not None
assert self._llm is not None
assert self._collector is not None
while True:
if gamestate.get("won", False):
self._finish_reason = "won"
logger.info("Game won! Waiting for GAME_OVER state...")
break
current_state = gamestate.get("state", "")
logger.info(f"State: {current_state}")
await asyncio.sleep(0.5)
await self._balatro.call("gamestate")
match current_state:
case "SELECTING_HAND" | "SHOP" | "SMODS_BOOSTER_OPENED" | "BLIND_SELECT":
response = await self._get_llm_response(gamestate)
gamestate = await self._execute_tool_call(response)
case "ROUND_EVAL":
gamestate = await self._balatro.call("cash_out")
case "GAME_OVER":
self._finish_reason = "lost"
logger.info("Game over!")
break
case _:
await asyncio.sleep(1)
gamestate = await self._balatro.call("gamestate")
async def _get_llm_response(self, gamestate: dict[str, Any]) -> ChatCompletion:
"""Get LLM response for current game state."""
assert self._balatro is not None
assert self._llm is not None
assert self._collector is not None
# Take screenshot BEFORE building the request so it can be included in the prompt
next_custom_id = self._collector.peek_next_custom_id()
screenshot_path = self._collector.screenshot_dir / f"{next_custom_id}.png"
screenshot_b64: str | None = None
try:
await self._balatro.call(
"screenshot", {"path": _to_wine_path(screenshot_path)}
)
screenshot_b64 = base64.b64encode(screenshot_path.read_bytes()).decode()
except BalatroError as e:
logger.warning(f"Screenshot failed: {e}")
except Exception as e:
logger.warning(f"Screenshot read failed: {e}")
strategy_content = self.strategy.render_strategy(gamestate)
gamestate_content = self.strategy.render_gamestate(gamestate)
memory_content = self.strategy.render_memory(
history=self._history[-10:],
last_error=self._last_error_msg,
last_failure=self._last_failed_msg,
)
content: list[dict[str, Any]] = [
{
"type": "text",
"text": strategy_content,
"cache_control": {"type": "ephemeral"},
},
]
if screenshot_b64:
content.append(
{
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,{screenshot_b64}"},
}
)
content.extend(
[
{"type": "text", "text": gamestate_content},
{"type": "text", "text": memory_content},
]
)
messages = [{"role": "user", "content": content}]
tools = self.strategy.get_tools(gamestate["state"])
request_data = {
"model": self.task.model,
"messages": messages,
"tools": tools,
**self.model_config,
}
custom_id = self._collector.write_request(request_data)
request_id = str(time.time_ns() // 1_000_000)
try:
response = await self._llm.call(
model=self.task.model,
messages=messages,
tools=tools,
model_config=self.model_config,
)
self._collector.write_response(
id=str(time.time_ns() // 1_000_000),
custom_id=custom_id,
response=ChatCompletionResponse(
request_id=request_id,
status_code=200,
body=response.model_dump(),
),
)
return response
except LLMTimeoutError as e:
self._collector.write_response(
id=str(time.time_ns() // 1_000_000),
custom_id=custom_id,
error=ChatCompletionError(code="timeout", message=str(e)),
)
self._finish_reason = "llm_abort"
raise BotError("3 consecutive LLM timeouts") from e
except LLMClientError as e:
self._collector.write_response(
id=str(time.time_ns() // 1_000_000),
custom_id=custom_id,
error=ChatCompletionError(code="error", message=str(e)),
)
self._finish_reason = "llm_abort"
raise BotError(f"LLM error: {e}") from e
async def _execute_tool_call(self, response: ChatCompletion) -> dict[str, Any]:
"""Execute tool call from LLM response."""
assert self._balatro is not None
assert self._collector is not None
################################################################################
# Parse tool call from LLM response
################################################################################
message = response.choices[0].message
if not hasattr(message, "tool_calls") or not message.tool_calls:
return await self._handle_error_call(
f"No tool calls in LLM response: {message.content}"
)
tool_call = message.tool_calls[0]
function_obj = getattr(tool_call, "function", tool_call)
fn_name = getattr(function_obj, "name", None)
if not fn_name:
return await self._handle_error_call("Invalid tool call: missing name")
fn_args_str = getattr(function_obj, "arguments", None)
if not fn_args_str:
return await self._handle_error_call("Invalid tool call: missing arguments")
try:
fn_args = json.loads(fn_args_str)
except json.JSONDecodeError as e:
return await self._handle_error_call(
f"Invalid JSON in tool call arguments: {e}"
)
################################################################################
# Execute tool call
################################################################################
try:
logger.info(f"Executing: {fn_name}({fn_args})")
gamestate = await self._balatro.call(fn_name, fn_args)
self._collector.reset_failures()
# Reset both consecutive counters on success
self._consecutive_errors = 0
self._consecutive_faileds = 0
self._last_error_msg = None
self._last_failed_msg = None
self._collector.record_call("successful")
self._collector.write_gamestate(gamestate)
self._history.append({"method": fn_name, "params": fn_args})
return gamestate
except BalatroError as e:
return await self._handle_failed_call(f"BalatroError: {e}")
except httpx.TransportError as e:
logger.warning(f"Game transport error during tool call: {e}")
self._collector.record_call("failed")
try:
return await self._balatro.call("gamestate")
except Exception:
self._finish_reason = "connection_abort"
raise BotError(f"Game unresponsive after transport error: {e}") from e
async def _handle_error_call(self, msg: str) -> dict[str, Any]:
"""Handle invalid LLM response (no valid tool call)."""
assert self._balatro is not None
assert self._collector is not None
logger.warning(f"Error call: {msg}")
self._last_error_msg = msg
self._collector.record_failure()
self._collector.record_call("error")
# Track consecutive error calls separately
self._consecutive_errors += 1
self._consecutive_faileds = 0
if self._consecutive_errors >= Collector.MAX_CONSECUTIVE_FAILURES:
self._finish_reason = "consecutive_error_calls"
raise BotError("Too many consecutive error calls")
return await self._balatro.call("gamestate")
async def _handle_failed_call(self, msg: str) -> dict[str, Any]:
"""Handle valid tool call that resulted in BalatroError."""
assert self._balatro is not None
assert self._collector is not None
logger.warning(f"Failed call: {msg}")
self._last_failed_msg = msg
self._collector.record_failure()
self._collector.record_call("failed")
# Track consecutive failed calls separately
self._consecutive_faileds += 1
self._consecutive_errors = 0
if self._consecutive_faileds >= Collector.MAX_CONSECUTIVE_FAILURES:
self._finish_reason = "consecutive_failed_calls"
raise BotError("Too many consecutive failed calls")
return await self._balatro.call("gamestate")