текстовая игра на основе llm + interrupt: README.md
This commit is contained in:
+55
-89
@@ -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.
|
**Текстовая игра на основе LLM + interrupt**
|
||||||
The LLM writes the beginning of a story, pauses for user input (a choice), and then continues the narrative based on that choice.
|
Использует **LangGraph**, **LangChain** и **questionary** для создания интерактивной истории, где пользователь выбирает ход событий.
|
||||||
|
|
||||||
> **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.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Table of Contents
|
## 🚀 Что это?
|
||||||
|
|
||||||
- [What It Does](#what-it-does)
|
- **LLM** генерирует начало сюжета и несколько вариантов развития.
|
||||||
- [Prerequisites](#prerequisites)
|
- Система ставит «паузы» (interrupt) – пользователь в консоли делает выбор через `questionary`.
|
||||||
- [Installation](#installation)
|
- После выбора LLM дописывает короткую концовку, учитывая выбранный путь.
|
||||||
- [Running the Game](#running-the-game)
|
|
||||||
- [Example Session](#example-session)
|
Идеально подходит для демонстрации возможностей LangGraph: состояние, узлы и прерывания.
|
||||||
- [Project Structure](#project-structure)
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## What It Does
|
## 📦 Предварительные требования
|
||||||
|
|
||||||
* Generates a short interactive story using an LLM (OpenAI GPT‑4 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`.
|
| Python | 3.10+ |
|
||||||
* Continues the story based on the chosen option.
|
| 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
|
```bash
|
||||||
# Clone the repo
|
# 1. Клонируйте репозиторий (или скачайте файлы)
|
||||||
git clone https://github.com/your-username/interactive-text-adventure.git
|
git clone https://github.com/yourname/text-adventure.git
|
||||||
cd interactive-text-adventure
|
cd text-adventure
|
||||||
|
|
||||||
# Create a virtual environment (recommended)
|
# 2. Создайте виртуальное окружение (рекомендуется)
|
||||||
python -m venv .venv
|
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
|
pip install -r requirements.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
`requirements.txt` contains:
|
`requirements.txt`:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
langgraph>=0.1.0
|
|
||||||
langchain>=0.2.0
|
|
||||||
langchain-openai>=0.1.0
|
langchain-openai>=0.1.0
|
||||||
|
langgraph>=0.2.0
|
||||||
questionary>=1.10.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
|
```bash
|
||||||
# From the project root
|
|
||||||
python client.py
|
python client.py
|
||||||
```
|
```
|
||||||
|
|
||||||
You can also run the graph directly (useful for debugging):
|
После запуска вы увидите приглашение ввести тему истории, после чего LLM сгенерирует начало и варианты развития. Выберите один из вариантов – игра завершится короткой концовкой.
|
||||||
|
|
||||||
```bash
|
|
||||||
# Run only the graph logic without the CLI wrapper
|
|
||||||
python graph.py
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Example Session
|
## 📖 Пример работы
|
||||||
|
|
||||||
Below is a sample console output when you run `client.py`:
|
|
||||||
|
|
||||||
```
|
```
|
||||||
$ python 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.
|
1️⃣ Пытается открыть дверь
|
||||||
>
|
2️⃣ Смотрит на звёзды
|
||||||
> What do you do?
|
3️⃣ Включает систему жизнеобеспечения
|
||||||
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.
|
|
||||||
|
|
||||||
Enter your choice (1‑3): 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
|
- **`agent.py`** – определяет граф LangGraph: узлы генерации, прерывания и завершения.
|
||||||
interactive-text-adventure/
|
- **`client.py`** – пользовательский интерфейс в консоли, использует `questionary` для выбора вариантов.
|
||||||
├── 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.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
Happy storytelling! 🎲✨
|
## 🤝 Вклад
|
||||||
|
|
||||||
|
Если хотите улучшить игру (добавить больше веток, изменить логику), откройте Pull Request. Убедитесь, что тесты проходят (`pytest`) и код соответствует PEP8.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Счастливого кода! 🚀**
|
||||||
Reference in New Issue
Block a user