"""LangGraph Supervisor construction -- connects registry, agents, LLM, and persistence.""" from __future__ import annotations from typing import TYPE_CHECKING from langgraph.prebuilt import create_react_agent from langgraph_supervisor import create_supervisor from app.agents import get_tools_by_names if TYPE_CHECKING: from langchain_core.language_models import BaseChatModel from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver from langgraph.graph.state import CompiledStateGraph from app.registry import AgentRegistry SUPERVISOR_PROMPT = ( "You are a customer support supervisor. " "Route customer requests to the appropriate agent based on their description. " "For order status and tracking queries, use the order_lookup agent. " "For order modifications like cancellations, use the order_actions agent. " "For anything else, use the fallback agent." ) def build_agent_nodes( registry: AgentRegistry, llm: BaseChatModel, ) -> list: """Create LangGraph react agent nodes from registry configurations.""" agent_nodes = [] for agent_config in registry.list_agents(): tools = get_tools_by_names(agent_config.tools) system_prompt = ( f"You are the {agent_config.name} agent. " f"Personality: {agent_config.personality.tone}. " f"{agent_config.description} " f"Permission level: {agent_config.permission}." ) agent_node = create_react_agent( model=llm, tools=tools, name=agent_config.name, prompt=system_prompt, ) agent_nodes.append(agent_node) return agent_nodes def build_graph( registry: AgentRegistry, llm: BaseChatModel, checkpointer: AsyncPostgresSaver, ) -> CompiledStateGraph: """Build and compile the LangGraph supervisor graph.""" agent_nodes = build_agent_nodes(registry, llm) workflow = create_supervisor( agent_nodes, model=llm, prompt=SUPERVISOR_PROMPT, output_mode="full_history", ) return workflow.compile(checkpointer=checkpointer)