This project integrates Langchain with FastAPI in an Asynchronous, Scalable manner, providing a framework for document indexing and retrieval, using PostgreSQL/pgvector.
- ID-based RAG - Files organized by
file_idfor integration with LibreChat - Dash Assistant - Dashboard and chart search system with multi-signal retrieval
The API evolves over time to employ different querying/re-ranking methods, embedding models, and vector stores.
Complete end-to-end setup for dashboard and chart search functionality.
- Docker and Docker Compose
- Python 3.10+ with dependencies installed
- PostgreSQL with pgvector support
docker compose up -d db
Wait for PostgreSQL to be ready (health check will confirm).
python -m app.dash_assistant.migrate
This creates all necessary tables, indexes, and optimization functions.
# Complete data ingestion pipeline
python -m app.dash_assistant.ingestion.index_jobs \
--dashboards-csv tests/fixtures/superset/dashboards.csv \
--charts-csv tests/fixtures/superset/charts.csv \
--md-dir tests/fixtures/superset/md \
--enrichment-yaml tests/fixtures/superset/enrichment.yaml \
--complete# Create embeddings for semantic search (only missing chunks)
python -m app.dash_assistant.ingestion.index_jobs --only-missinguvicorn main:app --reload --host 0.0.0.0 --port 8000
curl -X POST "http://localhost:8000/dash/query" \ -H "Content-Type: application/json" \ -d '{"q":"где найти retention","top_k":3}'
{
"results": [
{
"title": "User Retention Dashboard",
"url": "https://superset.company.com/superset/dashboard/42/",
"score": 0.95,
"charts": [
{
"title": "Monthly Retention Cohorts",
"viz_type": "heatmap",
"url": "https://superset.company.com/explore/?slice_id=123"
}
],
"why": "семантическая близость по содержимому, совпадения в тексте: retention"
},
{
"title": "Product Usage Metrics",
"url": "https://superset.company.com/superset/dashboard/15/",
"score": 0.78,
"charts": [
{
"title": "User Engagement Trends",
"viz_type": "line",
"url": "https://superset.company.com/explore/?slice_id=456"
}
],
"why": "совпадение по заголовку, популярность учтена"
}
],
"debug": {
"query_processing_time_ms": 145,
"total_candidates": 12,
"rrf_scores": {"42": 0.95, "15": 0.78},
"signal_sources": ["fts", "vector", "trigram"]
}
}Complete Slack integration with slash commands and interactive buttons for dashboard search.
- Slash Commands:
/dash-search <query>for searching dashboards - Interactive Buttons: Feedback buttons that update after clicking
- Block Kit UI: Rich formatting with dashboard links and charts
- Signature Verification: Secure request validation
- Retry Protection: Handles Slack retry requests properly
-
Create Slack App at https://api.slack.com/apps
-
Configure Slash Command:
- Command:
/dash-search - Request URL:
https://your-domain.com/slack/command - Description: "Search dashboards"
- Usage Hint:
<query>
- Command:
-
Enable Interactivity:
- Request URL:
https://your-domain.com/slack/interactive
- Request URL:
-
Set Environment Variables:
export SLACK_SIGNING_SECRET="your_signing_secret_here"
-
Install App to your workspace and invite bot to channels
POST /slack/command- Handles slash commandsPOST /slack/interactive- Handles button interactionsGET /slack/health- Health check for Slack integration
When users click feedback buttons (👍/👎), the buttons automatically update to show confirmation:
- 👍 → ✅ Полезно (green)
- 👎 → ❌ Не полезно (red)
This provides immediate visual feedback that the action was processed.
{
"response_type": "in_channel",
"text": "По запросу 'retention' найдено 2 дашбордов.",
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "🔍 Найденные дашборды"
}
},
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*1. User Retention Dashboard*\n<https://superset.company.com/dashboard/42|Открыть дашборд>"
},
{
"type": "mrkdwn",
"text": "*Релевантность:* 0.95\n*Почему найден:* семантическая близость по содержимому"
}
]
},
{
"type": "actions",
"block_id": "fb_123",
"elements": [
{
"type": "button",
"text": {"type": "plain_text", "text": "Открыть"},
"url": "https://superset.company.com/dashboard/42",
"style": "primary"
},
{
"type": "button",
"text": {"type": "plain_text", "text": "👍"},
"value": "{\"qid\": 123, \"vote\": \"up\", \"entity_id\": 42}",
"action_id": "feedback"
},
{
"type": "button",
"text": {"type": "plain_text", "text": "👎"},
"value": "{\"qid\": 123, \"vote\": \"down\", \"entity_id\": 42}",
"action_id": "feedback"
}
]
}
]
}# Test health check curl http://localhost:8000/slack/health # Test slash command (requires proper Slack signature) curl -X POST http://localhost:8000/slack/command \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "text=revenue analytics&user_id=U123&user_name=testuser"
# Start all services (database + API) docker-compose up -d # Run migrations docker-compose exec fastapi python -m app.dash_assistant.migrate # Check status docker-compose logs fastapi --tail=20 curl http://localhost:8000/health curl http://localhost:8000/dash/health curl http://localhost:8000/slack/health
The docker-compose.yaml includes all necessary environment variables:
environment: - DB_HOST=db - DB_PORT=5432 - DB_NAME=rag_api - DB_USER=postgres - DB_PASSWORD=password - POSTGRES_HOST=db - POSTGRES_PORT=5432 - POSTGRES_DB=rag_api - POSTGRES_USER=postgres - POSTGRES_PASSWORD=password
The system uses 1536-dimensional embeddings (compatible with OpenAI standard) to work with pgvector 0.5.1 limitations:
- Mock Embeddings (default): Deterministic vectors for testing
- OpenAI Embeddings: Set
EMBEDDINGS_PROVIDER=OPENAIandOPENAI_API_KEY - Dimension: Configurable via
EMBEDDINGS_DIMENSION(default: 1536)
For convenience, use the provided Makefile:
# Complete setup (recommended for first time) make setup-complete # Development setup (DB + migrations only) make setup-dev # Individual steps make docker-db # Start database make migrate # Run migrations make ingest-complete # Load test data make optimize-db # Optimize after loading # Utilities make migrate-list # Check migration status make help # Show all commands
For detailed instructions, see Dash Assistant README.
The project includes GitHub Actions CI workflow (.github/workflows/ci.yml) that:
- Tests on Python 3.10 & 3.11 with matrix builds
- PostgreSQL 16 with pgvector service for integration tests
- MOCK embeddings provider - no external API calls in CI
- Automated migrations before running tests
- Code quality checks - linting, formatting, type checking
- Security scanning - bandit and safety checks
- Test coverage reporting
The CI automatically sets:
EMBEDDINGS_PROVIDER: MOCK # No external API calls EMBEDDINGS_DIMENSION: 3072 # Test dimension POSTGRES_DB: rag_api # Test database OPENAI_API_KEY: "" # Explicitly empty
This ensures tests run deterministically without external dependencies.
- Document Management: Methods for adding, retrieving, and deleting documents.
- Vector Store: Utilizes Langchain's vector store for efficient document retrieval.
- Asynchronous Support: Offers async operations for enhanced performance.
- Configure
.envfile based on section below - Setup pgvector database:
- Run an existing PSQL/PGVector setup, or,
- Docker:
docker compose up(also starts RAG API)- or, use docker just for DB:
docker compose -f ./db-compose.yaml up
- or, use docker just for DB:
- Run API:
- Docker:
docker compose up(also starts PSQL/pgvector)- or, use docker just for RAG API:
docker compose -f ./api-compose.yaml up
- or, use docker just for RAG API:
- Local:
- Make sure to setup
DB_HOSTto the correct database hostname - Run the following commands (preferably in a virtual environment)
- Make sure to setup
- Docker:
pip install -r requirements.txt uvicorn main:app
The following environment variables are required to run the application:
-
RAG_OPENAI_API_KEY: The API key for OpenAI API Embeddings (if using default settings).- Note:
OPENAI_API_KEYwill work butRAG_OPENAI_API_KEYwill override it in order to not conflict with LibreChat setting.
- Note:
-
RAG_OPENAI_BASEURL: (Optional) The base URL for your OpenAI API Embeddings -
RAG_OPENAI_PROXY: (Optional) Proxy for OpenAI API Embeddings- Note: When using with LibreChat, you can also set
HTTP_PROXYandHTTPS_PROXYenvironment variables in thedocker-compose.override.ymlfile (see Proxy Configuration section below)
- Note: When using with LibreChat, you can also set
-
VECTOR_DB_TYPE: (Optional) select vector database type, default topgvector. -
POSTGRES_USE_UNIX_SOCKET: (Optional) Set to "True" when connecting to the PostgreSQL database server with Unix Socket. -
POSTGRES_DB: (Optional) The name of the PostgreSQL database, used whenVECTOR_DB_TYPE=pgvector. -
POSTGRES_USER: (Optional) The username for connecting to the PostgreSQL database. -
POSTGRES_PASSWORD: (Optional) The password for connecting to the PostgreSQL database. -
DB_HOST: (Optional) The hostname or IP address of the PostgreSQL database server. -
DB_PORT: (Optional) The port number of the PostgreSQL database server. -
RAG_HOST: (Optional) The hostname or IP address where the API server will run. Defaults to "0.0.0.0" -
RAG_PORT: (Optional) The port number where the API server will run. Defaults to port 8000. -
JWT_SECRET: (Optional) The secret key used for verifying JWT tokens for requests.- The secret is only used for verification. This basic approach assumes a signed JWT from elsewhere.
- Omit to run API without requiring authentication
-
COLLECTION_NAME: (Optional) The name of the collection in the vector store. Default value is "testcollection". -
CHUNK_SIZE: (Optional) The size of the chunks for text processing. Default value is "1500". -
CHUNK_OVERLAP: (Optional) The overlap between chunks during text processing. Default value is "100". -
RAG_UPLOAD_DIR: (Optional) The directory where uploaded files are stored. Default value is "./uploads/". -
PDF_EXTRACT_IMAGES: (Optional) A boolean value indicating whether to extract images from PDF files. Default value is "False". -
DEBUG_RAG_API: (Optional) Set to "True" to show more verbose logging output in the server console, and to enable postgresql database routes -
DEBUG_PGVECTOR_QUERIES: (Optional) Set to "True" to enable detailed PostgreSQL query logging for pgvector operations. Useful for debugging performance issues with vector database queries. -
CONSOLE_JSON: (Optional) Set to "True" to log as json for Cloud Logging aggregations -
EMBEDDINGS_PROVIDER: (Optional) either "openai", "bedrock", "azure", "huggingface", "huggingfacetei", "vertexai", or "ollama", where "huggingface" uses sentence_transformers; defaults to "openai" -
EMBEDDINGS_MODEL: (Optional) Set a valid embeddings model to use from the configured provider.- Defaults
- openai: "text-embedding-3-small"
- azure: "text-embedding-3-small" (will be used as your Azure Deployment)
- huggingface: "sentence-transformers/all-MiniLM-L6-v2"
- huggingfacetei: "http://huggingfacetei:3000". Hugging Face TEI uses model defined on TEI service launch.
- vertexai: "text-embedding-004"
- ollama: "nomic-embed-text"
- bedrock: "amazon.titan-embed-text-v1"
-
RAG_AZURE_OPENAI_API_VERSION: (Optional) Default is2023-05-15. The version of the Azure OpenAI API. -
RAG_AZURE_OPENAI_API_KEY: (Optional) The API key for Azure OpenAI service.- Note:
AZURE_OPENAI_API_KEYwill work butRAG_AZURE_OPENAI_API_KEYwill override it in order to not conflict with LibreChat setting.
- Note:
-
RAG_AZURE_OPENAI_ENDPOINT: (Optional) The endpoint URL for Azure OpenAI service, including the resource.- Example:
https://YOUR_RESOURCE_NAME.openai.azure.com. - Note:
AZURE_OPENAI_ENDPOINTwill work butRAG_AZURE_OPENAI_ENDPOINTwill override it in order to not conflict with LibreChat setting.
- Example:
-
HF_TOKEN: (Optional) if needed forhuggingfaceoption. -
OLLAMA_BASE_URL: (Optional) defaults tohttp://ollama:11434. -
ATLAS_SEARCH_INDEX: (Optional) the name of the vector search index if using Atlas MongoDB, defaults tovector_index -
MONGO_VECTOR_COLLECTION: Deprecated for MongoDB, please useATLAS_SEARCH_INDEXandCOLLECTION_NAME -
AWS_DEFAULT_REGION: (Optional) defaults tous-east-1 -
AWS_ACCESS_KEY_ID: (Optional) needed for bedrock embeddings -
AWS_SECRET_ACCESS_KEY: (Optional) needed for bedrock embeddings -
AWS_SESSION_TOKEN: (Optional) may be needed for bedrock embeddings -
GOOGLE_APPLICATION_CREDENTIALS: (Optional) needed for Google VertexAI embeddings. This should be a path to a service account credential file in JSON format, as accepted by langchain -
RAG_CHECK_EMBEDDING_CTX_LENGTH(Optional) Default is true, disabling this will send raw input to the embedder, use this for custom embedding models.
Make sure to set these environment variables before running the application. You can set them in a .env file or as system environment variables.
Instead of using the default pgvector, we could use Atlas MongoDB as the vector database. To do so, set the following environment variables
VECTOR_DB_TYPE=atlas-mongo ATLAS_MONGO_DB_URI=<mongodb+srv://...> COLLECTION_NAME=<vector collection> ATLAS_SEARCH_INDEX=<vector search index>
The ATLAS_MONGO_DB_URI could be the same or different from what is used by LibreChat. Even if it is the same, the $COLLECTION_NAME collection needs to be a completely new one, separate from all collections used by LibreChat. In addition, create a vector search index for collection above (remember to assign $ATLAS_SEARCH_INDEX) with the following json:
{
"fields": [
{
"numDimensions": 1536,
"path": "embedding",
"similarity": "cosine",
"type": "vector"
},
{
"path": "file_id",
"type": "filter"
}
]
}Follow one of the four documented methods to create the vector index.
When using the RAG API with LibreChat and you need to configure proxy settings, you can set the HTTP_PROXY and HTTPS_PROXY environment variables in the docker-compose.override.yml file (from the LibreChat repository):
rag_api: environment: - HTTP_PROXY=<your-proxy> - HTTPS_PROXY=<your-proxy>
This configuration will ensure that all HTTP/HTTPS requests from the RAG API container are routed through your specified proxy server.
Make sure your RDS Postgres instance adheres to this requirement:
The pgvector extension version 0.5.0 is available on database instances in Amazon RDS running PostgreSQL 15.4-R2 and higher, 14.9-R2 and higher, 13.12-R2 and higher, and 12.16-R2 and higher in all applicable AWS Regions, including the AWS GovCloud (US) Regions.
In order to setup RDS Postgres with RAG API, you can follow these steps:
-
Create a RDS Instance/Cluster using the provided AWS Documentation.
-
Login to the RDS Cluster using the Endpoint connection string from the RDS Console or from your IaC Solution output.
-
The login is via the Master User.
-
Create a dedicated database for rag_api:
create database rag_api;. -
Create a dedicated user\role for that database:
create role rag; -
Switch to the database you just created:
\c rag_api -
Enable the Vector extension:
create extension vector; -
Use the documentation provided above to set up the connection string to the RDS Postgres Instance\Cluster.
Notes:
- Even though you're logging with a Master user, it doesn't have all the super user privileges, that's why we cannot use the command:
create role x with superuser; - If you do not enable the extension, rag_api service will throw an error that it cannot create the extension due to the note above.
Run the following commands to install pre-commit formatter, which uses black code formatter:
pip install pre-commit pre-commit install
For rapid development and testing without long Docker builds:
# Start demo with code mounted as volume (fast updates) docker-compose -f docker-compose.demo.yaml -f docker-compose.dev.yaml up -d # Test API endpoints ./test-quick.sh # Access Swagger UI (no auth required in demo) open http://localhost:8000/docs
Benefits:
- ✅ Code changes apply instantly (no rebuild)
- ✅ Starts in ~10 seconds vs 10+ minutes
- ✅ Perfect for development and debugging
-
Enable Slack routes (already done in main.py):
from app.dash_assistant.slack import router as slack_router app.include_router(slack_router)
-
Create ngrok tunnel:
ngrok http 8000 # Use the HTTPS URL in Slack App settings -
Configure Slack App at https://api.slack.com/apps:
- Slash Commands:
/dash-search→https://your-ngrok-url/slack/command - Interactivity: On →
https://your-ngrok-url/slack/interactive - OAuth Scopes:
commands,chat:write - Reinstall to Workspace
- Slash Commands:
/dash-search retention
Returns formatted cards with 👍/👎 feedback buttons.
curl https://your-ngrok-url/slack/health
# {"status":"healthy","service":"slack-integration"}| Mode | Command | Use Case | Speed |
|---|---|---|---|
| Fast Dev | docker-compose -f docker-compose.demo.yaml -f docker-compose.dev.yaml up -d |
Development, debugging | ~10s |
| Full Build | docker-compose -f docker-compose.demo.yaml up -d --build |
Production testing | ~10min |
- ✅ No Authentication required (DEMO_MODE=true)
- ✅ Mock Embeddings (no OpenAI API key needed)
- ✅ Sample Data (2 dashboards, 4 charts)
- ✅ Full Search (FTS + Vector + Trigram)
- ✅ Query Logging and Feedback Tracking
- ✅ Slack Integration with interactive buttons