nat.control_flow.router_agent.agent#

Attributes#

Classes#

RouterAgentGraphState

State schema for the Router Agent Graph.

RouterAgentGraph

Configurable Router Agent for routing requests to different branches.

Functions#

create_router_agent_prompt(...)

Create a Router Agent prompt from the configuration.

Module Contents#

logger#
class RouterAgentGraphState(/, **data: Any)#

Bases: pydantic.BaseModel

State schema for the Router Agent Graph.

This class defines the state structure used throughout the Router Agent’s execution graph, containing messages, routing information, and branch selection.

Attributes:

messages: A list of messages representing the conversation history. forward_message: The message to be forwarded to the chosen branch. chosen_branch: The name of the branch selected by the router agent.

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

messages: list[langchain_core.messages.base.BaseMessage] = None#
forward_message: langchain_core.messages.base.BaseMessage = None#
chosen_branch: str = None#
class RouterAgentGraph(
llm: langchain_core.language_models.BaseChatModel,
branches: list[langchain_core.tools.BaseTool],
prompt: langchain_core.prompts.chat.ChatPromptTemplate,
max_router_retries: int = 3,
callbacks: list[langchain_core.callbacks.base.AsyncCallbackHandler] | None = None,
detailed_logs: bool = False,
log_response_max_chars: int = 1000,
)#

Bases: nat.agent.base.BaseAgent

Configurable Router Agent for routing requests to different branches.

A Router Agent analyzes incoming requests and routes them to one of the configured branches based on the conte nt and context. It makes a single routing decision and executes only the selected branch before returning.

This agent is useful for creating multi-path workflows where different types of requests need to be handled by specialized sub-agents or tools.

Initialize the Router Agent.

Args:

llm: The language model to use for routing decisions. branches: List of tools/branches that the agent can route to. prompt: The chat prompt template for the routing agent. max_router_retries: Maximum number of retries if branch selection fails. callbacks: Optional list of async callback handlers. detailed_logs: Whether to enable detailed logging. log_response_max_chars: Maximum characters to log in responses.

_branches#
_branches_dict#
agent#
max_router_retries = 3#
_get_branch(branch_name: str) langchain_core.tools.BaseTool | None#
async agent_node(state: RouterAgentGraphState)#

Execute the agent node to select a branch for routing.

This method processes the incoming request and determines which branch should handle it. It uses the configured LLM to analyze the request and select the most appropriate branch.

Args:

state: The current state of the router agent graph.

Returns:

RouterAgentGraphState: Updated state with the chosen branch.

Raises:

RuntimeError: If the agent fails to choose a branch after max retries.

async branch_node(state: RouterAgentGraphState)#

Execute the selected branch with the forwarded message.

This method calls the tool/branch that was selected by the agent node and processes the response.

Args:

state: The current state containing the chosen branch and message.

Returns:

RouterAgentGraphState: Updated state with the branch response.

Raises:

RuntimeError: If no branch was chosen or branch execution fails. ValueError: If the requested tool is not found in the configuration.

async _build_graph(state_schema)#
async build_graph()#

Build and compile the router agent execution graph.

Creates a state graph with agent and branch nodes, configures the execution flow, and compiles the graph for execution.

Returns:

The compiled execution graph.

Raises:

Exception: If graph building or compilation fails.

static validate_system_prompt(system_prompt: str) bool#

Validate that the system prompt contains required variables.

Checks that the system prompt includes necessary template variables for branch information that the router agent needs.

Args:

system_prompt: The system prompt string to validate.

Returns:

True if the prompt is valid, False otherwise.

static validate_user_prompt(user_prompt: str) bool#

Validate that the user prompt contains required variables.

Checks that the user prompt includes necessary template variables for chat history and other required information.

Args:

user_prompt: The user prompt string to validate.

Returns:

True if the prompt is valid, False otherwise.

create_router_agent_prompt(
config: nat.control_flow.router_agent.register.RouterAgentWorkflowConfig,
) langchain_core.prompts.chat.ChatPromptTemplate#

Create a Router Agent prompt from the configuration.

Builds a ChatPromptTemplate using either custom prompts from the config or default system and user prompts. Validates the prompts to ensure they contain required template variables.

Args:

config: The router agent workflow configuration containing prompt settings.

Returns:

A configured ChatPromptTemplate for the router agent.

Raises:

ValueError: If the system_prompt or user_prompt validation fails.