YouTube link: FunctionChain: OpenAI Function Calling Simplified in Node.js
- Install the package using npm or yarn:
npm install ai-function-chain
# or
yarn add ai-function-chain
# or
pnpm install ai-function-chain
- Create a file named
.env
at the root of your project. Obtain your OpenAI API Key from here, and add it to the.env
file:
OPENAI_API_KEY=your_openai_api_key
To setup FunctionChain
:
- Create an
index.js
file in the root of your project. - Import the
FunctionChain
class fromai-function-chain
and instantiate it. - Call the
call
method with a message. Optionally, you can specify a set of functions to execute.
import { FunctionChain } from "ai-function-chain";
const functionChain = new FunctionChain();
async function main() {
const res1 = await functionChain.call("Get me the latest price of Bitcoin");
const res2 = await functionChain.call("Open the calculator on my computer");
const res3 = await functionChain.call("Get me the latest price of Ethereum", {
functionArray: ["fetchCryptoPrice"] // Optionally specify which functions to use
});
const res4 = await functionChain.call("Take a screenshot.");
const res5 = await functionChain.call("What was apple's revenue in the last year?");
console.log(res1, res2, res3, res4, res5);
}
main();
You can customize FunctionChain instance by specifying different OpenAI model and a custom directory for your function modules:
const initOptions = {
openaiOptions: {
model: "gpt-3.5-turbo-0613", // specify a different model if needed
},
functionsDirectory: "./myFunctions", // specify a custom directory if you have one
};
const functionChain = new FunctionChain(initOptions);
- Create a new JavaScript file for your function in the
functionsDirectory
specified while creating theFunctionChain
instance. - Follow the following pattern to define your function:
import { exec } from 'child_process';
export const execute = (options) => {
const { appName } = options;
return new Promise((resolve, reject) => {
exec(`open -a "${appName}"`, (error, stdout, stderr) => {
if (error) {
console.warn(error);
reject(`Error opening ${appName}: ${error.message}`);
}
resolve(`${appName} opened successfully.`);
});
});
}
export const details = {
name: "openApp",
description: "Opens a specified application on your computer",
parameters: {
type: "object",
properties: {
appName: {
type: "string",
description: "The name of the application to open"
},
},
required: ["appName"],
},
example: "Open the 'Calculator' application"
};
After setting up index.js
and adding your functions, run your project using:
npm run dev