Skip to content

chaitanyame/privachat_agents

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

11 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PrivaChat Agents πŸ”

Advanced AI-powered research service with RAG, document processing, and multi-agent intelligence.

Built with Python, FastAPI, Pydantic AI, PostgreSQL, and OpenRouter - delivering comprehensive research capabilities with cited sources.

License: MIT Python FastAPI Docker


✨ Features

πŸš€ High Performance

  • Redis caching for 75% cost reduction ($730/year β†’ $182/year)
  • Async processing for 3x faster responses
  • HTTP connection pooling for 30-50% faster API calls
  • Sub-6 second response times for complex queries

πŸ€– Multi-Agent Intelligence

  • Search Agent: Query decomposition and source discovery
  • Research Agent: Deep analysis and synthesis
  • Synthesis Agent: Citation-rich answer generation
  • Temporal Detection: SpaCy-powered time-aware queries

πŸ“š RAG Pipeline (pgvector)

  • Document processing with Dockling
  • 384-dimensional embeddings (Sentence Transformers)
  • Semantic search with cosine similarity
  • Full-text search (FTS) support

πŸ’° Cost Optimized

  • Free-tier LLM usage (DeepSeek via OpenRouter)
  • Intelligent caching with configurable TTLs
  • ~$15/month for moderate usage

πŸ” Privacy-Focused Search

  • SearxNG integration (no tracking)
  • Crawl4AI for web crawling
  • Document upload support
  • Local processing

πŸ—οΈ Architecture


β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  
β”‚   Client    β”‚
β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜  
       β”‚
       β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   FastAPI Server (Port 8001)        β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚   β”‚  Research Pipeline           β”‚  β”‚
β”‚   β”‚  β€’ Multi-agent orchestration β”‚  β”‚
β”‚   β”‚  β€’ Query decomposition       β”‚  β”‚
β”‚   β”‚  β€’ Source validation         β”‚  β”‚
β”‚   β”‚  β€’ Temporal detection (SpaCy)β”‚  β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚   β”‚  Redis Cache Layer           β”‚  β”‚
β”‚   β”‚  β€’ Response cache (1d TTL)   β”‚  β”‚
β”‚   β”‚  β€’ Session storage           β”‚  β”‚
β”‚   β”‚  β€’ 75% cost reduction        β”‚  β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚   β”‚  RAG Pipeline (pgvector)     β”‚  β”‚
β”‚   β”‚  β€’ Document processing       β”‚  β”‚
β”‚   β”‚  β€’ Embedding generation      β”‚  β”‚
β”‚   β”‚  β€’ Semantic search           β”‚  β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
       β”‚               β”‚               β”‚
       β–Ό               β–Ό               β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  SearxNG    β”‚ β”‚  PostgreSQL β”‚ β”‚    Redis     β”‚
β”‚  Port 4000  β”‚ β”‚  Port 5433  β”‚ β”‚  Port 6380   β”‚
β”‚             β”‚ β”‚  + pgvector β”‚ β”‚              β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Performance Metrics:

  • First query (cold): ~5s
  • Cached query: ~1s (5x faster)
  • Research mode: <10s with 30+ sources
  • Embedding generation: <100ms

πŸš€ Quick Start

πŸ’‘ Recommended: Use Docker for the easiest setup experience. All services are pre-configured and will work out of the box.

Prerequisites

  • Docker and Docker Compose (required)
  • OpenRouter API key - Get your free API key at openrouter.ai/keys
  • Python 3.11+ (only for local development without Docker)

Installation (Docker - Recommended)

  1. Clone the repository
git clone https://github.com/chaitanyame/privachat_agents.git
cd privachat_agents
  1. Set up environment variables

Copy the example environment file and configure it:

cp .env.example .env

Then edit .env and configure the following required settings:

# Required: Get your free API key at https://openrouter.ai/keys
OPENROUTER_API_KEY=sk-or-your-actual-key-here

# Required: Set a strong password for PostgreSQL
POSTGRES_PASSWORD=your_secure_password_here

Optional but recommended:

# Enable Langfuse monitoring (optional)
LANGFUSE_ENABLED=true
LANGFUSE_PUBLIC_KEY=pk-lf-...
LANGFUSE_SECRET_KEY=sk-lf-...

# Adjust search behavior (optional)
SEARXNG_PAGES=3
SEARXNG_CATEGORIES=general,news,science,IT

⚠️ Important: Never commit your .env file with real credentials! The .env file is already in .gitignore.

  1. Start the services
docker compose up -d

This will start:

  • API Server (port 8001) - Research API with FastAPI
  • Streamlit UI (port 8503) - Testing interface
  • PostgreSQL (port 5433) - Database with pgvector
  • Redis (port 6380) - Cache layer
  • SearxNG (port 4000) - Privacy-focused search
  1. Verify it's working
