`@xenova/transformers` only ship node.js and browser output, it's not possible to load this in edge runtime and workerd
This reverts commit 34fb1d8992.
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Development Commands
This project uses pnpm as the package manager and Turbo for build orchestration:
-`pnpm install` - Install all dependencies
-`pnpm build` - Build all packages using Turbo
-`pnpm dev` - Start development mode for all packages
-`pnpm test` - Run all unit tests
-`pnpm e2e` - Run end-to-end tests
-`pnpm lint` - Run ESLint across all packages
-`pnpm type-check` - Run TypeScript type checking across workspace
-`pnpm format` - Check code formatting with Prettier
-`pnpm format:write` - Auto-fix formatting issues
-`pnpm circular-check` - Check for circular dependencies using madge
For individual package development:
-`turbo run build --filter="@llamaindex/core"` - Build specific package
-`turbo run test --filter="@llamaindex/core"` - Test specific package
- Navigate to specific package directory and run `pnpm test` for focused testing
-`pnpm clean` - Remove all build artifacts and node_modules across workspace
## Architecture Overview
LlamaIndex.TS is a TypeScript data framework for LLM applications organized as a pnpm monorepo with multiple runtime environment support (Node.js, Deno, Bun, Vercel Edge, Cloudflare Workers).
### Package Structure
**Core Packages:**
-`packages/core/` - Abstract base classes and interfaces for all runtime environments
-`packages/llamaindex/` - Main package that aggregates core functionality
-`packages/env/` - Environment-specific compatibility layers for different JS runtimes
**Provider Packages (`packages/providers/`):**
- LLM providers: `openai/`, `anthropic/`, `ollama/`, `google/`, `groq/`, etc.
- Vector stores: `storage/pinecone/`, `storage/chroma/`, `storage/qdrant/`, etc.
- Embeddings: Various embedding providers integrated within LLM packages
- Readers: `assemblyai/`, `discord/`, `notion/` for data ingestion
**Specialized Packages:**
-`packages/cloud/` - LlamaCloud integration for managed services
-`packages/tools/` - Function calling tools and utilities
-`packages/readers/` - File format readers (PDF, DOCX, etc.)
### Key Architectural Patterns
**Runtime Abstraction:** Core functionality is runtime-agnostic, with environment-specific implementations in separate entry points (`index.ts`, `index.edge.ts`, `index.workerd.ts`).
**Provider Pattern:** LLMs, embeddings, and vector stores implement common interfaces from `@llamaindex/core`, allowing easy swapping between providers.
**Modular Design:** Each provider is a separate package to minimize bundle size - users install only what they need.
- **Agents and Workflows:** Abstractions for building agentic workflows and agents in `packages/workflow`
- **Chat Engines:** Conversational interfaces in `core/chat-engine/`
- **Query Engines:** Document querying with retrieval in `core/query-engine/`
- **Indices:** VectorStoreIndex, SummaryIndex, KeywordTable in `llamaindex/indices/`
- **Node Parsers:** Text splitting and chunking in `core/node-parser/`
- **Ingestion Pipeline:** Document processing workflows in `llamaindex/ingestion/`
- **Storage:** Chat stores, document stores, index stores, and KV stores in `core/storage/`
### Deprecated Components
- **Agents:** ReAct and function calling agents in `core/agent/` and `llamaindex/agent/`
### Testing Structure
- Unit tests in each package's `tests/` directory
- E2E tests in `e2e/` directory with runtime-specific examples
- Tests depend on build artifacts, so always run `pnpm build` before testing
### Multi-Runtime Support
The codebase supports multiple JavaScript runtimes through conditional exports and separate entry points. When making changes, consider compatibility across Node.js, Deno, Bun, and edge runtimes.
### Development Notes
- The project uses Husky for git hooks with lint-staged for pre-commit formatting and linting
- All packages use bunchee for building with dual CJS/ESM support
- Core package exports are organized as sub-modules (e.g., `@llamaindex/core/llms`, `@llamaindex/core/embeddings`)
- Always run `pnpm build` before running tests, as tests depend on build artifacts
We recommend you to understand the basics of Node.js, TypeScript, pnpm, and of course, LLM before contributing.
packages/core which is the main NPM library llamaindex
There are some important folders in the repository:
examples is where the demo code lives
### Turborepo docs
You can checkout how Turborepo works using the default [README-turborepo.md](/README-turborepo.md)
-`packages/*`: Contains the source code of the packages. Each package is a separate npm package.
-`llamaindex`: The starter package for LlamaIndex.TS, which contains the all sub-packages.
-`core`: The core package of LlamaIndex.TS, which contains the abstract classes and interfaces. It is designed for
all JS runtime environments.
-`env`: The environment package of LlamaIndex.TS, which contains the environment-specific classes and interfaces. It
includes compatibility layers for Node.js, Deno, Vercel Edge Runtime, Cloudflare Workers...
-`providers/*`: The providers package of LlamaIndex.TS, which contains the providers for LLM and other services.
-`apps/*`: The applications based on LlamaIndex.TS.
-`next`: Our documentation website based on Next.js.
-`examples`: The code examples of LlamaIndex.TS using Node.js.
## Getting Started
Install NodeJS. Preferably v18 using nvm or n.
Inside the LlamaIndexTS directory:
Make sure you have Node.js LTS (Long-term Support) installed. You can check your Node.js version by running:
```shell
node -v
# v22.x.x
```
npm i -g pnpm ts-node
### Use pnpm
```shell
npm install -g pnpm
```
### Install dependencies
```shell
pnpm install
pnpm install -g tsx
```
Note: we use pnpm in this repo, which has a lot of the same functionality and CLI options as npm but it does do some things better in a monorepo, like centralizing dependencies and caching.
### Build the packages
PNPM's has documentation on its [workspace feature](https://pnpm.io/workspaces) and Turborepo had some [useful documentation also](https://turbo.build/repo/docs/core-concepts/monorepos/running-tasks).
To build all packages, run:
### Running Typescript
When we publish to NPM we will have a tsc compiled version of the library in JS. For now, the easiest thing to do is use ts-node.
### Test cases
To run them, run
```
pnpm run test
```shell
pnpm build
```
To write new test cases write them in [packages/core/src/tests](/packages/core/src/tests)
### Start Developing
We use Jest https://jestjs.io/ to write our test cases. Jest comes with a bunch of built in assertions using the expect function: https://jestjs.io/docs/expect
You can launch the package in dev-mode by running:
### Demo applications
There is an existing ["example"](/examples/README.md) demos folder with mainly NodeJS scripts. Feel free to add additional demos to that folder. If you would like to try out your changes in the core package with a new demo, you need to run the build command in the README.
You can create new demo applications in the apps folder. Just run pnpm init in the folder after you create it to create its own package.json
### Installing packages
To install packages for a specific package or demo application, run
```
pnpm add [NPM Package] --filter [package or application i.e. core or docs]
```shell
pnpm dev
```
To install packages for every package or application run
This will use turbo to run all packages in watch-mode. This means you can make changes and have them automatically built.
If you want to customize what packages are built/watched, you can run turbo directly and adjust the filter:
```shell
pnpm turbo run dev --filter="./packages/core" --concurrency=100
```
pnpm add -w [NPM Package]
In another terminal, you can write and run any script needed to quickly test your changes. For example:
"The user is a software engineer who loves TypeScript and LlamaIndex.",
messageRole:"system",
}),
],
});
asyncfunctionmain() {
constresult=awaitmemory.getLLM();
console.log(result);
}
voidmain().catch(console.error);
```
And run it with:
```shell
pnpm exec tsx my_script.ts
```
This flow allows you to easily test your changes without having to build the entire project.
Once you are happy with your changes, be sure to add tests (and confirm existing tests are passing!).
### Run tests
#### Unit tests
After build, to run all unit tests, call:
```shell
pnpm test
```
Unit tests are located in the `tests` folder of each package. They are using their own package (e.g. `@llamaindex/core-tests` for `@llamaindex/core`). The tests are importing the package under test and the test package is not published.
#### E2E tests
To run all E2E tests, call:
```shell
pnpm e2e
```
All E2E tests are in the `e2e` folder.
### Docs
To contribute to the docs, go to the docs website folder and run the Docusaurus instance.
See the [docs](./apps/next/README.md) for more information.
```bash
cd apps/docs
pnpm install
pnpm start
```
## Adding a new package
That should start a webserver which will serve the docs on https://localhost:3000
Please follow these steps to add a new package:
Any changes you make should be reflected in the browser. If you need to regenerate the API docs and find that your TSDoc isn't getting the updates, feel free to remove apps/docs/api. It will automatically regenerate itself when you run pnpm start again.
1. Only add new packages to the `packages/providers` folder.
2. Use the `package.json` and `tsconfig.json` of an existing packages as template.
3. Reference your new package in the root `tsconfig.json` file
4. Add your package to the `examples/package.json` file if you add a new example.
## Publishing
## Before sending a PR
To publish a new version of the library, run
Before sending a PR, make sure of the following:
1. Tests are all running and you added meaningful tests for your change.
2. If you have a new feature, document it in the `apps/next` docs folder.
3. If you have a new feature, add a new example in the `examples` folder.
4. You have a descriptive changeset for each PR:
### Bumping the versions of packages you've modified
We use [changesets](https://github.com/changesets/changesets) for managing versions and changelogs. To create a new
changeset, run in the root folder:
```shell
pnpm new-llamaindex
pnpm new-create-llama
pnpm release
git push # push to the main branch
git push --tags
pnpm changeset
```
You will be prompted to choose what packages need their versions bumped, and what kind of bump (major, minor or patch) is needed. Once you carry out this operation, the bumping will be automatic after the PR is merged.
## Publishing (maintainers only)
The [Release Github Action](.github/workflows/release.yml) is automatically generating and updating a
PR called "Release {version}".
This PR will update the `package.json` and `CHANGELOG.md` files of each package according to
the current changesets in the [.changeset](.changeset) folder.
If this PR is merged it will automatically add version tags to the repository and publish the updated packages to NPM.
This Turborepo includes the following packages/apps:
### Apps and Packages
-`docs`: a [Next.js](https://nextjs.org/) app
-`web`: another [Next.js](https://nextjs.org/) app
-`ui`: a stub React component library shared by both `web` and `docs` applications
-`eslint-config-custom`: `eslint` configurations (includes `eslint-config-next` and `eslint-config-prettier`)
-`tsconfig`: `tsconfig.json`s used throughout the monorepo
Each package/app is 100% [TypeScript](https://www.typescriptlang.org/).
### Utilities
This Turborepo has some additional tools already setup for you:
- [TypeScript](https://www.typescriptlang.org/) for static type checking
- [ESLint](https://eslint.org/) for code linting
- [Prettier](https://prettier.io) for code formatting
### Build
To build all apps and packages, run the following command:
```
cd my-turborepo
pnpm build
```
### Develop
To develop all apps and packages, run the following command:
```
cd my-turborepo
pnpm dev
```
### Remote Caching
Turborepo can use a technique known as [Remote Caching](https://turbo.build/repo/docs/core-concepts/remote-caching) to share cache artifacts across machines, enabling you to share build caches with your team and CI/CD pipelines.
By default, Turborepo will cache locally. To enable Remote Caching you will need an account with Vercel. If you don't have an account you can [create one](https://vercel.com/signup), then enter the following commands:
```
cd my-turborepo
npx turbo login
```
This will authenticate the Turborepo CLI with your [Vercel account](https://vercel.com/docs/concepts/personal-accounts/overview).
Next, you can link your Turborepo to your Remote Cache by running the following command from the root of your Turborepo:
LlamaIndex is a data framework for your LLM application.
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in Typescript and Javascript.
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in JS runtime environments with TypeScript support.
Documentation: https://ts.llamaindex.ai/
@@ -19,58 +24,58 @@ Try examples online:
LlamaIndex.TS aims to be a lightweight, easy to use set of libraries to help you integrate large language models into your applications with your own data.
## Getting started with an example:
## Compatibility
LlamaIndex.TS requires Node v18 or higher. You can download it from https://nodejs.org or use https://nvm.sh (our preferred option).
See our official document: https://ts.llamaindex.ai/docs/llamaindex/getting_started
asyncfunctionmain() {
// Load essay from abramov.txt in Node
constessay=awaitfs.readFile(
"node_modules/llamaindex/examples/abramov.txt",
"utf-8",
);
### Adding provider packages
// Create Document object with essay
constdocument=newDocument({text: essay});
In most cases, you'll also need to install provider packages to use LlamaIndexTS. These are for adding AI models, file readers for ingestion or storing documents, e.g. in vector databases.
// Split text and create embeddings. Store them in a VectorStoreIndex
For example, to use the OpenAI LLM, you would install the following package:
// Query the index
constqueryEngine=index.asQueryEngine();
constresponse=awaitqueryEngine.query({
query:"What did the author do in college?",
});
// Output response
console.log(response.toString());
}
main();
```
Then you can run it using
```bash
pnpm dlx ts-node example.ts
```shell
npm install @llamaindex/openai
pnpm install @llamaindex/openai
yarn add @llamaindex/openai
```
## Playground
@@ -79,59 +84,13 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
## Core concepts for getting started:
- [Document](/packages/core/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
- [Node](/packages/core/src/Node.ts): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
- [Embedding](/packages/core/src/Embedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that quesiton.
- [Indices](/packages/core/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
- [QueryEngine](/packages/core/src/QueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query.
- [ChatEngine](/packages/core/src/ChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices.
- [SimplePrompt](/packages/core/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
## Note: NextJS:
If you're using NextJS App Router, you'll need to use the NodeJS runtime (default) and add the following config to your next.config.js to have it use imports/exports in the same way Node does.
```js
exportconstruntime="nodejs";// default
```
```js
// next.config.js
/** @type {import('next').NextConfig} */
constnextConfig={
experimental:{
serverComponentsExternalPackages:["pdf2json"],
},
webpack:(config)=>{
config.resolve.alias={
...config.resolve.alias,
sharp$:false,
"onnxruntime-node$":false,
};
returnconfig;
},
};
module.exports=nextConfig;
```
## Supported LLMs:
- OpenAI GPT-3.5-turbo and GPT-4
- Anthropic Claude Instant and Claude 2
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
- MistralAI Chat LLMs
See our documentation: https://ts.llamaindex.ai/docs/llamaindex/getting_started/concepts
## Contributing:
We are in the very early days of LlamaIndex.TS. If you’re interested in hacking on it with us check out our [contributing guide](/CONTRIBUTING.md)
Please see our [contributing guide](CONTRIBUTING.md) for more information.
You are highly encouraged to contribute to LlamaIndex.TS!
import CodeSource from "!raw-loader!../../../../examples/chatEngine";
# Chat Engine
Chat Engine is a class that allows you to create a chatbot from a retriever. It is a wrapper around a retriever that allows you to chat with it in a conversational manner.
LlamaIndex.TS helps you build LLM-powered applications (e.g. Q&A, chatbot) over custom data.
In this high-level concepts guide, you will learn:
- how an LLM can answer questions using your own data.
- key concepts and modules in LlamaIndex.TS for composing your own query pipeline.
## Answering Questions Across Your Data
LlamaIndex uses a two stage method when using an LLM with your data:
1.**indexing stage**: preparing a knowledge base, and
2.**querying stage**: retrieving relevant context from the knowledge to assist the LLM in responding to a question

This process is also known as Retrieval Augmented Generation (RAG).
LlamaIndex.TS provides the essential toolkit for making both steps super easy.
Let's explore each stage in detail.
### Indexing Stage
LlamaIndex.TS help you prepare the knowledge base with a suite of data connectors and indexes.

[**Data Loaders**](../modules/data_loader.md):
A data connector (i.e. `Reader`) ingest data from different data sources and data formats into a simple `Document` representation (text and simple metadata).
[**Documents / Nodes**](../modules/documents_and_nodes/index.md): A `Document` is a generic container around any data source - for instance, a PDF, an API output, or retrieved data from a database. A `Node` is the atomic unit of data in LlamaIndex and represents a "chunk" of a source `Document`. It's a rich representation that includes metadata and relationships (to other nodes) to enable accurate and expressive retrieval operations.
[**Data Indexes**](../modules/data_index.md):
Once you've ingested your data, LlamaIndex helps you index data into a format that's easy to retrieve.
Under the hood, LlamaIndex parses the raw documents into intermediate representations, calculates vector embeddings, and stores your data in-memory or to disk.
### Querying Stage
In the querying stage, the query pipeline retrieves the most relevant context given a user query,
and pass that to the LLM (along with the query) to synthesize a response.
This gives the LLM up-to-date knowledge that is not in its original training data,
(also reducing hallucination).
The key challenge in the querying stage is retrieval, orchestration, and reasoning over (potentially many) knowledge bases.
LlamaIndex provides composable modules that help you build and integrate RAG pipelines for Q&A (query engine), chatbot (chat engine), or as part of an agent.
These building blocks can be customized to reflect ranking preferences, as well as composed to reason over multiple knowledge bases in a structured way.

#### Building Blocks
[**Retrievers**](../modules/retriever.md):
A retriever defines how to efficiently retrieve relevant context from a knowledge base (i.e. index) when given a query.
The specific retrieval logic differs for difference indices, the most popular being dense retrieval against a vector index.
The easiest way to get started with LlamaIndex is by using `create-llama`. This CLI tool enables you to quickly start building a new LlamaIndex application, with everything set up for you.
Just run
<Tabs>
<TabItem value="1" label="npm" default>
```bash
npx create-llama@latest
```
</TabItem>
<TabItem value="2" label="Yarn">
```bash
yarn create llama
```
</TabItem>
<TabItem value="3" label="pnpm">
```bash
pnpm create llama@latest
```
</TabItem>
</Tabs>
to get started. Once your app is generated, run
```bash npm2yarn
npm run dev
```
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app
## Installation from NPM
```bash npm2yarn
npm install llamaindex
```
### Environment variables
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
```bash
export OPENAI_API_KEY="sk-......" # Replace with your key from https://platform.openai.com/account/api-keys
```
If you want to have it automatically loaded every time, add it to your `.zshrc/.bashrc`.
WARNING: do not check in your OpenAI key into version control.
Once you have [installed LlamaIndex.TS using NPM](installation) and set up your OpenAI key, you're ready to start your first app:
In a new folder:
```bash npm2yarn
npm install typescript
npm install @types/node
npx tsc --init # if needed
```
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
```ts
// example.ts
import fs from "fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
async function main() {
// Load essay from abramov.txt in Node
const essay = await fs.readFile(
"node_modules/llamaindex/examples/abramov.txt",
"utf-8",
);
// Create Document object with essay
const document = new Document({ text: essay });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What did the author do in college?",
});
// Output response
console.log(response.toString());
}
main();
```
Then you can run it using
```bash
npx ts-node example.ts
```
Ready to learn more? Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
LlamaIndex.TS is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. While a python package is also available (see [here](https://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
## 🚀 Why LlamaIndex.TS?
At their core, LLMs offer a natural language interface between humans and inferred data. Widely available models come pre-trained on huge amounts of publicly available data, from Wikipedia and mailing lists to textbooks and source code.
Applications built on top of LLMs often require augmenting these models with private or domain-specific data. Unfortunately, that data can be distributed across siloed applications and data stores. It's behind APIs, in SQL databases, or trapped in PDFs and slide decks.
That's where **LlamaIndex.TS** comes in.
## 🦙 How can LlamaIndex.TS help?
LlamaIndex.TS provides the following tools:
- **Data loading** ingest your existing `.txt`, `.pdf`, `.csv`, `.md` and `.docx` data directly
- **Data indexes** structure your data in intermediate representations that are easy and performant for LLMs to consume.
- **Engines** provide natural language access to your data. For example:
- Query engines are powerful retrieval interfaces for knowledge-augmented output.
- Chat engines are conversational interfaces for multi-message, "back and forth" interactions with your data.
## 👨👩👧👦 Who is LlamaIndex for?
LlamaIndex.TS provides a core set of tools, essential for anyone building LLM apps with JavaScript and TypeScript.
Our high-level API allows beginner users to use LlamaIndex.TS to ingest and query their data.
For more complex applications, our lower-level APIs allow advanced users to customize and extend any module—data connectors, indices, retrievers, and query engines, to fit their needs.
## Getting Started
`npm install llamaindex`
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.md) to build your first application.
Once you're up and running, [High-Level Concepts](./getting_started/concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our Examples section on the sidebar.
An “agent” is an automated reasoning and decision engine. It takes in a user input/query and can make internal decisions for executing that query in order to return the correct result. The key agent components can include, but are not limited to:
- Breaking down a complex question into smaller ones
- Choosing an external Tool to use + coming up with parameters for calling the Tool
- Planning out a set of tasks
- Storing previously completed tasks in a memory module
## Getting Started
LlamaIndex.TS comes with a few built-in agents, but you can also create your own. The built-in agents include:
QueryEngineTool is a tool that allows you to query a vector index. In this example, we will create a vector index from a set of documents and then create a QueryEngineTool from the vector index. We will then create an OpenAIAgent with the QueryEngineTool and chat with the agent.
## Setup
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
```bash
pnpm i llamaindex
```
Then you can import the necessary classes and functions.
```ts
import {
OpenAIAgent,
SimpleDirectoryReader,
VectorStoreIndex,
QueryEngineTool,
} from "llamaindex";
```
## Create a vector index
Now we can create a vector index from a set of documents.
```ts
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
import CodeSource from "!raw-loader!../../../../examples/readers/src/simple-directory-reader";
import CodeSource2 from "!raw-loader!../../../../examples/readers/src/custom-simple-directory-reader";
# Loader
Before you can start indexing your documents, you need to load them into memory.
### SimpleDirectoryReader
[](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
It is a simple reader that reads all files from a directory and its subdirectories.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Currently, it supports reading `.csv`, `.docx`, `.html`, `.md` and `.pdf` files,
but support for other file types is planned.
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions.
Or pass new readers for `fileExtToReader` to support more file types.
`Document`s and `Node`s are the basic building blocks of any index. While the API for these objects is similar, `Document` objects represent entire files, while `Node`s are smaller pieces of that original document, that are suitable for an LLM and Q&A.
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
This can be explicitly set in the `ServiceContext` object.
A transformation is something that takes a list of nodes as an input, and returns a list of nodes. Each component that implements the Transformatio class has both a `transform` definition responsible for transforming the nodes
Currently, the following components are Transformation objects:
To use Azure OpenAI, you only need to set a few environment variables together with the `OpenAI` class.
For example:
## Environment Variables
```
export AZURE_OPENAI_KEY="<YOUR KEY HERE>"
export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart?tabs=command-line%2Cpython&pivots=rest-api>"
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
To use Azure OpenAI, you only need to set a few environment variables.
For example:
```
export AZURE_OPENAI_KEY="<YOUR KEY HERE>"
export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart?tabs=command-line%2Cpython&pivots=rest-api>"
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
The `NodeParser` in LlamaIndex is responsible for splitting `Document` objects into more manageable `Node` objects. When you call `.fromDocuments()`, the `NodeParser` from the `ServiceContext` is used to do this automatically for you. Alternatively, you can use it to split documents ahead of time.
The Cohere Reranker is a postprocessor that uses the Cohere API to rerank the results of a search query.
## Setup
Firstly, you will need to install the `llamaindex` package.
```bash
pnpm install llamaindex
```
Now, you will need to sign up for an API key at [Cohere](https://cohere.ai/). Once you have your API key you can import the necessary modules and create a new instance of the `CohereRerank` class.
```ts
import{
CohereRerank,
Document,
OpenAI,
VectorStoreIndex,
serviceContextFromDefaults,
}from"llamaindex";
```
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
## Increase similarity topK to retrieve more results
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
```ts
constretriever=index.asRetriever();
retriever.similarityTopK=5;
```
## Create a new instance of the CohereRerank class
Then you can create a new instance of the `CohereRerank` class and pass in your API key and the number of results you want to return.
```ts
constnodePostprocessor=newCohereRerank({
apiKey:"<COHERE_API_KEY>",
topN: 4,
});
```
## Create a query engine with the retriever and node postprocessor
```ts
constqueryEngine=index.asQueryEngine({
retriever,
nodePostprocessors:[nodePostprocessor],
});
// log the response
constresponse=awaitqueryEngine.query("Where did the author grown up?");
Node postprocessors are a set of modules that take a set of nodes, and apply some kind of transformation or filtering before returning them.
In LlamaIndex, node postprocessors are most commonly applied within a query engine, after the node retrieval step and before the response synthesis step.
LlamaIndex offers several node postprocessors for immediate use, while also providing a simple API for adding your own custom postprocessors.
## Usage Pattern
An example of using a node postprocessors is below:
```ts
import{
Node,
NodeWithScore,
SimilarityPostprocessor,
CohereRerank,
}from"llamaindex";
constnodes: NodeWithScore[]=[
{
node: newTextNode({text:"hello world"}),
score: 0.8,
},
{
node: newTextNode({text:"LlamaIndex is the best"}),
Now you can use the `filteredNodes` and `rerankedNodes` in your application.
## Using Node Postprocessors in LlamaIndex
Most commonly, node-postprocessors will be used in a query engine, where they are applied to the nodes returned from a retriever, and before the response synthesis step.
A query engine wraps a `Retriever` and a `ResponseSynthesizer` into a pipeline, that will use the query string to fetech nodes and then send them to the LLM to generate a response.
The basic concept of the Sub Question Query Engine is that it splits a single query into multiple queries, gets an answer for each of those queries, and then combines those different answers into a single coherent response for the user. You can think of it as the "think this through step by step" prompt technique but iterating over your data sources!
### Getting Started
The easiest way to start trying the Sub Question Query Engine is running the subquestion.ts file in [examples](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/subquestion.ts).
```bash
npx ts-node subquestion.ts
```
### Tools
SubQuestionQueryEngine is implemented with Tools. The basic idea of Tools is that they are executable options for the large language model. In this case, our SubQuestionQueryEngine relies on QueryEngineTool, which as you guessed it is a tool to run queries on a QueryEngine. This allows us to give the model an option to query different documents for different questions for example. You could also imagine that the SubQuestionQueryEngine could use a Tool that searches for something on the web or gets an answer using Wolfram Alpha.
You can learn more about Tools by taking a look at the LlamaIndex Python documentation https://gpt-index.readthedocs.io/en/latest/core_modules/agent_modules/tools/root.html
Metadata filtering is a way to filter the documents that are returned by a query based on the metadata associated with the documents. This is useful when you want to filter the documents based on some metadata that is not part of the document text.
You can also check our multi-tenancy blog post to see how metadata filtering can be used in a multi-tenant environment. [https://blog.llamaindex.ai/building-multi-tenancy-rag-system-with-llamaindex-0d6ab4e0c44b] (the article uses the Python version of LlamaIndex, but the concepts are the same).
## Setup
Firstly if you haven't already, you need to install the `llamaindex` package:
```bash
pnpm i llamaindex
```
Then you can import the necessary modules from `llamaindex`:
```ts
import{
ChromaVectorStore,
Document,
VectorStoreIndex,
storageContextFromDefaults,
}from"llamaindex";
constcollectionName="dog_colors";
```
## Creating documents with metadata
You can create documents with metadata using the `Document` class:
```ts
constdocs=[
newDocument({
text:"The dog is brown",
metadata:{
color:"brown",
dogId:"1",
},
}),
newDocument({
text:"The dog is red",
metadata:{
color:"red",
dogId:"2",
},
}),
];
```
## Creating a ChromaDB vector store
You can create a `ChromaVectorStore` to store the documents:
Next, we need to define some basic rules and parse the documents into nodes. We will use the `SimpleNodeParser` to parse the documents into nodes and `ServiceContext` to define the rules (eg. LLM API key, chunk size, etc.):
```ts
constnodeParser=newSimpleNodeParser({
chunkSize: 1024,
});
constserviceContext=serviceContextFromDefaults({
nodeParser,
llm: newOpenAI(),
});
```
## Creating Indices
Next, we need to create some indices. We will create a `VectorStoreIndex` and a `SummaryIndex`:
Next, we need to create a router query engine. We will use the `RouterQueryEngine` to create a router query engine:
We're defining two query engines, one for summarization and one for retrieving specific context. The router query engine will select the most appropriate query engine based on the query.
```ts
constqueryEngine=RouterQueryEngine.fromDefaults({
queryEngineTools:[
{
queryEngine: vectorQueryEngine,
description:"Useful for summarization questions related to Abramov",
},
{
queryEngine: summaryQueryEngine,
description:"Useful for retrieving specific context from Abramov",
},
],
serviceContext,
});
```
## Querying the Router Query Engine
Finally, we can query the router query engine:
```ts
constsummaryResponse=awaitqueryEngine.query({
query:"Give me a summary about his past experiences?",
The ResponseSynthesizer is responsible for sending the query, nodes, and prompt templates to the LLM to generate a response. There are a few key modes for generating a response:
-`Refine`: "create and refine" an answer by sequentially going through each retrieved text chunk.
This makes a separate LLM call per Node. Good for more detailed answers.
-`CompactAndRefine` (default): "compact" the prompt during each LLM call by stuffing as
many text chunks that can fit within the maximum prompt size. If there are
too many chunks to stuff in one prompt, "create and refine" an answer by going through
multiple compact prompts. The same as `refine`, but should result in less LLM calls.
-`TreeSummarize`: Given a set of text chunks and the query, recursively construct a tree
and return the root node as the response. Good for summarization purposes.
-`SimpleResponseBuilder`: Given a set of text chunks and the query, apply the query to each text
chunk while accumulating the responses into an array. Returns a concatenated string of all
responses. Good for when you need to run the same query separately against each text
A retriever in LlamaIndex is what is used to fetch `Node`s from an index using a query string. Aa `VectorIndexRetriever` will fetch the top-k most similar nodes. Meanwhile, a `SummaryIndexRetriever` will fetch all nodes no matter the query.
Storage in LlamaIndex.TS works automatically once you've configured a `StorageContext` object. Just configure the `persistDir` and attach it to an index.
Right now, only saving and loading from disk is supported, with future integrations planned!
LlamaIndex provides **one-click observability** 🔭 to allow you to build principled LLM applications in a production setting.
A key requirement for principled development of LLM applications over your data (RAG systems, agents) is being able to observe, debug, and evaluate
your system - both as a whole and for each component.
This feature allows you to seamlessly integrate the LlamaIndex library with powerful observability/evaluation tools offered by our partners.
Configure a variable once, and you'll be able to do things like the following:
- View LLM/prompt inputs/outputs
- Ensure that the outputs of any component (LLMs, embeddings) are performing as expected
- View call traces for both indexing and querying
Each provider has similarities and differences. Take a look below for the full set of guides for each one!
## OpenLLMetry
[OpenLLMetry](https://github.com/traceloop/openllmetry-js) is an open-source project based on OpenTelemetry for tracing and monitoring
LLM applications. It connects to [all major observability platforms](https://www.traceloop.com/docs/openllmetry/integrations/introduction) and installs in minutes.
موصل البيانات (أي `Reader`) يقوم بتجميع البيانات من مصادر بيانات مختلفة وتنسيقات بيانات مختلفة في تمثيل بسيط للـ `Document` (نص وبيانات تعريفية بسيطة).
[**المستندات / العقد**](./modules/high_level/documents_and_nodes.md): المستند هو حاوية عامة حول أي مصدر بيانات - على سبيل المثال، ملف PDF، نتائج واجهة برمجة التطبيقات، أو بيانات استرداد من قاعدة بيانات. العقد هو الوحدة الذرية للبيانات في LlamaIndex ويمثل "قطعة" من المستند الأصلي. إنه تمثيل غني يتضمن بيانات تعريفية وعلاقات (مع عقد أخرى) لتمكين عمليات الاسترجاع الدقيقة والتعبيرية.
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
نقدم العديد من الأمثلة من البداية إلى النهاية باستخدام LlamaIndex.TS في المستودع
تحقق من الأمثلة أدناه أو جربها وأكملها في دقائق مع دروس تفاعلية على Github Codespace المقدمة من Dev-Docs [هنا](https://codespaces.new/team-dev-docs/lits-dev-docs-playground?devcontainer_path=.devcontainer%2Fjavascript_ltsquickstart%2Fdevcontainer.json):
يستخدم هذا المثال العديد من المكونات منخفضة المستوى، مما يزيل الحاجة إلى محرك استعلام فعلي. يمكن استخدام هذه المكونات في أي مكان، في أي تطبيق، أو تخصيصها وتصنيفها الفرعي لتلبية احتياجاتك الخاصة.
`تمت ترجمة هذه الوثيقة تلقائيًا وقد تحتوي على أخطاء. لا تتردد في فتح طلب سحب لاقتراح تغييرات.`
LlamaIndex.TS هو إطار بيانات لتطبيقات LLM لاستيعاب وتنظيم والوصول إلى البيانات الخاصة أو الخاصة بالمجال. في حين أن حزمة Python متاحة أيضًا (انظر [هنا](https://docs.llamaindex.ai/en/stable/)), يوفر LlamaIndex.TS ميزات أساسية في حزمة بسيطة ، محسنة للاستخدام مع TypeScript.
## 🚀 لماذا LlamaIndex.TS؟
في جوهرها ، توفر LLMs واجهة لغة طبيعية بين البشر والبيانات المستنتجة. تأتي النماذج المتاحة على نطاق واسع محملة مسبقًا بكميات هائلة من البيانات المتاحة للجمهور ، من ويكيبيديا وقوائم البريد الإلكتروني إلى الكتب المدرسية وشفرة المصدر.
غالبًا ما تتطلب التطبيقات المبنية على LLMs تعزيز هذه النماذج بالبيانات الخاصة أو الخاصة بالمجال. للأسف ، يمكن توزيع هذه البيانات عبر تطبيقات ومخازن بيانات معزولة. إنها خلف واجهات برمجة التطبيقات ، في قواعد البيانات SQL ، أو محبوسة في ملفات PDF وعروض تقديمية.
هنا يأتي دور **LlamaIndex.TS**.
## 🦙 كيف يمكن أن يساعد LlamaIndex.TS؟
يوفر LlamaIndex.TS الأدوات التالية:
- **تحميل البيانات**: استيعاب البيانات الحالية الخاصة بك بتنسيقات `.txt`, `.pdf`, `.csv`, `.md` و `.docx` مباشرة.
- **فهارس البيانات**: تنظيم البيانات الخاصة بك في تمثيلات وسيطة سهلة وفعالة للاستخدام من قبل LLMs.
- **المحركات**: توفر واجهات الوصول إلى اللغة الطبيعية لبياناتك. على سبيل المثال:
- محركات الاستعلام هي واجهات استرجاع قوية للإخراج المعزز بالمعرفة.
- محركات الدردشة هي واجهات محادثة للتفاعلات "ذهابًا وإيابًا" متعددة الرسائل مع بياناتك.
## 👨👩👧👦 من أجل من هو LlamaIndex؟
يوفر LlamaIndex.TS مجموعة أدوات أساسية ، ضرورية لأي شخص يقوم ببناء تطبيقات LLM باستخدام JavaScript و TypeScript.
يتيح لنا واجهة برمجة التطبيقات على مستوى عالي استخدام LlamaIndex.TS لاستيعاب واستعلام البيانات الخاصة بهم.
بالنسبة للتطبيقات المعقدة أكثر ، تتيح لنا واجهات برمجة التطبيقات على مستوى أدنى للمستخدمين المتقدمين تخصيص وتوسيع أي وحدة - موصلات البيانات والفهارس وأجهزة الاسترجاع ومحركات الاستعلام - لتناسب احتياجاتهم.
## البدء
`npm install llamaindex`
تتضمن وثائقنا [تعليمات التثبيت](./installation.mdx) و[دليل البداية](./starter.md) لبناء تطبيقك الأول.
بمجرد أن تكون جاهزًا وتعمل ، يحتوي [مفاهيم عالية المستوى](./getting_started/concepts.md) على نظرة عامة على الهندسة المعمارية المتعددة المستويات لـ LlamaIndex. لمزيد من الأمثلة العملية التفصيلية ، يمكنك الاطلاع على [دروس النهاية إلى النهاية](./end_to_end.md).
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.