Coverage for app / agents / router.py: 97%

70 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2RouterAgent — conditional routing between nodes in the execution graph. 

3 

4RouterAgent.route() is designed to be used directly as a LangGraph 

5conditional edge function: 

6 

7 router = RouterAgent(candidates=["solver_a", "solver_b"]) 

8 builder.add_conditional_edge("router_node", router.route, edge_map) 

9 

10The choice is structured output (``structured_call``): the candidates are 

11the schema's ``Literal``, so a route that decodes natively can only name one 

12of them. It used to be free text scanned for the first candidate name it 

13mentioned — "not solver_a, solver_b" routed to solver_a. 

14""" 

15 

16from __future__ import annotations 

17 

18import hashlib 

19from typing import Any, Literal 

20 

21from langchain_core.messages import ( 

22 AIMessage, 

23 BaseMessage, 

24 HumanMessage, 

25 SystemMessage, 

26) 

27from langchain_core.runnables import RunnableConfig 

28from langchain_core.tools import StructuredTool 

29from pydantic import BaseModel, Field, create_model 

30 

31from app.agents.base import WorkerAgent, AgentCapability 

32from app.agents.enums import AgentRole 

33from app import prompts 

34from app.services import metering 

35from app.documents.spec import Confidence 

36from app.util import safe_json, vocab 

37from app.util.logger import get_logger 

38from app.util.model_output import ModelOutput 

39 

40logger = get_logger(__name__) 

41 

42 

43class RoutingDecision(BaseModel): 

44 """Structured output from a RouterAgent.""" 

45 

46 next_agent: str = Field(description="ID of the next node to route to") 

47 reasoning: str = Field(default="") 

48 confidence: str = Field(default="high", description=vocab.listing(Confidence)) 

49 alternatives: list[str] = Field( 

50 default_factory=list, description="Other valid routing options considered" 

51 ) 

52 

53 

54class RouterAgent(WorkerAgent): 

55 """ 

56 Agent that inspects graph state and returns the ID of the next node. 

57 

58 The model fills a schema whose one decision is a candidate 

59 (``_route_choice``). If it cannot, the first candidate (or "end") is 

60 used as a safe fallback. In a graph the decision is the node's result, 

61 so the conditional edge reads it (``route_from_state``) and the model is 

62 asked once. 

63 

64 Usage with AgentGraphBuilder:: 

65 

66 router = RouterAgent(candidates=["solver_a", "solver_b"]) 

67 builder.add_agent("router_node", router) 

68 builder.add_conditional_edge( 

69 "router_node", 

70 router.route, 

71 {"solver_a": "solver_a", "solver_b": "solver_b"}, 

72 ) 

73 """ 

74 

75 DEFAULT_ROLE = AgentRole.ROUTER 

76 DEFAULT_SYSTEM_PROMPT = prompts.ROUTER 

77 DEFAULT_MAX_ITERATIONS = 3 

78 

79 def __init__( 

80 self, 

81 name: str = "router", 

82 candidates: list[str] | None = None, 

83 **kwargs: Any, 

84 ) -> None: 

85 super().__init__(name=name, **kwargs) 

86 self.candidates: list[str] = list(candidates or []) 

87 self._choice: type[ModelOutput] | None = None 

88 self.add_capability( 

89 AgentCapability( 

90 name="routing", 

91 description="Determine the optimal next agent given current context", 

92 required=True, 

93 ) 

94 ) 

95 

96 def _route_choice(self) -> type[ModelOutput]: 

97 """What the model fills: one of the candidates, and why. Built once 

98 per router; named by its candidates, so two routers' refusals are 

99 remembered apart (``provider_refusals``).""" 

100 if self._choice is None: 

101 digest = hashlib.sha256("|".join(self.candidates).encode()).hexdigest() 

102 self._choice = create_model( 

103 f"RouteChoice_{digest[:8]}", 

104 __base__=ModelOutput, 

105 next_node=( 

106 Literal[tuple(self.candidates)], # type: ignore[valid-type] 

107 Field(description="The agent to hand the task to next"), 

108 ), 

109 basis=(str, Field(default="", description="One sentence on why")), 

110 ) 

111 return self._choice 

112 

113 async def _decide( 

114 self, messages: list[BaseMessage], config: RunnableConfig | None = None 

115 ) -> RoutingDecision: 

116 """The choice, from one structured call; the first candidate when the 

