FastAPI Service Architecture
Relevant source files
The following files were used as context for generating this wiki page:
The FastAPI service architecture within the narrative-ai application serves as the core intelligence layer for the MCP Games ecosystem. Its primary purpose is to generate dynamic, context-aware narrative content for Choose Your Own Adventure (CYOA) experiences by leveraging Large Language Models (LLMs) and context retrieved from Model Context Protocol (MCP) servers.
This service acts as an AI-powered engine that processes user context, previous choices, and story states to produce consistent plot branching and character modeling. It is designed to integrate seamlessly with the broader monorepo architecture, including the Next.js frontend and Express.js MCP connector.
Sources: apps/narrative-ai/README.md:1-12, README.md:37-43
Core Components and Technology Stack
The service is built using a modern Python-based stack centered around FastAPI for high-performance asynchronous API handling.
Implementation Stack
- Web Framework: FastAPI for API routing and Pydantic for data validation.
- Task Orchestration: LangChain for managing LLM chains and prompt engineering.
- LLM Integration: SDKs for OpenAI (GPT-4) and Anthropic.
- Environment Management:
python-dotenvfor configuration via.envfiles. - Server: Uvicorn for running the ASGI application.
Sources: apps/narrative-ai/requirements.txt:1-10, apps/narrative-ai/main.py:1-15
Service Infrastructure
The application implements Cross-Origin Resource Sharing (CORS) middleware to allow communication from the frontend application and other microservices.
The diagram shows the request flow from the user interface through the FastAPI validation layer to the AI generation logic.
Sources: apps/narrative-ai/main.py:18-24, README.md:20-25
API Design and Data Models
The service exposes endpoints for scene generation, choice creation, and state management. All requests and responses are validated using Pydantic models to ensure type safety.
Pydantic Data Models
| Model Name | Field | Type | Description |
|---|---|---|---|
| GenerateSceneRequest | story_id | str | Unique identifier for the current story session |
user_context | Dict | Aggregated data from MCP servers (GitHub, Linear, etc.) | |
previous_choice | Optional[str] | The ID of the choice made in the previous scene | |
| GenerateChoicesRequest | story_id | str | Unique identifier for the current story session |
current_scene | str | Text of the scene requiring choices | |
user_context | Dict | Relevant context for personalizing options | |
| NarrativeResponse | text | str | The generated story text or choice content |
metadata | Dict | Model info, token usage, and session IDs |
Sources: apps/narrative-ai/main.py:27-42
Endpoint Specification
| Method | Endpoint | Description |
|---|---|---|
GET | /health | Service health status check |
POST | /api/generate/scene | Generates the next narrative block based on context and choices |
POST | /api/generate/choices | Generates contextually relevant branches for the player |
POST | /api/generate/consequence | Generates specific outcome text for a selected choice |
GET | /api/story/{story_id} | Retrieves the current state and history of a story |
Sources: apps/narrative-ai/main.py:45-81, apps/narrative-ai/README.md:21-27
Narrative Generation Logic
The generation process involves injecting semantic data retrieved from MCP servers into LLM prompts. This allows the narrative to adapt to real-world user data, such as recent GitHub contributions or Linear issues.
The sequence diagram illustrates how the FastAPI service acts as an intermediary, enriching prompts with context before calling the LLM.
Sources: README.md:120-136, apps/narrative-ai/main.py:49-60
Configuration and Environment
The service relies on environment variables for sensitive credentials and model configuration. This is managed via a .env file at the root of the service directory.
| Variable | Required | Default / Example |
|---|---|---|
OPENAI_API_KEY | Yes | your_key_here |
ANTHROPIC_API_KEY | Yes | your_key_here |
DEFAULT_MODEL | No | gpt-4-turbo-preview |
Sources: apps/narrative-ai/README.md:31-37, apps/narrative-ai/main.py:6-15
Narrative Consistency and Validation
To maintain a coherent story across multiple branching paths, the architecture includes components for consequence tracking and consistency validation. This ensures that variables set in earlier scenes (e.g., character traits or items acquired) remain valid in future generations.
Relevant data structures include:
Plot branching: Tracking the tree of decisions.Consequence tracking: Mapping choices to specific narrative outcomes.Variable substitution: Injecting state variables into the AI-generated text.
Sources: apps/narrative-ai/README.md:8-12, packages/shared-types/src/index.ts:77-105
The FastAPI service architecture provides a robust, type-safe foundation for AI-driven storytelling. By abstracting LLM complexities and providing specialized endpoints for narrative elements, it enables the creation of personalized gaming experiences that respond dynamically to external data sources.