Build an AI Agent with OpenAI Functions and The Node SDK
AboutCommentsNotes
Build an AI Agent with OpenAI Functions and The Node SDK
Expand for more info
index.js
run
preview
console
import OpenAI from "openai";

const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY
});

async function getLocation() {
const response = await fetch('https://ipapi.co/json/');
const locationData = await response.json();
return locationData;
}

async function getCurrentWeather(latitude, longitude) {
const url = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&hourly=apparent_temperature`;
const response = await fetch(url);
const weatherData = await response.json();
return weatherData;
}

const functionDefinitions = [
{
name: "getCurrentWeather",
description: "Get the current weather in a given location given in latitude and longitude",
parameters: {
type: "object",
properties: {
latitude: {
type: "string",
},
longitude: {
type: "string",
}
},
required: ["longitude", "latitude"]
}
},
{
name: "getLocation",
description: "Get the user's location based on their IP address",
parameters: {
type: "object",
properties: {}
}
}
]

const availableFunctions = {
getCurrentWeather,
getLocation
};

const messages = [{
role: "system",
content: `You are a helpful assistant. Only use the functions you have been provided with.`
}];

async function agent(userInput) {
messages.push({
role: "user",
content: userInput,
});

for (let i = 0; i < 5; i++) {
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: messages,
functions: functionDefinitions
});

const { finish_reason, message } = response.choices[0];
console.log(message);


if (finish_reason === "function_call") {
const functionName = message.function_call.name;
const functionToCall = availableFunctions[functionName];
const functionArgs = JSON.parse(message.function_call.arguments);
const functionArgsArr = Object.values(functionArgs);
const functionResponse = await functionToCall.apply(null, functionArgsArr);

messages.push({
role: "function",
name: functionName,
content: `
The result of the last function was this: ${JSON.stringify(functionResponse)}
`
});
}

else if (finish_reason === "stop") {
messages.push(message);
return message.content;
}
}
return "The maximum number of iterations has been met without a suitable answer. Please try again with a more specific input.";
}

agent("Please suggest some activities based on my location and the weather.");
Console
{role:
"assistant"
, content:
null
, function_call:
{name:
"getLocation"
, arguments:
"{}"
}
}
,
{role:
"assistant"
, content:
null
, function_call:
{name:
"getCurrentWeather"
, arguments:
" { "latitude": "59.955", "longitude": "10.859" }"
}
}
,
{role:
"assistant"
, content:
"Based on your location in Oslo, Norway, and the current weather, which appears to be cool but not too cold, here are a few activities you might enjoy: 1. Visit the Viking Ship Museum: The museum is indoors, perfect for a cool day. It houses well-preserved Viking ships and artifacts from the Viking period. 2. Explore the Oslofjord: Even though it's a bit chilly, exploring the fjord can offer beautiful scenery. Dress warmly! 3. Enjoy a stroll in the Vigeland Sculpture Park: This popular tourist destination showcases the large collection of sculptures by Gustav Vigeland. The weather should be perfect to enjoy this outdoor activity. 4. Visit the National Gallery: If you prefer indoor activities and are interested in art, the National gallery hosts an impressive collection which includes Edvard Munch's The Scream. 5. Go for a coffee: Norwegian people love their coffee. You can visit one of the cosy cafes in the city centre, sit back, relax, and watch the world go by. Remember to dress warmly and enjoy your day in Oslo!"
}
,
/index.html
-9:08