Skip to main content

Agent tutorial

We have a comprehensive, step-by-step guide to building agents in LlamaIndex.TS that we recommend to learn what agents are and how to build them for production. But building a basic agent is simple:

Set up

In a new folder:

npm init
npm install -D typescript @types/node

Run agent

Create the file example.ts. This code will:

  • Create two tools for use by the agent:
    • A sumNumbers tool that adds two numbers
    • A divideNumbers tool that divides numbers
  • Give an example of the data structure we wish to generate
  • Prompt the LLM with instructions and the example, plus a sample transcript
import { FunctionTool, OpenAIAgent } from "llamaindex";

const sumNumbers = FunctionTool.from(
({ a, b }: { a: number; b: number }) => `${a + b}`,
{
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "The first number",
},
b: {
type: "number",
description: "The second number",
},
},
required: ["a", "b"],
},
},
);

const divideNumbers = FunctionTool.from(
({ a, b }: { a: number; b: number }) => `${a / b}`,
{
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "The dividend a to divide",
},
b: {
type: "number",
description: "The divisor b to divide by",
},
},
required: ["a", "b"],
},
},
);

async function main() {
const agent = new OpenAIAgent({
tools: [sumNumbers, divideNumbers],
});

const response = await agent.chat({
message: "How much is 5 + 5? then divide by 2",
});

console.log(response.message);
}

void main().then(() => {
console.log("Done");
});

To run the code:

npx tsx example.ts

You should expect output something like:

{
content: 'The sum of 5 + 5 is 10. When you divide 10 by 2, you get 5.',
role: 'assistant',
options: {}
}
Done