119 lines
3.5 KiB
Python
119 lines
3.5 KiB
Python
"""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,
|
|
temperature=settings.llm_temperature,
|
|
max_tokens=settings.llm_max_tokens,
|
|
api_key=settings.api_key,
|
|
)
|
|
|
|
|
|
class State(TypedDict):
|
|
"""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) -> 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"]
|
|
|
|
# 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)
|
|
|
|
# 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, # Routes to "tools" if tool calls are requested, else to END
|
|
)
|
|
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") -> 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,
|
|
)
|
|
return response["messages"][-1].content
|
|
|
|
|
|
async def main() -> None:
|
|
"""CLI test harness for testing agent retrieval and response generation."""
|
|
session_id = "test_user_session"
|
|
|
|
# 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()) |