DEV Community

Anoop
Anoop

Posted on • Updated on

Create AI agents and tools using GPT in NodeJS πŸš€πŸ€–

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 an agent that can find interesting news articles for you

Image description

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

Image description

This article will explain how you can build autonomous agents using openai-agent package I published recently - It allows you to easily convert your regular NodeJS functions as tools for agents you may build using the OpenAI functions API, abstracting most of it. Now you can create a bunch of functions, and the agent will use it's GPT brain to pick and choose the one to run step by step, also figuring out the parameters to pass etc. Essentially, replacing your deterministic paths with general intelligence. Interested?

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
Enter fullscreen mode Exit fullscreen mode

Before you start

First, make sure you have Node.js and typescript dependencies installed. If you don't have it installed, you can download it from the official Node.js website.

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

"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"declaration": true
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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...
  }
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

Collapse
 
vampeyer profile image
Jake T. (Vampeyer )

That is super awesome - I dont know how I did not see this earlier , yeah thats pretty cool , hey do you have any other like more detailed instrustions on how to do that in a docker sontainer ? just the skeleton ?

Thx , This is cool -

Collapse
 
digital_pig profile image
Digital Pig

It's a shame this isn't opensource so we could use local models. I checked through the code but there is no way from a config standpoint to set the base URL.

Thanks though