Implement function calling (tools) with an LLM to fetch real-time data.
Code Playground
JavaScript (V8)
Loading...
Console Output
// Output will appear here...
// For React: ReactDOM.createRoot(rootElement).render(<App />);
// For React: ReactDOM.createRoot(rootElement).render(<App />);
Recommended Answer
Implementation:
import OpenAI from 'openai';
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
// Mock function to get weather
function getCurrentWeather(location) {
// In reality, this would call a weather API
return JSON.stringify({
location,
temperature: "72°F",
condition: "Sunny"
});
}
async function chatWithTools(userMessage) {
const tools = [
{
type: "function",
function: {
name: "getCurrentWeather",
description: "Get the current weather for a location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city name, e.g., San Francisco"
}
},
required: ["location"]
}
}
}
];
// First API call
let messages = [{ role: "user", content: userMessage }];
let response = await openai.chat.completions.create({
model: "gpt-4",
messages,
tools,
});
const responseMessage = response.choices[0].message;
messages.push(responseMessage);
// Check if the model wants to call a function
const toolCalls = responseMessage.tool_calls;
if (toolCalls) {
for (const toolCall of toolCalls) {
const functionName = toolCall.function.name;
const functionArgs = JSON.parse(toolCall.function.arguments);
let functionResponse;
if (functionName === "getCurrentWeather") {
functionResponse = getCurrentWeather(functionArgs.location);
}
messages.push({
role: "tool",
tool_call_id: toolCall.id,
content: functionResponse,
});
}
// Second API call with function results
const secondResponse = await openai.chat.completions.create({
model: "gpt-4",
messages,
});
return secondResponse.choices[0].message.content;
}
return responseMessage.content;
}
// Usage
const answer = await chatWithTools("What's the weather in Boston?");
console.log(answer);