curl http://localhost:8001/health

Access the Streamlit UI at: http://localhost:8503


πŸ“– API Usage

Basic Research Request

curl -X POST http://localhost:8001/api/v1/search \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What are the latest developments in AI?",
    "mode": "search",
    "max_sources": 20
  }'

Deep Research Mode

curl -X POST http://localhost:8001/api/v1/research \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Explain quantum computing and its applications",
    "mode": "research",
    "max_sources": 30
  }'

Response Format

{
  "session_id": "uuid-here",
  "query": "What are the latest developments in AI?",
  "answer": "Detailed answer with citations...",
  "sources": [
    {
      "title": "Article Title",
      "url": "https://example.com/article",
      "relevance_score": 0.95,
      "content_snippet": "..."
    }
  ],
  "execution_time_seconds": 5.2
}

πŸ—‚οΈ Project Structure

privachat_agents/
β”œβ”€β”€ privachat_agents/           # Main Python package
β”‚   β”œβ”€β”€ agents/                 # AI agents (Pydantic AI)
β”‚   β”‚   β”œβ”€β”€ search_agent.py     # Search orchestration
β”‚   β”‚   β”œβ”€β”€ research_agent.py   # Deep research
β”‚   β”‚   └── synthesis_agent.py  # Answer synthesis
β”‚   β”œβ”€β”€ api/v1/                 # FastAPI routes
β”‚   β”‚   └── endpoints/
β”‚   β”‚       β”œβ”€β”€ search.py       # Search endpoints
β”‚   β”‚       └── research.py     # Research endpoints
β”‚   β”œβ”€β”€ clients/                # External API clients
β”‚   β”‚   β”œβ”€β”€ searxng_client.py   # SearxNG integration
β”‚   β”‚   └── web_crawler.py      # Crawl4AI wrapper
β”‚   β”œβ”€β”€ core/                   # Core configuration
β”‚   β”‚   β”œβ”€β”€ config.py           # Settings management
β”‚   β”‚   └── pipelines/          # Processing pipelines
β”‚   β”œβ”€β”€ database/               # SQLAlchemy models
β”‚   β”‚   β”œβ”€β”€ models.py           # Database tables
β”‚   β”‚   └── repositories/       # Data access layer
β”‚   β”œβ”€β”€ models/                 # Pydantic schemas
β”‚   β”‚   └── schemas/            # Request/response models
β”‚   β”œβ”€β”€ rag/                    # RAG pipeline
β”‚   β”‚   β”œβ”€β”€ vector_store.py     # pgvector operations
β”‚   β”‚   └── embeddings.py       # Sentence transformers
β”‚   β”œβ”€β”€ services/               # Business logic
β”‚   β”‚   β”œβ”€β”€ llm/                # LLM integrations
β”‚   β”‚   └── cache/              # Redis caching
β”‚   └── main.py                 # FastAPI application
β”œβ”€β”€ tests/                      # Test suite
β”‚   β”œβ”€β”€ unit/                   # Unit tests
β”‚   β”œβ”€β”€ integration/            # Integration tests
β”‚   └── e2e/                    # End-to-end tests
β”œβ”€β”€ alembic/                    # Database migrations
β”œβ”€β”€ config/searxng/             # SearxNG settings
β”œβ”€β”€ docs/                       # Documentation
β”œβ”€β”€ scripts/                    # Utility scripts
β”œβ”€β”€ ui/                         # User interfaces
β”‚   └── streamlit_app.py        # Testing UI
β”œβ”€β”€ docker-compose.yml          # Service orchestration
β”œβ”€β”€ Dockerfile                  # API container
β”œβ”€β”€ Dockerfile.streamlit        # UI container
β”œβ”€β”€ pyproject.toml              # Package configuration
β”œβ”€β”€ requirements.txt            # Dependencies
└── requirements-dev.txt        # Dev dependencies

πŸŽ›οΈ Configuration

Environment Variables

# Required
OPENROUTER_API_KEY=sk-or-...
OPENROUTER_MODEL=openrouter/auto
POSTGRES_PASSWORD=your_secure_password

# Database
DATABASE_URL=postgresql+asyncpg://research_user:${POSTGRES_PASSWORD}@postgres:5432/research_db
POSTGRES_USER=research_user
POSTGRES_DB=research_db

# Redis Cache
REDIS_URL=redis://redis:6379/0
REDIS_ENABLED=true

# Search
SEARXNG_API_URL=http://searxng:8080

# Server
API_HOST=0.0.0.0
API_PORT=8001
LOG_LEVEL=INFO

# Optional: Langfuse Monitoring
LANGFUSE_ENABLED=false
LANGFUSE_PUBLIC_KEY=pk-...
LANGFUSE_SECRET_KEY=sk-...