117 model could not make one.""" 

118 from app.services.structured_output import structured_call 

119 

120 if not self.candidates: 

121 return RoutingDecision(next_agent="end") 

122 result = await structured_call( 

123 self.resolve_llm(), 

124 self._route_choice(), 

125 messages, 

126 purpose=metering.Step.route, 

127 config=config, 

128 ) 

129 if result.value is None: 

130 logger.warning( 

131 "[router:%s] no choice (%s) — routing to %r", 

132 self.name, 

133 result.failure, 

134 self.candidates[0], 

135 ) 

136 return RoutingDecision(next_agent=self.candidates[0], confidence="low") 

137 return RoutingDecision( 

138 next_agent=result.value.next_node, reasoning=result.value.basis 

139 ) 

140 

141 async def execute(self, input_data: Any) -> RoutingDecision: 

142 return await self._decide(self._build_messages(input_data)) 

143 

144 async def process_with_history( 

145 self, 

146 task_content: str, 

147 prior_messages: list[BaseMessage], 

148 extra_tools: list[StructuredTool] | None = None, 

149 extra_system_context: str = "", 

150 on_tool_call: Any = None, 

151 config: RunnableConfig | None = None, 

152 request_context: str = "", 

153 answer_format_requested: bool = False, 

154 ) -> tuple[Any, list[BaseMessage]]: 

155 """As a graph node: the decision is the node's result, kept on 

156 ``state.results`` for ``route_from_state`` — the router used to 

157 answer in prose here and be asked again by its edge.""" 

158 system = "\n\n".join(filter(None, [self.system_prompt, extra_system_context])) 

159 task = ( 

160 f"{request_context}\n\n{task_content}" if request_context else task_content 

161 ) 

162 messages: list[BaseMessage] = [ 

163 SystemMessage(content=system), 

164 *prior_messages, 

165 HumanMessage(content=self._ask(task)), 

166 ] 

167 decision = await self._decide(messages, config) 

168 return decision, [AIMessage(content=decision.next_agent, name=self.name)] 

169 

170 async def route(self, state: Any) -> str: 

171 """ 

172 Convenience method for use as a LangGraph conditional edge function. 

173 Returns the next node ID directly (string). 

174 """ 

175 decision = await self.execute(state) 

176 return decision.next_agent 

177 

178 async def route_from_state(self, state: Any) -> str: 

179 """ 

180 Read the routing key from state.results if the node already executed. 

181 

182 When a RouterAgent node runs inside a LangGraph graph, its RoutingDecision 

183 is stored in ``state.results[self.name]``. This method reads that cached 

184 decision so the conditional edge function does not invoke the LLM a second 

185 time. 

186 

187 Falls back to ``route(state)`` (full LLM invocation) if no prior result is 

188 found — e.g. when called outside a graph execution or before the node runs. 

189 

190 Validates the chosen key against ``self.candidates`` and returns the first 

191 candidate as a safe default if the cached value is not in the allowed set. 

192 """ 

193 result = state.results.get(self.name) if hasattr(state, "results") else None 

194 if isinstance(result, RoutingDecision): 

195 key = result.next_agent 

196 if key in self.candidates: 

197 return key 

198 logger.warning( 

199 "[router:%s] cached next_agent=%r not in candidates=%s — falling back", 

200 self.name, 

201 key, 

202 self.candidates, 

203 ) 

204 return await self.route(state) 

205 

206 def _ask(self, context: str) -> str: 

207 return ( 

208 f"{context}\n\n" 

209 f"Candidates: {vocab.listing(self.candidates, sep=', ') or 'none'}\n\n" 

210 "Choose the agent to hand the task to next." 

211 ) 

212 

213 def _build_messages(self, input_data: Any) -> list[BaseMessage]: 

214 # Serialise state cleanly if it's a Pydantic model, excluding the 

215 # full messages list to keep the prompt concise. 

216 if hasattr(input_data, "model_dump"): 

217 state_str = safe_json.dumps( 

218 input_data.model_dump(exclude={"messages"}), indent=2 

219 ) 

220 else: 

221 state_str = str(input_data) 

222 return self.build_messages(self._ask(f"Current state:\n{state_str}"))