docs: reconcile project status and local stack operations
Refresh entry points and progress checkpoints, document schema revision 0006, and consolidate the final ElevenLabs/GapGPT profile and host prerequisites. Preserve dated activation evidence and distinguish implementation, targeted validation, incomplete full-suite checks and remaining human acceptance gates. Validation: 409 local Markdown link targets resolved and staged whitespace checks passed.
This commit is contained in:
@@ -1,333 +1,72 @@
|
||||
For the current modular document/voice backend, use the [Phase 4 startup and recovery guide](docs/guides/phase4-backend-operations.md) and [acceptance evidence](docs/guides/realtime-agent-phase4-acceptance.md). 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](docs/guides/ingestion-operator-handoff.md), 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](docs/specifications/RAG-AI-Phase1-Delivery-Plan.md), with new browser uploads and direct Persian speech-to-speech. Ingestion Phases 1-4 plus the [Phase 5 worker, publication and retry](docs/guides/worker-orchestration.md) 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](docs/README.md) and [recorded setup/validation](docs/guides/ingestion-foundation-setup.md). 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)
|
||||
|
||||
[](https://fastapi.tiangolo.com)
|
||||
[](https://github.com/langchain-ai/langgraph)
|
||||
[](https://github.com/langchain-ai/langchain)
|
||||
[](https://www.trychroma.com/)
|
||||
[-blue.svg?style=flat-square)](https://github.com/qdrant/fastembed)
|
||||
[](https://www.python.org/)
|
||||
[](LICENSE)
|
||||
|
||||
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](#-key-features)
|
||||
- [Architecture & Workflow](#-architecture--workflow)
|
||||
- [Project Structure](#-project-structure)
|
||||
- [Tech Stack](#-tech-stack)
|
||||
- [Getting Started](#-getting-started)
|
||||
- [Prerequisites](#prerequisites)
|
||||
- [Installation](#installation)
|
||||
- [Environment Configuration](#environment-configuration)
|
||||
- [Running the Application](#-running-the-application)
|
||||
- [Starting the FastAPI Server](#starting-the-fastapi-server)
|
||||
- [Running the CLI Test Harness](#running-the-cli-test-harness)
|
||||
- [API Reference](#-api-reference)
|
||||
- [Health Check](#1-health-check)
|
||||
- [Chat with Assistant](#2-chat-with-assistant)
|
||||
- [Adding Custom Documentation](#-adding-custom-documentation)
|
||||
- [Contributing](#-contributing)
|
||||
- [License](#-license)
|
||||
|
||||
---
|
||||
|
||||
## ✨ Key Features
|
||||
|
||||
- **Autonomous Agentic RAG (LangGraph)**: Uses a compiled `StateGraph` with 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
|
||||
|
||||
```mermaid
|
||||
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
|
||||
|
||||
```text
|
||||
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](https://fastapi.tiangolo.com/)
|
||||
- **Agent Workflow**: [LangGraph](https://github.com/langchain-ai/langgraph)
|
||||
- **LLM Orchestration**: [LangChain](https://github.com/langchain-ai/langchain) & [LangChain-OpenAI](https://github.com/langchain-ai/langchain-openai)
|
||||
- **Vector Database**: [ChromaDB](https://www.trychroma.com/)
|
||||
- **Embeddings**: [FastEmbed](https://github.com/qdrant/fastembed) (`BAAI/bge-small-en-v1.5`)
|
||||
- **Data Validation & Settings**: [Pydantic](https://docs.pydantic.dev/) & [pydantic-settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/)
|
||||
- **Server**: [Uvicorn](https://www.uvicorn.org/)
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Getting Started
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- **Python 3.11+** installed on your machine.
|
||||
- An API key for an OpenAI-compatible provider (such as [OpenRouter](https://openrouter.ai/) or [OpenAI](https://platform.openai.com/)).
|
||||
|
||||
### Installation
|
||||
|
||||
1. **Clone the repository:**
|
||||
```bash
|
||||
git clone https://github.com/11linear11/rag-technical-docs-assistant.git
|
||||
cd rag-technical-docs-assistant
|
||||
```
|
||||
|
||||
2. **Create and activate a virtual environment:**
|
||||
```bash
|
||||
# On Linux/macOS
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
|
||||
# On Windows
|
||||
python -m venv .venv
|
||||
.venv\Scripts\activate
|
||||
```
|
||||
|
||||
3. **Install dependencies:**
|
||||
```bash
|
||||
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`:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
Edit `.env` and fill in your settings:
|
||||
|
||||
```env
|
||||
# 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:
|
||||
|
||||
```bash
|
||||
python -m app.server --host 0.0.0.0 --port 8000
|
||||
```
|
||||
|
||||
- **Interactive Swagger Documentation**: [http://localhost:8000/docs](http://localhost:8000/docs)
|
||||
- **ReDoc Documentation**: [http://localhost:8000/redoc](http://localhost:8000/redoc)
|
||||
|
||||
### Running the CLI Test Harness
|
||||
|
||||
You can test the agent directly from your terminal:
|
||||
|
||||
```bash
|
||||
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`
|
||||
|
||||
```json
|
||||
{
|
||||
"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
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "How can I implement custom exception handlers in FastAPI?",
|
||||
"thread_id": "optional-session-uuid-or-id"
|
||||
}
|
||||
```
|
||||
|
||||
> **Note**: If `thread_id` is omitted, the system generates a new UUID and preserves the conversation context for subsequent requests using that returned `thread_id`.
|
||||
|
||||
#### cURL Example
|
||||
|
||||
```bash
|
||||
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`)
|
||||
|
||||
```json
|
||||
{
|
||||
"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
|
||||
|
||||
1. Place any Markdown (`.md`) files into the `data/documents/` directory.
|
||||
2. If the vector database (`data/vector_db/`) already exists and you want to trigger a complete re-index, simply remove the existing database folder:
|
||||
```bash
|
||||
rm -rf ./data/vector_db
|
||||
```
|
||||
3. Restart the service or run the agent. The `ContextRetriever` will automatically detect the missing store, load all `.md` files, chunk them, compute embeddings using FastEmbed, and persist the new vector database.
|
||||
|
||||
---
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
Contributions are welcome! To contribute:
|
||||
|
||||
1. Fork the repository.
|
||||
2. Create your feature branch (`git checkout -b feature/amazing-feature`).
|
||||
3. Commit your changes (`git commit -m 'Add amazing feature'`).
|
||||
4. Push to the branch (`git push origin feature/amazing-feature`).
|
||||
5. Open a Pull Request.
|
||||
|
||||
---
|
||||
|
||||
## 📄 License
|
||||
|
||||
This project is open-source and licensed under the [MIT License](LICENSE).
|
||||
Live uses the bounded single-process entrypoint above; run ingestion separately with
|
||||
`python -m app.worker`. See the [voice integration guide](docs/guides/frontend-voice-integration-example.md)
|
||||
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](docs/guides/realtime-agent-phase3-handoff.md).
|
||||
API and worker must share immutable original/extraction storage. New job profiles
|
||||
freeze the OCR gate; existing/legacy jobs and factual review remain unchanged.
|
||||
# Technical Documentation Assistant
|
||||
|
||||
Phase 1 backend for independently uploaded documents and grounded Persian voice.
|
||||
The application uses a modular FastAPI API, a separate ingestion worker,
|
||||
PostgreSQL/pgvector, durable original/extraction storage, and backend-owned search.
|
||||
The Angular frontend is maintained in the sibling faq_chatbot_frontend repository.
|
||||
|
||||
Start with [current status](docs/current-status.md), the
|
||||
[documentation index](docs/README.md), and the
|
||||
[startup and recovery guide](docs/guides/phase4-backend-operations.md).
|
||||
The [local Windows runbook](docs/guides/current-local-stack.md) describes the
|
||||
last recorded isolated speech stack; it is not a production deployment recipe.
|
||||
|
||||
## Current capabilities
|
||||
|
||||
- Authenticated upload, processing status, retained extraction review, retry,
|
||||
active knowledge selection and soft deletion with request replay protection.
|
||||
- Immutable independent document IDs, fenced worker publication and
|
||||
organization-scoped retrieval over eligible uploaded PostgreSQL chunks.
|
||||
- Shared backend search and private voice adapters for OpenAI, Gemini and the
|
||||
development-only Local S2S engine, with pinned session profiles.
|
||||
- Local strict extractive grounding before TTS and up to ten whole source chunks
|
||||
within 12,000 characters. This is not a guarantee that uploaded facts are true.
|
||||
- Public model identifiers and allowed voice-provider selection; arbitrary model,
|
||||
credential and general settings editing remain deferred.
|
||||
|
||||
Implementation, fixture tests, real-provider checks and human acceptance are
|
||||
separate claims. See [current status and remaining gates](docs/current-status.md).
|
||||
|
||||
## Setup
|
||||
|
||||
Python 3.11+, PostgreSQL with pgvector and configured provider access are required.
|
||||
Use the frozen embedding profile and durable directories for the target database.
|
||||
Never change an existing embedding identity merely to make startup succeed.
|
||||
|
||||
~~~powershell
|
||||
.venv/Scripts/python -m pip install -e ".[api,voice,embedding,test]"
|
||||
.venv/Scripts/alembic upgrade head
|
||||
.venv/Scripts/python -m app.server --host 127.0.0.1 --port 8080
|
||||
# Separate process, with an authorized ingestion queue:
|
||||
.venv/Scripts/python -m app.worker
|
||||
~~~
|
||||
|
||||
Configure from [.env.example](.env.example). Provision a new installation with
|
||||
app.bootstrap/app.provision as described in the operations guide. Persistent
|
||||
provider keys stay server-side. The supported voice API entry point is app.server.
|
||||
|
||||
The current Live schema requirement is 0006_voice_model_settings. Apply forward
|
||||
migrations before starting the API; do not edit applied revisions.
|
||||
|
||||
## Validation
|
||||
|
||||
~~~powershell
|
||||
.venv/Scripts/python -m pytest -m "not postgres"
|
||||
.venv/Scripts/python -m pytest -m postgres --require-postgres
|
||||
git diff --check
|
||||
~~~
|
||||
|
||||
PostgreSQL acceptance requires an isolated TEST_DATABASE_URL and pgvector;
|
||||
missing configuration must fail acceptance. Ordinary skips are not database proof.
|
||||
See [test guidance](tests/README.md). No build/lint pipeline is defined here.
|
||||
|
||||
## Scope and legacy prototype
|
||||
|
||||
The [Phase 1 delivery plan](docs/specifications/RAG-AI-Phase1-Delivery-Plan.md)
|
||||
governs scope, with dated authorized amendments indexed in the reference map.
|
||||
Full text history and general settings editing remain deferred.
|
||||
|
||||
The older app.main / app.services agent uses Chroma/FastEmbed and the optional
|
||||
prototype dependencies. That path does not represent uploaded-document search
|
||||
or the supported modular voice startup. Project specifications under docs are
|
||||
not organization knowledge and must not be ingested as the user corpus.
|
||||
|
||||
Reference in New Issue
Block a user