50 lines
1.4 KiB
Python
50 lines
1.4 KiB
Python
"""Agent graph built with LangGraph StateGraph."""
|
|
|
|
from typing import Annotated, TypedDict
|
|
|
|
from langchain_core.messages import BaseMessage, AIMessage
|
|
from langgraph.graph import StateGraph, START, END
|
|
from langgraph.graph.message import add_messages
|
|
from langgraph.prebuilt import ToolNode
|
|
|
|
from llm import create_model
|
|
from tools import grep, list_dir, read_file, replace_in_file, write_file
|
|
|
|
TOOLS = [read_file, grep, write_file, list_dir, replace_in_file]
|
|
|
|
|
|
class AgentState(TypedDict):
|
|
messages: Annotated[list[BaseMessage], add_messages]
|
|
|
|
|
|
def call_model(state: AgentState) -> dict:
|
|
"""Invoke the LLM with the current message history."""
|
|
model = create_model().bind_tools(TOOLS)
|
|
response = model.invoke(state["messages"])
|
|
return {"messages": [response]}
|
|
|
|
|
|
def should_continue(state: AgentState) -> str:
|
|
"""Route to tools if the last message has tool calls, otherwise end."""
|
|
last = state["messages"][-1]
|
|
if isinstance(last, AIMessage) and last.tool_calls:
|
|
return "tools"
|
|
return END
|
|
|
|
|
|
def build_graph() -> StateGraph:
|
|
"""Construct and compile the agent execution graph."""
|
|
graph = StateGraph(AgentState)
|
|
|
|
graph.add_node("agent", call_model)
|
|
graph.add_node("tools", ToolNode(TOOLS))
|
|
|
|
graph.add_edge(START, "agent")
|
|
graph.add_conditional_edges("agent", should_continue, {
|
|
"tools": "tools",
|
|
END: END,
|
|
})
|
|
graph.add_edge("tools", "agent")
|
|
|
|
return graph.compile()
|