Python-based AI backend — reference architecture for projects using LLMs, RAG, and agents.
Directory Layout
src/
├── ai/ # AI Core
│ ├── agents/ # LangChain/CrewAI agents
│ ├── llm/ # OpenAI/Anthropic/Gemini clients
│ ├── rag/ # RAG pipeline (retrieval + generation)
│ └── embeddings/ # Vector embeddings
├── api/
│ ├── routes/
│ │ ├── chat.py # Streaming chat endpoints
│ │ ├── rag.py # Document search endpoints
│ │ └── agents.py # Agent management
│ └── websocket/ # Real-time AI streaming
├── core/
│ ├── config.py # AI provider configs
│ ├── database.py # PostgreSQL + Vector DB
│ └── cache.py # Redis for LLM caching
├── domain/ # Business logic
│ ├── models/ # Pydantic models
│ ├── services/ # AI services
│ └── repositories/ # Data access
├── infrastructure/
│ ├── vector_dbs/ # Pinecone / Weaviate / Qdrant
│ └── monitoring/ # LangSmith, OpenTelemetry
└── workflows/ # AI pipelines
├── document_processing.py
└── chat_orchestration.py
data/ # Knowledge base for RAG
├── documents/ # Source files
├── chunks/ # Processed chunks
└── embeddings/ # Vector embeddings
prompts/ # Prompt management
├── system/
├── user/
└── templates/
tests/
├── ai/ # LLM & RAG tests
├── integration/
└── e2e/
docker-compose.yml # Vector DBs, Redis, monitoring
requirements-ai.txt # AI-specific packages
.env # API keys & configs
Key Features This Structure Supports
| Feature | Location |
|---|---|
| Multi-LLM provider support | src/ai/llm/ |
| RAG with vector search | src/ai/rag/ + data/ + src/infrastructure/vector_dbs/ |
| AI agent framework | src/ai/agents/ |
| Real-time streaming | src/api/websocket/ |
| Prompt versioning | prompts/ |
| Observability | src/infrastructure/monitoring/ (LangSmith, OpenTelemetry) |
| Knowledge base management | data/ |
Notes
domain/follows DDD: models → services → repositoriescore/database.pymanages both relational (PostgreSQL) and vector store connectionscache.py(Redis) avoids redundant LLM calls for repeated queriesrequirements-ai.txtkept separate from generalrequirements.txtto isolate heavy AI dependencies