- 
                Notifications
    You must be signed in to change notification settings 
- Fork 486
feat: Implement new FunctionTarget #2031
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
| @gabriel-eidelman this is a great addition to the framework. Following our discussion, let's refactor to keep the FunctionTarget functionality separate from the core group chat code and work on incorporating adding the ability to include a message in the conversation from the function. | 
| Hello! Great addition, nice work. Note... I think it may be a good idea to add some kind of message indicating there is a tool being executed via a handoff such as '[FUNCTION HANDOFF] - whatevertheoutput is'. | 
| @gabriel-eidelman thanks for the PR! Please remember to run pre-commit: https://docs.ag2.ai/latest/docs/contributor-guide/pre-commit/ | 
…onTargetMessage classes
a9e5c94    to
    a0e531d      
    Compare
  
    | Still to do: 
 @bassilkhilo-ag2 @gabriel-eidelman - Can you assist in helping to explain the message broadcasting requirement. | 
| @marklysze, we don't support handoffs in RemoteAgents yet. So, I don't think it should be designed with an impact on Remote Agents. I have no concerns about this feature - it seems like we can support it without any problems if we find a way to support regular hand-offs in Remote Agents. | 
| 
 Great, thanks @Lancetnik, appreciated | 
| PR Review: FunctionTarget ImplementationSummaryThis PR introduces a FunctionTarget class that allows agents to pass their output to a function upon completion, providing better control over output validation, parsing, and routing. This is a valuable addition to the AG2 framework. Positive Aspects ✅
 Critical Issues Found 🔴1. Bug in Message Construction (CRITICAL)Location: autogen/agentchat/group/targets/function_target.py:66-74 When messages is a string, the code has inconsistent variable assignments that will cause UnboundLocalError. Line 66-74: The first branch assigns to messages instead of messages_list, and if the loop does not find a matching agent, messages_list is never assigned before being returned on line 77. Fix: Use messages_list consistently in all branches and initialize it before the conditionals. 2. Potential UnboundLocalError (CRITICAL)If isinstance(target, (AgentTarget, AgentNameTarget)) is true but the for loop does not find a matching agent, messages_list is undefined when returned. Fix: Add a fallback assignment after the loop or initialize messages_list before the conditionals. High Priority Issues 🟡3. Missing Unit TestsLocation: test/agentchat/test_function_targets.py The test file only contains an integration test requiring LLM API calls. It lacks: 
 Recommendation: Follow the pattern in test/agentchat/group/targets/test_transition_target.py which has comprehensive unit tests. 4. Type Import InconsistencyLocation: autogen/agentchat/group/targets/function_target.py:9 Other files in the same directory import Optional from typing (see transition_target.py:6, group_chat_target.py:5). While using | None is fine, consistency with the codebase is preferred. Minor Issues 🟢5. Error Message QualityLine 106: Error message could include agent name for better debugging. 6. Documentation ClarityLine 50: FunctionTargetResult docstring should clarify that a string message is sent to the target agent (not broadcast to all). 7. Pydantic Config StyleLines 36-37: Verify if codebase uses Pydantic v1 or v2 and use consistent config style. Security & Performance ✅
 Recommendations
 Overall AssessmentThis is a valuable feature with good design, but has critical bugs that will cause runtime failures. The bugs are easily fixable. Once addressed, this will be a solid addition to AG2. Recommendation: Request changes to fix critical bugs and add unit tests before merging. Review by Claude Code | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for a great addition to handoffs @gabriel-eidelman!
If you can create a separate PR with some additions to the documentation, that would be great!
| Codecov Report❌ Patch coverage is  
 
 ... and 20 files with indirect coverage changes 🚀 New features to boost your workflow:
 | 
Why are these changes needed?
The FunctionTarget represents a logical next step in the development of the AG2 Framework. It is very often useful or even critical to pass an agent's output into a function, whether to validate the output, parse it, extract it, save it to context, allow for more complex routing, or anything else. Traditionally, in order to have an agent pass to a function upon completion, you would have to explicitly instruct it in its prompt to call the tool and instruct the agent regarding what to pass in. There are two main problems with this approach:
The FunctionTarget solves this problem elegantly. Subclassing the TransitionTarget class, it is easy to define in the same way that we would an AgentTarget:
agent.handoffs.set_after_work(FunctionTarget(afterwork_function))The afterwork_function is expected to have the following signature by default:
def afterwork_function(agent_output: str, context_variables: Any) -> FunctionTargetResult:Custom Parameters:
To add more parameters, place them after context_variables. It is important to note that arguments are passed in positionally, so the order needs to be maintained. Here is an example:
def afterwork_function(agent_output: str, context_variables: Any, extra_bool: bool) -> FunctionTargetResult:We pass in this parameter using the extra_args parameter which expects a dictionary as follows:
agent.handoffs.set_after_work(FunctionTarget(afterwork_function, extra_args: {"extra_bool": True}))When the agent finishes its turn, its output (along with context_variables) is automatically passed to this function, where you can implement any custom logic.
Potential use cases:
Return Type
The returned FunctionTargetResult has the following signature:
if messages is a str, then it will by default send the message to the 'next' agent (the target agent). Otherwise messages are of the following type:
this allows for fine-grained control in message handling if beneficial for a given use case. An example use would be passing a large input to the next agent, and passing a status update to all other agents. All messages are sent from the chat manager.
An example implementation is provided in test/agentchat/test_function_targets.py
Checks