Accessing OpenAI Function API From #NodeJs / #Typescript — To Invoke Functions & Build Agents

Anoop 🖖🏼
5 min readJun 21, 2023

--

This article will explain how you can build autonomous agents using the OpenAI Function API from NodeJs & Typescript — Invoking NodeJS functions directly using the openai-agent package

AI agents are code or mechanisms which act to achieve predetermined goals. The same way you give a bunch of tools to someone and ask them to go and accomplish a goal, you can ask the agent to perform a task for you, equipping your agent with the required tools. For example, here is a simple agent that'll use a set of functions to search the web to get you what you ask.

Here is another agent that can do anything in your computer (I advise a docker container), based on your instructions using your terminal

You can see the package here openai-agent, and the link to Github repo for the package is below. But first, let us see how to create few agents. You being the neo, now you can own them.

Using the OpenAI-Agent Framework 📢

Built in TypeScript, the OpenAI-Agent Framework is designed to make your life easier and your code cleaner. You can build agents that interact in a chat-like manner, perform tasks, and integrate real-world tooling. And the best part? It’s straightforward to use!

First, ensure that you have Node.js and npm installed. This package is built using TypeScript, so you might also want to have the TypeScript compiler installed globally. You can install it using npm:

npm install -g typescript

Important: As this library uses experimental reflection decorators, add this to your tsconfig.json

"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": true

Get on Board: Installing and Configuring OpenAI-Agent 🛠️

Let the fun begin. To install the OpenAI Agent package, run the following command:

npm install openai-agent

To interact with OpenAI’s GPT Functions and creating agents, you’ll need an OpenAI API key and the model ID you want to use. To provide these details, create a .env file in the root of your project. You should visit OpenAI site and you obtain an API key after registering.

OPENAI_API_KEY=your_openai_api_key
OPENAI_MODEL=gpt-3.5-turbo-0613
SERPAPI_API_KEY=your_serp_key

SERPAPI_API_KEY is optional and required only if you use the InternetTools, you can get a free one from https://serpapi.com/

You’ll need to replace your_openai_api_key and your_serp_key with your actual OpenAI API key and the SERP key

Building an Agent 🤖

Creating an agent is as simple as instantiating the OpenAIAgent class. Here's a basic example:

import { OpenAIAgent } from 'openai-agent';
const myAgent = new OpenAIAgent(myApiKey, myModel);

If you have your .env file added, you don’t need to provide any parameters when you create the agent. Now your agent is ready to go!

Creating Custom Functions 🔧

The real power of OpenAIAgent Framework comes from its ability to call predefined functions using OpenAIFunction decorator. This lets you create highly interactive and versatile agents.

Here’s an example of a function that searches the Internet:

import { OpenAIFunction } from 'openai-agent';
class MyFunctions {
@OpenAIFunction(
"Searches the internet using SerpApi to get search results",
{
query: {
type: "string",
description: "The search query",
required: true,
},
}
)
async searchInternet(query: string): Promise<string> {
// Your search implementation here...
}
}

Example Usage 📝

Once you’ve set up your agent and functions, you can put them together like this:

import { OpenAIAgent } from 'openai-agent';
// Initialize your OpenAI Agent
const myAgent = new OpenAIAgent(myApiKey, myModel);
// Provide your functions to the agent
const result = await myAgent.runAgent(
"search the internet for 'best AI tools'",
[new MyFunctions()]
);
console.log(result.content);

Crazier Example Usages 👩‍💻

Here are some more examples of how you can use this to create agents with few built in function kits (TerminalFunctions and InternetFunctions). Please know what you do, as this will let the agent use your terminal to issue commands to get to it’s goal. Don’t wreck the world.

Agent that can use your Terminal 💻

const agent1 = new OpenAIAgent(process.env.OPENAI_API_KEY, process.env.OPENAI_MODEL);
const osInfoResponse = await agent1.runAgent(
[{ role: "user", content: "get my os info and write a poem about it" }],
[new TerminalFunctions()],5
);
console.log(osInfoResponse?.content);

Agent that can Search the Web 🌐

const agent2= new OpenAIAgent(process.env.OPENAI_API_KEY, process.env.OPENAI_MODEL);
const internetSearchResponse = await agent2.runAgent(
[{ role: "user", content: 'search internet for latest news on OpenAI functions and get me the titles & links to top 5 articles' }],
[new InternetFunctions()], 10
);
console.log(internetSearchResponse?.content);

Agent that can use your Terminal to do what you ask 🛠

const agent3= new OpenAIAgent(process.env.OPENAI_API_KEY, process.env.OPENAI_MODEL);
const taskResponse = await agent3.runAgent(
[{ role: "user", content: 'you are an expert ai assistant. Ask the user to give you inputs and do what she/he asks for, and do this in a loop, till he types exit' }],
[new TerminalFunctions()], 10
);
console.log(taskResponse?.content);

Concluding Thoughts 🎉

The OpenAI-Agent Framework opens a new, exciting path to creating powerful and versatile autonomous agents. Whether you want to fetch data from the Internet, manipulate files, control hardware, or just find a good joke, this package is a fantastic tool to have in your toolkit.

Remember, the only limit to what you can build with OpenAI-Agent is your imagination. So, go ahead and give it a try! Happy coding, and let the AI revolution continue!

--

--

Anoop 🖖🏼

I build stuff. Futurist, Speaker, Author. 2x Entrepreneur, Investor. Ex Director @ Merck, MVP @ Microsoft. Follow in twitter @amazedsaint