Files
smart-support/backend/app/graph.py
Yaojia Wang af53111928 refactor: fix architectural issues across frontend and backend
Address all architecture review findings:

P0 fixes:
- Add API key authentication for admin endpoints (analytics, replay, openapi)
  and WebSocket connections via ADMIN_API_KEY env var
- Add PostgreSQL-backed PgSessionManager and PgInterruptManager for
  multi-worker production deployments (in-memory defaults preserved)

P1 fixes:
- Implement actual tool generation in OpenAPI approve_job endpoint
  using generate_tool_code() and generate_agent_yaml()
- Add missing clarification, interrupt_expired, and tool_result message
  handlers in frontend ChatPage

P2 fixes:
- Replace monkey-patching on CompiledStateGraph with typed GraphContext
- Replace 9-param dispatch_message with WebSocketContext dataclass
- Extract duplicate _envelope() into shared app/api_utils.py
- Replace mutable module-level counter with crypto.randomUUID()
- Remove hardcoded mock data from ReviewPage, use api.ts wrappers
- Remove `as any` type escape from ReplayPage

All 516 tests passing, 0 TypeScript errors.
2026-04-06 15:59:14 +02:00

103 lines
3.2 KiB
Python

"""LangGraph Supervisor construction -- connects registry, agents, LLM, and persistence."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING
from langchain.agents import create_agent
from langgraph_supervisor import create_supervisor
from app.agents import get_tools_by_names
from app.graph_context import GraphContext
if TYPE_CHECKING:
from langchain_core.language_models import BaseChatModel
from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver
from app.intent import IntentClassifier
from app.registry import AgentRegistry
logger = logging.getLogger(__name__)
SUPERVISOR_PROMPT = (
"You are a customer support supervisor. "
"Route customer requests to the appropriate agent based on their description.\n\n"
"Available agents and their roles:\n"
"{agent_descriptions}\n\n"
"Routing rules:\n"
"- For order status and tracking queries, use the order_lookup agent.\n"
"- For order modifications like cancellations, use the order_actions agent.\n"
"- For discounts, promotions, or coupon codes, use the discount agent.\n"
"- For anything else or when uncertain, use the fallback agent.\n"
"- If the user's request involves multiple actions, execute them in order.\n"
"- If a previous intent classification is provided, follow it.\n"
)
def _format_agent_descriptions(registry: AgentRegistry) -> str:
"""Build agent description text for the supervisor prompt."""
lines = []
for agent in registry.list_agents():
lines.append(f"- {agent.name}: {agent.description}")
return "\n".join(lines)
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_agent(
model=llm,
tools=tools,
name=agent_config.name,
system_prompt=system_prompt,
)
agent_nodes.append(agent_node)
return agent_nodes
def build_graph(
registry: AgentRegistry,
llm: BaseChatModel,
checkpointer: AsyncPostgresSaver,
intent_classifier: IntentClassifier | None = None,
) -> GraphContext:
"""Build and compile the LangGraph supervisor graph.
Returns a GraphContext that bundles the compiled graph with its
associated registry and intent classifier.
"""
agent_nodes = build_agent_nodes(registry, llm)
agent_descriptions = _format_agent_descriptions(registry)
prompt = SUPERVISOR_PROMPT.format(agent_descriptions=agent_descriptions)
workflow = create_supervisor(
agents=agent_nodes,
model=llm,
prompt=prompt,
output_mode="full_history",
)
compiled = workflow.compile(checkpointer=checkpointer)
return GraphContext(
graph=compiled,
registry=registry,
intent_classifier=intent_classifier,
)