Retain and revalidate interrupted searches, resolve abandoned provider calls, recover invalid source reports privately, and expose only declared sources. Improve Persian delivery and provider event replay capacity. Include regression coverage and contract updates.
For the current modular document/voice backend, use the Phase 4 startup and recovery guide and acceptance evidence. Install .[api,voice,embedding], apply online migrations, and run one python -m app.server process with a separate python -m app.worker. Service readiness does not certify calibrated retrieval or usable grounded voice. The paragraphs and prototype walkthrough below preserve older checkpoints.
Phase 6 adds integration validation and operator handoff, redacted worker heartbeat/stage diagnostics and an opt-in real-provider smoke command. The existing chat retriever still uses Chroma/FastEmbed and does not search uploaded PostgreSQL chunks. Scoped pgvector search and authorized knowledge selection are the next milestone; published documents remain inactive.
Current target: the English LangChain Live document MVP, with new browser uploads and direct Persian speech-to-speech. Ingestion Phases 1-4 plus the Phase 5 worker, publication and retry are implemented. Durable review decisions/resume and factual FAQ inclusion are implemented behind trusted backend services. Scoped uploaded-document retrieval, HTTP identity/upload/review transport, Live and UI remain planned. See documentation and implementation order and recorded setup/validation. The four sample files are acceptance examples, not the accepted corpus. The startup/API details below describe the legacy prototype.
🤖 Technical Documentation Assistant (RAG Agent)
A Retrieval-Augmented Generation (RAG) prototype built with FastAPI, LangGraph, LangChain, and ChromaDB. The sections below document that existing Markdown/text prototype. The target Live MVP will connect the separate PostgreSQL/pgvector ingestion pipeline through shared LangChain retrieval; production readiness and zero-hallucination behavior are not established.
📑 Table of Contents
- Key Features
- Architecture & Workflow
- Project Structure
- Tech Stack
- Getting Started
- Running the Application
- API Reference
- Adding Custom Documentation
- Contributing
- License
✨ Key Features
- Autonomous Agentic RAG (LangGraph): Uses a compiled
StateGraphwith conditional tool routing (tools_condition), cyclical reasoning loops, and multi-turn conversational memory (MemorySaver). - Intent Distillation & Query Reformulation: Analyzes incoming natural language queries and distills them into high-precision technical search terms before invoking vector retrieval.
- Strict Grounded Reasoning & Anti-Hallucination: System prompts mandate that answers are strictly based on retrieved documentation chunks. If context is missing, the agent explicitly clarifies or states its limitations.
- Document Source Citations: Automatically tracks and references origin files (e.g.,
fastapi_handling_errors.md) in responses. - Fast Local Embeddings: Utilizes
FastEmbed(BAAI/bge-small-en-v1.5) for lightweight, high-performance CPU/GPU vector embeddings without incurring third-party embedding API costs. - Persistent ChromaDB Store: Automated document ingestion, chunking via
RecursiveCharacterTextSplitter, and persistent vector indexing. - Asynchronous REST API: Powered by FastAPI with Pydantic validation, CORS middleware, and automatic Swagger/ReDoc OpenAPI documentation.
🏛️ Architecture & Workflow
flowchart TD
User([User / Client]) -->|POST /api/v1/chat| API[FastAPI Router]
API --> AgentExec[LangGraph Agent Engine]
subgraph LangGraph ["LangGraph Agent Loop"]
AgentExec --> AgentNode[Agent Node: LLM Reasoning]
AgentNode -->|Inspect Query| IntentCheck{Needs Retrieval?}
IntentCheck -->|Ambiguous| Clarify[Ask Clarifying Questions]
IntentCheck -->|Clear Technical Query| ToolCall[Reformulate Query & Call Tool]
ToolCall --> RetrieverTool[retriever_tool]
RetrieverTool --> ToolNode[Tool Execution Node]
ToolNode --> ContextRetriever[Context Retriever]
ContextRetriever --> ChromaDB[(Chroma Vector Store)]
ChromaDB -->|Top-K Chunks| RetrieverTool
ToolNode -->|Document Context| AgentNode
AgentNode -->|Final Answer + Citations| Checkpoint[MemorySaver State Checkpointer]
end
Checkpoint --> Response[Format ChatResponse]
Response --> User
📁 Project Structure
rag-technical-docs-assistant/
├── app/
│ ├── __init__.py # Application package init
│ ├── main.py # FastAPI entrypoint, middleware & routers
│ ├── api/
│ │ ├── __init__.py # API routers package
│ │ └── v1/
│ │ ├── __init__.py # API v1 package
│ │ └── chat.py # Chat endpoint handler (POST /api/v1/chat)
│ ├── core/
│ │ ├── __init__.py # Core package
│ │ └── config.py # Pydantic Settings and environment config
│ ├── schemas/
│ │ ├── __init__.py # Schemas package
│ │ └── chat.py # ChatRequest and ChatResponse models
│ └── services/
│ ├── __init__.py # Services package
│ ├── doc_processor.py # Markdown document loader and text chunker
│ ├── retriever.py # ContextRetriever with FastEmbed & ChromaDB
│ ├── agent/
│ │ ├── __init__.py # Agent package
│ │ ├── prompt.py # System prompts and prompt templates
│ │ └── exec.py # LangGraph workflow, state graph, and executor
│ └── tools/
│ ├── __init__.py # Tools package
│ └── retriever_tool.py # LangChain @tool for documentation retrieval
├── data/
│ ├── documents/ # Raw markdown technical documentation files
│ │ ├── fastapi_handling_errors.md
│ │ ├── fastapi_settings.md
│ │ └── _style_guide.md
│ └── vector_db/ # Persistent ChromaDB vector database files
├── tests/ # Automated tests directory
├── .env.example # Example environment variables template
├── .gitignore # Git ignore patterns
└── README.md # Project documentation
🛠️ Tech Stack
- Framework: FastAPI
- Agent Workflow: LangGraph
- LLM Orchestration: LangChain & LangChain-OpenAI
- Vector Database: ChromaDB
- Embeddings: FastEmbed (
BAAI/bge-small-en-v1.5) - Data Validation & Settings: Pydantic & pydantic-settings
- Server: Uvicorn
🚀 Getting Started
Prerequisites
- Python 3.11+ installed on your machine.
- An API key for an OpenAI-compatible provider (such as OpenRouter or OpenAI).
Installation
-
Clone the repository:
git clone https://github.com/11linear11/rag-technical-docs-assistant.git cd rag-technical-docs-assistant -
Create and activate a virtual environment:
# On Linux/macOS python3 -m venv .venv source .venv/bin/activate # On Windows python -m venv .venv .venv\Scripts\activate -
Install dependencies:
pip install -e ".[prototype]"(Or install the core packages:
fastapi uvicorn langgraph langchain langchain-openai langchain-chroma chromadb fastembed pydantic-settings)
Environment Configuration
Copy the sample environment file .env.example to .env:
cp .env.example .env
Edit .env and fill in your settings:
# Application Settings
APP_NAME="Technical Documentation Assistant"
APP_VERSION="1.0.0"
APP_ENVIRONMENT="development"
# LLM Configuration (OpenRouter, OpenAI, or any OpenAI-compatible provider)
API_KEY="your_api_key_here"
LLM_BASE_URL="https://openrouter.ai/api/v1"
LLM_MODEL="gpt-4o-mini"
LLM_TEMPERATURE=0.0
LLM_MAX_TOKENS=2048
LLM_MAX_ITERATIONS=3
# RAG & Storage Configuration
CHUNK_SIZE=1000
CHUNK_OVERLAP=200
DOCS_DIR="./data/documents"
CHROMA_PERSIST_DIR="./data/vector_db"
| Variable | Type | Default | Description |
|---|---|---|---|
APP_NAME |
str |
Technical Documentation Assistant |
Name of the application |
APP_VERSION |
str |
1.0.0 |
Application release version |
APP_ENVIRONMENT |
str |
development |
Deployment environment (development, production) |
API_KEY |
str |
(Required) | API key for LLM provider |
LLM_BASE_URL |
str |
https://openrouter.ai/api/v1 |
Base URL for LLM API |
LLM_MODEL |
str |
gpt-4o-mini |
LLM model identifier |
LLM_TEMPERATURE |
float |
0.0 |
Sampling temperature for LLM completions |
LLM_MAX_TOKENS |
int |
2048 |
Max tokens generated per completion |
LLM_MAX_ITERATIONS |
int |
3 |
Maximum agent reasoning loop iterations |
CHUNK_SIZE |
int |
1000 |
Character size for document chunking |
CHUNK_OVERLAP |
int |
200 |
Overlap character count between chunks |
DOCS_DIR |
str |
./data/documents |
Path to directory containing source Markdown docs |
CHROMA_PERSIST_DIR |
str |
./data/vector_db |
Path where Chroma database is persisted |
💻 Running the Application
Starting the FastAPI Server
Start the application with Uvicorn:
python -m app.server --host 0.0.0.0 --port 8000
- Interactive Swagger Documentation: http://localhost:8000/docs
- ReDoc Documentation: http://localhost:8000/redoc
Running the CLI Test Harness
You can test the agent directly from your terminal:
python -m app.services.agent.exec
📡 API Reference
1. Health Check
Checks if the service is running and ready.
- URL:
/api/v1/health - Method:
GET - Response:
200 OK
{
"status": "healthy"
}
2. Chat with Assistant
Sends a query to the agent. Supports stateful conversations using thread_id.
- URL:
/api/v1/chat - Method:
POST - Headers:
Content-Type: application/json
Request Body
{
"query": "How can I implement custom exception handlers in FastAPI?",
"thread_id": "optional-session-uuid-or-id"
}
Note
: If
thread_idis omitted, the system generates a new UUID and preserves the conversation context for subsequent requests using that returnedthread_id.
cURL Example
curl -X POST "http://localhost:8000/api/v1/chat" \
-H "Content-Type: application/json" \
-d '{
"query": "How do I handle custom exceptions in FastAPI?",
"thread_id": "session-123"
}'
Successful Response (200 OK)
{
"response": "To handle custom exceptions in FastAPI, you can define a custom exception class and register an `@app.exception_handler`...\n\n**Source:** `fastapi_handling_errors.md`",
"thread_id": "session-123"
}
📚 Adding Custom Documentation
- Place any Markdown (
.md) files into thedata/documents/directory. - If the vector database (
data/vector_db/) already exists and you want to trigger a complete re-index, simply remove the existing database folder:rm -rf ./data/vector_db - Restart the service or run the agent. The
ContextRetrieverwill automatically detect the missing store, load all.mdfiles, chunk them, compute embeddings using FastEmbed, and persist the new vector database.
🤝 Contributing
Contributions are welcome! To contribute:
- Fork the repository.
- Create your feature branch (
git checkout -b feature/amazing-feature). - Commit your changes (
git commit -m 'Add amazing feature'). - Push to the branch (
git push origin feature/amazing-feature). - Open a Pull Request.
📄 License
This project is open-source and licensed under the MIT License.
Live uses the bounded single-process entrypoint above; run ingestion separately with
python -m app.worker. See the voice integration guide
for backend provider settings, transport limits, recovery and acceptance prerequisites.
Document/knowledge endpoints and backend-only INGEST_OCR_REVIEW_REQUIRED
(default true) are documented in the Phase 3 frontend handoff.
API and worker must share immutable original/extraction storage. New job profiles
freeze the OCR gate; existing/legacy jobs and factual review remain unchanged.