{"id":50720192,"url":"https://github.com/4ssh1/choose-your-adventure","last_synced_at":"2026-06-09T23:01:58.552Z","repository":{"id":351535689,"uuid":"1190961277","full_name":"4ssh1/choose-your-adventure","owner":"4ssh1","description":"An asynchronous FastAPI backend that leverages the Groq LLM to generate, persist, and serve branching 'choose your own adventure' stories using an active polling job system and SQLAlchemy","archived":false,"fork":false,"pushed_at":"2026-04-15T11:28:07.000Z","size":85,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2026-04-15T13:33:33.118Z","etag":null,"topics":["backend","fastapi","groq","llm","python","sqlalchemy","story-generator"],"latest_commit_sha":null,"homepage":"https://choose-your-adventure.pxxl.click","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/4ssh1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-24T19:38:20.000Z","updated_at":"2026-04-15T11:28:10.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/4ssh1/choose-your-adventure","commit_stats":null,"previous_names":["4ssh1/choose-your-adventure"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/4ssh1/choose-your-adventure","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4ssh1%2Fchoose-your-adventure","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4ssh1%2Fchoose-your-adventure/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4ssh1%2Fchoose-your-adventure/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4ssh1%2Fchoose-your-adventure/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/4ssh1","download_url":"https://codeload.github.com/4ssh1/choose-your-adventure/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/4ssh1%2Fchoose-your-adventure/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34129072,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-09T02:00:06.510Z","response_time":63,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["backend","fastapi","groq","llm","python","sqlalchemy","story-generator"],"created_at":"2026-06-09T23:01:57.524Z","updated_at":"2026-06-09T23:01:58.542Z","avatar_url":"https://github.com/4ssh1.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Choose Your Own Adventure API \n\n## Overview\nThis service is a FastAPI backend that generates branching \"choose your own adventure\" stories using an LLM (Groq API), stores stories and nodes in a SQL database via SQLAlchemy, and exposes API endpoints for asynchronous story generation and retrieval.\n\nThe project creates a background job when a story is requested. The client first receives a `job_id`, then polls a job-status endpoint until generation is complete, and finally fetches the full generated story tree.\n\n**Frontend repo: https://github.com/4ssh1/fable-weaver**\n\n## Tech Stack\n\u003cdiv align=\"center\"\u003e  \n  \u003ch3\u003e🛠️ Tech Stack\u003c/h3\u003e\n  \n  \u003cimg src=\"https://img.shields.io/badge/Python-3.14+-3776AB?logo=python\u0026logoColor=white\u0026style=for-the-badge\" alt=\"Python\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/FastAPI-009688?logo=fastapi\u0026logoColor=white\u0026style=for-the-badge\" alt=\"FastAPI\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/SQLAlchemy-FF4A3E?logo=sqlalchemy\u0026logoColor=white\u0026style=for-the-badge\" alt=\"SQLAlchemy\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/Pydantic-FF6F00?logo=pydantic\u0026logoColor=white\u0026style=for-the-badge\" alt=\"Pydantic\"\u003e\n  \u003cimg src=\"https://img.shields.io/badge/Groq-00A3FF?logo=groq\u0026logoColor=white\u0026style=for-the-badge\" alt=\"Groq\"\u003e\n\u003c/div\u003e\n\n## Production Environment Variables\nCreate a `.env` file in the project root.\n\nRequired and supported settings:\n\n- `GROQ_API_KEY`:\n  - Required.\n  - Used by `core/story_generator.py` for authenticated LLM calls.\n- `DATABASE_URL`:\n  - Optional (default: `sqlite:///./database.db`).\n  - Set this to a production-grade database URL in production.\n- `API_PREFIX`:\n  - Optional (default: `/api`).\n- `ALLOWED_ORIGINS`:\n  - Optional.\n  - Comma-separated list of origins for CORS. Example: `https://app.example.com,https://admin.example.com`\n- `DEBUG`:\n  - Optional (default: `False`).\n- `RATE_LIMIT_ENABLED`:\n  - Optional (default: `True`).\n  - Enables/disables API rate limiting middleware.\n- `RATE_LIMIT_REQUESTS`:\n  - Optional (default: `30`).\n  - Maximum requests allowed from a single client IP within the rate-limit window.\n- `RATE_LIMIT_WINDOW_SECONDS`:\n  - Optional (default: `60`).\n  - Sliding-window duration for request counting.\n\nExample:\n\n```env\nGROQ_API_KEY=your_groq_api_key_here\nDATABASE_URL=postgresql+psycopg2://user:password@host:5432/choose_adventure\nAPI_PREFIX=/api\nALLOWED_ORIGINS=https://app.example.com,https://admin.example.com\nDEBUG=False\nRATE_LIMIT_ENABLED=True\nRATE_LIMIT_REQUESTS=30\nRATE_LIMIT_WINDOW_SECONDS=60\n```\n\n## Install and Run\nFrom the project root:\n\n```bash\nuv sync\nuv run uvicorn main:app --host 0.0.0.0 --port 8000\n```\n\nor simply:\n```bash\nuv run main.py\n```\n\nNotes:\n- `create_tables()` is executed on app startup in `main.py`, so tables are auto-created from SQLAlchemy models.\n- For production, it is however recommended to run behind a reverse proxy and use process management \n- Rate limiting is in-memory and per application instance (works without Redis). In multi-instance deployments, limits are enforced independently by each instance.\n\n## API Base URLs\n- Local service base: `http://localhost:8000`\n- API base (default prefix): `http://localhost:8000/api`\n- Swagger UI: `http://localhost:8000/docs`\n- ReDoc: `http://localhost:8000/redoc`\n\n## Endpoints and Flow\nCurrent routers are mounted under `API_PREFIX` and split by domain:\n\n- Stories router (`/stories`): create story job + fetch full story\n- Jobs router (`/jobs`): query job status\n\nTypical client flow:\n\n1. POST a story-generation request (`theme`) to create a job.\n2. Receive `job_id` with initial status.\n3. Poll job status until it becomes `completed` (or `failed`).\n4. Use returned `story_id` to fetch full story tree.\n\n## Step-by-Step: Test Swagger Docs (Required Flow)\nUse these exact steps in Swagger so the async workflow is tested correctly.\n\n### Step 1: Start the API\nRun:\n\n```bash\nuv run uvicorn main:app --host 0.0.0.0 --port 8000\n```\n\nConfirm service is up by opening:\n- `http://localhost:8000/docs`\n\n### Step 2: Open Swagger UI\nIn browser, open:\n- `http://localhost:8000/docs`\n\nYou should see two tags:\n- `stories`\n- `jobs`\n\n### Step 3: Create a Story Job\nIn Swagger:\n\n1. Expand `POST /api/stories/`.\n2. Click **Try it out**.\n3. Provide request body, for example:\n\n```json\n{\n  \"theme\": \"space pirates\"\n}\n```\n\n4. Click **Execute**.\n5. Verify response includes:\n   - `job_id`\n   - `status` (typically `pending` first)\n\nImportant behavior:\n- A `session_id` cookie is set by this endpoint.\n- Story generation runs in a FastAPI background task after the response returns.\n\n### Step 4: Poll Job Status Until Complete\nIn Swagger, use the jobs status endpoint repeatedly.\n\n1. Expand `GET /api/jobs/{job.id}`.\n2. Click **Try it out**.\n3. Paste the `job_id` from Step 3 into the path parameter input.\n4. Click **Execute**.\n5. Observe `status` transitions:\n   - `pending` -\u003e `processing` -\u003e `completed`\n   - or `failed` (if generation failed)\n\nRepeat this call until one terminal state is reached:\n- `completed`: continue to Step 5\n- `failed`: inspect `error` in response and stop\n\n### Step 5: Retrieve the Generated Story\nAfter status is `completed`:\n\n1. Copy `story_id` from the completed job response.\n2. Expand `GET /api/stories/{story_id}`.\n3. Click **Try it out**.\n4. Enter `story_id`.\n5. Click **Execute**.\n\nValidate response fields:\n- `id`, `title`, `session_id`, `created_at`\n- `root_node` (entry node)\n- `all_nodes` (map of all generated nodes and options)\n\n### Step 6: Functional Validation Checklist\nA successful end-to-end Swagger test should confirm:\n\n- Story job can be created with a theme.\n- Job status endpoint eventually returns `completed`.\n- Completed job contains non-null `story_id`.\n- Story retrieval returns a complete branching structure:\n  - Node content exists.\n  - Ending flags (`is_ending`, `is_winning`) are present.\n  - Options include text and next `node_id` references.\n\n## Project Architecture\nThe app follows a layered FastAPI architecture:\n\n1. API Layer (`routes/`):\n   - Defines HTTP contracts and request handling.\n   - Delegates persistence and generation logic.\n   - Handles cookies, background tasks, and response mapping.\n\n2. Schema Layer (`schemas/`):\n   - Pydantic models for request/response validation.\n   - Controls API payload shape.\n\n3. Domain/Service Layer (`core/`):\n   - Prompt templates and LLM schemas.\n   - Story generation service (`StoryGenerator`) that:\n     - Calls LLM via HTTP.\n     - Validates generated JSON against strict Pydantic schema.\n     - Persists story graph recursively.\n\n4. Persistence Layer (`models/`, `db/`):\n   - SQLAlchemy models for stories, nodes, and jobs.\n   - DB session lifecycle and engine config.\n\n5. App Bootstrap (`main.py`):\n   - FastAPI app creation.\n   - Middleware setup (CORS).\n   - Router registration.\n   - Startup table creation.\n\n## Directory Structure\n\n```text\n.\n┣ core\n ┃ ┣ __pycache__\n ┃ ┣ config.py\n ┃ ┣ models.py\n ┃ ┣ prompts.py\n ┃ ┣ story_generator.py\n ┃ ┗ __init__.py\n ┣ db\n ┃ ┣ __pycache__\n ┃ ┣ database.py\n ┃ ┗ __init__.py\n ┣ models\n ┃ ┣ __pycache__\n ┃ ┣ job.py\n ┃ ┣ story.py\n ┃ ┗ __init__.py\n ┣ routes\n ┃ ┣ __pycache__\n ┃ ┣ job.py\n ┃ ┣ story.py\n ┃ ┗ __init__.py\n ┣ schemas\n ┃ ┣ __pycache__\n ┃ ┣ job.py\n ┃ ┣ story.py\n ┃ ┗ __init__.py\n ┣ __pycache__\n ┣ .env\n ┣ .gitignore\n ┣ .python-version\n ┣ database.db\n ┣ main.py\n ┣ pyproject.toml\n ┣ README.md\n ┣ uv.lock\n ┗ __init__.py       \n```\n\n## Data Model Summary\n- `stories` table:\n  - One row per generated story session and title metadata.\n- `story_nodes` table:\n  - One row per story node.\n  - Includes content, ending flags, and JSON options list.\n- `story_jobs` table:\n  - Async job tracking (`pending`, `processing`, `completed`, `failed`).\n  - Stores `story_id` when done, and `error` when failed.\n\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F4ssh1%2Fchoose-your-adventure","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F4ssh1%2Fchoose-your-adventure","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F4ssh1%2Fchoose-your-adventure/lists"}