#How can I call a tool in ChatGPT completions endpoint in Javascript
1 messages · Page 1 of 1 (latest)
Hi @sullen onyx. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To call a custom function using the ChatGPT completions endpoint in JavaScript, you can use the OpenAI Node.js SDK. Here's a basic example of how you can do this:
- First, you need to define your custom function in the
toolsparameter. This is an array of function specifications that you provide to the model. The model will then generate function arguments that adhere to these specifications.
let tools = [
{
"name": "myFunction",
"type": "function",
"description": "This is my custom function",
"args": [
{
"name": "arg1",
"type": "string",
"description": "This is the first argument",
"optional": false
},
// Add more arguments as needed
]
}
];
- Then, you can use the
chat.completions.create()method to send a request to the Chat completions endpoint. In the configuration object for this method, you can specify thetoolsparameter to include your custom function.
async function agent(userInput) {
messages.push({
role: "user",
content: userInput,
});
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: messages,
tools: tools,
});
console.log(response);
}
- When you receive the response from the API, you can check the
tool_callsfield to see if the model has generated any function calls. If it has, you can then execute these function calls in your own code.
let functionCalls = response.choices[0].message.tool_calls;
if (functionCalls) {
for (let functionCall of functionCalls) {
let functionName = functionCall.function.name;
let functionArgs = JSON.parse(functionCall.function.arguments);
// Execute the function call in your own code
// For example, if you have a function called "myFunction" defined in your code:
if (functionName === "myFunction") {
myFunction(functionArgs);
}
}
}
Please note that the OpenAI API will not actually execute any function calls. It's up to you to execute these function calls in your own code.