feat(exec): add exec.py

This commit is contained in:
11linear11
2026-08-30 14:09:52 -04:00
parent 0d30af2d12
commit 8387804442
6 changed files with 151 additions and 13 deletions
+6 -1
View File
@@ -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
+90
View File
@@ -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())
+30
View File
@@ -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"),
])
-8
View File
@@ -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])
+7 -4
View File
@@ -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)