broad-hairdresser-84880
09/18/2025, 3:33 PM1.0.4 version of agentsJS and openai’s gpt-realtime
When the agent calls a tool I’m frequently seeing:
FunctionCallOutput {
id: 'item_a91de3c0-962',
type: 'function_call_output',
name: 'check_address',
callId: 'call_OpS9uUTt27Yd3Bri',
output: 'An internal error occurred',
isError: true,
createdAt: 1758209049266
}
This seems to be related to using an async/await function inside the tool whilst the agent is saying (something like..) “let me just check that”
e.g.
export default function check_address(serviceId: string) {
return llm.tool({
description: `
check customers address is valid and available for delivery.
Read back the delivery time and cost.
`,
parameters: z.object({
address: z.string().describe('The address to check for delivery availability'),
}),
execute: async ({ address }, { ctx, abortSignal }) => {
const encodedAddress = encodeURIComponent(address.trim());
const url = `${process.env.ORDERING_ENDPOINT}/${serviceId}/address/?address=${encodedAddress}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.ORDERING_API_KEY}`,
},
});
const responseText = await response.text();
return responseText;
Because this alternative seems to work fine:
export default function check_address(serviceId: string) {
return llm.tool({
description: `
check customers address is valid and available for delivery.
Read back the delivery time and cost.
`,
parameters: z.object({
address: z.string().describe('The address to check for delivery availability'),
}),
execute: async ({ address }, { ctx, abortSignal }) => {
return "this works fine!";
Tried a heck of a lot of workarounds for this (manualy generating a reply, returning promises etc etc…).
Is this a framework bug?
Thanks!refined-appointment-81829
09/18/2025, 4:39 PMbitter-ghost-46918
09/19/2025, 4:02 AMAn internal error occurred usually would means an error inside function tool implementation. For the fetch operation above, have you tested if it's working without using the function tool? Like this:
const encodedAddress = encodeURIComponent(address.trim());
const url = `${process.env.ORDERING_ENDPOINT}/${serviceId}/address/?address=${encodedAddress}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.ORDERING_API_KEY}`,
},
});
const responseText = await response.text();broad-hairdresser-84880
09/19/2025, 5:01 AMbitter-ghost-46918
09/19/2025, 8:09 AMconst callApi = async () => { ... };
and calling it inside tool:
llm.tool({
description: "...",
parameters: z.object({
...
}),
execute: async ({ ... }, { ctx, abortSignal }) => {
return await callApi();
}
});
Are you saying that the tool call will be 70% succeed even if callApi works 100% of time?broad-hairdresser-84880
09/19/2025, 8:23 AMFunctionCallOutput is sometimes An internal error occurred and sometimes it logs the correct response. (a simple text response from the network e.g. ADDRESS VALID: £3.50 delivery)
the agent is generally speaking over the trigger of the function call, something like “let me just check that address”, the pattern seems to be that if the agent is quiet while the function call is triggered and eventually returned, it works fine.
So from my testing at least, that seems to be the bug - the agents ‘speaking/thinking/listening’ states are causing an issue when triggering or returning data from an async function within the tool function.
• if i edit the prompt so that the agent stays silent before/during a function call, this works as expected
• if the network call takes a while (few seconds) - this also seems to work as expected (the agent has finished speaking by the time the function returns)
• if i try to fake extend the function time e,g. await new Promise => timeout(resolve, 2000) the agent throws the internal error again.
• Also randomly, if i just return plain text from the function without running any async functions, this worksbroad-hairdresser-84880
09/19/2025, 8:26 AMvoice.AgentSessionEventTypes.FunctionToolsExecuted, voice.AgentSessionEventTypes.AgentStateChanged ) etcbroad-hairdresser-84880
09/19/2025, 8:27 AMbitter-ghost-46918
09/19/2025, 8:40 AMbroad-hairdresser-84880
09/19/2025, 8:43 AMbroad-hairdresser-84880
09/19/2025, 8:44 AMbitter-ghost-46918
09/19/2025, 8:45 AMawait new Promise => timeout(resolve, 2000), let me see if I can reprobroad-hairdresser-84880
09/19/2025, 8:45 AMbroad-hairdresser-84880
09/19/2025, 10:30 AMexport default defineAgent({
prewarm: async (proc: JobProcess) => {
proc.userData.vad = await silero.VAD.load();
},
entry: async (ctx: JobContext) => {
console.log(`Starting metadata ${JSON.stringify(ctx, null, 2)}`);
const agent = new voice.Agent({
instructions: `
when callers wants the weather, get the weather
# Tools
## Tool Call Behavior
- Before calling any tool, provide immediate feedback: "One moment please", "Let me check that", "I'll look that up"
- Wait for tool response before continuing conversation
- Call tools ONE AT A TIME and wait for response before calling another
- Never call the same tool multiple times for the same task
## get_weather(location)
**Purpose**: Get the current weather information for a specific location.
**When to use**: When a user asks about the weather in a specific area.
**When NOT to use**: When the user is asking about a different topic.
**Preamble phrases**:
- "Let me just check the weather for you"
- "I'll verify the weather in that area"
- "Checking the weather for your area now"
`,
tools: {
get_weather: llm.tool({
description: 'Gets the current weather information.',
parameters: z.object({ location: z.string() }),
execute: async ({ location }, { ctx }) => {
await new Promise((resolve) => setTimeout(resolve, 5000));
return `the weather is sunny in ${location}`;
},
}),
},
allowInterruptions: true,
});
const session = new voice.AgentSession({
llm: new openai.realtime.RealtimeModel({
turnDetection: {
type: 'server_vad',
threshold: 0.9,
prefix_padding_ms: 300,
silence_duration_ms: 500,
create_response: true,
interrupt_response: true,
},
voice: 'marin' as const,
model: 'gpt-realtime-2025-08-28' as const,
temperature: 0.7,
}),
// Enable parallel processing and remove tool limitations
voiceOptions: {
maxToolSteps: 2, // Remove tool step limitations
allowInterruptions: true, // Allow speech interruptions during function calls
},
});
await session.start({
agent,
room: ctx.room,
inputOptions: {
// For telephony applications, use `TelephonyBackgroundVoiceCancellation` for best results
noiseCancellation: TelephonyBackgroundVoiceCancellation(),
},
});
const participant = await ctx.waitForParticipant();
session.on(voice.AgentSessionEventTypes.ConversationItemAdded, (ev) => {
console.log('conversation_item_added', ev);
});
session.on(voice.AgentSessionEventTypes.AgentStateChanged, (ev) => {
console.log('agent_state_changed', ev);
});
session.on(voice.AgentSessionEventTypes.FunctionToolsExecuted, (event) => {
console.log('function_tools_executed', event);
});
session.generateReply({
instructions: `Use UK accent, say 'Hello, how can i help?'`,
});
},
});
cli.runApp(
new WorkerOptions({ agent: fileURLToPath(import.meta.url), agentName: process.env.AGENT_NAME }),
);broad-hairdresser-84880
09/19/2025, 10:31 AMconversation_item_added {
type: 'conversation_item_added',
item: ChatMessage {
id: 'item_CHSeU0V1TfHYHGghI4LRY',
type: 'message',
role: 'user',
content: [ "Hi there, what's the weather like in Wakefield?" ],
interrupted: false,
hash: undefined,
createdAt: 1758277753402
},
createdAt: 1758277753402
}
agent_state_changed {
type: 'agent_state_changed',
oldState: 'listening',
newState: 'speaking',
createdAt: 1758277753686
}
agent_state_changed {
type: 'agent_state_changed',
oldState: 'speaking',
newState: 'listening',
createdAt: 1758277755657
}
conversation_item_added {
type: 'conversation_item_added',
item: ChatMessage {
id: 'item_CHSeWPKIC2VsN11q6gcdl',
type: 'message',
role: 'assistant',
content: [ 'Let me just check the weather for you in Wakefield.' ],
interrupted: false,
hash: undefined,
createdAt: 1758277755658
},
createdAt: 1758277755658
}
agent_state_changed {
type: 'agent_state_changed',
oldState: 'listening',
newState: 'thinking',
createdAt: 1758277755658
}
function_tools_executed {
type: 'function_tools_executed',
functionCalls: [],
functionCallOutputs: [
FunctionCallOutput {
id: 'item_c275d240-f9c',
type: 'function_call_output',
name: 'get_weather',
callId: 'call_QN4pBVZfMNl8kTwo',
output: 'An internal error occurred',
isError: true,
createdAt: 1758277755657
}
],
createdAt: 1758277755659
}
[11:29:15.420] INFO (91496): Executing LLM tool call
function: "get_weather"
arguments: {
"location": "Wakefield"
}
speech_id: "speech_6d04b55b-283"
agent_state_changed {
type: 'agent_state_changed',
oldState: 'thinking',
newState: 'speaking',
createdAt: 1758277756313
}
agent_state_changed {
type: 'agent_state_changed',
oldState: 'speaking',
newState: 'listening',
createdAt: 1758277764964
}
conversation_item_added {
type: 'conversation_item_added',
item: ChatMessage {
id: 'item_CHSeZflP7C2Nk9noGaHNJ',
type: 'message',
role: 'assistant',
content: [
"I'm sorry, it looks like there was a problem retrieving the weather information. Could you please try again in a moment, or let me know if there's another location you'd like to check?"
],
interrupted: false,
hash: undefined,
createdAt: 1758277764965
},
createdAt: 1758277764965
}bitter-ghost-46918
09/22/2025, 7:07 AMbroad-hairdresser-84880
09/22/2025, 7:08 AMbroad-hairdresser-84880
09/22/2025, 7:09 AMbroad-hairdresser-84880
09/22/2025, 7:33 PMbroad-hairdresser-84880
10/01/2025, 1:00 PMconst agent = new voice.Agent({
instructions: `
YOU ARE BRITISH UK ENGLISH SPEAKING
when callers wants options for an item, get the options
# Tools
## Tool Call Behavior
- Wait for tool response before continuing conversation
- Call tools ONE AT A TIME and wait for response before calling another
- Never call the same tool multiple times for the same task
## MENU
London Pizza | id: 85954 | price: £5.2 | OPTIONS AVAILABLE
Funghi Pizza | id: 85955 | price: £5.2 | OPTIONS AVAILABLE
Pepperoni Pizza | id: 85956 | price: £5.4 | OPTIONS AVAILABLE
## get_options(item_id)
**Purpose**: Get the current options information for a specific item.
**When to use**: ALWAYS USE When a user asks for a specific item.
**When NOT to use**: When the user is asking about a different topic.
`,
tools: {
get_options: llm.tool({
description: 'Get options for the specific items ordered',
parameters: z.object({
item_ids: z
.array(
z
.number()
.describe(
'The ids of the menu items being ordered. Found alongside the item in the menu',
),
)
.describe('The ids of the menu items being ordered'),
}),
execute: async ({ item_ids }, { ctx }) => {
await ctx.waitForPlayout();
return 'BBQ or Thin Base';
},
}),
},
allowInterruptions: true,
});broad-hairdresser-84880
10/01/2025, 1:01 PMawait ctx.waitForPlayout();
with any async call, this throws a function call error…
conversation_item_added {
type: 'conversation_item_added',
item: ChatMessage {
id: 'item_CLqgfZw494z9dRyoG9fSo',
type: 'message',
role: 'assistant',
content: [
'Sure, let me quickly check the options available for the London Pizza. One moment.'
],
interrupted: false,
hash: undefined,
createdAt: 1759323458794
},
createdAt: 1759323458794
}
agent_state_changed {
type: 'agent_state_changed',
oldState: 'listening',
newState: 'thinking',
createdAt: 1759323458796
}
function_tools_executed {
type: 'function_tools_executed',
functionCalls: [],
functionCallOutputs: [
FunctionCallOutput {
id: 'item_5e5569e7-c7a',
type: 'function_call_output',
name: 'get_options',
callId: 'call_URq2mJnEAgXY4zMz',
output: 'An internal error occurred',
isError: true,
createdAt: 1759323457792
}
],
createdAt: 1759323458797
}
agent_state_changed {
type: 'agent_state_changed',
oldState: 'thinking',
newState: 'speaking',
createdAt: 1759323459529
}broad-hairdresser-84880
10/01/2025, 1:02 PMbroad-hairdresser-84880
10/01/2025, 1:09 PMexecute: async ({ item_ids }, { ctx }) => {
const doCall = async () => {
ctx.speechHandle.removeDoneCallback(doCall);
const res = await fetch(
`${process.env.ORDERING_ENDPOINT}/api/voice/outlet/red-pepper-1711531352/items/${item_ids.join(',')}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.ORDERING_API_KEY}`,
},
},
).then((r) => r.text());
ctx.session.generateReply({
instructions: res,
});
};
return ctx.speechHandle.addDoneCallback(doCall);
},