Function calling with Assistants API

I’m trying to create an assistant using Assistants API that would call a function for handling REST API calls to my database, so the assistant could retreive data from my database and and answer questions based on it.

What I’m struggling with is actually calling the function and passing function data back to the assistant, as I’m currently stuck on “status”:“requires_action”. Based on the documentation (OpenAI Platform) I know I should provide outputs back to the run object, but I’m not sure when to do so.

Should I periodically check run status and then call the function manually with information in function object if status is “requires_action”? If anyone has a working example I would greatly appreciate it! :smiley:

I’m fairly new to this so sorry if I’m asking something fairly obvious.

1 Like

EDIT: This line in the code below is wrong. At first, I thought assistant can request only one tool call at the same time, but after switching to GPT4 Turbo, it sometimes requests multiple tool calls simultaneously. All calls outputs have to be passed at the same time! I’ll post an updated code a bit later.

const toolCall = runStatus.required_action.submit_tool_outputs.tool_calls[0];

This is the best solution I came up with for now. I think there should be a better solution, but I can’t seem to find it.

const waitForRunCompletion = async (threadId, runId) => {
  let runComplete = false;
  while (!runComplete) {
    const runStatus = await openai.beta.threads.runs.retrieve(threadId, runId);

    runComplete =
      runStatus.status === "completed" || runStatus.status === "failed";

    console.log("Run status:", JSON.stringify(runStatus));

    if (runStatus.status === "requires_action") {
      const toolCall = runStatus.required_action.submit_tool_outputs.tool_calls[0];
      const value = eval(`${toolCall.function.name}(${toolCall.function.arguments.location})`)
      const id = toolCall.id;

      await openai.beta.threads.runs.submitToolOutputs(threadId, runId, {
        tool_outputs: [{ tool_call_id: id, output: value }],
      });
    }
  }
  console.log("Run complete");
};
2 Likes

toolCall, {
id: ‘call_56cm1K5j0H9825QqezaPTa2J’,
type: ‘function’,
function: { name: ‘get_stock_price’, arguments: ‘{“symbol”:“AAPL”}’ }
}

I’m getting this error on this line const value = eval({toolCall.function.name}({toolCall.function.arguments.location}))

ReferenceError: get_stock_price is not defined

Do you have get_stock_price function defined in your code?