#How can I call a tool in ChatGPT completions endpoint in Javascript

1 messages · Page 1 of 1 (latest)

sullen onyx
#

How to call a custom function in javascript?

wicked wedgeBOT
#

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:

  1. First, you need to define your custom function in the tools parameter. 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
    ]
  }
];
  1. 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 the tools parameter 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);
}
  1. When you receive the response from the API, you can check the tool_calls field 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.

For more details, you can refer to the OpenAI Cookbook (https://cookbook.openai.com/examples/how_to_build_an_agent_with_the_node_sdk#creating-the-agent-function) and the OpenAI API documentation (https://platform.openai.com/docs/guides/function-calling).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: