diff --git a/solutions/69b1a07c67bbf488a1177da4_текстовая_игра_на_основе_llm___interrupt/README.md b/solutions/69b1a07c67bbf488a1177da4_текстовая_игра_на_основе_llm___interrupt/README.md index 5015955..f504ba2 100644 --- a/solutions/69b1a07c67bbf488a1177da4_текстовая_игра_на_основе_llm___interrupt/README.md +++ b/solutions/69b1a07c67bbf488a1177da4_текстовая_игра_на_основе_llm___interrupt/README.md @@ -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 text‑adventure 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. -- 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. +1. **Clone the repository** -This demonstrates: -- State management with `TypedDict` -- Custom interrupt nodes (`langgraph.types.interrupt`) -- Human‑in‑the‑loop pattern -- Checkpointing (in‑memory in this example) + ```bash + git clone https://github.com/your-username/text-adventure-llm.git + cd text-adventure-llm + ``` ---- +2. **Create a virtual environment (recommended)** -## ⚙️ Installation + ```bash + python -m venv .venv + source .venv/bin/activate # On Windows: .\.venv\Scripts\activate + ``` -```bash -# Create a virtual environment (optional but recommended) -python -m venv .venv -source .venv/bin/activate # Windows: .venv\Scripts\activate +3. **Install dependencies** -# Install dependencies -pip install langgraph==0.1.9 \ - langchain==1.2.10 \ - langchain-openai==1.1.9 \ - questionary -``` + ```bash + pip install --upgrade pip + pip install -r requirements.txt + ``` -> **OpenAI API key** -> The script uses `ChatOpenAI` from LangChain, which requires an OpenAI key. Export it as an environment variable: + `requirements.txt` contains: -```bash -export OPENAI_API_KEY="sk-..." -# Windows: set OPENAI_API_KEY=sk-... -``` + ```text + langchain==0.2.0 + 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: -``` -. -├── solution.py # Main script – the graph definition and runner -└── README.md # You’re reading it now -``` + ```bash + export OPENAI_API_KEY="sk-..." + # Windows PowerShell: + $env:OPENAI_API_KEY = "sk-..." + ``` --- ## 🚀 Running the Game +The entire game logic is in `solution.py`. Simply execute it with Python: + ```bash python solution.py ``` -You’ll 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 -$ python solution.py -LLM: "You stand at the crossroads of destiny, with three paths before you..." -Options: - 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. +| File | Purpose | +|------|---------| +| `solution.py` | Main game loop, LangChain configuration, prompt template, and interaction logic. | +| `requirements.txt` | Python dependencies required to run the project. | --- -## 🔧 Customization Tips +## 🔧 Extending the Game -| What | How | -|------|-----| -| **Different LLM** | Replace `ChatOpenAI()` with another LangChain model (e.g., Anthropic). | -| **Persisting state** | Swap `InMemorySaver` for `SQLiteSaver`, `RedisSaver`, etc. | -| **More complex choices** | Add additional interrupt nodes or loop back to earlier parts of the story. | +- **Change the model**: Edit `model_name` in `ChatOpenAI(...)`. +- **Adjust temperature**: Lower values make responses more deterministic; higher values increase creativity. +- **Add new prompts**: Modify `prompt_template.template` to change how the LLM is instructed. +- **Persist history**: Currently, only the last user input and accumulated story are passed. You can store a full conversation log if needed. --- ## 📜 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. --- \ No newline at end of file