Upload 3 files
Browse files- README.md +74 -7
- app.py +468 -0
- requirements.txt +3 -0
README.md
CHANGED
|
@@ -1,13 +1,80 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 6.
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
pinned: false
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: The Infinite Tavern
|
| 3 |
+
emoji: ⚔️
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: yellow
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 6.22.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
license: mit
|
| 11 |
---
|
| 12 |
|
| 13 |
+
# The Infinite Tavern
|
| 14 |
+
|
| 15 |
+
A configurable fantasy role-playing game with a Gradio interface and an AI Dungeon Master powered by the OpenAI Responses API.
|
| 16 |
+
|
| 17 |
+
## Features
|
| 18 |
+
|
| 19 |
+
- Campaign menus for setting, tone, complexity, narration length, rules style, and content boundary
|
| 20 |
+
- English or European Portuguese narration
|
| 21 |
+
- Editable Dungeon Master, campaign, and per-turn prompts
|
| 22 |
+
- Up to eight configurable player characters
|
| 23 |
+
- d20 roller with modifiers; the result is queued for the next AI turn
|
| 24 |
+
- Campaign ledger for locations, objectives, allies, foes, discoveries, conditions, and open threads
|
| 25 |
+
- Local JSON save/load
|
| 26 |
+
- Bounded conversation context (the latest 20 messages) to control token use
|
| 27 |
+
- API key read only from the environment
|
| 28 |
+
|
| 29 |
+
## Run
|
| 30 |
+
|
| 31 |
+
Python 3.10 or newer is recommended.
|
| 32 |
+
|
| 33 |
+
```bash
|
| 34 |
+
cd dnd_chatgpt_game
|
| 35 |
+
python -m venv .venv
|
| 36 |
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
| 37 |
+
pip install -r requirements.txt
|
| 38 |
+
cp .env.example .env
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Set `OPENAI_API_KEY` in your shell. The official OpenAI SDK reads it automatically:
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
export OPENAI_API_KEY="your_key_here"
|
| 45 |
+
python app.py
|
| 46 |
+
```
|
| 47 |
+
|
| 48 |
+
Open `http://127.0.0.1:7860`.
|
| 49 |
+
|
| 50 |
+
The app defaults to `gpt-5.6-luna`; change the model in the interface or with `OPENAI_MODEL`. API usage is billed to the API project associated with the key.
|
| 51 |
+
|
| 52 |
+
## Character format
|
| 53 |
+
|
| 54 |
+
Enter one character per line:
|
| 55 |
+
|
| 56 |
+
```text
|
| 57 |
+
Kael | human ranger | patient tracker; longbow; wounded left hand
|
| 58 |
+
Mira | elven wizard | curious; specializes in illusions
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
## Prompt placeholders
|
| 62 |
+
|
| 63 |
+
The main Dungeon Master prompt may contain:
|
| 64 |
+
|
| 65 |
+
- `{campaign_config}`
|
| 66 |
+
- `{characters}`
|
| 67 |
+
- `{ledger}`
|
| 68 |
+
- `{custom_prompt}`
|
| 69 |
+
|
| 70 |
+
Invalid placeholders produce a visible interface error instead of an API request.
|
| 71 |
+
|
| 72 |
+
## Notes
|
| 73 |
+
|
| 74 |
+
This is a narrative aid, not an official Dungeons & Dragons rules implementation. The default prompt uses “D&D 5e-inspired” adjudication without reproducing proprietary rulebook text. Campaign saves may contain the story text you entered or generated; keep the `saves/` folder private if needed.
|
| 75 |
+
|
| 76 |
+
## Hugging Face Spaces
|
| 77 |
+
|
| 78 |
+
Create a Gradio Space and upload the files in this folder to the repository root. In **Settings → Variables and secrets**, add `OPENAI_API_KEY` as a **Secret**. Do not commit the key or a populated `.env` file. The app binds to `0.0.0.0` by default for Spaces.
|
| 79 |
+
|
| 80 |
+
The app can run on either CPU Basic or ZeroGPU. For ZeroGPU, `app.py` registers an unused `@spaces.GPU` marker so the runtime accepts the Space. The game itself does not invoke that function: narration remains an OpenAI API call and normal gameplay does not request a GPU allocation.
|
app.py
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Configurable AI Dungeon Master built with Gradio and the OpenAI Responses API."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import random
|
| 8 |
+
import re
|
| 9 |
+
from copy import deepcopy
|
| 10 |
+
from datetime import datetime, timezone
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
import gradio as gr
|
| 15 |
+
from openai import OpenAI
|
| 16 |
+
from dotenv import load_dotenv
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
import spaces
|
| 20 |
+
except ImportError: # Available automatically on Hugging Face ZeroGPU.
|
| 21 |
+
spaces = None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
load_dotenv()
|
| 25 |
+
APP_TITLE = "The Infinite Tavern"
|
| 26 |
+
DEFAULT_MODEL = os.getenv("OPENAI_MODEL", "gpt-5.6-luna")
|
| 27 |
+
SAVE_DIR = Path(os.getenv("DND_SAVE_DIR", "saves"))
|
| 28 |
+
|
| 29 |
+
BASE_DM_PROMPT = """You are the Dungeon Master for a cooperative fantasy role-playing game inspired by Dungeons & Dragons.
|
| 30 |
+
|
| 31 |
+
Core rules:
|
| 32 |
+
- Narrate vividly but leave consequential choices to the players.
|
| 33 |
+
- Never decide a player character's actions, words, emotions, or dice results.
|
| 34 |
+
- Maintain continuity with the campaign ledger and transcript.
|
| 35 |
+
- When an uncertain action needs a check, either use the supplied roll or ask for exactly one appropriate d20 check and state the ability/skill and DC.
|
| 36 |
+
- Honor established inventory, injuries, spell limits, relationships, clues, and consequences.
|
| 37 |
+
- Keep combat readable: state immediate threats, approximate distances, and whose turn it is.
|
| 38 |
+
- Do not bury the choice. End every turn with 2–4 concrete options plus permission to attempt anything else.
|
| 39 |
+
- Treat this as fiction. Avoid real-world instructions that would enable wrongdoing.
|
| 40 |
+
|
| 41 |
+
Campaign configuration:
|
| 42 |
+
{campaign_config}
|
| 43 |
+
|
| 44 |
+
Player characters:
|
| 45 |
+
{characters}
|
| 46 |
+
|
| 47 |
+
Campaign ledger:
|
| 48 |
+
{ledger}
|
| 49 |
+
|
| 50 |
+
Additional campaign instructions:
|
| 51 |
+
{custom_prompt}
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
START_PROMPT = """Open the campaign with a strong scene, a specific immediate problem, and a reason for this party to act together. Introduce at most three named NPCs. End at the first meaningful player decision."""
|
| 55 |
+
|
| 56 |
+
CONTINUE_PROMPT = """Resolve the party's declared action fairly, applying the supplied dice result if present. Advance the world, update consequences, and present the next meaningful decision."""
|
| 57 |
+
|
| 58 |
+
COMPLEXITY_GUIDANCE = {
|
| 59 |
+
"Simple": "Use short scenes, obvious stakes, few NPCs, forgiving DCs, and minimal bookkeeping.",
|
| 60 |
+
"Standard": "Use layered encounters, meaningful trade-offs, recurring NPCs, and moderate tactical detail.",
|
| 61 |
+
"Intricate": "Use factions with conflicting goals, hidden motives, resource pressure, hard trade-offs, and clues that reward inference.",
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
LENGTH_GUIDANCE = {
|
| 65 |
+
"Brief": "Write about 180–300 words.",
|
| 66 |
+
"Balanced": "Write about 350–550 words.",
|
| 67 |
+
"Cinematic": "Write about 600–850 words, with sensory detail but no filler.",
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
LANGUAGE_GUIDANCE = {
|
| 71 |
+
"English": (
|
| 72 |
+
"Write all narration, dialogue, choices, rules explanations, location labels, "
|
| 73 |
+
"and quest labels in English. Preserve character and place names."
|
| 74 |
+
),
|
| 75 |
+
"Português (Portugal)": (
|
| 76 |
+
"Write all narration, dialogue, choices, rules explanations, location labels, "
|
| 77 |
+
"and quest labels in European Portuguese (pt-PT), not Brazilian Portuguese. "
|
| 78 |
+
"Preserve character and place names."
|
| 79 |
+
),
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
CSS = """
|
| 83 |
+
:root { --ink: #f2e8d5; --gold: #d6a64a; --wine: #6f263d; }
|
| 84 |
+
.gradio-container { max-width: 1280px !important; }
|
| 85 |
+
.hero { padding: 1.2rem 1.4rem; border: 1px solid #6e5430; border-radius: 18px;
|
| 86 |
+
background: radial-gradient(circle at 15% 0%, #4c2830 0, #211923 45%, #15131a 100%); }
|
| 87 |
+
.hero h1 { color: #f4d28a; margin: 0 0 .2rem 0; font-family: Georgia, serif; }
|
| 88 |
+
.hero p { color: #dbcdb7; margin: 0; }
|
| 89 |
+
.status-card { border-left: 4px solid #d6a64a !important; }
|
| 90 |
+
.primary-btn { background: linear-gradient(90deg, #7b2f46, #9b603c) !important; color: white !important; }
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
if spaces is not None:
|
| 95 |
+
@spaces.GPU
|
| 96 |
+
def zerogpu_registration_marker() -> str:
|
| 97 |
+
"""Register this API-only app with the Hugging Face ZeroGPU runtime.
|
| 98 |
+
|
| 99 |
+
Gameplay never calls this function, so normal use does not request a GPU
|
| 100 |
+
allocation or consume ZeroGPU quota.
|
| 101 |
+
"""
|
| 102 |
+
return "ZeroGPU runtime registered"
|
| 103 |
+
else:
|
| 104 |
+
def zerogpu_registration_marker() -> str:
|
| 105 |
+
"""Local fallback when the Hugging Face spaces module is unavailable."""
|
| 106 |
+
return "CPU runtime"
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def empty_state() -> dict[str, Any]:
|
| 110 |
+
return {
|
| 111 |
+
"history": [],
|
| 112 |
+
"ledger": {
|
| 113 |
+
"location": "Not yet established",
|
| 114 |
+
"quest": "Not yet established",
|
| 115 |
+
"objectives": [],
|
| 116 |
+
"allies": [],
|
| 117 |
+
"foes": [],
|
| 118 |
+
"discoveries": [],
|
| 119 |
+
"inventory_changes": [],
|
| 120 |
+
"conditions": [],
|
| 121 |
+
"open_threads": [],
|
| 122 |
+
},
|
| 123 |
+
"turn": 0,
|
| 124 |
+
"started": False,
|
| 125 |
+
"last_roll": None,
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def parse_characters(text: str) -> list[dict[str, str]]:
|
| 130 |
+
"""Parse one character per line: Name | class/species | notes."""
|
| 131 |
+
characters = []
|
| 132 |
+
for raw_line in (text or "").splitlines():
|
| 133 |
+
line = raw_line.strip()
|
| 134 |
+
if not line:
|
| 135 |
+
continue
|
| 136 |
+
parts = [part.strip() for part in line.split("|", 2)]
|
| 137 |
+
parts += [""] * (3 - len(parts))
|
| 138 |
+
characters.append({"name": parts[0], "archetype": parts[1], "notes": parts[2]})
|
| 139 |
+
return characters
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def campaign_config(
|
| 143 |
+
campaign_name: str,
|
| 144 |
+
language: str,
|
| 145 |
+
setting: str,
|
| 146 |
+
tone: str,
|
| 147 |
+
complexity: str,
|
| 148 |
+
response_length: str,
|
| 149 |
+
rules_style: str,
|
| 150 |
+
safety: str,
|
| 151 |
+
) -> str:
|
| 152 |
+
return "\n".join(
|
| 153 |
+
[
|
| 154 |
+
f"Campaign: {campaign_name or 'Untitled campaign'}",
|
| 155 |
+
f"Language: {language}. {LANGUAGE_GUIDANCE[language]}",
|
| 156 |
+
f"Setting: {setting}",
|
| 157 |
+
f"Tone: {tone}",
|
| 158 |
+
f"Complexity: {complexity}. {COMPLEXITY_GUIDANCE[complexity]}",
|
| 159 |
+
f"Response length: {response_length}. {LENGTH_GUIDANCE[response_length]}",
|
| 160 |
+
f"Rules style: {rules_style}",
|
| 161 |
+
f"Content boundary: {safety}",
|
| 162 |
+
]
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def build_instructions(
|
| 167 |
+
base_prompt: str,
|
| 168 |
+
custom_prompt: str,
|
| 169 |
+
config: str,
|
| 170 |
+
characters: list[dict[str, str]],
|
| 171 |
+
ledger: dict[str, Any],
|
| 172 |
+
) -> str:
|
| 173 |
+
template = base_prompt or BASE_DM_PROMPT
|
| 174 |
+
values = {
|
| 175 |
+
"campaign_config": config,
|
| 176 |
+
"characters": json.dumps(characters, ensure_ascii=False, indent=2),
|
| 177 |
+
"ledger": json.dumps(ledger, ensure_ascii=False, indent=2),
|
| 178 |
+
"custom_prompt": custom_prompt or "None.",
|
| 179 |
+
}
|
| 180 |
+
try:
|
| 181 |
+
return template.format(**values)
|
| 182 |
+
except (KeyError, ValueError) as exc:
|
| 183 |
+
raise gr.Error(f"The base prompt has an invalid placeholder: {exc}") from exc
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def api_messages(history: list[dict[str, str]], player_text: str) -> list[dict[str, str]]:
|
| 187 |
+
recent = history[-20:]
|
| 188 |
+
messages = [{"role": row["role"], "content": row["content"]} for row in recent]
|
| 189 |
+
messages.append({"role": "user", "content": player_text})
|
| 190 |
+
return messages
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def call_dm(model: str, instructions: str, messages: list[dict[str, str]]) -> str:
|
| 194 |
+
if not os.getenv("OPENAI_API_KEY"):
|
| 195 |
+
raise gr.Error("OPENAI_API_KEY is not set. Add it to your environment and restart the app.")
|
| 196 |
+
client = OpenAI()
|
| 197 |
+
try:
|
| 198 |
+
response = client.responses.create(
|
| 199 |
+
model=(model or DEFAULT_MODEL).strip(),
|
| 200 |
+
instructions=instructions,
|
| 201 |
+
input=messages,
|
| 202 |
+
)
|
| 203 |
+
except Exception as exc:
|
| 204 |
+
raise gr.Error(f"OpenAI request failed: {exc}") from exc
|
| 205 |
+
text = (response.output_text or "").strip()
|
| 206 |
+
if not text:
|
| 207 |
+
raise gr.Error("The model returned no narration. Try again or choose another model.")
|
| 208 |
+
return text
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def chat_pairs(history: list[dict[str, str]]) -> list[dict[str, str]]:
|
| 212 |
+
return [{"role": item["role"], "content": item["content"]} for item in history]
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def ledger_markdown(state: dict[str, Any]) -> str:
|
| 216 |
+
ledger = state["ledger"]
|
| 217 |
+
lines = [
|
| 218 |
+
f"### Turn {state['turn']}",
|
| 219 |
+
f"**Location:** {ledger['location']}",
|
| 220 |
+
f"**Quest:** {ledger['quest']}",
|
| 221 |
+
]
|
| 222 |
+
for label, key in [
|
| 223 |
+
("Objectives", "objectives"), ("Allies", "allies"), ("Foes", "foes"),
|
| 224 |
+
("Discoveries", "discoveries"), ("Conditions", "conditions"),
|
| 225 |
+
("Open threads", "open_threads"),
|
| 226 |
+
]:
|
| 227 |
+
values = ledger.get(key) or []
|
| 228 |
+
lines.append(f"**{label}:** " + ("; ".join(values) if values else "—"))
|
| 229 |
+
if state.get("last_roll"):
|
| 230 |
+
lines.append(f"**Last roll:** {state['last_roll']}")
|
| 231 |
+
return "\n\n".join(lines)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def infer_ledger(state: dict[str, Any], narration: str) -> None:
|
| 235 |
+
"""Conservatively record explicit headings emitted by the DM, without another API call."""
|
| 236 |
+
patterns = {
|
| 237 |
+
"location": r"(?im)^\*{0,2}(?:location|current location)\*{0,2}:\s*(.+)$",
|
| 238 |
+
"quest": r"(?im)^\*{0,2}(?:quest|objective)\*{0,2}:\s*(.+)$",
|
| 239 |
+
}
|
| 240 |
+
for key, pattern in patterns.items():
|
| 241 |
+
match = re.search(pattern, narration)
|
| 242 |
+
if match:
|
| 243 |
+
state["ledger"][key] = match.group(1).strip()[:180]
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def validate_setup(characters_text: str) -> list[dict[str, str]]:
|
| 247 |
+
characters = parse_characters(characters_text)
|
| 248 |
+
if not characters:
|
| 249 |
+
raise gr.Error("Add at least one character using: Name | class/species | notes")
|
| 250 |
+
if len(characters) > 8:
|
| 251 |
+
raise gr.Error("Use at most eight player characters.")
|
| 252 |
+
return characters
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def run_turn(
|
| 256 |
+
player_action: str,
|
| 257 |
+
state: dict[str, Any] | None,
|
| 258 |
+
campaign_name: str,
|
| 259 |
+
language: str,
|
| 260 |
+
setting: str,
|
| 261 |
+
tone: str,
|
| 262 |
+
complexity: str,
|
| 263 |
+
response_length: str,
|
| 264 |
+
rules_style: str,
|
| 265 |
+
safety: str,
|
| 266 |
+
characters_text: str,
|
| 267 |
+
custom_prompt: str,
|
| 268 |
+
base_prompt: str,
|
| 269 |
+
start_prompt: str,
|
| 270 |
+
turn_prompt: str,
|
| 271 |
+
model: str,
|
| 272 |
+
) -> tuple[list[dict[str, str]], dict[str, Any], str, str]:
|
| 273 |
+
state = deepcopy(state or empty_state())
|
| 274 |
+
characters = validate_setup(characters_text)
|
| 275 |
+
action = (player_action or "").strip()
|
| 276 |
+
is_start = not state["started"]
|
| 277 |
+
if not is_start and not action:
|
| 278 |
+
raise gr.Error("Describe what the party attempts.")
|
| 279 |
+
|
| 280 |
+
config = campaign_config(
|
| 281 |
+
campaign_name, language, setting, tone, complexity,
|
| 282 |
+
response_length, rules_style, safety,
|
| 283 |
+
)
|
| 284 |
+
instructions = build_instructions(base_prompt, custom_prompt, config, characters, state["ledger"])
|
| 285 |
+
supplied_roll = f"\nSupplied dice result: {state['last_roll']}" if state.get("last_roll") else ""
|
| 286 |
+
if is_start:
|
| 287 |
+
player_text = (start_prompt or START_PROMPT) + supplied_roll
|
| 288 |
+
else:
|
| 289 |
+
player_text = f"{turn_prompt or CONTINUE_PROMPT}\n\nParty declaration: {action}{supplied_roll}"
|
| 290 |
+
|
| 291 |
+
narration = call_dm(model, instructions, api_messages(state["history"], player_text))
|
| 292 |
+
visible_player_text = action if action else "Begin the adventure."
|
| 293 |
+
state["history"].extend([
|
| 294 |
+
{"role": "user", "content": visible_player_text},
|
| 295 |
+
{"role": "assistant", "content": narration},
|
| 296 |
+
])
|
| 297 |
+
state["turn"] += 1
|
| 298 |
+
state["started"] = True
|
| 299 |
+
state["last_roll"] = None
|
| 300 |
+
infer_ledger(state, narration)
|
| 301 |
+
return chat_pairs(state["history"]), state, ledger_markdown(state), ""
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def roll_d20(modifier: float, label: str, state: dict[str, Any] | None) -> tuple[str, dict[str, Any], str]:
|
| 305 |
+
state = deepcopy(state or empty_state())
|
| 306 |
+
natural = random.SystemRandom().randint(1, 20)
|
| 307 |
+
mod = int(modifier or 0)
|
| 308 |
+
total = natural + mod
|
| 309 |
+
clean_label = (label or "Check").strip()[:60]
|
| 310 |
+
result = f"{clean_label}: d20 **{natural}** {mod:+d} = **{total}**"
|
| 311 |
+
state["last_roll"] = f"{clean_label}: natural {natural}, modifier {mod:+d}, total {total}"
|
| 312 |
+
return result, state, ledger_markdown(state)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def edit_ledger(state: dict[str, Any] | None, raw_json: str) -> tuple[dict[str, Any], str]:
|
| 316 |
+
state = deepcopy(state or empty_state())
|
| 317 |
+
try:
|
| 318 |
+
update = json.loads(raw_json)
|
| 319 |
+
except json.JSONDecodeError as exc:
|
| 320 |
+
raise gr.Error(f"Ledger JSON is invalid: {exc}") from exc
|
| 321 |
+
if not isinstance(update, dict):
|
| 322 |
+
raise gr.Error("Ledger JSON must be an object.")
|
| 323 |
+
allowed = set(state["ledger"])
|
| 324 |
+
for key, value in update.items():
|
| 325 |
+
if key in allowed:
|
| 326 |
+
state["ledger"][key] = value
|
| 327 |
+
return state, ledger_markdown(state)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def ledger_json(state: dict[str, Any] | None) -> str:
|
| 331 |
+
return json.dumps((state or empty_state())["ledger"], ensure_ascii=False, indent=2)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def reset_game() -> tuple[list, dict[str, Any], str, str, str]:
|
| 335 |
+
state = empty_state()
|
| 336 |
+
return [], state, ledger_markdown(state), "", "Campaign reset. Configuration was preserved."
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def save_game(state: dict[str, Any] | None, campaign_name: str, characters_text: str) -> tuple[str, str]:
|
| 340 |
+
state = state or empty_state()
|
| 341 |
+
SAVE_DIR.mkdir(parents=True, exist_ok=True)
|
| 342 |
+
slug = re.sub(r"[^a-z0-9]+", "-", (campaign_name or "campaign").lower()).strip("-") or "campaign"
|
| 343 |
+
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
|
| 344 |
+
path = SAVE_DIR / f"{slug}-{stamp}.json"
|
| 345 |
+
payload = {"version": 1, "campaign_name": campaign_name, "characters_text": characters_text, "state": state}
|
| 346 |
+
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 347 |
+
return str(path), f"Saved {state['turn']} turns."
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def load_game(file_path: str | None) -> tuple[list[dict[str, str]], dict[str, Any], str, str, str, str]:
|
| 351 |
+
if not file_path:
|
| 352 |
+
raise gr.Error("Choose a saved JSON file.")
|
| 353 |
+
try:
|
| 354 |
+
payload = json.loads(Path(file_path).read_text(encoding="utf-8"))
|
| 355 |
+
state = payload["state"]
|
| 356 |
+
if not isinstance(state.get("history"), list) or not isinstance(state.get("ledger"), dict):
|
| 357 |
+
raise ValueError("missing history or ledger")
|
| 358 |
+
except (OSError, ValueError, KeyError, json.JSONDecodeError) as exc:
|
| 359 |
+
raise gr.Error(f"Could not load this campaign: {exc}") from exc
|
| 360 |
+
return (
|
| 361 |
+
chat_pairs(state["history"]), state, ledger_markdown(state),
|
| 362 |
+
payload.get("campaign_name", "Loaded campaign"), payload.get("characters_text", ""),
|
| 363 |
+
f"Loaded turn {state.get('turn', 0)}.",
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def create_ui() -> gr.Blocks:
|
| 368 |
+
with gr.Blocks(title=APP_TITLE) as demo:
|
| 369 |
+
game_state = gr.State(empty_state())
|
| 370 |
+
gr.HTML(f"<div class='hero'><h1>⚔ {APP_TITLE}</h1><p>A configurable AI Dungeon Master. Shape the world, gather your party, and make dangerous choices.</p></div>")
|
| 371 |
+
|
| 372 |
+
with gr.Row():
|
| 373 |
+
with gr.Column(scale=7):
|
| 374 |
+
chatbot = gr.Chatbot(label="Adventure", height=590, buttons=["copy", "copy_all"])
|
| 375 |
+
player_action = gr.Textbox(
|
| 376 |
+
label="What does the party do?", placeholder="I examine the runes while Kael watches the corridor…", lines=3,
|
| 377 |
+
)
|
| 378 |
+
with gr.Row():
|
| 379 |
+
send_btn = gr.Button("Take action", variant="primary", elem_classes="primary-btn")
|
| 380 |
+
begin_btn = gr.Button("Begin adventure")
|
| 381 |
+
reset_btn = gr.Button("New campaign", variant="stop")
|
| 382 |
+
|
| 383 |
+
with gr.Column(scale=4):
|
| 384 |
+
ledger_view = gr.Markdown(ledger_markdown(empty_state()), elem_classes="status-card")
|
| 385 |
+
with gr.Accordion("Dice roller", open=True):
|
| 386 |
+
with gr.Row():
|
| 387 |
+
roll_label = gr.Textbox(value="Ability check", label="Check")
|
| 388 |
+
modifier = gr.Number(value=0, precision=0, label="Modifier")
|
| 389 |
+
roll_btn = gr.Button("Roll d20")
|
| 390 |
+
roll_result = gr.Markdown("No roll queued.")
|
| 391 |
+
|
| 392 |
+
with gr.Accordion("Campaign setup", open=True):
|
| 393 |
+
campaign_name = gr.Textbox(value="The Ashen Crown", label="Campaign name")
|
| 394 |
+
language = gr.Radio(
|
| 395 |
+
["English", "Português (Portugal)"],
|
| 396 |
+
value="English",
|
| 397 |
+
label="Game language / Idioma do jogo",
|
| 398 |
+
)
|
| 399 |
+
setting = gr.Dropdown(
|
| 400 |
+
["Classic high fantasy", "Dark fantasy", "Sword & sorcery", "Magitech", "Mythic antiquity", "Custom"],
|
| 401 |
+
value="Classic high fantasy", label="Setting",
|
| 402 |
+
)
|
| 403 |
+
with gr.Row():
|
| 404 |
+
tone = gr.Dropdown(["Heroic", "Mysterious", "Comic", "Grim", "Political", "Horror"], value="Mysterious", label="Tone")
|
| 405 |
+
complexity = gr.Radio(["Simple", "Standard", "Intricate"], value="Standard", label="Complexity")
|
| 406 |
+
with gr.Row():
|
| 407 |
+
response_length = gr.Dropdown(["Brief", "Balanced", "Cinematic"], value="Balanced", label="Narration")
|
| 408 |
+
rules_style = gr.Dropdown(["Rules-light", "D&D 5e-inspired", "Tactical", "Narrative-first"], value="D&D 5e-inspired", label="Rules")
|
| 409 |
+
safety = gr.Dropdown(
|
| 410 |
+
["Family-friendly", "Teen adventure: no graphic content", "Mature themes: fade to black"],
|
| 411 |
+
value="Teen adventure: no graphic content", label="Content boundary",
|
| 412 |
+
)
|
| 413 |
+
characters_text = gr.Textbox(
|
| 414 |
+
value="Kael | human ranger | patient tracker; longbow\nMira | elven wizard | curious; specializes in illusions",
|
| 415 |
+
label="Characters — one per line", info="Name | class/species | personality, abilities, inventory", lines=5,
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
with gr.Accordion("AI and prompt editor", open=False):
|
| 419 |
+
model = gr.Textbox(value=DEFAULT_MODEL, label="OpenAI model")
|
| 420 |
+
custom_prompt = gr.Textbox(
|
| 421 |
+
value="Keep a subtle ancient-machine mystery beneath the fantasy setting.",
|
| 422 |
+
label="Campaign-specific instructions", lines=4,
|
| 423 |
+
)
|
| 424 |
+
base_prompt = gr.Textbox(value=BASE_DM_PROMPT, label="Dungeon Master prompt", lines=16)
|
| 425 |
+
start_prompt = gr.Textbox(value=START_PROMPT, label="Opening-scene prompt", lines=4)
|
| 426 |
+
turn_prompt = gr.Textbox(value=CONTINUE_PROMPT, label="Per-turn prompt", lines=5)
|
| 427 |
+
gr.Markdown("Available placeholders: `{campaign_config}`, `{characters}`, `{ledger}`, `{custom_prompt}`")
|
| 428 |
+
|
| 429 |
+
with gr.Accordion("Campaign ledger editor", open=False):
|
| 430 |
+
ledger_editor = gr.Code(value=ledger_json(empty_state()), language="json", label="Ledger JSON")
|
| 431 |
+
with gr.Row():
|
| 432 |
+
refresh_ledger_btn = gr.Button("Refresh JSON")
|
| 433 |
+
apply_ledger_btn = gr.Button("Apply ledger edits")
|
| 434 |
+
|
| 435 |
+
with gr.Accordion("Save or load", open=False):
|
| 436 |
+
save_btn = gr.Button("Save campaign")
|
| 437 |
+
saved_file = gr.File(label="Download save")
|
| 438 |
+
load_file = gr.File(label="Upload campaign JSON", file_types=[".json"], type="filepath")
|
| 439 |
+
load_btn = gr.Button("Load campaign")
|
| 440 |
+
status = gr.Markdown()
|
| 441 |
+
|
| 442 |
+
turn_inputs = [
|
| 443 |
+
player_action, game_state, campaign_name, language, setting, tone, complexity, response_length,
|
| 444 |
+
rules_style, safety, characters_text, custom_prompt, base_prompt, start_prompt, turn_prompt, model,
|
| 445 |
+
]
|
| 446 |
+
turn_outputs = [chatbot, game_state, ledger_view, player_action]
|
| 447 |
+
send_btn.click(run_turn, turn_inputs, turn_outputs)
|
| 448 |
+
player_action.submit(run_turn, turn_inputs, turn_outputs)
|
| 449 |
+
begin_btn.click(run_turn, turn_inputs, turn_outputs)
|
| 450 |
+
roll_btn.click(roll_d20, [modifier, roll_label, game_state], [roll_result, game_state, ledger_view])
|
| 451 |
+
refresh_ledger_btn.click(ledger_json, game_state, ledger_editor)
|
| 452 |
+
apply_ledger_btn.click(edit_ledger, [game_state, ledger_editor], [game_state, ledger_view])
|
| 453 |
+
reset_btn.click(reset_game, outputs=[chatbot, game_state, ledger_view, player_action, status])
|
| 454 |
+
save_btn.click(save_game, [game_state, campaign_name, characters_text], [saved_file, status])
|
| 455 |
+
load_btn.click(load_game, load_file, [chatbot, game_state, ledger_view, campaign_name, characters_text, status])
|
| 456 |
+
return demo
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
demo = create_ui()
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
if __name__ == "__main__":
|
| 463 |
+
demo.queue(default_concurrency_limit=4).launch(
|
| 464 |
+
server_name=os.getenv("GRADIO_SERVER_NAME", "0.0.0.0"),
|
| 465 |
+
server_port=int(os.getenv("GRADIO_SERVER_PORT", "7860")),
|
| 466 |
+
css=CSS,
|
| 467 |
+
theme=gr.themes.Base(),
|
| 468 |
+
)
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=6.22,<7
|
| 2 |
+
openai>=1.60,<3
|
| 3 |
+
python-dotenv>=1.0,<2
|