Add per-game adventure text with RAG-based retrieval

Players can now paste the full text of a freely available adventure
when creating a game, and the DM will follow it instead of inventing
its own plot/NPCs/locations. Reuses the existing rulebook RAG
pipeline (chunking, local embedding) rather than injecting the raw
text into every turn, since real adventure modules range from a few
pages to hundreds — far beyond what fits in a prompt.

- New adventure_chunks table (game-scoped, unlike the global
  rulebook_chunks) + Game.adventure_text storing the raw source.
- ingest_adventure_text() chunks/embeds synchronously during
  POST /api/games when adventure_text is non-empty.
- build_adventure_rag_block() retrieves by similarity to the latest
  player message, scoped to game_id — plus always includes chunk 0
  (the adventure's opening) regardless of the query, since early
  Session-0 messages rarely resemble the adventure's actual hook and
  pure similarity search could miss the beginning entirely.
- System prompt instructs the DM to follow provided adventure
  excerpts strictly, deviating only when players clearly go off-script.
- Frontend: optional adventure-text field in the game creation form,
  a has_adventure flag surfaced as a small badge on the game card and
  session header.

Verified with an isolated two-game test that chunks/retrieval never
leak across games (the critical failure mode here), and live against
x.ai: a custom-written one-shot's specific NPCs, location, and hook
appeared verbatim in the DM's opening scene instead of invented ones.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Thorsten
2026-09-02 13:13:59 +02:00
parent ff4c6f07e3
commit b77f066259
14 changed files with 224 additions and 6 deletions
+6
View File
@@ -13,6 +13,7 @@ from app.models.character import Character
from app.models.game import Game, GameParticipant
from app.models.message import Message
from app.models.user import User
from app.rag.adventure_ingestion import ingest_adventure_text
from app.schemas.game import GameCreate, GameJoin, GameRead
from app.schemas.game_setup import GameSetupChatRequest, GameSetupChatResponse
from app.schemas.message import MessageRead
@@ -73,6 +74,7 @@ async def _serialize_games(
my_character_id=viewer_participation.get(game.id),
status=game.status,
ended_reason=game.ended_reason,
has_adventure=bool(game.adventure_text.strip()),
)
)
return result
@@ -98,6 +100,7 @@ async def create_game(
game = Game(
name=payload.name,
description=payload.description,
adventure_text=payload.adventure_text,
creator_id=user.id,
participation_code=_generate_participation_code(),
)
@@ -108,6 +111,9 @@ async def create_game(
await session.commit()
await session.refresh(game)
if payload.adventure_text.strip():
await ingest_adventure_text(session, game.id, payload.adventure_text)
serialized = await _serialize_games(session, [game], user.id)
return serialized[0]