{"id":31644529,"url":"https://github.com/rsp2k/django-ollama","last_synced_at":"2026-05-04T11:35:57.830Z","repository":{"id":317570729,"uuid":"1064814505","full_name":"rsp2k/django-ollama","owner":"rsp2k","description":"Production-ready Django integration for Ollama LLMs with native async support, WebSocket streaming, and comprehensive test coverage","archived":false,"fork":false,"pushed_at":"2025-10-01T17:28:15.000Z","size":417,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-01T19:21:53.228Z","etag":null,"topics":["async","django","llm","ollama","websocket"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rsp2k.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","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":"2025-09-26T15:38:02.000Z","updated_at":"2025-10-01T17:28:19.000Z","dependencies_parsed_at":"2025-10-01T19:22:03.810Z","dependency_job_id":"916357a4-893d-4a64-bd73-db1c58e0838e","html_url":"https://github.com/rsp2k/django-ollama","commit_stats":null,"previous_names":["rsp2k/django-ollama"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/rsp2k/django-ollama","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsp2k%2Fdjango-ollama","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsp2k%2Fdjango-ollama/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsp2k%2Fdjango-ollama/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsp2k%2Fdjango-ollama/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rsp2k","download_url":"https://codeload.github.com/rsp2k/django-ollama/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rsp2k%2Fdjango-ollama/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":278722768,"owners_count":26034461,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-07T02:00:06.786Z","response_time":59,"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":["async","django","llm","ollama","websocket"],"created_at":"2025-10-07T04:53:43.688Z","updated_at":"2025-10-07T04:53:46.281Z","avatar_url":"https://github.com/rsp2k.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Django-Ollama\n\n[![PyPI version](https://badge.fury.io/py/django-ollama.svg)](https://badge.fury.io/py/django-ollama)\n[![Python versions](https://img.shields.io/pypi/pyversions/django-ollama.svg)](https://pypi.org/project/django-ollama/)\n[![Django versions](https://img.shields.io/badge/Django-4.2%2B-blue.svg)](https://www.djangoproject.com/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nDjango integration for [Ollama](https://ollama.ai/) local LLM with real-time chat capabilities through WebSockets.\n\n## Features\n\n🚀 **Easy Integration**: Drop-in Django app with minimal configuration\n💬 **Real-time Chat**: WebSocket-powered streaming responses\n🧠 **Knowledge Base**: Link any Django model to provide context\n🔄 **Session Management**: Persistent chat sessions with conversation history\n🎨 **Flexible API**: Both sync and async Python API\n🔧 **Production Ready**: Comprehensive testing, type hints, and documentation\n\n## Quick Start\n\n### Installation\n\n```bash\npip install django-ollama\n```\n\n### Settings\n\nAdd to your Django `INSTALLED_APPS`:\n\n```python\nINSTALLED_APPS = [\n    # ... your other apps\n    'channels',  # Required for WebSocket support\n    'django_ollama',\n]\n\n# Ollama configuration\nOLLAMA_HOST = \"http://localhost:11434\"  # Default\nOLLAMA_DEFAULT_MODEL = \"llama3.2\"  # Default\n\n# Channels configuration for WebSocket support\nASGI_APPLICATION = \"your_project.asgi.application\"\nCHANNEL_LAYERS = {\n    \"default\": {\n        \"BACKEND\": \"channels_redis.core.RedisChannelLayer\",\n        \"CONFIG\": {\n            \"hosts\": [(\"127.0.0.1\", 6379)],\n        },\n    },\n}\n```\n\n### Database Migration\n\n```bash\npython manage.py migrate django_ollama\n```\n\n### WebSocket Routing\n\nAdd to your `routing.py`:\n\n```python\nfrom channels.routing import ProtocolTypeRouter, URLRouter\nfrom channels.auth import AuthMiddlewareStack\nfrom django.urls import path\nfrom django_ollama.consumers import OllamaChatConsumer\n\napplication = ProtocolTypeRouter({\n    \"websocket\": AuthMiddlewareStack(\n        URLRouter([\n            path(\"ws/chat/\", OllamaChatConsumer.as_asgi()),\n        ])\n    ),\n})\n```\n\n## Usage Examples\n\n### Python API\n\n```python\nfrom django_ollama import chat, generate\n\n# Simple chat\nresponse = chat(\"What is Django?\")\nprint(response['message']['content'])\n\n# Conversation with history\nmessages = [\n    {\"role\": \"user\", \"content\": \"Hello\"},\n    {\"role\": \"assistant\", \"content\": \"Hi! How can I help?\"},\n    {\"role\": \"user\", \"content\": \"What is Python?\"}\n]\nresponse = chat(messages=messages)\n\n# Streaming response\nfor chunk in chat(\"Tell me a story\", stream=True):\n    print(chunk['message']['content'], end='')\n\n# Text generation\nresponse = generate(\"Complete this: Django is\")\nprint(response['response'])\n```\n\n### Async API\n\n```python\nimport asyncio\nfrom django_ollama import achat, agenerate\n\nasync def main():\n    # Async chat\n    response = await achat(\"What is Django?\")\n    print(response['message']['content'])\n\n    # Async streaming\n    async for chunk in achat(\"Tell me about AI\", stream=True):\n        print(chunk['message']['content'], end='')\n\nasyncio.run(main())\n```\n\n### WebSocket Client (JavaScript)\n\n```javascript\nconst ws = new WebSocket('ws://localhost:8000/ws/chat/');\n\n// Send a message\nws.send(JSON.stringify({\n    type: 'chat_message',\n    message: 'Hello, AI!',\n    model: 'llama3.2',\n    stream: true\n}));\n\n// Handle responses\nws.onmessage = function(event) {\n    const data = JSON.parse(event.data);\n\n    if (data.type === 'chat_chunk') {\n        // Stream content as it arrives\n        document.getElementById('chat').innerHTML += data.content;\n    } else if (data.type === 'chat_complete') {\n        console.log('Chat completed:', data.full_message);\n    } else if (data.type === 'error') {\n        console.error('Error:', data.message);\n    }\n};\n```\n\n### Knowledge Base Integration\n\n```python\nfrom django_ollama.models import KnowledgeBase, KnowledgeBaseContent\nfrom django.contrib.contenttypes.models import ContentType\nfrom myapp.models import Article\n\n# Create a knowledge base\nkb = KnowledgeBase.objects.create(\n    name=\"Company Docs\",\n    description=\"Internal documentation\"\n)\n\n# Link existing Django models\narticle = Article.objects.create(\n    title=\"Django Best Practices\",\n    content=\"Here are some Django best practices...\"\n)\n\n# Your model needs an __ai_text__ method or property\nclass Article(models.Model):\n    title = models.CharField(max_length=200)\n    content = models.TextField()\n\n    def __ai_text__(self):\n        return f\"{self.title}\\\\n\\\\n{self.content}\"\n\n# Add to knowledge base\nKnowledgeBaseContent.objects.create(\n    knowledge_base=kb,\n    content_object=article,\n    title=\"Django Best Practices Guide\"\n)\n\n# Use in chat sessions\nfrom django_ollama.models import ChatSession\n\nsession = ChatSession.objects.create(\n    name=\"Help Session\",\n    model=\"llama3.2\",\n    knowledge_base=kb,\n    system_prompt=\"Use the knowledge base to answer questions about Django.\"\n)\n```\n\n## WebSocket Message Types\n\n### Client → Server\n\n```javascript\n// Start a new session\n{\n    \"type\": \"start_session\",\n    \"name\": \"My Chat Session\",\n    \"model\": \"llama3.2\",\n    \"system_prompt\": \"You are a helpful assistant\"\n}\n\n// Send chat message\n{\n    \"type\": \"chat_message\",\n    \"message\": \"Your question here\",\n    \"model\": \"llama3.2\",  // optional\n    \"session_id\": \"uuid\",  // optional\n    \"stream\": true  // optional, default: true\n}\n\n// End session\n{\n    \"type\": \"end_session\"\n}\n```\n\n### Server → Client\n\n```javascript\n// Session started\n{\n    \"type\": \"session_started\",\n    \"session_id\": \"uuid\",\n    \"model\": \"llama3.2\",\n    \"name\": \"My Chat Session\"\n}\n\n// Chat response start\n{\n    \"type\": \"chat_start\",\n    \"session_id\": \"uuid\",\n    \"model\": \"llama3.2\"\n}\n\n// Streaming content\n{\n    \"type\": \"chat_chunk\",\n    \"content\": \"partial response...\"\n}\n\n// Chat complete\n{\n    \"type\": \"chat_complete\",\n    \"full_message\": \"complete response text\"\n}\n\n// Error\n{\n    \"type\": \"error\",\n    \"message\": \"Error description\"\n}\n```\n\n## Models\n\n### KnowledgeBase\n\nOrganize documents and content for AI context.\n\n```python\nkb = KnowledgeBase.objects.create(\n    name=\"Documentation\",\n    description=\"Product documentation and guides\",\n    is_active=True\n)\n```\n\n### ChatSession\n\nPersistent chat conversations with history.\n\n```python\nsession = ChatSession.objects.create(\n    name=\"Customer Support\",\n    model=\"llama3.2\",\n    user=request.user,  # optional\n    knowledge_base=kb,  # optional\n    system_prompt=\"You are a helpful customer support agent.\",\n    is_active=True\n)\n```\n\n### ChatMessage\n\nIndividual messages within sessions.\n\n```python\nmessage = ChatMessage.objects.create(\n    session=session,\n    role=\"user\",  # or \"assistant\", \"system\"\n    content=\"Hello, I need help with...\",\n    metadata={\"source\": \"web\", \"ip\": \"127.0.0.1\"}\n)\n```\n\n## Configuration\n\n### Environment Variables\n\n```bash\n# Ollama server configuration\nOLLAMA_HOST=http://localhost:11434\nOLLAMA_DEFAULT_MODEL=llama3.2\n\n# File upload limits\nDJANGO_OLLAMA_MAX_FILE_SIZE=104857600  # 100MB default\n```\n\n### Django Settings\n\n```python\n# Ollama configuration\nOLLAMA_HOST = \"http://localhost:11434\"\nOLLAMA_DEFAULT_MODEL = \"llama3.2\"\n\n# File upload configuration\nDJANGO_OLLAMA_MAX_FILE_SIZE = 100 * 1024 * 1024  # 100MB\n\n# Logging\nLOGGING = {\n    'version': 1,\n    'handlers': {\n        'console': {\n            'class': 'logging.StreamHandler',\n        },\n    },\n    'loggers': {\n        'django_ollama': {\n            'handlers': ['console'],\n            'level': 'INFO',\n        },\n    },\n}\n```\n\n## 🧪 Test Dashboard\n\nDjango-Ollama includes a powerful **real-time test monitoring dashboard** that provides comprehensive analytics and live monitoring of your test suites.\n\n### ✨ Dashboard Features\n\n- **🔴 Live Test Monitoring**: Real-time WebSocket updates during test execution\n- **📊 Interactive Analytics**: Charts, trends, and comprehensive test statistics\n- **🎨 Beautiful Terminal UI**: Gruvbox-inspired theme with professional design\n- **📱 Multi-Device Support**: Responsive design for desktop, tablet, and mobile\n- **🔍 Smart Test Classification**: Automatic categorization of Unit, Integration, API, and E2E tests\n- **📈 Historical Trends**: Long-term performance analysis and flakiness detection\n- **🐳 Production Ready**: Docker support, security features, and enterprise-grade architecture\n\n### 🚀 Quick Start with Dashboard\n\n```bash\n# 1. Install dashboard dependencies\npip install -r test_dashboard/requirements.txt\n\n# 2. Launch the dashboard server\ncd test_dashboard\npython launch_dashboard.py\n\n# 3. In another terminal, run your tests with dashboard integration\npytest --dashboard --dashboard-websocket tests/\n\n# 4. Open http://localhost:8080 to see real-time results!\n```\n\n### 📚 Complete Dashboard Documentation\n\nThe test dashboard system is comprehensively documented:\n\n- **[📊 Dashboard Overview](docs/TEST_DASHBOARD.md)** - Complete feature guide\n- **[🔧 Installation Guide](docs/INSTALLATION.md)** - Detailed setup instructions\n- **[🔌 API Reference](docs/API_REFERENCE.md)** - REST API and WebSocket documentation\n- **[🐳 Docker Deployment](docs/DOCKER_DEPLOYMENT.md)** - Container deployment guide\n- **[📈 Performance Guide](docs/PERFORMANCE.md)** - Optimization and benchmarks\n\n### 🎯 Dashboard Usage Examples\n\n```bash\n# Basic dashboard integration\npytest --dashboard\n\n# Custom database and WebSocket support\npytest --dashboard --dashboard-db=myproject.db --dashboard-websocket\n\n# Named test runs for releases\npytest --dashboard --dashboard-name=\"Release 2.1.0 Tests\"\n\n# Production CI/CD integration\npytest --dashboard --dashboard-name=\"Build ${BUILD_NUMBER}\" \\\n       --dashboard-db=/data/ci-dashboard.db\n```\n\n### 📊 Dashboard API Integration\n\n```python\nfrom test_dashboard.database import TestDashboardDB\nfrom test_dashboard.models import TestResult, TestStatus, TestType\n\n# Programmatic dashboard integration\ndb = TestDashboardDB(\"dashboard.db\")\n\n# Create test run with metadata\nrun_id = db.create_test_run(\n    test_command=\"pytest tests/api/\",\n    git_branch=\"feature/new-endpoint\",\n    git_commit=\"abc123\",\n    environment_info={\n        \"python_version\": \"3.11.0\",\n        \"django_version\": \"4.2.0\",\n        \"ci_build\": \"12345\"\n    }\n)\n\n# Add test results\ntest_result = TestResult(\n    test_name=\"test_chat_endpoint\",\n    test_file=\"tests/api/test_chat.py\",\n    test_type=TestType.API,\n    status=TestStatus.PASSED,\n    duration_seconds=1.23\n)\n\ndb.add_test_result(run_id, test_result)\n```\n\n### 🏆 Enterprise Features\n\n- **High Performance**: SQLite with WAL mode, connection pooling, optimized queries\n- **Real-Time Updates**: WebSocket broadcasting with connection management\n- **Security**: CORS protection, input validation, SQL injection prevention\n- **Scalability**: Supports 100+ concurrent users, handles 1000+ test runs efficiently\n- **Monitoring**: Built-in health checks, metrics, and alerting capabilities\n- **Multi-Environment**: Development, staging, and production configurations\n\n---\n\n## Development\n\n### Setup Development Environment\n\n```bash\n# Clone the repository\ngit clone https://github.com/yourusername/django-ollama.git\ncd django-ollama\n\n# Install in development mode\nmake install-dev\n\n# Run tests\nmake test\n\n# Run tests with coverage\nmake test-cov\n\n# Run tests with dashboard monitoring\npytest --dashboard --dashboard-websocket tests/\n\n# Format code\nmake format\n\n# Run linting\nmake lint\n\n# Run all checks\nmake check\n```\n\n### Running Tests\n\n```bash\n# Install test dependencies\npip install -e .[dev]\n\n# Run all tests\npytest\n\n# Run with coverage\npytest --cov=src/django_ollama --cov-report=html\n\n# Run specific test file\npytest tests/test_models.py\n\n# Run with markers\npytest -m \"not integration\"  # Skip integration tests\npytest -m \"ollama\"  # Only Ollama-dependent tests\n```\n\n### Using with Docker\n\nCreate a `docker-compose.yml`:\n\n```yaml\nservices:\n  ollama:\n    image: ollama/ollama:latest\n    ports:\n      - \"11434:11434\"\n    volumes:\n      - ollama_data:/root/.ollama\n\n  redis:\n    image: redis:alpine\n    ports:\n      - \"6379:6379\"\n\n  django:\n    build: .\n    ports:\n      - \"8000:8000\"\n    environment:\n      - OLLAMA_HOST=http://ollama:11434\n      - REDIS_URL=redis://redis:6379/0\n    depends_on:\n      - ollama\n      - redis\n\nvolumes:\n  ollama_data:\n```\n\n## Requirements\n\n- Python 3.9+\n- Django 4.2+\n- channels 4.0+\n- channels-redis 4.0+\n- ollama 0.3.0+\n\n## Contributing\n\n1. Fork the repository\n2. Create a feature branch: `git checkout -b feature/amazing-feature`\n3. Make your changes and add tests\n4. Run the test suite: `make check`\n5. Commit your changes: `git commit -m 'Add amazing feature'`\n6. Push to the branch: `git push origin feature/amazing-feature`\n7. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Changelog\n\n### [Unreleased]\n\n#### Added\n- Initial release\n- WebSocket chat consumer with streaming support\n- Knowledge base integration with generic foreign keys\n- Session management with conversation history\n- Comprehensive test suite\n- Type hints throughout\n- Async API support\n- File upload handling for knowledge bases\n\n#### Changed\n- Enhanced from original ollama-django app\n- Modern src-layout package structure\n- Improved error handling and validation\n- Better documentation and examples\n\n## Acknowledgments\n\n- [Ollama](https://ollama.ai/) for the fantastic local LLM platform\n- [Django](https://www.djangoproject.com/) for the web framework\n- [Django Channels](https://channels.readthedocs.io/) for WebSocket support\n\n## Support\n\n- 📖 [Documentation](https://django-ollama.readthedocs.io/)\n- 🐛 [Issue Tracker](https://github.com/yourusername/django-ollama/issues)\n- 💬 [Discussions](https://github.com/yourusername/django-ollama/discussions)\n- 📧 [Email Support](mailto:support@django-ollama.com)\n\n---\n\n**Made with ❤️ for the Django and Ollama communities**","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frsp2k%2Fdjango-ollama","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frsp2k%2Fdjango-ollama","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frsp2k%2Fdjango-ollama/lists"}