Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/stupid-pugs-deliver.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@openai/agents-core": patch
---

fix: #753 Emit agent_tool_end event when function tools throw errors
10 changes: 10 additions & 0 deletions packages/agents-core/src/runImplementation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1357,6 +1357,16 @@ export async function executeFunctionToolCalls<TContext = UnknownContext>(
error: String(error),
},
});

// Emit agent_tool_end even on error to maintain consistent event lifecycle
const errorResult = String(error);
runner.emit('agent_tool_end', state._context, agent, toolRun.tool, errorResult, {
toolCall: toolRun.toolCall,
});
agent.emit('agent_tool_end', state._context, toolRun.tool, errorResult, {
toolCall: toolRun.toolCall,
});

throw error;
}
},
Expand Down
44 changes: 44 additions & 0 deletions packages/agents-core/test/runImplementation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1771,6 +1771,50 @@ describe('executeFunctionToolCalls', () => {
expect(invokeSpy).toHaveBeenCalled();
});

it('emits agent_tool_end even when function tool throws error', async () => {
const errorMessage = 'Tool execution failed';
const t = tool({
name: 'failing_tool',
description: 'A tool that throws an error',
parameters: z.object({}),
// Disable default error handler to force raw error propagation
errorFunction: null,
execute: vi.fn(async () => {
throw new Error(errorMessage);
}),
}) as any;

const start = vi.fn();
const end = vi.fn();
runner.on('agent_tool_start', start);
runner.on('agent_tool_end', end);

// Tool should throw because we disabled the error handler
await expect(
withTrace('test', () =>
executeFunctionToolCalls(
state._currentAgent,
[{ toolCall, tool: t }],
runner,
state,
),
),
).rejects.toThrow();

// Both start and end should be emitted, even though tool threw
expect(start).toHaveBeenCalledWith(state._context, state._currentAgent, t, {
toolCall,
});
expect(end).toHaveBeenCalled();
expect(end).toHaveBeenCalledWith(
state._context,
state._currentAgent,
t,
expect.stringContaining(errorMessage),
{ toolCall },
);
});

it('propagates nested run result interruptions when provided by agent tools', async () => {
const t = makeTool(false);
const nestedAgent = new Agent({ name: 'Nested' }) as Agent<
Expand Down