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

This commit is contained in:
2026-05-28 09:55:04 +00:00
parent fc28048814
commit 75372e9743
@@ -1,140 +1,106 @@
# Interactive Text Adventure “Choose Your Own Story”
# 📚 Мини‑игра «Выбери свою историю»
A lightweight Python project that turns a large language model into an interactive storytelling engine.
The LLM writes the beginning of a story, pauses for user input (a choice), and then continues the narrative based on that choice.
> **TL;DR**
> 1. Run `client.py` to start the game.
> 2. The AI presents you with a scenario and three options.
> 3. Pick an option via the terminal prompt.
> 4. The AI finishes the story for you.
**Текстовая игра на основе LLM + interrupt**
Использует **LangGraph**, **LangChain** и **questionary** для создания интерактивной истории, где пользователь выбирает ход событий.
---
## Table of Contents
## 🚀 Что это?
- [What It Does](#what-it-does)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Running the Game](#running-the-game)
- [Example Session](#example-session)
- [Project Structure](#project-structure)
- **LLM** генерирует начало сюжета и несколько вариантов развития.
- Система ставит «паузы» (interrupt) – пользователь в консоли делает выбор через `questionary`.
- После выбора LLM дописывает короткую концовку, учитывая выбранный путь.
Идеально подходит для демонстрации возможностей LangGraph: состояние, узлы и прерывания.
---
## What It Does
## 📦 Предварительные требования
* Generates a short interactive story using an LLM (OpenAI GPT4 or any compatible model).
* Uses **LangGraph** to manage state and flow, pausing execution at a custom *interrupt* node.
* Presents the user with three narrative choices via `questionary`.
* Continues the story based on the chosen option.
| Пакет | Версия |
|-------|--------|
| Python | 3.10+ |
| pip | - |
| OpenAI API key | Переменная окружения `OPENAI_API_KEY` |
> **Важно**: Установите ключ в переменную окружения перед запуском:
> ```bash
> export OPENAI_API_KEY="sk-..."
> ```
---
## Prerequisites
| Component | Minimum Version | Notes |
|-----------|-----------------|-------|
| Python | 3.10+ | Tested on 3.11 |
| OpenAI API key | | Set as environment variable `OPENAI_API_KEY` |
| LangGraph | Latest (pip install) | Handles graph execution and checkpoints |
| LangChain | Latest (pip install) | Core LLM integration |
| questionary | Latest (pip install) | Terminal UI for choices |
> **Optional**: If you want to run the model locally, replace `ChatOpenAI` with a local LLM provider supported by LangChain.
---
## Installation
## ⚙️ Установка
```bash
# Clone the repo
git clone https://github.com/your-username/interactive-text-adventure.git
cd interactive-text-adventure
# 1. Клонируйте репозиторий (или скачайте файлы)
git clone https://github.com/yourname/text-adventure.git
cd text-adventure
# Create a virtual environment (recommended)
# 2. Создайте виртуальное окружение (рекомендуется)
python -m venv .venv
source .venv/bin/activate # On Windows: .\.venv\Scripts\activate
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install dependencies
# 3. Установите зависимости
pip install -r requirements.txt
```
`requirements.txt` contains:
`requirements.txt`:
```text
langgraph>=0.1.0
langchain>=0.2.0
langchain-openai>=0.1.0
langgraph>=0.2.0
questionary>=1.10.0
```
---
## Running the Game
The entry point is `client.py`. It builds the graph, starts execution, and handles user interaction.
## ▶️ Запуск
```bash
# From the project root
python client.py
```
You can also run the graph directly (useful for debugging):
```bash
# Run only the graph logic without the CLI wrapper
python graph.py
```
После запуска вы увидите приглашение ввести тему истории, после чего LLM сгенерирует начало и варианты развития. Выберите один из вариантов – игра завершится короткой концовкой.
---
## Example Session
Below is a sample console output when you run `client.py`:
## 📖 Пример работы
```
$ python client.py
Welcome to "Choose Your Own Story"!
Введите тему истории: приключения в космосе
LLM генерирует начальный сюжет...
The AI has generated the following scenario:
> You find yourself in a dimly lit cavern, the sound of dripping water echoing around you.
>
> What do you do?
1. Explore deeper into the darkness.
2. Search for an exit on the far wall.
3. Call out to see if anyone else is there.
> Что делает герой?
1️⃣ Пытается открыть дверь
2️⃣ Смотрит на звёзды
3️⃣ Включает систему жизнеобеспечения
Enter your choice (13): 2
Выберите вариант (1/2/3): 2
You chose: "Search for an exit on the far wall."
LLM продолжает историю...
```
The AI continues the story:
> You move cautiously toward the far wall, feeling the damp stone under your feet...
**Результат:**
```
Герой, стоя в открытом космосе, смотрел на бесконечный океан звёзд. Внутри него раздался тихий шёпот неизвестного сигнала... (и так далее)
```
---
## Project Structure
## 📚 Как это работает
```text
interactive-text-adventure/
├── client.py # CLI entry point starts the graph and handles user input
├── graph.py # LangGraph definition: nodes, state, interrupt logic
├── requirements.txt # Dependencies
└── README.md # This file
```
- **client.py**
*Initializes the LLM, memory, and graph.
Calls `graph.run()` which pauses at the interrupt node, then resumes after user input.*
- **graph.py**
*Defines `StoryState` (theme, story text, etc.).
Implements a custom interrupt node that yields control to the CLI for user choice.*
Feel free to extend the game by adding more nodes, richer state, or different LLM providers.
- **`agent.py`** – определяет граф LangGraph: узлы генерации, прерывания и завершения.
- **`client.py`** – пользовательский интерфейс в консоли, использует `questionary` для выбора вариантов.
---
Happy storytelling! 🎲✨
## 🤝 Вклад
Если хотите улучшить игру (добавить больше веток, изменить логику), откройте Pull Request. Убедитесь, что тесты проходят (`pytest`) и код соответствует PEP8.
---
**Счастливого кода! 🚀**