Files
smart-support/backend/app/graph.py
Yaojia Wang f0699436c5 refactor: engineering improvements -- API versioning, structured logging, Alembic, error standardization, test coverage
- API versioning: all REST endpoints prefixed with /api/v1/
- Structured logging: replaced stdlib logging with structlog (console/JSON modes)
- Alembic migrations: versioned DB schema with initial migration
- Error standardization: global exception handlers for consistent envelope format
- Interrupt cleanup: asyncio background task for expired interrupt removal
- Integration tests: +30 tests (analytics, replay, openapi, error, session APIs)
- Frontend tests: +57 tests (all components, pages, useWebSocket hook)
- Backend: 557 tests, 89.75% coverage | Frontend: 80 tests, 16 test files
2026-04-06 23:19:29 +02:00

104 lines
3.2 KiB
Python

"""LangGraph Supervisor construction -- connects registry, agents, LLM, and persistence."""
from __future__ import annotations
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
import structlog
logger = structlog.get_logger()
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,
)