# rag-qa-project
**Repository Path**: svnspot/rag-qa-project
## Basic Information
- **Project Name**: rag-qa-project
- **Description**: No description available
- **Primary Language**: Unknown
- **License**: MulanPSL-2.0
- **Default Branch**: main
- **Homepage**: None
- **GVP Project**: No
## Statistics
- **Stars**: 0
- **Forks**: 0
- **Created**: 2026-04-24
- **Last Updated**: 2026-04-24
## Categories & Tags
**Categories**: Uncategorized
**Tags**: None
## README
# ๐ค RAG Q&A System
### Production-Ready Retrieval-Augmented Generation with FastAPI & LangChain
[](https://www.python.org/downloads/)
[](https://fastapi.tiangolo.com)
[](https://python.langchain.com)
[](LICENSE)
[](https://github.com/features/actions)
[](https://www.docker.com/)
[](https://aws.amazon.com/apprunner/)
[Features](#-features) โข
[Quick Start](#-quick-start) โข
[API Docs](#-api-endpoints) โข
[Deployment](#-deployment) โข
[Contributing](#-contributing)
---
## ๐ Overview
A **production-ready** RAG (Retrieval-Augmented Generation) system that enables intelligent Q&A over your documents. Built with modern AI stack and battle-tested in production environments.
### ๐ฏ What is RAG?
RAG combines the power of **retrieval** (finding relevant information) with **generation** (creating coherent answers) to provide accurate, context-aware responses to your questions based on your own documents.
### ๐ Key Highlights
- ๐ **Production Ready**: Docker + CI/CD + AWS deployment
- ๐ง **Smart AI**: Powered by OpenAI GPT-4o & LangChain
- ๐ **Observable**: LangSmith integration for full tracing
- โ
**Evaluated**: RAGAS metrics for answer quality
- ๐ **Secure**: Non-root Docker, API validation, error handling
- โก **Fast**: Async operations, streaming responses
- ๐ **Scalable**: Cloud-native architecture
---
## โจ Features
### ๐ Document Management
- โ
Upload **PDF**, **TXT**, and **CSV** files
- โ
Automatic text extraction and chunking
- โ
Smart document splitting with overlap
- โ
Vector storage in Qdrant Cloud
### ๐ฌ Intelligent Q&A
- โ
Natural language questions
- โ
Context-aware answers
- โ
Source attribution (see which docs were used)
- โ
Streaming responses for real-time feedback
- โ
Multiple query modes (standard, search-only)
### ๐ Observability & Quality
- โ
**LangSmith Tracing**: Full chain visibility, token tracking, cost analysis
- โ
**RAGAS Evaluation**: Faithfulness & answer relevancy metrics
- โ
**Structured Logging**: Comprehensive error tracking
- โ
**Health Checks**: Readiness & liveness endpoints
### ๐ ๏ธ Developer Experience
- โ
**Auto-generated Swagger docs** at `/docs`
- โ
**Type-safe** Pydantic models
- โ
**Comprehensive tests** with 70%+ coverage
- โ
**Hot reload** in development
- โ
**CI/CD pipeline** with GitHub Actions
---
## ๐๏ธ Architecture
```mermaid
graph LR
A[๐ค User] -->|Upload Docs| B[FastAPI]
A -->|Ask Question| B
B --> C[๐ Document Processor]
C --> D[๐ข OpenAI Embeddings]
D --> E[(Qdrant Vector DB)]
B --> F[๐ RAG Chain]
F --> E
F --> G[๐ค OpenAI GPT-4o]
G --> H[๐ RAGAS Evaluator]
F --> I[๐ LangSmith]
H --> A
```
### Tech Stack
| Component | Technology | Purpose |
|-----------|------------|---------|
| ๐ Language | **Python 3.12** | Modern Python with type hints |
| ๐ API Framework | **FastAPI** | High-performance async API |
| ๐ง RAG Framework | **LangChain** | LLM orchestration |
| ๐๏ธ Vector DB | **Qdrant Cloud** | Semantic search |
| ๐ข Embeddings | **text-embedding-3-small** | Document encoding |
| ๐ค LLM | **GPT-4o-mini** | Answer generation |
| ๐ Evaluation | **RAGAS** | Quality metrics |
| ๐ Observability | **LangSmith** | Tracing & monitoring |
| ๐ณ Container | **Docker** | Containerization |
| โ๏ธ Cloud | **AWS App Runner** | Serverless hosting |
| ๐ CI/CD | **GitHub Actions** | Automated pipeline |
---
## ๐ Quick Start
### Prerequisites
- ๐ Python 3.12+
- ๐ OpenAI API key ([Get one](https://platform.openai.com/api-keys))
- ๐๏ธ Qdrant Cloud account ([Sign up](https://cloud.qdrant.io))
### 1๏ธโฃ Clone & Install
```bash
# Clone repository
git clone https://github.com/yourusername/rag-qa-project.git
cd rag-qa-project
# Install with UV (recommended)
uv sync
# Or with pip
pip install -r requirements.txt
```
### 2๏ธโฃ Configure Environment
```bash
# Copy environment template
cp .env.example .env
# Edit with your credentials
nano .env
```
**Required variables:**
```bash
OPENAI_API_KEY=sk-proj-your-key-here
QDRANT_URL=https://your-cluster.qdrant.io
QDRANT_API_KEY=your-qdrant-api-key
```
**Optional - LangSmith Observability:**
```bash
LANGCHAIN_TRACING_V2=true
LANGCHAIN_API_KEY=lsv2_pt_your-key-here
LANGCHAIN_PROJECT=rag-qa-production
```
### 3๏ธโฃ Run Application
```bash
# Development mode with hot reload
uvicorn app.main:app --reload
# Or using Python
python -m app.main
```
### 4๏ธโฃ Access API
๐ **Swagger UI**: http://localhost:8000/docs
๐ **ReDoc**: http://localhost:8000/redoc
๐ **Health Check**: http://localhost:8000/health
---
## ๐ API Endpoints
### Document Management
| Endpoint | Method | Description | Example |
|----------|--------|-------------|---------|
| ๐ค `/documents/upload` | POST | Upload document | [See below](#upload-document) |
| โน๏ธ `/documents/info` | GET | Get collection stats | `curl /documents/info` |
| ๐๏ธ `/documents/collection` | DELETE | Delete all documents | `curl -X DELETE /documents/collection` |
### Query & Search
| Endpoint | Method | Description | Features |
|----------|--------|-------------|----------|
| ๐ฌ `/query` | POST | Ask a question | Sources, Evaluation |
| ๐ `/query/stream` | POST | Streaming response | Real-time tokens |
| ๐ `/query/search` | POST | Search only | No generation |
### Health & Monitoring
| Endpoint | Method | Description |
|----------|--------|-------------|
| โค๏ธ `/health` | GET | Basic health check |
| โ
`/health/ready` | GET | Readiness with DB status |
---
## ๐ก Usage Examples
### Upload a Document
```bash
curl -X POST "http://localhost:8000/documents/upload" \
-H "Content-Type: multipart/form-data" \
-F "file=@research_paper.pdf"
```
**Response:**
```json
{
"message": "Document uploaded and processed successfully",
"filename": "research_paper.pdf",
"chunks_created": 42,
"document_ids": ["uuid-1", "uuid-2", ...]
}
```
### Ask a Question
```bash
curl -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{
"question": "What is the main contribution of this paper?",
"include_sources": true,
"enable_evaluation": false
}'
```
**Response:**
```json
{
"question": "What is the main contribution of this paper?",
"answer": "The main contribution is...",
"sources": [
{
"content": "Excerpt from page 3...",
"metadata": {"source": "research_paper.pdf", "page": 3}
}
],
"processing_time_ms": 1234.5
}
```
### Query with RAGAS Evaluation
```bash
curl -X POST "http://localhost:8000/query" \
-H "Content-Type: application/json" \
-d '{
"question": "Summarize the methodology",
"include_sources": true,
"enable_evaluation": true
}'
```
**Response includes evaluation scores:**
```json
{
"question": "Summarize the methodology",
"answer": "The methodology involves...",
"sources": [...],
"processing_time_ms": 3456.7,
"evaluation": {
"faithfulness": 0.95,
"answer_relevancy": 0.87,
"evaluation_time_ms": 1200.5,
"error": null
}
}
```
---
## ๐ณ Docker Deployment
### Using Docker Compose (Recommended)
```bash
# Build and run
docker-compose up --build
# Run in detached mode
docker-compose up -d
# View logs
docker-compose logs -f app
# Stop
docker-compose down
```
### Using Docker Directly
```bash
# Build image
docker build -t rag-qa-system .
# Run container
docker run -p 8000:8000 --env-file .env rag-qa-system
# Run with custom port
docker run -p 3000:8000 --env-file .env rag-qa-system
```
---
## โ๏ธ Deployment
### AWS App Runner (Serverless)
Fully automated deployment with GitHub Actions:
1๏ธโฃ **Setup AWS Resources**
```bash
# Create ECR repository
aws ecr create-repository --repository-name rag-qa-system --region us-east-1
# Create IAM role for App Runner
aws iam create-role --role-name AppRunnerECRAccessRole --assume-role-policy-document file://trust-policy.json
```
2๏ธโฃ **Configure GitHub Secrets**
Add these secrets in: `Settings โ Secrets and variables โ Actions`
- `AWS_ACCESS_KEY_ID`
- `AWS_SECRET_ACCESS_KEY`
- `APP_RUNNER_ECR_ACCESS_ROLE_ARN`
- `OPENAI_API_KEY`
- `QDRANT_URL`
- `QDRANT_API_KEY`
- `LANGCHAIN_API_KEY` (optional)
3๏ธโฃ **Deploy**
```bash
# Push to main branch
git push origin main
# GitHub Actions automatically:
# โ
Runs tests
# โ
Builds Docker image
# โ
Pushes to ECR
# โ
Deploys to App Runner
```
4๏ธโฃ **Access Your API**
Your app will be available at: `https://xxxxx.us-east-1.awsapprunner.com`
๐ **Full Guide**: See [AWS Deployment Guide](docs/AWS_DEPLOYMENT_GUIDE.md)
---
## ๐งช Testing
### Run All Tests
```bash
# Install dev dependencies
uv sync --extra dev
# Run tests with coverage
pytest --cov=app --cov-report=html
# View coverage report
open htmlcov/index.html
```
### Run Specific Tests
```bash
# Test query endpoints
pytest tests/test_query.py -v
# Test RAG chain
pytest tests/test_rag_chain.py -v
# Test RAGAS evaluator
pytest tests/test_ragas_evaluator.py -v
```
### Code Quality
```bash
# Format code
uv run black app/ tests/
# Lint code
uv run ruff check app/ tests/
# Fix linting issues
uv run ruff check app/ tests/ --fix
# Type checking
uv run mypy app/
```
---
## โ๏ธ Configuration
### Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| **Required** |||
| `OPENAI_API_KEY` | - | OpenAI API key |
| `QDRANT_URL` | - | Qdrant Cloud URL |
| `QDRANT_API_KEY` | - | Qdrant API key |
| **Document Processing** |||
| `COLLECTION_NAME` | `rag_documents` | Vector collection name |
| `CHUNK_SIZE` | `1000` | Text chunk size |
| `CHUNK_OVERLAP` | `200` | Chunk overlap tokens |
| **AI Models** |||
| `EMBEDDING_MODEL` | `text-embedding-3-small` | OpenAI embedding model |
| `LLM_MODEL` | `gpt-4o-mini` | OpenAI chat model |
| `LLM_TEMPERATURE` | `0.0` | LLM temperature (0-2) |
| **RAGAS Evaluation** |||
| `RAGAS_LLM_MODEL` | (uses `LLM_MODEL`) | Model for evaluation |
| `RAGAS_TIMEOUT_SECONDS` | `30.0` | Evaluation timeout |
| **LangSmith Observability** |||
| `LANGCHAIN_TRACING_V2` | `false` | Enable LangSmith tracing |
| `LANGCHAIN_API_KEY` | - | LangSmith API key |
| `LANGCHAIN_PROJECT` | `rag-qa-production` | Project name |
| **API Settings** |||
| `API_HOST` | `0.0.0.0` | API host |
| `API_PORT` | `8000` | API port |
| `LOG_LEVEL` | `INFO` | Logging level |
---
## ๐ Project Structure
```
rag-qa-project/
โโโ ๐ app/ # Application code
โ โโโ main.py # FastAPI app entry
โ โโโ config.py # Configuration
โ โโโ ๐ api/
โ โ โโโ ๐ routes/ # API endpoints
โ โ โ โโโ health.py # Health checks
โ โ โ โโโ documents.py # Document management
โ โ โ โโโ query.py # Q&A endpoints
โ โ โโโ schemas.py # Pydantic models
โ โโโ ๐ core/ # Business logic
โ โ โโโ document_processor.py # Doc loading & chunking
โ โ โโโ embeddings.py # Embedding service
โ โ โโโ vector_store.py # Qdrant operations
โ โ โโโ rag_chain.py # RAG orchestration
โ โ โโโ ragas_evaluator.py # Quality evaluation
โ โโโ ๐ utils/
โ โโโ logger.py # Logging setup
โโโ ๐ tests/ # Test suite
โ โโโ conftest.py # Pytest fixtures
โ โโโ test_query.py # API tests
โ โโโ test_rag_chain.py # RAG tests
โ โโโ test_ragas_evaluator.py # Evaluation tests
โโโ ๐ .github/workflows/ # CI/CD pipelines
โ โโโ ci.yml # Continuous Integration
โ โโโ deploy.yml # Deployment to AWS
โโโ ๐ docs/ # Documentation
โ โโโ AWS_DEPLOYMENT_GUIDE.md # AWS setup guide
โโโ Dockerfile # Production container
โโโ docker-compose.yml # Local development
โโโ pyproject.toml # Project config (UV)
โโโ requirements.txt # Python dependencies
โโโ requirements-dev.txt # Dev dependencies
โโโ .env.example # Environment template
โโโ CLAUDE.md # Project instructions
โโโ README.md # This file
```
---
## ๐ CI/CD Pipeline
### Continuous Integration (`.github/workflows/ci.yml`)
Runs on every push and pull request:
1. โ
**Code Quality**
- Ruff linting
- Black formatting check
2. โ
**Testing**
- Unit tests with pytest
- 70%+ code coverage required
- Coverage reports uploaded
3. โ
**Docker Build**
- Multi-stage build
- Image size optimization
- Container health check
4. โ
**Security**
- Bandit security scan
- Dependency vulnerability check (Safety)
### Continuous Deployment (`.github/workflows/deploy.yml`)
Deploys to AWS on push to `main`:
1. ๐๏ธ **Build & Push**
- Build Docker image
- Tag with commit SHA + latest
- Push to AWS ECR
2. ๐ **Deploy**
- Update App Runner service
- Zero-downtime deployment
- Auto-rollback on failure
3. โ
**Verify**
- Health check
- Smoke tests
---
## ๐ค Contributing
We welcome contributions! Here's how you can help:
### ๐ Report Bugs
Found a bug? [Open an issue](https://github.com/yourusername/rag-qa-project/issues) with:
- Clear description
- Steps to reproduce
- Expected vs actual behavior
- Environment details
### ๐ก Suggest Features
Have an idea? [Create a feature request](https://github.com/yourusername/rag-qa-project/issues/new) with:
- Use case description
- Proposed solution
- Alternative approaches considered
### ๐ง Submit Pull Requests
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Add tests for new functionality
5. Ensure all tests pass (`pytest`)
6. Format code (`black app/ tests/`)
7. Lint code (`ruff check app/ tests/`)
8. Commit changes (`git commit -m 'Add amazing feature'`)
9. Push to branch (`git push origin feature/amazing-feature`)
10. Open a Pull Request
### ๐ Development Guidelines
- โ
Write tests for new features
- โ
Maintain >70% code coverage
- โ
Follow PEP 8 style guide
- โ
Add docstrings to functions
- โ
Update documentation
- โ
Keep commits atomic and descriptive
---
## ๐ Additional Resources
### Documentation
- ๐ [FastAPI Docs](https://fastapi.tiangolo.com/)
- ๐ฆ [LangChain Docs](https://python.langchain.com/)
- ๐๏ธ [Qdrant Docs](https://qdrant.tech/documentation/)
- ๐ค [OpenAI API Docs](https://platform.openai.com/docs)
- ๐ [RAGAS Docs](https://docs.ragas.io/)
- ๐ [LangSmith Docs](https://docs.smith.langchain.com/)
### Tutorials & Guides
- ๐ [Building Production RAG Systems](https://www.anthropic.com/research/building-rag-systems)
- ๐ [FastAPI Best Practices](https://github.com/zhanymkanov/fastapi-best-practices)
- ๐ณ [Docker Best Practices](https://docs.docker.com/develop/dev-best-practices/)
---
## ๐ License
This project is licensed under the **MIT License** - see the [LICENSE](LICENSE) file for details.
```
MIT License
Copyright (c) 2025 RAG Q&A System Contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
```
---
## ๐ Acknowledgments
Built with amazing open-source tools:
- ๐ [FastAPI](https://fastapi.tiangolo.com/) - Modern web framework
- ๐ฆ [LangChain](https://python.langchain.com/) - LLM framework
- ๐๏ธ [Qdrant](https://qdrant.tech/) - Vector database
- ๐ค [OpenAI](https://openai.com/) - AI models
- ๐ณ [Docker](https://www.docker.com/) - Containerization
- โ๏ธ [AWS](https://aws.amazon.com/) - Cloud infrastructure
- ๐ [RAGAS](https://docs.ragas.io/) - RAG evaluation
- ๐ [LangSmith](https://smith.langchain.com/) - Observability
Special thanks to all [contributors](https://github.com/yourusername/rag-qa-project/graphs/contributors)!
---
## ๐ฌ Support
- ๐ง **Email**: your.email@example.com
- ๐ฌ **Issues**: [GitHub Issues](https://github.com/yourusername/rag-qa-project/issues)
- ๐ **Documentation**: [Wiki](https://github.com/yourusername/rag-qa-project/wiki)
- ๐ฆ **Twitter**: [@yourhandle](https://twitter.com/yourhandle)
---
### โญ Star this repo if you find it helpful!
**Made with โค๏ธ by the RAG Q&A Team**
[Report Bug](https://github.com/yourusername/rag-qa-project/issues) โข
[Request Feature](https://github.com/yourusername/rag-qa-project/issues) โข
[Contribute](CONTRIBUTING.md)