Refactor create_react_agent to use internal _AgentBuilder helper class #5697
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR refactors the
create_react_agent
function to use an internal_AgentBuilder
helper class, addressing maintainability and readability issues with the original implementation.Problem
The
create_react_agent
function had grown to over 700 lines of complex, intertwined logic that was difficult to maintain, understand, and modify. The function handled multiple responsibilities including:Solution
This refactoring introduces an internal
_AgentBuilder
class that encapsulates and organizes the agent construction logic into focused, manageable methods:Core
_AgentBuilder
Methods__init__
: Parameter validation and initialization_setup_model_and_tools()
: Model resolution and tool binding_create_model_node()
: Core LLM interaction node creation_create_structured_response_node()
: Structured output formatting_create_model_router()
: Execution flow routing after model calls_create_tools_router()
: Post-tool-call routing for return_direct behavior_setup_hooks()
: Pre/post model hook integrationbuild()
: Final graph assembly and compilationKey Benefits
create_react_agent
function is now just 25 lines vs 700+ linesExample
The refactored
create_react_agent
function now simply delegates to the builder:The
_AgentBuilder
class handles all the complex logic internally while maintaining the exact same functionality and behavior.Fixes #5692.
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.