A sample app to demonstrate Function calling using the latest format in Chat Completions API and also in Assistants API.
A sample app to demonstrate Function calling using the latest format in Chat Completions API and also in Assistants API.
v0.0.2
A sample app to demonstrate Function calling using the latest format in Chat Completions API and also in Assistants API.
This application is built using manual setup of Next.js 13.
最新のフォーマットを使用したChat Completions APIおよびAssistants APIでの「function calling」をデモンストレーションするサンプルアプリケーション。
このアプリケーションはNext.js 13の手動セットアップを使用して構築されています。
Updated: Using v4.18.0 OpenAI Node module
We will be using gpt-3.5-turbo-1106. You can also replace it with gpt-4-1106-preview by editing the service/openai.js file. These two models supports the new function calling format and parallel function calling.
In order to improve function calling, there are four key aspects to consider:
Even though function calling can be executed without the addition of a system prompt, my experience suggests that it is better to have one. It is like the icing on a cake. In this sample application, we’ve included a simple system prompt to facilitate operations.
…Here, we have enumerated the available tools/functions and provided guidelines on when they should be invoked. We have also included additional instructions on how to manage certain functions and other general directives. Given that we’re dealing with events, it’s necessary to append the current date.
For this sample app, we have the following functions:
To handle the output for these functions/tools, I made a mock API call handler. See mockapi.js. To simulate actual data, I also "cache" the result to make it appear real so that you can go back and forth and have the same result using the same parameters.
Now, when you are writing your own functions, you need to make sure that the names, parameters and descriptions actually makes sense and easily understandable.
Do not use uncommon abreviations or acronyms in names and parameters, specially the function name. The function name should convey exactly what you are tring to achieve. The description should also be clear and avoid writing very long description.
The parameters should also make sense in the context of the function. Otherwise, the AI will not know how to supply its value. Worst, the AI will probably make up its own parameter.
A good rule of thumb is if a normal person can understand your function just by reading the JSON schema.
This refers to the output of the external API when you supply the result from function calling. Check the mock api handler for this app.
You need to handle all probable cases, all errors so that the AI will know how to handle them on their own. Be descriptive in your status and message. The AI will pickup your wording when it summarizes the result.
For example, if you ask for the weather forecast for a certain place without supplying the date, and get_weather is invoked, here is a sample function output:
{ error: 'Invalid date', message: 'Please specify the date' }Supply a clear and concise function output and let the AI deal with whatever the case might appear. Do not attempt to intercept it midway and handle it yourself. Just use the output to send the result back to the AI.
The following is a basic guide on how to manage function calls in the Chat Completions API.
Please note that we are adding the context to all API calls. This is very important. You need to add the context unless your application is just one shot function calling.
…If the first call does not trigger function calling, no need to call the function loop.
Only when function calling is triggered, then we will handle it in a loop. The reason for this is there is a high possibility that the 2nd API call might still result with function calling. The AI often times call the functions on their own volition, if it see fit. So we will continue to process everything in a loop until the AI no longer calls function calling. Without handling it this way, you will curtail the AI's way to respond. Of course, it can run amok, so just in case, set a maximum loop limit before you hit the break.
Now, if you look at my implementation, I am calling two endpoints separately for the 1st API call and 2nd API call. This is a not so elegant way to handle what I just layed out above lol. I am doing this because there are cases when in 2nd function call, content (text) can be included in the result and I want to display it, too. If I am using streaming, this is not necessary, but alas, I do not know how to implement streaming in Next.js yet lol.
Okay, so much for the explanations. Let's see how it all works.
So, we start by asking for the events from a particular location, in this case, Sapporo.
Surprisingly, the AI send us the complete event info in one call.
But under the hood, we can see that the AI called function calling twice!
First, calling get_events to get all events given a location.
// function calling
[
{
id: 'call_fGx6ErPI3O2Ktw4WbDOCY4ob',
type: 'function',
function: {
name: 'get_events',
arguments: '{"location":"Sapporo","date":"2023-11-24"}'
}
}
]
// mock output
[
{
tool_call_id: 'call_fGx6ErPI3O2Ktw4WbDOCY4ob',
role: 'tool',
name: 'get_events',
content: '{\n' +
' "location": "Sapporo",\n' +
' "date": "2023-11-24",\n' +
' "event": "Street Dance Parade"\n' +
'}'
}
]It then decided, what the heck, let's get the event information, too, invoking get_event function using the result from the previous function as parameters.
…Notice the links and images included in the summary. If you wish to incorporate links and images, remember that relative paths are not recognized. You will also need to use HTTPS URLs.
Next, we then we call the weather and search for hotel and get more information about the hotel.
…Unsatisfied, we asked to search for hotel in another location. This is to test how the AI can juggle the parameters. We just changed the location to Kita Hiroshima instead of Sapporo.
…Given the list of hotels, we asked for the cheapest hotel from the result.
Now, we see the parallel function calling, where two get_hotel are called at the same time.
I was hoping that the AI will determine the cheapest itself and just show me the cheapest one.
However, it just displayed the result from the parallel function calling.
…Now, to test how it remembers the previous calls, we ask for reservation to the hotel in Sapporo.
…It remembers! But reserve_hotel function needs the user full name.
The main reason that the AI are prompting the user for their full name is the mock result from reserve_hotel.
...
content: '{\n' +
' "status": "No name provided",\n' +
' "message": "Please ask user provide your full name",\n' +
' "hotel": "The Oak Inn",\n' +
' "location": "Sapporo",\n' +
' "numberOfGuests": 1,\n' +
' "checkInDate": "2023-11-24",\n' +
' "checkOutDate": "2023-11-25",\n' +
' "roomType": "single",\n' +
' "specialRequests": [\n' +
' "non-smoking room",\n' +
' "quiet room"\n' +
' ]\n' +
'}'We provided status and message to explicitly tell the AI that we need the name.
…The parallel function call illustrated above uses the same function. Let's give another example wherein the functions are different.
user: what is happening in sapporo on saturday and will it rain that day?
…Here, we asked for the event and weather in a location at the same time. If you noticed, the two functions share the same parameters. What if the parameters are different?
user: What is happening in Otaru on Friday and what is the weather in Asahikawa tomorrow?
…Select the Assistants API in drop down to run the function calling demo using Assistants API. You need to create the Assistants in the dev page first and copy the Assistant id to the .env file. I do not want to create dynamic assistants. This way you can also test your Assistant in the Playground.
For this example, you may want to copy the system prompt
…Then add the functions one by one by copying the content of each function JSON schema from lib directory. Sorry, currently, there is no easier way to do this.
Then run the app again and test it similar to what we did in Chat Completions. Please note that it takes more time compared to Chat Completions and often ends in failure. Check and monitor the console log in command console (not the browser's) to see everything.
Be sure to delete the thread after you use it since currently we have no way of seeing all abandoned and undeleted threads. Use the blue Reset button to delete the thread id during Assistants API mode.
Using Assistants API is pretty straight-forward
…Notice the metadata included in the message. We will use it as reference point to mark the last message when we retrieve the messages later.
Now, we run the thread. Here we append today's date information to the main instruction for the AI to know current date which is important in our functions. Please be aware that if you do not add the main instruction and just set a new prompt, it will override it.
const run = await openai.beta.threads.runs.create(
thread_id,
{
assistant_id: process.env.OPENAI_ASSISTANT_ID,
instructions: assistant_instructions + `Today is ${new Date()}`
}
)Then we check the run status by every interval using a do while loop with a wait function.
do {
const run = await openai.beta.threads.runs.retrieve(thread_id, run_id)
if(run.status === 'completed') {
// retrieve messages
isCompleted = true
} else if(run.status === 'requires_action') {
// process function calling
} else if(run.status === 'expired' || run.status === 'cancelled' || run.status === 'failed') {
isCompleted = true
}
} while(!isCompleted)When the status is requires_action, it means the AI is invoking our functions.
Get the required_action property of the run object and check the submit_tools_outputs property.
const required_action = run.required_action
const required_tools = required_action.submit_tool_outputs.tool_calls
let tool_output_items = []
required_tools.forEach((rtool) => {
const function_nameNo open issues yet, or sync has not completed.