-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathrouter.py
More file actions
84 lines (64 loc) · 3.01 KB
/
router.py
File metadata and controls
84 lines (64 loc) · 3.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""Routing functions for conditional edges in the agent graph."""
from typing import Literal
from ..exceptions import AgentNodeRoutingException
from .types import FLOW_CONTROL_TOOLS, AgentGraphNode, AgentGraphState
from .utils import (
count_consecutive_thinking_messages,
extract_current_tool_call_index,
find_latest_ai_message,
)
def create_route_agent(thinking_messages_limit: int = 0):
"""Create a routing function configured with thinking_messages_limit.
Args:
thinking_messages_limit: Max consecutive thinking messages before error
Returns:
Routing function for LangGraph conditional edges
"""
def route_agent(
state: AgentGraphState,
) -> str | Literal[AgentGraphNode.AGENT, AgentGraphNode.TERMINATE]:
"""Route after agent: handles sequential tool execution.
Routing logic:
1. Get current tool call index from messages
2. If current tool call index is None (all tools completed), route to AGENT
3. If current tool call is a flow control tool, route to TERMINATE
4. Otherwise, route to the specific tool node
Returns:
- str: Single tool node name for sequential execution
- AgentGraphNode.AGENT: When all tool calls completed or no tool calls
- AgentGraphNode.TERMINATE: For control flow termination
Raises:
AgentNodeRoutingException: When encountering unexpected state
"""
messages = state.messages
last_message = find_latest_ai_message(messages)
if last_message is None:
raise AgentNodeRoutingException(
"No AIMessage found in messages for routing."
)
if not last_message.tool_calls:
consecutive_thinking_messages = count_consecutive_thinking_messages(
messages
)
if consecutive_thinking_messages > thinking_messages_limit:
raise AgentNodeRoutingException(
f"Agent exceeded consecutive completions limit without producing tool calls "
f"(completions: {consecutive_thinking_messages}, max: {thinking_messages_limit}). "
f"This should not happen as tool_choice='required' is enforced at the limit."
)
if last_message.content:
return AgentGraphNode.AGENT
raise AgentNodeRoutingException(
f"Agent produced empty response without tool calls "
f"(completions: {consecutive_thinking_messages}, has_content: False)"
)
current_index = extract_current_tool_call_index(messages)
# all tool calls completed, go back to agent
if current_index is None:
return AgentGraphNode.AGENT
current_tool_call = last_message.tool_calls[current_index]
current_tool_name = current_tool_call["name"]
if current_tool_name in FLOW_CONTROL_TOOLS:
return AgentGraphNode.TERMINATE
return current_tool_name
return route_agent