Get up and running with LlamaIndex.TS in just a few minutes. This guide will walk you through creating your first Retrieval-Augmented Generation (RAG) application.
First, install the main package and an LLM provider. We’ll use OpenAI for this example.
npm install llamaindex @llamaindex/openai
The core llamaindex package provides the framework, while @llamaindex/openai adds OpenAI LLM and embedding support.
2
Set Up Your API Key
You’ll need an OpenAI API key. Get one at platform.openai.com/api-keys.Set your API key as an environment variable:
export OPENAI_API_KEY="sk-..."
Or create a .env file:
.env
OPENAI_API_KEY=sk-...
3
Create Your First RAG Application
Create a file called app.ts with the following code:
app.ts
import { Document, VectorStoreIndex } from "llamaindex";import fs from "node:fs/promises";async function main() { // Load your document const essay = await fs.readFile("./data.txt", "utf-8"); const document = new Document({ text: essay }); // Create an index from your document const index = await VectorStoreIndex.fromDocuments([document]); // Create a query engine const queryEngine = index.asQueryEngine(); // Query your data const response = await queryEngine.query({ query: "What is the main topic of this document?", }); console.log(response.toString());}main().catch(console.error);
Replace "./data.txt" with the path to any text file you want to query.
4
Run Your Application
Execute your application:
npx tsx app.ts
Or if using Node.js with TypeScript:
node --loader tsx app.ts
You should see a response generated from your document!
For more advanced use cases, create an agent that can use tools:
agent.ts
import { openai } from "@llamaindex/openai";import { agent } from "@llamaindex/workflow";import { tool } from "llamaindex";import { z } from "zod";// Define a toolconst weatherTool = tool({ name: "get_weather", description: "Get the current weather for a location", parameters: z.object({ address: z.string().describe("The address"), }), execute: ({ address }) => `${address} is sunny and 72°F!`,});async function main() { // Create an agent with tools const weatherAgent = agent({ llm: openai({ model: "gpt-4o", }), tools: [weatherTool], }); // Run the agent const result = await weatherAgent.run( "What's the weather like in San Francisco?" ); console.log(result.data.message);}main().catch(console.error);
Agents require the @llamaindex/workflow package for orchestration: