How to use context variables in AG2 OnCondition handoff strings?
In AG2, OnCondition's condition string seems to accept only plain text, so how can a handoff condition reference context_variables, for example transferring only when {situation} == 'B'? I know OnCondition.available can take a callable, but it only acts as an AND prerequisite and does not let the condition string itself reference variables.
Originally asked on GitHub: https://github.com/ag2ai/ag2/issues/348
2 answers
Status: fixed. This feature was implemented in AG2 and merged as PR #349. Use
UpdateConditionfor theconditionargument ofOnCondition; it expands{variable}placeholders fromcontext_variables, following the same convention asUpdateSystemMessage.Example from the maintainer's test:
pythonregister_hand_off( order_triage_agent, [ OnCondition( target=authentication_agent, condition="The customer is not logged in, authenticate the customer.", available="requires_login", ), OnCondition( target=order_mgmt_agent, condition=UpdateCondition("The customer is logged in, continue with the order triage if {customer_tier} == 2."), available="logged_in", ), AfterWork(AfterWorkOption.REVERT_TO_USER), ], )The maintainer confirmed the injected condition works as expected: when the condition string is false, the LLM avoids calling the handoff.
OnCondition.availableis still separate and is ANDed with the condition string; it can load a callable to check variables, but it does not give the condition string itself access to variables. For OR-style logic between a text situation and variables, write it inside theUpdateConditionstring, for example"transfer to AgentC when user is frustrated or {situation} == 'B' or {situation} == 'C'".Use a build of AG2 that includes PR #349.
Did this work for you?What @marklysze tried on GitHub (Worked)
A maintainer tested
UpdateConditionin a sample handoff usingcondition=UpdateCondition("The customer is logged in, continue with the order triage if {customer_tier} == 2.")and confirmed the LLM skipped the handoff when the condition string was false.Source: https://github.com/ag2ai/ag2/issues/348#issuecomment-2572252403 (opens external site)
Did this work for you?
Related questions
- AG2 0.5 upgrade breaks `from autogen import ...` — how to fix?
- AG2 + Gemini function calling: 400 "function response turn must come immediately after a function call turn"
- ag2 LLMConfig.where(tags='tool') fails when tags is a list in OAI_CONFIG_LIST
- How to get structured outputs from Bedrock in ag2 when response_format is ignored?
- Does AG2 support remote/distributed agents (A2A)?