doc update

This commit is contained in:
11linear11
2026-08-31 07:13:50 -04:00
parent 15089dc0fe
commit cb54a35c90
18 changed files with 653 additions and 98 deletions
+1
View File
@@ -0,0 +1 @@
"""Core business logic and RAG pipeline services package."""
+1
View File
@@ -0,0 +1 @@
"""LangGraph agent package for conversational reasoning and tool execution."""
+70 -41
View File
@@ -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())
+10 -1
View File
@@ -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),
+33 -8
View File
@@ -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)
+48 -15
View File
@@ -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()
+1
View File
@@ -0,0 +1 @@
"""Custom agent tools package."""
+25 -6
View File
@@ -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