Hi all, facing an issues with function calling on ...
# agents
b
Hi all, facing an issues with function calling on the latest
1.0.4
version of agentsJS and openai’s gpt-realtime When the agent calls a tool I’m frequently seeing:
Copy code
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.
Copy code
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:
Copy code
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!
r
@bitter-ghost-46918 FYI
b
Hey @broad-hairdresser-84880, the
An 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:
Copy code
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();
b
Hi @bitter-ghost-46918 . Thanks for getting back to me on this. Yeah the network call is all good. The version I posted here was stripped down for brevity but when testing for real all the logging I added suggests it completes fine (200 status, correct response text etc). Even in isolation like above, works fine. One thing I noticed is that the agent tries the function call a 2nd (sometimes 3rd) time if the function errors and seems to accept the 2nd or 3rd response as successful and reads back the response. By this point the agent has finished talking so seems more ‘ready’ to accept new data from the tool. This is what lead me to think it’s the speaking/turn/agent state that is the issue. Or! the agent gets stuck in a ‘sorry, let me try that again’ loop of calling the function (network call succeeds -> data returned -> function error -> ‘sorry, let me try that again’ … and so on) Note, I have some functions with longer running network calls which seem to work ok about 70% of the time but on the odd occasion it’s the same issue. I really welcome any suggestions for a workaround here cos my agent is damn near perfect 😬 😂 Thank you for your help. I can provide further logging if it would help?
b
Hey @broad-hairdresser-84880, just to clarify a little bit: are you saying that an async operation is working when been called standalone, but if been called within a function tool, the tool will triggers an internal error? For example, say you have a network request:
Copy code
const callApi = async () => { ... };
and calling it inside tool:
Copy code
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?
b
correct yeah. The actual async network call always succeeds and returns the correct data. The function
FunctionCallOutput
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 works
cant seem to nail down the exact pattern. The logs from the event listeners are firing kinda randomly so its hard to get proper timing of the events (
voice.AgentSessionEventTypes.FunctionToolsExecuted, voice.AgentSessionEventTypes.AgentStateChanged
) etc
maybe worth noting also (just speaking directly to your example above), im returning plain text from the function, not a promise (also something i have tried unsuccessfully). Again, any help here much appreciated, thanks
b
I think right now for function tool returns, it must be a valid JS object, Map, Set, or a primitive type like string/number is also fine. It will triggers an Internal error if this is not the case. Are there any tool you have does not returning such a valid tool return type?
b
no, they’re all returning plain text strings
I dont think this is the issue because sometimes it works fine with the same response
b
Ok this is interesting, could you send me any example like the fake tool extension call with
await new Promise => timeout(resolve, 2000)
, let me see if I can repro
b
sure yeah, leave it with me, thanks 👍
👍 1
Hi again @bitter-ghost-46918 - managed to create a minimal example here:
Copy code
export 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 }),
);
and the logs for my conversation here:
Copy code
conversation_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
}
b
I tested this on the latest agent js and it works fine. We recently had a fix on the related issue. Could you try upgrading agent-js and see it this issue has been resolved?
b
Hi @bitter-ghost-46918 is this 1.0.5?
yes text 1
…looks that way anyway - amazing news thanks!! I’ll give it a go today 🙏 👍
👍 1
Hi again @bitter-ghost-46918 seems better though it’s still not entirely reliable. I’ll get you another example across. There is still a talk/function failure happening when a certain pattern is hit. Details to follow with example
hi again @bitter-ghost-46918 - sorry for the delay on this, ive updated to V1.0.6 and still have the same issue, minimal example of the agent…
Copy code
const 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,
    });
You can actually replace the
Copy code
await ctx.waitForPlayout();
with any async call, this throws a function call error…
Copy code
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
}
seems 100% related to handling async functions + speaking from inside a tool call
im not sure if this helps but i have a really nasty workaround that seems to work perfectly…
Copy code
execute: 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);
          },