{"id":28816770,"url":"https://github.com/kkrajid/story_generator","last_synced_at":"2026-04-13T12:01:59.485Z","repository":{"id":298949957,"uuid":"1001647338","full_name":"kkrajid/story_generator","owner":"kkrajid","description":"FastAPI-based web service that creates characters and generates personalized AI stories using Google Gemini. Features async PostgreSQL integration, comprehensive error handling, and RESTful endpoints for character management and story generation.","archived":false,"fork":false,"pushed_at":"2025-06-14T04:56:02.000Z","size":28,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-07-28T09:46:21.922Z","etag":null,"topics":["ai","async","character-generator","fastapi","gemini-ai","postgresql","pydantic","python","rest-api","sqlalchemy","story-generator","storytelling","uvicorn","web-service"],"latest_commit_sha":null,"homepage":"","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/kkrajid.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}},"created_at":"2025-06-13T18:42:19.000Z","updated_at":"2025-06-14T04:56:05.000Z","dependencies_parsed_at":"2025-06-13T19:42:02.025Z","dependency_job_id":"9d300959-9e77-43e5-bda7-443f83538205","html_url":"https://github.com/kkrajid/story_generator","commit_stats":null,"previous_names":["kkrajid/story_generator"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/kkrajid/story_generator","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kkrajid%2Fstory_generator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kkrajid%2Fstory_generator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kkrajid%2Fstory_generator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kkrajid%2Fstory_generator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kkrajid","download_url":"https://codeload.github.com/kkrajid/story_generator/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kkrajid%2Fstory_generator/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31751705,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-13T09:16:15.125Z","status":"ssl_error","status_checked_at":"2026-04-13T09:16:05.023Z","response_time":93,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"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":["ai","async","character-generator","fastapi","gemini-ai","postgresql","pydantic","python","rest-api","sqlalchemy","story-generator","storytelling","uvicorn","web-service"],"created_at":"2025-06-18T17:06:52.335Z","updated_at":"2026-04-13T12:01:59.461Z","avatar_url":"https://github.com/kkrajid.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Character Story Generator API\n\nA FastAPI-based web service that creates characters and generates personalized stories about them using Google's Gemini AI.\n\n## 🌐 Live Demo\n\nCheck out the live application at [https://quirktale.xyz/](https://quirktale.xyz/)\n\n## 🚀 Features\n\n- **Character Management**: Create and store character profiles with detailed descriptions\n- **AI Story Generation**: Generate engaging stories using Google's Gemini AI\n- **Multiple Story Types**: Support for general, mystery, adventure, funny, and heartwarming stories\n- **Story Improvement**: Enhance existing stories based on feedback\n- **RESTful API**: Clean, documented API endpoints\n- **Async Support**: Built with modern async/await patterns\n- **Database Integration**: PostgreSQL with SQLAlchemy ORM\n- **Request Tracking**: Unique request IDs for debugging and monitoring\n- **Comprehensive Error Handling**: Detailed error responses with proper HTTP status codes\n\n## 🛠️ Tech Stack\n\n- **Framework**: FastAPI\n- **AI Service**: Google Gemini AI (gemini-1.5-flash)\n- **Database**: Supabase (PostgreSQL)\n- **ORM**: SQLAlchemy (async)\n- **Validation**: Pydantic\n- **Environment**: Python 3.8+\n\n## 📋 Prerequisites\n\n- Python 3.8 or higher\n- Supabase account and project\n- Google Gemini API key\n\n## 🔧 Installation\n\n1. **Clone the repository**\n   ```bash\n   git clone https://github.com/kkrajid/story_generator.git\n   cd story_generator\n   ```\n\n2. **Create virtual environment**\n   ```bash\n   python -m venv venv\n   source venv/bin/activate  # On Windows: venv\\Scripts\\activate\n   ```\n\n3. **Install dependencies**\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n4. **Set up environment variables**\n   \n   Create a `.env` file in the project root with your Supabase credentials:\n   ```env\n   # Supabase Database Configuration\n   DB_USER=postgres\n   DB_PASS=your_database_password\n   DB_HOST=db.your-project-ref.supabase.co\n   DB_NAME=postgres\n   \n   # Google Gemini AI\n   GEMINI_API_KEY=your_gemini_api_key\n   ```\n\n5. **Set up Supabase Database**\n   \n   The project uses Supabase as the database provider. Follow these steps to set up your database:\n\n   1. Create a Supabase account at https://supabase.com\n   2. Create a new project\n   3. Get your database credentials from the project settings:\n      - Go to Project Settings \u003e Database\n      - Find your connection string or individual credentials\n   4. Update the `.env` file with your Supabase credentials\n   5. The database is automatically created in Supabase, so you don't need to run any CREATE DATABASE commands\n\n   Note: The default database name in Supabase is `postgres`. Make sure to use the correct host URL from your Supabase project settings.\n\n## 🚀 Running the Application\n\n### Development Mode\n```bash\npython main.py\n```\n\n### Production Mode\n```bash\nuvicorn main:app --host 0.0.0.0 --port 8000\n```\n\nThe API will be available at:\n- **API**: http://localhost:8000\n- **Interactive Docs**: http://localhost:8000/docs\n- **Alternative Docs**: http://localhost:8000/redoc\n\n## 📚 API Endpoints\n\n### Health Check\n- `GET /` - Basic health check\n- `GET /health` - Detailed health check with service status\n\n### Characters\n- `POST /characters/` - Create a new character\n- `GET /characters/{character_id}` - Get character by ID\n- `GET /characters/` - List all characters\n\n### Stories\n- `POST /stories/generate/` - Generate a story for a character\n\n## 📖 Usage Examples\n\n### Creating a Character\n```bash\ncurl -X POST \"http://localhost:8000/characters/\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"Alice Wonder\",\n    \"details\": \"A curious 12-year-old girl who loves exploring mysterious places and solving puzzles. She has bright blue eyes, golden hair, and always carries a small notebook to write down her discoveries.\"\n  }'\n```\n\n### Generating a Story\n```bash\ncurl -X POST \"http://localhost:8000/stories/generate/\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"Alice Wonder\"\n  }'\n```\n\n### Python Client Example\n```python\nimport requests\n\n# Create a character\ncharacter_data = {\n    \"name\": \"Detective Holmes\",\n    \"details\": \"A brilliant detective with keen observation skills and logical reasoning abilities.\"\n}\n\nresponse = requests.post(\"http://localhost:8000/characters/\", json=character_data)\ncharacter = response.json()\n\n# Generate a story\nstory_request = {\"name\": \"Detective Holmes\"}\nstory_response = requests.post(\"http://localhost:8000/stories/generate/\", json=story_request)\nstory = story_response.json()\n\nprint(f\"Generated story ({story['word_count']} words):\")\nprint(story['story'])\n```\n\n## 🗂️ Project Structure\n\n```\ncharacter-story-generator/\n├── main.py              # FastAPI application entry point\n├── config.py            # Configuration management\n├── database.py          # Database connection and session management\n├── models.py            # SQLAlchemy database models\n├── schemas.py           # Pydantic models for request/response validation\n├── routes.py            # API route definitions\n├── db_service.py        # Database service layer\n├── ai_service.py        # AI story generation service\n├── middleware.py        # Custom middleware and exception handlers\n├── exceptions.py        # Custom exception classes\n├── requirements.txt     # Python dependencies\n├── .env                 # Environment variables (create this)\n├── app.log             # Application logs (auto-generated)\n└── README.md           # This file\n```\n\n## 🎨 Story Types\n\nThe API supports different story types through the `story_type` parameter:\n\n- **general** (default): Balanced story with character development\n- **mystery**: Puzzle-solving adventures with clues and revelations\n- **adventure**: Action-packed stories with exciting challenges\n- **funny**: Humorous stories with comedic situations\n- **heartwarming**: Emotional stories focusing on relationships and feelings\n\n## 🔍 Error Handling\n\nThe API provides comprehensive error handling with detailed responses:\n\n```json\n{\n  \"error\": \"Character not found\",\n  \"detail\": \"Character with name 'Unknown Character' not found\",\n  \"timestamp\": \"2025-06-14T10:30:00Z\",\n  \"request_id\": \"550e8400-e29b-41d4-a716-446655440000\"\n}\n```\n\nCommon HTTP status codes:\n- `200` - Success\n- `404` - Character not found\n- `422` - Validation error\n- `500` - Server error (database or AI service issues)\n- `503` - Service unavailable\n\n## 📊 Logging\n\nThe application logs important events and errors:\n- Request/response tracking with unique request IDs\n- Character creation and retrieval operations\n- Story generation attempts and results\n- Database connection issues\n- AI service errors\n\nLogs are written to both console and `app.log` file.\n\n## 🔐 Environment Variables\n\n| Variable | Description | Required | Default |\n|----------|-------------|----------|---------|\n| `DB_USER` | PostgreSQL username | No | `postgres` |\n| `DB_PASS` | PostgreSQL password | Yes | - |\n| `DB_HOST` | PostgreSQL host | Yes | - |\n| `DB_NAME` | PostgreSQL database name | No | `postgres` |\n| `GEMINI_API_KEY` | Google Gemini API key | Yes | - |\n\n## 🧪 Testing\n\n### Manual Testing\nUse the interactive API documentation at `/docs` to test endpoints manually.\n\n### Health Check\n```bash\ncurl http://localhost:8000/health\n```\n\nExpected response:\n```json\n{\n  \"status\": \"healthy\",\n  \"database\": \"connected\",\n  \"gemini_ai\": \"configured\"\n}\n```\n\n## 🚨 Troubleshooting\n\n### Common Issues\n\n1. **Database Connection Error**\n   - Verify PostgreSQL is running\n   - Check database credentials in `.env`\n   - Ensure database exists\n\n2. **Gemini AI Configuration Error**\n   - Verify `GEMINI_API_KEY` is set correctly\n   - Check API key permissions and quotas\n\n3. **Story Generation Fails**\n   - Check network connectivity\n   - Verify Gemini API quotas\n   - Review application logs for details\n\n4. **Import Errors**\n   - Ensure all dependencies are installed: `pip install -r requirements.txt`\n   - Check Python version compatibility (3.8+)\n\n### Debug Mode\nSet logging level to DEBUG in `config.py`:\n```python\nlogging.basicConfig(level=logging.DEBUG)\n```\n\n## 🤝 Contributing\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature-name`\n3. Make your changes and add tests\n4. Commit your changes: `git commit -am 'Add feature'`\n5. Push to the branch: `git push origin feature-name`\n6. Submit a pull request\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the LICENSE file for details.\n\n## 🆘 Support\n\nIf you encounter any issues or have questions:\n1. Check the troubleshooting section above\n2. Review application logs in `app.log`\n3. Open an issue on GitHub with detailed error information\n4. Include request IDs from error responses for faster debugging\n\n## 🔮 Future Enhancements\n\n- [ ] User authentication and authorization\n- [ ] Story templates and themes\n- [ ] Character relationship mapping\n- [ ] Story continuation and chapters\n- [ ] Export stories to different formats (PDF, EPUB)\n- [ ] Story rating and feedback system\n- [ ] Bulk character import/export\n- [ ] Advanced story customization options ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkkrajid%2Fstory_generator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkkrajid%2Fstory_generator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkkrajid%2Fstory_generator/lists"}