Text Adventure Game LLM + Interrupt

A lightweight textbased adventure game that uses a large language model (LLM) to generate dynamic responses to player commands.
The project demonstrates how to integrate LangChain with an OpenAI chat model and use Rich for pretty console output.

⚠️ Prerequisites The code is written for Python3.10+.
It requires an OpenAI API key set in the environment variable OPENAI_API_KEY.


📦 Installation

# 1️⃣ Clone the repository (or copy the single file)
git clone https://github.com/yourname/text-adventure-llm.git
cd text-adventure-llm

# 2️⃣ Create a virtual environment (recommended)
python -m venv .venv
source .venv/bin/activate   # On Windows: .\.venv\Scripts\activate

# 3️⃣ Install dependencies
pip install --upgrade pip
pip install langchain==0.1.0  # or the latest compatible version
pip install rich

Tip

If you prefer a singlefile solution, just copy solution.py into your project directory and skip step2.


🚀 Running the Game

# Make sure your OpenAI key is exported:
export OPENAI_API_KEY="sk-..."

# Run the script
python solution.py

The game will start in an interactive console.
Type any command (e.g., look around, go north, take sword) and press Enter.
The LLM will generate a narrative response, which is printed with Rich formatting.


📁 File Overview

File Purpose
solution.py Main entry point defines TextAdventureGame and runs the REPL loop.

If you want to experiment with different models or temperatures:

game = TextAdventureGame(model_name="gpt-4", temperature=0.5)

🎮 Example Session

$ python solution.py
Welcome to the LLM Adventure! Type your commands below.

> look around
You find yourself in a dimly lit cavern, the walls dripping with moisture. A faint glow emanates from a crystal on the far wall.

> take crystal
The crystal hums as you grasp it; its light warms your hand and reveals hidden runes etched into the stone floor.

> go north
A narrow passage leads deeper underground. The air grows colder, and distant echoes hint at unseen dangers.

...

🛠️ Extending

  • Custom prompts Modify TextAdventureGame to prepend a system prompt or context.
  • Interrupt handling Add keyboard interrupt logic (Ctrl+C) to pause or exit gracefully.
  • State persistence Store the game state in a file or database for longterm sessions.

📄 License

MIT © 2026. Feel free to fork, modify, and share!

S
Description
Решения домашних заданий
Readme 33 KiB
Languages
Python 100%