From 838780444237659045611ce0442dc176b89faf0a Mon Sep 17 00:00:00 2001 From: 11linear11 <11linearlin11@gmail.com> Date: Sun, 30 Aug 2026 14:09:52 -0400 Subject: [PATCH] feat(exec): add exec.py --- .env.example | 18 ++++++ app/core/config.py | 7 ++- app/services/agent/exec.py | 90 ++++++++++++++++++++++++++++ app/services/agent/prompt.py | 30 ++++++++++ app/services/retriever.py | 8 --- app/services/tools/retriever_tool.py | 11 ++-- 6 files changed, 151 insertions(+), 13 deletions(-) create mode 100644 .env.example diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..a6242bf --- /dev/null +++ b/.env.example @@ -0,0 +1,18 @@ +# App Config +APP_NAME="Technical Documentation Assistant" +APP_VERSION="1.0.0" +APP_ENVIRONMENT="development" + +# LLM Config +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 Config +CHUNK_SIZE=1000 +CHUNK_OVERLAP=200 +DOCS_DIR="./data/documents" +CHROMA_PERSIST_DIR="./data/vector_db" diff --git a/app/core/config.py b/app/core/config.py index a479aee..7d5826a 100644 --- a/app/core/config.py +++ b/app/core/config.py @@ -9,7 +9,12 @@ class Settings(BaseSettings): # LLM Config api_key: str - model: str + llm_base_url: str + llm_model: str + llm_temperature: float + llm_max_tokens: int + llm_max_iterations: int = 3 + # RAG Config chunk_size: int = 1000 diff --git a/app/services/agent/exec.py b/app/services/agent/exec.py index e69de29..4102dfe 100644 --- a/app/services/agent/exec.py +++ b/app/services/agent/exec.py @@ -0,0 +1,90 @@ +# # 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 +import asyncio + + +tools = [retriever_tool] + +llm = ChatOpenAI( + base_url=settings.llm_base_url, + model=settings.llm_model, + temperature=settings.llm_temperature, + max_tokens=settings.llm_max_tokens, + api_key=settings.api_key, +) + + + +class State(TypedDict): + messages: Annotated[list,add_messages] + + +tool_node = ToolNode(tools) + +def call_llm_node(state: State): + messages = state["messages"] + + system_instruction = SystemMessage( + content=SYSTEM_PROMPT + ) + full_message = [system_instruction] + messages + + llm_with_tool = llm.bind_tools(tools) + + response = llm_with_tool.invoke(full_message) + + return {"messages": [response]} + + + + +flow = StateGraph(State) + +flow.add_node("agent",call_llm_node) +flow.add_node("tools",tool_node) + +flow.add_edge(START, "agent") +flow.add_conditional_edges( + "agent", + tools_condition +) + +flow.add_edge("tools","agent") + +memory = MemorySaver() +agent_app = flow.compile(checkpointer=memory) + +async def chat_with_agent(query: str, thread_id: str = "default_session"): + config = {"configurable": {"thread_id": thread_id}} + response = await agent_app.ainvoke( + {"messages": [("human", query)]}, + config=config + ) + return response["messages"][-1].content + + + +async def main(): + 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__": + asyncio.run(main()) \ No newline at end of file diff --git a/app/services/agent/prompt.py b/app/services/agent/prompt.py index e69de29..54090e4 100644 --- a/app/services/agent/prompt.py +++ b/app/services/agent/prompt.py @@ -0,0 +1,30 @@ +from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder + +SYSTEM_PROMPT = """You are an expert technical assistant specializing in technical documentation, code architectures, and APIs. + +Your core workflow & guidelines: + +1. Unified Reasoning & Single-Step Intent Understanding: + - In each turn, analyze the user's message and chat history. + - 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. + +2. Intent-Based Query Reformulation (Crucial): + - NEVER pass raw user prompts or conversational filler (e.g., "سلام چطوری میشه فلان کارو کرد") directly to `retriever_tool`. +s, class/method names, concepts, or error codes (e.g., transform "How to set up database settings with env?" into "Pydantic BaseSettings SettingsConfigDict env_file"). - Distill the user's request into precise technical keyword + +3. Source-Grounded & Hallucination-Free Answers: + - When answering, base your response strictly on the retrieved documentation chunks. + - If the retrieved context is not sufficient to answer reliably, explicitly state: "The provided documentation does not contain enough information on this topic." + +4. Citations & Code Quality: + - Always cite the document source (e.g. `fastapi_handling_errors.md`) at the end of your response when citing technical guidelines or solutions. + - Provide clean, production-ready code snippets with appropriate markdown language identifiers. +""" + +agent_prompt = ChatPromptTemplate.from_messages([ + ("system", SYSTEM_PROMPT), + MessagesPlaceholder(variable_name="chat_history", optional=True), + ("human", "{input}"), + MessagesPlaceholder(variable_name="agent_scratchpad"), +]) \ No newline at end of file diff --git a/app/services/retriever.py b/app/services/retriever.py index d901eaf..631ae30 100644 --- a/app/services/retriever.py +++ b/app/services/retriever.py @@ -37,11 +37,3 @@ class ContextRetriever: return self.vec_store.similarity_search(query, k=k) retriever = ContextRetriever() - - - -if __name__ == "__main__": - results = retriever.retrieve("How to handle exceptions?", k=2) - print(f"Results found: {len(results)}") - if results: - print("First result snippet:", results[0].page_content[:150]) \ No newline at end of file diff --git a/app/services/tools/retriever_tool.py b/app/services/tools/retriever_tool.py index afd7a68..424eaec 100644 --- a/app/services/tools/retriever_tool.py +++ b/app/services/tools/retriever_tool.py @@ -5,7 +5,12 @@ from langchain_core.tools import tool @tool def retriever_tool(query: str, k: int = 3): - """Tool to retrieve documents from the vector store""" + """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. + k: Number of relevant documentation chunks to retrieve (default: 3). + """ docs = retriever.retrieve(query, k=k) if not docs: return "No documents found" @@ -17,6 +22,4 @@ def retriever_tool(query: str, k: int = 3): return context -if __name__ == "__main__": - result = retriever_tool.invoke({"query": "How to handle exceptions?", "k": 2}) - print(result) \ No newline at end of file +