Create AI agents and tools using GPT in NodeJS 🚀🤖
Tags: javascript, openai, webdev, typescript
Published: 2023-06-21 11:01:37

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ji0g906jnkaiwch0x99o.jpeg)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d2s84f58h1lukwheu4c0.png)

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](https://www.npmjs.com/package/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](https://nodejs.org/) and [npm](https://www.npmjs.com/) 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:

```bash
npm install -g typescript
```

### 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
```


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

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

```bash
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:

```ts
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:

```ts
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:

```ts
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 💻

```typescript
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 🌐

```typescript
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 🛠

```typescript
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!

- [Checkout the github repo](https://github.com/etherlegend/openai-agent)
- [Connect & ask questions in twitter](https://twitter.com/etherlegend)
- [Read about Function APIs here if you are not aware about it](https://openai.com/blog/function-calling-and-other-api-updates?ref=upstract.com) - how ever, specific knowledge of OpenAI API/structure is not required to use this package.