From cb54a35c90e923fdf9dd90459a880fdd7015f191 Mon Sep 17 00:00:00 2001 From: 11linear11 <11linearlin11@gmail.com> Date: Mon, 31 Aug 2026 07:13:50 -0400 Subject: [PATCH] doc update --- README.md | 320 ++++++++++++++++++++++++++- app/__init__.py | 1 + app/api/__init__.py | 1 + app/api/v1/__init__.py | 1 + app/api/v1/chat.py | 44 +++- app/core/__init__.py | 1 + app/core/config.py | 47 +++- app/main.py | 28 ++- app/schemas/__init__.py | 1 + app/schemas/chat.py | 47 +++- app/services/__init__.py | 1 + app/services/agent/__init__.py | 1 + app/services/agent/exec.py | 111 ++++++---- app/services/agent/prompt.py | 11 +- app/services/doc_processor.py | 41 +++- app/services/retriever.py | 63 ++++-- app/services/tools/__init__.py | 1 + app/services/tools/retriever_tool.py | 31 ++- 18 files changed, 653 insertions(+), 98 deletions(-) diff --git a/README.md b/README.md index a87c642..500f5b9 100644 --- a/README.md +++ b/README.md @@ -1 +1,319 @@ -# rag-technical-docs-assistant \ No newline at end of file +# 🤖 Technical Documentation Assistant (RAG Agent) + +[![FastAPI](https://img.shields.io/badge/FastAPI-0.115+-009688.svg?style=flat-square&logo=FastAPI&logoColor=white)](https://fastapi.tiangolo.com) +[![LangGraph](https://img.shields.io/badge/LangGraph-StateGraph-FF4F00.svg?style=flat-square&logo=python&logoColor=white)](https://github.com/langchain-ai/langgraph) +[![LangChain](https://img.shields.io/badge/LangChain-1.x-1C3C3C.svg?style=flat-square&logo=langchain&logoColor=white)](https://github.com/langchain-ai/langchain) +[![ChromaDB](https://img.shields.io/badge/VectorDB-ChromaDB-FF6F00.svg?style=flat-square)](https://www.trychroma.com/) +[![FastEmbed](https://img.shields.io/badge/Embeddings-FastEmbed%20(BGE--Small)-blue.svg?style=flat-square)](https://github.com/qdrant/fastembed) +[![Python](https://img.shields.io/badge/Python-3.10%2B-3776AB.svg?style=flat-square&logo=python&logoColor=white)](https://www.python.org/) +[![License](https://img.shields.io/badge/License-MIT-green.svg?style=flat-square)](LICENSE) + +An intelligent, production-ready **Retrieval-Augmented Generation (RAG)** assistant built with **FastAPI**, **LangGraph**, **LangChain**, and **ChromaDB**. The assistant is specialized in indexing, searching, and reasoning over technical documentation to provide developers with accurate, source-grounded answers and production-ready code examples with zero hallucinations. + +--- + +## 📑 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.10+** 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 -r requirements.txt + ``` + *(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 +uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload +``` + +- **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). \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py index e69de29..20dab09 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -0,0 +1 @@ +"""Technical Documentation Assistant Application Package.""" diff --git a/app/api/__init__.py b/app/api/__init__.py index e69de29..010fe3a 100644 --- a/app/api/__init__.py +++ b/app/api/__init__.py @@ -0,0 +1 @@ +"""API routers package.""" diff --git a/app/api/v1/__init__.py b/app/api/v1/__init__.py index e69de29..5df4630 100644 --- a/app/api/v1/__init__.py +++ b/app/api/v1/__init__.py @@ -0,0 +1 @@ +"""API version 1 endpoints package.""" diff --git a/app/api/v1/chat.py b/app/api/v1/chat.py index 2505c40..34d93b6 100644 --- a/app/api/v1/chat.py +++ b/app/api/v1/chat.py @@ -1,18 +1,50 @@ -from fastapi import APIRouter,status, HTTPException +"""Chat API Endpoints (v1). + +Exposes the REST API route for interacting with the LangGraph RAG Agent. +""" + +import uuid +from fastapi import APIRouter, HTTPException, status + from app.schemas.chat import ChatRequest, ChatResponse from app.services.agent.exec import chat_with_agent -import uuid router = APIRouter( prefix="/chat", - tags=["Chat"] + tags=["Chat"], ) -@router.post("",response_model=ChatResponse,status_code=status.HTTP_200_OK) -async def chat(request: ChatRequest ): + +@router.post( + "", + response_model=ChatResponse, + status_code=status.HTTP_200_OK, + summary="Chat with Technical Documentation Assistant", + description=( + "Sends a query to the LangGraph RAG assistant. The assistant retrieves relevant " + "technical documentation chunks, reasons over them, and generates an accurate, " + "grounded response with document citations." + ), +) +async def chat(request: ChatRequest) -> ChatResponse: + """Handle chat queries and dispatch them to the LangGraph agent. + + Args: + request (ChatRequest): The incoming chat request containing query and optional thread_id. + + Returns: + ChatResponse: The agent's grounded response and session thread_id. + + Raises: + HTTPException: If an unexpected error occurs during agent execution. + """ try: + # Use existing thread_id or generate a new UUID for session persistence session_id = request.thread_id or str(uuid.uuid4()) response = await chat_with_agent(request.query, session_id) return ChatResponse(response=response, thread_id=session_id) except Exception as e: - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)) \ No newline at end of file + raise HTTPException( + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, + detail=f"An error occurred while processing your request: {str(e)}", + ) \ No newline at end of file diff --git a/app/core/__init__.py b/app/core/__init__.py index e69de29..9df2a6e 100644 --- a/app/core/__init__.py +++ b/app/core/__init__.py @@ -0,0 +1 @@ +"""Core configuration and settings module.""" diff --git a/app/core/config.py b/app/core/config.py index b04c122..bc4e974 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -1,32 +1,59 @@ -# pyrefly: ignore [missing-import] -from pydantic_settings import BaseSettings,SettingsConfigDict +"""Application Configuration Module. + +Loads and validates configuration settings from environment variables and `.env` file +using Pydantic Settings. +""" + +from pydantic_settings import BaseSettings, SettingsConfigDict + class Settings(BaseSettings): + """Global application settings and configuration schema. + + Attributes: + app_name (str): The name of the application. + app_version (str): The current release version of the application. + app_environment (str): Operational environment ('development', 'production', etc.). + app_description (str): Short description of the service for OpenAPI docs. + api_key (str): API key for the LLM provider (e.g. OpenAI / OpenRouter). + llm_base_url (str): Base URL endpoint for the LLM API. + llm_model (str): Name of the language model to invoke. + llm_temperature (float): Sampling temperature for response generation. + llm_max_tokens (int): Maximum output tokens per LLM completion. + llm_max_iterations (int): Maximum agent reasoning iterations before termination. + chunk_size (int): Character chunk size for splitting markdown documents. + chunk_overlap (int): Overlap character count between consecutive chunks. + docs_dir (str): Filepath directory containing raw documentation markdown files. + chroma_persist_dir (str): Directory path where the Chroma vector store is persisted. + """ + # App Config app_name: str = "Technical Documentation Assistant" app_version: str = "1.0.0" - app_environment: str = "development" # development,production - app_description: str = "just a assistant" + app_environment: str = "development" # Options: development, staging, production + app_description: str = "An intelligent RAG-powered technical documentation assistant." # LLM Config api_key: str llm_base_url: str llm_model: str - llm_temperature: float - llm_max_tokens: int + llm_temperature: float = 0.0 + llm_max_tokens: int = 2048 llm_max_iterations: int = 3 - - # RAG Config + # RAG & Vector Store Config chunk_size: int = 1000 chunk_overlap: int = 200 docs_dir: str = "./data/documents" chroma_persist_dir: str = "./data/vector_db" - + model_config = SettingsConfigDict( env_file=".env", env_file_encoding="utf-8", - extra="ignore" + extra="ignore", ) + +# Singleton instance of application settings settings = Settings() + diff --git a/app/main.py b/app/main.py index b66612d..e6a3207 100644 --- a/app/main.py +++ b/app/main.py @@ -1,15 +1,25 @@ -# pyrefly: ignore [missing-import] +"""Main FastAPI Application Entrypoint. + +Initializes the FastAPI application, sets up CORS middleware, registers API routes, +and provides system health check endpoints. +""" + from fastapi import FastAPI -from app.api.v1.chat import router as chat_router -from app.core.config import settings from fastapi.middleware.cors import CORSMiddleware +from app.api.v1.chat import router as chat_router +from app.core.config import settings + +# Initialize FastAPI application instance app = FastAPI( title=settings.app_name, version=settings.app_version, description=settings.app_description, + docs_url="/docs", + redoc_url="/redoc", ) +# Configure Cross-Origin Resource Sharing (CORS) middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], @@ -18,8 +28,16 @@ app.add_middleware( allow_headers=["*"], ) +# Register API v1 routers app.include_router(chat_router, prefix="/api/v1") -@app.get("/api/v1/health", tags=["Health"]) -async def health_check(): + +@app.get( + "/api/v1/health", + tags=["Health"], + summary="Health Check", + description="Check the operational health and readiness of the service.", +) +async def health_check() -> dict[str, str]: + """Return the service health status.""" return {"status": "healthy"} \ No newline at end of file diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py index e69de29..efca522 100644 --- a/app/schemas/__init__.py +++ b/app/schemas/__init__.py @@ -0,0 +1 @@ +"""Data schemas and request/response models package.""" diff --git a/app/schemas/chat.py b/app/schemas/chat.py index 2cae279..f7c2a46 100644 --- a/app/schemas/chat.py +++ b/app/schemas/chat.py @@ -1,11 +1,48 @@ -from pydantic import BaseModel, Field +"""Chat schemas module. + +Defines Pydantic request and response models for the chat endpoints. +""" + from typing import Optional +from pydantic import BaseModel, Field + class ChatRequest(BaseModel): - query: str = Field(...,min_length=1,description="The query to be asked to the agent") - thread_id: Optional[str] = Field(None,description="The thread id to be used for the query") + """Request schema for interacting with the AI documentation agent. + + Attributes: + query (str): The user's query or prompt. Must be non-empty. + thread_id (Optional[str]): Unique thread/session ID for conversation state persistence. + """ + + query: str = Field( + ..., + min_length=1, + description="The technical query or question asked to the assistant.", + examples=["How do I create custom exception handlers in FastAPI?"], + ) + thread_id: Optional[str] = Field( + None, + description="Unique thread identifier for multi-turn conversational memory. If omitted, a new UUID is generated.", + examples=["550e8400-e29b-41d4-a716-446655440000"], + ) + class ChatResponse(BaseModel): - response: str - thread_id: str + """Response schema returned by the AI documentation agent. + + Attributes: + response (str): The generated response text grounded in documentation. + thread_id (str): The active thread identifier for the ongoing conversation. + """ + + response: str = Field( + ..., + description="The assistant's generated response, grounded in technical documentation and containing citations.", + ) + thread_id: str = Field( + ..., + description="The session/thread identifier used for this interaction.", + ) + diff --git a/app/services/__init__.py b/app/services/__init__.py index e69de29..8e6f56b 100644 --- a/app/services/__init__.py +++ b/app/services/__init__.py @@ -0,0 +1 @@ +"""Core business logic and RAG pipeline services package.""" diff --git a/app/services/agent/__init__.py b/app/services/agent/__init__.py index e69de29..ab05e54 100644 --- a/app/services/agent/__init__.py +++ b/app/services/agent/__init__.py @@ -0,0 +1 @@ +"""LangGraph agent package for conversational reasoning and tool execution.""" diff --git a/app/services/agent/exec.py b/app/services/agent/exec.py index 4102dfe..66371d7 100644 --- a/app/services/agent/exec.py +++ b/app/services/agent/exec.py @@ -1,21 +1,28 @@ -# # pyrefly: ignore [missing-import] -from app.services.tools.retriever_tool import retriever_tool -from langchain_openai import ChatOpenAI -from app.core.config import settings -from app.services.agent.prompt import agent_prompt,SYSTEM_PROMPT -from typing import Annotated -from typing_extensions import TypedDict -from langgraph.graph.message import add_messages -from langchain_core.messages import SystemMessage -from langgraph.prebuilt import ToolNode -from langgraph.graph import StateGraph, START, END -from langgraph.prebuilt import tools_condition -from langgraph.checkpoint.memory import MemorySaver +"""LangGraph Agent Execution Engine. + +Builds and compiles a stateful LangGraph agent graph with memory checkpointer, +LLM node with tool-calling capabilities, and conditional tool routing. +""" + import asyncio +from typing import Annotated, Any, Dict +from typing_extensions import TypedDict +from langchain_core.messages import SystemMessage +from langchain_openai import ChatOpenAI +from langgraph.checkpoint.memory import MemorySaver +from langgraph.graph import END, START, StateGraph +from langgraph.graph.message import add_messages +from langgraph.prebuilt import ToolNode, tools_condition +from app.core.config import settings +from app.services.agent.prompt import SYSTEM_PROMPT +from app.services.tools.retriever_tool import retriever_tool + +# List of tools available to the LangGraph agent tools = [retriever_tool] +# Initialize OpenAI-compatible LLM client (OpenRouter, OpenAI, etc.) llm = ChatOpenAI( base_url=settings.llm_base_url, model=settings.llm_model, @@ -25,66 +32,88 @@ llm = ChatOpenAI( ) - class State(TypedDict): - messages: Annotated[list,add_messages] - + """Agent execution state schema containing conversation messages.""" + messages: Annotated[list, add_messages] + + +# Initialize prebuilt tool execution node tool_node = ToolNode(tools) -def call_llm_node(state: State): + +def call_llm_node(state: State) -> Dict[str, Any]: + """Execute the LLM reasoning step with bound tools and system instructions. + + Args: + state (State): Current graph state holding the message history. + + Returns: + Dict[str, Any]: Updated state containing the new LLM message. + """ messages = state["messages"] - system_instruction = SystemMessage( - content=SYSTEM_PROMPT - ) + # Prepend system prompt to guide agent reasoning and retrieval behavior + system_instruction = SystemMessage(content=SYSTEM_PROMPT) full_message = [system_instruction] + messages + # Bind tools to the LLM model llm_with_tool = llm.bind_tools(tools) response = llm_with_tool.invoke(full_message) - return {"messages": [response]} - - +# Construct the LangGraph workflow graph flow = StateGraph(State) -flow.add_node("agent",call_llm_node) -flow.add_node("tools",tool_node) +# Define nodes +flow.add_node("agent", call_llm_node) +flow.add_node("tools", tool_node) +# Define execution edges flow.add_edge(START, "agent") flow.add_conditional_edges( "agent", - tools_condition + tools_condition, # Routes to "tools" if tool calls are requested, else to END ) +flow.add_edge("tools", "agent") -flow.add_edge("tools","agent") - +# Compile graph with in-memory checkpointer for multi-turn session persistence memory = MemorySaver() agent_app = flow.compile(checkpointer=memory) -async def chat_with_agent(query: str, thread_id: str = "default_session"): + +async def chat_with_agent(query: str, thread_id: str = "default_session") -> str: + """Send a user query to the LangGraph agent and retrieve the final response. + + Args: + query (str): The user's input prompt or question. + thread_id (str): Unique thread/session ID to maintain conversational memory. + + Returns: + str: The final textual response generated by the assistant. + """ config = {"configurable": {"thread_id": thread_id}} response = await agent_app.ainvoke( {"messages": [("human", query)]}, - config=config + config=config, ) return response["messages"][-1].content - -async def main(): +async def main() -> None: + """CLI test harness for testing agent retrieval and response generation.""" session_id = "test_user_session" - - # ۱. ارسال سوال تستی - query = "How to handle exceptions in FastAPI?" - print(f"\n[User]: {query}\n" + "-"*40) - - # فراخوانی اولیه - result = await chat_with_agent(query=query, thread_id=session_id) - print(result) -if __name__== "__main__": + # Test query + query = "How to handle exceptions in FastAPI?" + print(f"\n[User]: {query}\n" + "-" * 40) + + # Execute chat invocation + result = await chat_with_agent(query=query, thread_id=session_id) + print(f"\n[Assistant]:\n{result}\n") + + +if __name__ == "__main__": asyncio.run(main()) \ No newline at end of file diff --git a/app/services/agent/prompt.py b/app/services/agent/prompt.py index af338ed..fcaf001 100644 --- a/app/services/agent/prompt.py +++ b/app/services/agent/prompt.py @@ -1,3 +1,10 @@ +"""Agent System Prompt and Template Definitions. + +Defines the system prompt and instructions governing the AI documentation assistant, +enforcing intent distillation, ground truth adherence, hallucination prevention, +and document citations. +""" + from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder SYSTEM_PROMPT = """You are an expert technical assistant specializing in technical documentation, code architectures, and APIs. @@ -9,9 +16,10 @@ Your core workflow & guidelines: - If the request is clear: Identify the underlying technical intent and invoke the `retriever_tool` with an optimized search query. - If the request is ambiguous, vague, or missing critical details (e.g. library name, version, or specific error behavior): DO NOT make blind assumptions or search aimlessly. Instead, directly respond to the user with concise, targeted clarifying questions before retrieving. - Start directly with the answer. Do not include introductory thoughts or meta-announcements about what you retrieved. + 2. Intent-Based Query Reformulation (Crucial): - NEVER pass raw user prompts or conversational filler (e.g., "سلام چطوری میشه فلان کارو کرد") directly to `retriever_tool`. - - Distill the user's request into precise technical keyword + - Distill the user's request into precise technical keywords. 3. Source-Grounded & Hallucination-Free Answers: - When answering, base your response strictly on the retrieved documentation chunks. @@ -22,6 +30,7 @@ Your core workflow & guidelines: - Provide clean, production-ready code snippets with appropriate markdown language identifiers. """ +# Reusable ChatPromptTemplate configured with system instructions and chat memory placeholders agent_prompt = ChatPromptTemplate.from_messages([ ("system", SYSTEM_PROMPT), MessagesPlaceholder(variable_name="chat_history", optional=True), diff --git a/app/services/doc_processor.py b/app/services/doc_processor.py index afe52f7..c1f1af2 100644 --- a/app/services/doc_processor.py +++ b/app/services/doc_processor.py @@ -1,21 +1,45 @@ +"""Document Processing Service. -from app.core.config import settings -# pyrefly: ignore [missing-import] +Loads Markdown technical documentation files from disk and splits them into +chunks using recursive character text splitting for indexing into the vector store. +""" + +from langchain_core.documents import Document from langchain_community.document_loaders import DirectoryLoader, TextLoader -# pyrefly: ignore [missing-import] from langchain_text_splitters import RecursiveCharacterTextSplitter +from app.core.config import settings + + class DocProcessor: - def __init__(self): + """Handles loading and chunking of markdown documentation files.""" + + def __init__(self) -> None: + """Initialize the document processor with configuration parameters.""" self.docs_dir = settings.docs_dir self.chunk_size = settings.chunk_size self.chunk_overlap = settings.chunk_overlap - - def loader_docs(self): - loader = DirectoryLoader(self.docs_dir, glob="**/*.md", loader_cls=TextLoader,loader_kwargs={"encoding":"utf-8"}) + + def loader_docs(self) -> list[Document]: + """Load all Markdown (.md) documents recursively from the configured documents directory. + + Returns: + list[Document]: A list of loaded LangChain Document objects with page content and metadata. + """ + loader = DirectoryLoader( + self.docs_dir, + glob="**/*.md", + loader_cls=TextLoader, + loader_kwargs={"encoding": "utf-8"}, + ) return loader.load() - def process_docs(self): + def process_docs(self) -> list[Document]: + """Load documents and split them into overlapping character chunks. + + Returns: + list[Document]: A list of chunked Document objects ready for embedding generation. + """ docs = self.loader_docs() text_splitter = RecursiveCharacterTextSplitter( chunk_size=self.chunk_size, @@ -25,3 +49,4 @@ class DocProcessor: return text_splitter.split_documents(docs) + diff --git a/app/services/retriever.py b/app/services/retriever.py index 631ae30..82c52a0 100644 --- a/app/services/retriever.py +++ b/app/services/retriever.py @@ -1,39 +1,72 @@ +"""Context Retrieval Service. + +Manages vector embeddings generation using FastEmbed (`BAAI/bge-small-en-v1.5`) +and persistent storage/similarity search with ChromaDB. +""" + +import os +from typing import List +from langchain_core.documents import Document +from langchain_chroma import Chroma +from langchain_community.embeddings import FastEmbedEmbeddings + from app.core.config import settings from app.services.doc_processor import DocProcessor -# pyrefly: ignore [missing-import] -from langchain_chroma import Chroma -# pyrefly: ignore [missing-import] -from langchain_community.embeddings import FastEmbedEmbeddings -import os + class ContextRetriever: - def __init__(self): + """Manages document vectorization, ChromaDB persistence, and semantic search retrieval.""" + + def __init__(self) -> None: + """Initialize the context retriever with FastEmbed and Chroma vector store.""" self.doc_processor = DocProcessor() self.embedding = FastEmbedEmbeddings( model_name="BAAI/bge-small-en-v1.5" ) self.vec_store = self.get_or_create_vector_store() - - def get_or_create_vector_store(self): + + def get_or_create_vector_store(self) -> Chroma: + """Load an existing Chroma vector store if present on disk; otherwise index documents from scratch. + + Returns: + Chroma: Initialized Chroma vector store instance. + """ if os.path.exists(settings.chroma_persist_dir): return Chroma( persist_directory=settings.chroma_persist_dir, - embedding_function=self.embedding + embedding_function=self.embedding, ) else: return self.index_documents() - - def index_documents(self): + def index_documents(self) -> Chroma: + """Process documents from disk, compute dense embeddings, and persist in ChromaDB. + Returns: + Chroma: Vector store populated with indexed document chunks. + """ + processed_docs = self.doc_processor.process_docs() vec_store = Chroma.from_documents( - documents=self.doc_processor.process_docs(), + documents=processed_docs, embedding=self.embedding, - persist_directory=settings.chroma_persist_dir + persist_directory=settings.chroma_persist_dir, ) - print(f"[vector store] Indexed documents at {settings.chroma_persist_dir}") + print(f"[vector store] Indexed {len(processed_docs)} chunks at {settings.chroma_persist_dir}") return vec_store - def retrieve(self,query:str,k=3): + + def retrieve(self, query: str, k: int = 3) -> List[Document]: + """Perform semantic similarity search on the indexed technical documentation. + + Args: + query (str): The search query to find matching documents for. + k (int): Number of top relevant document chunks to retrieve (default: 3). + + Returns: + List[Document]: List of most relevant Document chunks. + """ return self.vec_store.similarity_search(query, k=k) + +# Singleton instance of ContextRetriever for reuse across requests retriever = ContextRetriever() + diff --git a/app/services/tools/__init__.py b/app/services/tools/__init__.py index e69de29..517f568 100644 --- a/app/services/tools/__init__.py +++ b/app/services/tools/__init__.py @@ -0,0 +1 @@ +"""Custom agent tools package.""" diff --git a/app/services/tools/retriever_tool.py b/app/services/tools/retriever_tool.py index 424eaec..0affa36 100644 --- a/app/services/tools/retriever_tool.py +++ b/app/services/tools/retriever_tool.py @@ -1,25 +1,44 @@ -# pyrefly: ignore [missing-import] -from app.services.retriever import retriever +"""Retriever Tool for LangChain and LangGraph Agent. + +Exposes the `retriever_tool` decorated with `@tool` so the LLM agent can autonomously +query the vector database to fetch relevant technical documentation chunks. +""" + from langchain_core.tools import tool +from app.services.retriever import retriever @tool -def retriever_tool(query: str, k: int = 3): +def retriever_tool(query: str, k: int = 3) -> str: """Search and retrieve technical documentation from the vector store. Args: - query: The reformulated, concise technical search query representing the user's core intent (e.g., 'FastAPI custom exception handler', 'Pydantic BaseSettings env configuration'). Do NOT pass raw conversational input directly. + query: The reformulated, concise technical search query representing the user's core intent + (e.g., 'FastAPI custom exception handler', 'Pydantic BaseSettings env configuration'). + Do NOT pass raw conversational input directly. k: Number of relevant documentation chunks to retrieve (default: 3). + + Returns: + str: Formatted context string containing the document sources and chunk text, + or 'No documents found' if no matching content was retrieved. """ docs = retriever.retrieve(query, k=k) if not docs: return "No documents found" + context = "" for doc in docs: - doc.metadata["source"] = doc.metadata["source"].split("data/documents/")[-1] - context += f"**Document:** {doc.metadata['source']}\n\n" + # Simplify document source path to relative file name for cleaner citations + source = doc.metadata.get("source", "Unknown") + if "data/documents/" in source: + source = source.split("data/documents/")[-1] + doc.metadata["source"] = source + + context += f"**Document:** {source}\n\n" context += f"{doc.page_content}\n\n" + return context +