-
Notifications
You must be signed in to change notification settings - Fork 2k
Description
Question
Is there any way to stop the execution of the Runner based on the tool result or when the specific tool is called?
Why do I need this?
My system has a requirement that the AI answer generation should be stopped when my X tool is called. Once my X tool is called, I should be able to stop the agents and yield a text chunk with SKIP_AI_ANSWER
text.
The tool I need to "track" and halt execution is called by agent-as-a-tool
.
I've tried to do this by throwing an exception in the Agent hook like this:
class SkipAiToolResult(UserError):
"""Exception to indicate that the AI tool result should be skipped."""
pass
class MyHooks(AgentHooks):
async def on_tool_end(self, context: RunContextWrapper, agent: Agent, tool: Tool, result: str) -> None:
if tool.name == 'X':
raise SkipAiToolResult("Skipping answer")
and trying to catch it like this:
try:
result = await Runner.run(
starting_agent=orchestrator_agent,
input=chat_messages_to_sdk_items(messages),
context=AgentContext(),
)
except SkipAiToolResult as e:
yield 'data: SKIP_AI_ANSWER'
The problem is that this catch case doesn't seem to work. Runner still generates an answer, ignoring the exception thrown in MyHooks
.
Do you have any other ideas on how I can completely halt the execution of the Runner and do my custom logic in case it happens?
Thanks ahead!