Skip to content

Instantly share code, notes, and snippets.

@TranBaVinhSon
Created June 25, 2023 14:50
Show Gist options
  • Save TranBaVinhSon/4d6ca8e2bae1e056693da5c64bb3a688 to your computer and use it in GitHub Desktop.
Save TranBaVinhSon/4d6ca8e2bae1e056693da5c64bb3a688 to your computer and use it in GitHub Desktop.
Experiment of OpenAI Function Calling
import { ChatCompletionRequestMessage, Configuration, OpenAIApi } from "openai";
var prompt = require("prompt-sync")();
require("dotenv").config();
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function getWeather(location: string, unit = "fahrenheit") {
// Get the current weather in a given location
const weatherInfo = {
location: location,
temperature: "72",
unit: unit,
forecast: ["sunny", "windy"],
};
return weatherInfo;
}
async function getStockPrice(stockCode: string) {}
async function main() {
let input = "test";
const messages: ChatCompletionRequestMessage[] = [
{ role: "user", content: "Hello world" },
];
const functions = [
{
name: "getWeather",
description: "Get the current weather in a given location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city and state, e.g. San Francisco, CA",
},
unit: { type: "string", enum: ["celsius", "fahrenheit"] },
},
required: ["location"],
},
},
{
name: "getStockPrice",
description: "Get the current stock price of a given company stock code",
parameters: {
type: "object",
properties: {
stockCode: {
type: "string",
description: "The company stock code, e.g. AAPL, GOOG",
},
},
required: ["stockCode"],
},
},
];
while (input) {
const chatCompletion = await openai.createChatCompletion({
model: "gpt-3.5-turbo-0613",
messages: messages,
functions: functions,
});
const response = chatCompletion.data.choices[0].message;
console.log(response?.content);
if (response?.function_call) {
console.log("function call", response?.function_call);
// Handle logic here
}
const input = prompt(">");
if (response?.content) {
messages.push({
role: "system",
content: response?.content as any,
});
}
messages.push({
role: "user",
content: input as any,
});
}
}
main()
.then((result) => {
console.log("Finish");
})
.catch((error) => console.log(error?.response?.data));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment