Create a basic agent
We want to use await
so we're going to wrap all of our code in a main
function, like this:
// Your imports go here
async function main() {
// the rest of your code goes here
}
main().catch(console.error);
For the rest of this guide we'll assume your code is wrapped like this so we can use await
. You can run the code this way:
npx tsx example.ts
Load your dependencies
First we'll need to pull in our dependencies. These are:
- The OpenAI class to use the OpenAI LLM
- FunctionTool to provide tools to our agent
- OpenAIAgent to create the agent itself
- Settings to define some global settings for the library
- Dotenv to load our API key from the .env file
import { OpenAI, FunctionTool, OpenAIAgent, Settings } from "llamaindex";
import "dotenv/config";
Initialize your LLM
We need to tell our OpenAI class where its API key is, and which of OpenAI's models to use. We'll be using gpt-4o
, which is capable while still being pretty cheap. This is a global setting, so anywhere an LLM is needed will use the same model.
Settings.llm = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
model: "gpt-4o",
});
Turn on logging
We want to see what our agent is up to, so we're going to hook into some events that the library generates and print them out. There are several events possible, but we'll specifically tune in to llm-tool-call
(when a tool is called) and llm-tool-result
(when it responds).
Settings.callbackManager.on("llm-tool-call", (event) => {
console.log(event.detail.payload);
});
Settings.callbackManager.on("llm-tool-result", (event) => {
console.log(event.detail.payload);
});
Create a function
We're going to create a very simple function that adds two numbers together. This will be the tool we ask our agent to use.
const sumNumbers = ({ a, b }) => {
return `${a + b}`;
};