текстовая игра на основе llm + interrupt: README.md

This commit is contained in:
2026-05-27 12:13:41 +00:00
parent d8c93bded7
commit 87ec33432a
@@ -1,108 +1,104 @@
# Interactive Text Adventure with LLM and Interrupts # Text Adventure Game Powered by LLM + Interrupt
A minimal “Choose Your Own Story” game built on **LangGraph** that lets a large language model generate the narrative, pause for user input, and then continue based on the choice. A lightweight textadventure game that uses a large language model (LLM) via **LangChain** to generate dynamic storylines in real time.
The game runs entirely from the command line and can be extended with new prompts or models.
--- ---
## 📖 Overview ## 📦 Installation
- The graph starts by asking an LLM to write the opening of a story and propose several actions. 1. **Clone the repository**
- It then *interrupts* the flow, presenting those options in the console via **questionary**.
- After the player selects an option, the graph resumes and asks the LLM to finish the scene with that choice.
This demonstrates: ```bash
- State management with `TypedDict` git clone https://github.com/your-username/text-adventure-llm.git
- Custom interrupt nodes (`langgraph.types.interrupt`) cd text-adventure-llm
- Humanintheloop pattern ```
- Checkpointing (inmemory in this example)
--- 2. **Create a virtual environment (recommended)**
## ⚙️ Installation ```bash
python -m venv .venv
source .venv/bin/activate # On Windows: .\.venv\Scripts\activate
```
```bash 3. **Install dependencies**
# Create a virtual environment (optional but recommended)
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install dependencies ```bash
pip install langgraph==0.1.9 \ pip install --upgrade pip
langchain==1.2.10 \ pip install -r requirements.txt
langchain-openai==1.1.9 \ ```
questionary
```
> **OpenAI API key** `requirements.txt` contains:
> The script uses `ChatOpenAI` from LangChain, which requires an OpenAI key. Export it as an environment variable:
```bash ```text
export OPENAI_API_KEY="sk-..." langchain==0.2.0
# Windows: set OPENAI_API_KEY=sk-... langchain-openai==0.1.0
``` openai==1.30.0
```
--- 4. **Set your OpenAI API key**
## 📂 Project Structure The game uses the OpenAI API via LangChain.
Export the key as an environment variable:
``` ```bash
. export OPENAI_API_KEY="sk-..."
├── solution.py # Main script the graph definition and runner # Windows PowerShell:
└── README.md # Youre reading it now $env:OPENAI_API_KEY = "sk-..."
``` ```
--- ---
## 🚀 Running the Game ## 🚀 Running the Game
The entire game logic is in `solution.py`. Simply execute it with Python:
```bash ```bash
python solution.py python solution.py
``` ```
Youll see something like: You will see a welcome message and can start typing commands.
Type `exit` to quit.
### Example Session
``` ```
LLM: "You find yourself in a dimly lit tavern..." Добро пожаловать в текстовую приключенческую игру!
Options:
1) Order a drink
2) Ask about the town's rumors
3) Leave immediately
Enter choice (1-3):
```
Type `1`, `2` or `3` and press **Enter**. The LLM will then generate a short continuation based on your selection. Введите команду (или 'exit' для выхода): Я открываю дверь.
Ответ ведущего:
Ты осторожно открываешь старую деревянную дверь, которая скрипит под твоим весом. За дверью виднеется темный коридор, освещенный мерцающим светом факелов. Внутри слышен шёпот ветра и отдалённые шаги.
Введите команду (или 'exit'): Я смотрю вокруг.
Ответ ведущего:
Тебе удаётся разглядеть несколько старинных портретов на стенах, их глаза будто следят за каждым твоим движением. В центре коридора стоит массивный каменный стол с таинственными рунами.
Введите команду (или 'exit'): exit
Спасибо за игру! До встречи.
```
--- ---
## 📋 Example Session ## 📄 File Overview
```text | File | Purpose |
$ python solution.py |------|---------|
LLM: "You stand at the crossroads of destiny, with three paths before you..." | `solution.py` | Main game loop, LangChain configuration, prompt template, and interaction logic. |
Options: | `requirements.txt` | Python dependencies required to run the project. |
1) Take the left path into the forest.
2) Walk straight toward the looming castle.
3) Turn back to the village.
Enter choice (1-3): 2
LLM: "You stride confidently toward the castle gates, feeling the weight of history upon your shoulders..."
```
Feel free to modify `solution.py` to add more nodes, change prompts, or persist checkpoints with a different saver.
--- ---
## 🔧 Customization Tips ## 🔧 Extending the Game
| What | How | - **Change the model**: Edit `model_name` in `ChatOpenAI(...)`.
|------|-----| - **Adjust temperature**: Lower values make responses more deterministic; higher values increase creativity.
| **Different LLM** | Replace `ChatOpenAI()` with another LangChain model (e.g., Anthropic). | - **Add new prompts**: Modify `prompt_template.template` to change how the LLM is instructed.
| **Persisting state** | Swap `InMemorySaver` for `SQLiteSaver`, `RedisSaver`, etc. | - **Persist history**: Currently, only the last user input and accumulated story are passed. You can store a full conversation log if needed.
| **More complex choices** | Add additional interrupt nodes or loop back to earlier parts of the story. |
--- ---
## 📜 License ## 📜 License
This project is provided as a learning example and may be freely used, modified, and distributed. This project is released under the MIT License. Feel free to fork, modify, and distribute.
--- ---