Advanced Features
Function Calling
Use function calling to let GPT call your functions and integrate with external systems.
What is Function Calling?
Function calling (also called "tool use") allows you to define functions and let the model decide when and how to call them. The model doesn't actually execute the functions — it just tells you what function to call and with what arguments.
How It Works
- Define your functions with JSON schemas
- Pass them to the API in the
toolsparameter - If the model wants to call a function, it returns a
tool_callsresponse - Your code executes the function and returns the result
- Send the result back to the model for a final response
Use Cases
- Querying databases or APIs
- Getting real-time data (weather, stock prices)
- Executing code
- Sending emails or messages
- CRUD operations
Example
javascript
import OpenAI from 'openai';
const openai = new OpenAI();
// Define available tools
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "Get the current weather for a location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city and country, e.g. 'Paris, France'",
},
unit: {
type: "string",
enum: ["celsius", "fahrenheit"],
description: "Temperature unit",
},
},
required: ["location"],
},
},
},
{
type: "function",
function: {
name: "search_products",
description: "Search for products in the catalog",
parameters: {
type: "object",
properties: {
query: { type: "string", description: "Search query" },
max_price: { type: "number", description: "Maximum price filter" },
category: { type: "string", description: "Product category" },
},
required: ["query"],
},
},
},
];
// Simulated function implementations
const functions = {
get_weather: ({ location, unit = "celsius" }) => ({
location,
temperature: 22,
unit,
description: "Partly cloudy",
}),
search_products: ({ query, max_price, category }) => [
{ id: 1, name: "Widget Pro", price: 29.99 },
{ id: 2, name: "Super Widget", price: 49.99 },
],
};
// Agent loop
async function runAgent(userMessage) {
const messages = [{ role: "user", content: userMessage }];
while (true) {
const response = await openai.chat.completions.create({
model: "gpt-4o-mini",
messages,
tools,
tool_choice: "auto",
});
const message = response.choices[0].message;
messages.push(message);
if (!message.tool_calls) {
return message.content; // Final response
}
// Execute each tool call
for (const toolCall of message.tool_calls) {
const fnName = toolCall.function.name;
const args = JSON.parse(toolCall.function.arguments);
const result = functions[fnName]?.(args) ?? "Function not found";
messages.push({
role: "tool",
tool_call_id: toolCall.id,
content: JSON.stringify(result),
});
}
}
}
const answer = await runAgent("What's the weather in London?");
console.log(answer);Try it yourself — JAVASCRIPT