Docker Compose Ports

  • 8001 - Research API (FastAPI)
  • 8503 - Streamlit UI
  • 5433 - PostgreSQL (with pgvector)
  • 6380 - Redis cache
  • 4000 - SearxNG search engine

πŸ”§ Development

Running Locally (Without Docker)

# Install dependencies
pip install -r requirements.txt
pip install -r requirements-dev.txt

# Download SpaCy model
python -m spacy download en_core_web_sm

# Set environment variables
export OPENROUTER_API_KEY=your_key_here
export DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5433/research
export REDIS_URL=redis://localhost:6380

# Run database migrations
alembic upgrade head

# Run the server
uvicorn privachat_agents.main:app --reload --host 0.0.0.0 --port 8001

Viewing Logs

# All services
docker compose logs -f

# Specific service
docker compose logs -f api

# Search for specific patterns
docker compose logs api | grep -i "search\|error"

Rebuilding After Changes

docker compose build api
docker compose up -d api

πŸ§ͺ Testing

Run the comprehensive test suite:

# Run all tests
pytest tests/ -v

# Run with coverage
pytest --cov=privachat_agents --cov-report=html tests/

# Run specific test categories
pytest tests/unit/ -v          # Unit tests only
pytest tests/integration/ -v   # Integration tests
pytest tests/e2e/ -v           # End-to-end tests

# Run marked tests
pytest -m "unit and fast" -v

Quick Test Scripts

# Windows
run_tests.bat
run_all_tests.bat

# Linux/Mac
./run_tests.sh

Code Quality

# Linting
ruff check .
ruff check --fix .

# Type checking
mypy privachat_agents/

# Format code
ruff format .

πŸ“Š Performance Optimizations

The system includes 4 major performance optimizations:

1. Redis Caching (75% cost reduction)

  • Response cache: 1-day TTL
  • Session storage: Persistent across restarts
  • Result: Identical queries 5x faster (5s β†’ 1s)
  • Savings: $730/year β†’ $182/year

2. Async Processing (3x faster)

  • Concurrent source fetching with asyncio.gather()
  • Before: 9+ seconds for 3 URLs
  • After: ~3 seconds (3x faster)

3. HTTP Connection Pooling (30-50% faster)

  • Singleton httpx.AsyncClient
  • 100 max connections, 20 keep-alive
  • Connection reuse across all API calls

4. Optimized Embeddings

  • Sentence Transformers (384D)
  • Batch processing support
  • CPU/GPU adaptive

See docs/PROCESS_FLOWS.md for detailed architecture.


πŸ“ˆ Monitoring

Health Check

curl http://localhost:8001/health

API Documentation

# Interactive API docs (Swagger UI)
open http://localhost:8001/docs

# Alternative docs (ReDoc)
open http://localhost:8001/redoc

Container Status

docker compose ps

Database Status

docker compose exec postgres psql -U research_user -d research_db -c "SELECT count(*) FROM research_sessions;"

View Metrics (if Langfuse enabled)

Access Langfuse dashboard at your configured URL


πŸ› Troubleshooting

API returns empty responses

  • Check OpenRouter API key is set correctly: echo $OPENROUTER_API_KEY
  • Check logs: docker compose logs api
  • Verify health endpoint: curl http://localhost:8001/health

Cache not working

  • Verify Redis is running: docker compose ps redis
  • Check Redis connection: docker compose exec redis redis-cli PING
  • Review cache logs: docker compose logs api | grep -i cache

Slow responses

  • Check if caching is enabled (REDIS_ENABLED=true)
  • Verify async processing is working (logs show "concurrent")
  • Monitor Redis: docker stats

Database errors

  • Check migrations: alembic current
  • Run migrations: alembic upgrade head
  • Check pgvector extension: docker compose exec postgres psql -U research_user -d research_db -c "\dx"

SearxNG errors

  • Ensure SearxNG is running: curl http://localhost:4000
  • Check SearxNG logs: docker compose logs searxng
  • Verify configuration in config/searxng/settings.yml

🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Follow TDD principles (tests first!)
  4. Commit your changes (git commit -m 'Add amazing feature')
  5. Push to the branch (git push origin feature/amazing-feature)
  6. Open a Pull Request

Development Standards:

  • βœ… Write tests BEFORE implementation (TDD)
  • βœ… Minimum 80% test coverage
  • βœ… Type hints on all functions
  • βœ… Docstrings on all public APIs
  • βœ… Pass ruff and mypy checks

See CONTRIBUTING.md and .github/copilot-instructions.md for detailed guidelines.


πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ™ Acknowledgments


πŸ“ž Support


Made with ❀️ for the AI agent community

About

No description, website, or topics provided.

Resources

License

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Packages

 
 
 

Contributors

Languages