Compare commits

..

1 Commits

Author SHA1 Message Date
Alex Yang bb5565825d Update docusaurus.config.js 2024-11-14 17:30:43 -08:00
1298 changed files with 34390 additions and 100823 deletions
+6
View File
@@ -0,0 +1,6 @@
---
"@llamaindex/unit-test": patch
"@llamaindex/workflow": patch
---
feat(workflow): allow send event with no output
+5
View File
@@ -0,0 +1,5 @@
---
"@llamaindex/core": patch
---
feat: add async support to BaseChatStore and BaseChatStoreMemory
@@ -8,11 +8,6 @@ on:
branches:
- main
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
TURBO_REMOTE_ONLY: true
jobs:
lint:
runs-on: ubuntu-latest
+1 -6
View File
@@ -1,11 +1,6 @@
name: Publish Preview
on: [pull_request]
env:
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
TURBO_REMOTE_ONLY: true
jobs:
pre_release:
name: Pre Release
@@ -30,4 +25,4 @@ jobs:
run: pnpm run build
- name: Pre Release
run: pnpx pkg-pr-new publish --pnpm ./packages/* ./packages/providers/* ./packages/providers/storage/*
run: pnpx pkg-pr-new publish ./packages/* ./packages/providers/*
+6 -50
View File
@@ -83,34 +83,15 @@ jobs:
run: pnpm install
- name: Build
run: pnpm run build
- name: Use Build For Examples
run: |
pnpm link ../packages/llamaindex/
cd readers && pnpm link ../../packages/llamaindex/
working-directory: ./examples
- name: Run Type Check
run: pnpm run type-check
- name: Run Circular Dependency Check
run: pnpm run circular-check
e2e-npm:
runs-on: ubuntu-latest
name: Test using packages with npm
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Install dependencies
run: pnpm install
- name: Build packages
run: pnpm run build
- name: Pack packages
run: |
pnpm pack --pack-destination ${{ runner.temp }} -C packages/llamaindex
pnpm pack --pack-destination ${{ runner.temp }} -C packages/workflow
- name: Install packed packages
run: npm add ${{ runner.temp }}/*.tgz
working-directory: e2e/npm
- name: Run tests
run: npm test
working-directory: e2e/npm
e2e-llamaindex-examples:
strategy:
fail-fast: false
@@ -122,7 +103,6 @@ jobs:
- nextjs-node-runtime
- waku-query-engine
- llama-parse-browser
- vite-import-llamaindex
runs-on: ubuntu-latest
name: Build LlamaIndex Example (${{ matrix.packages }})
steps:
@@ -141,30 +121,6 @@ jobs:
run: pnpm run build
working-directory: e2e/examples/${{ matrix.packages }}
size-limit:
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
name: Size Limit
steps:
- uses: actions/checkout@v4
- uses: pnpm/action-setup@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install dependencies
run: pnpm install
- name: Build llamaindex
run: pnpm run build
- uses: andresz1/size-limit-action@94bc357df29c36c8f8d50ea497c3e225c3c95d1d
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
directory: e2e/examples/vite-import-llamaindex
skip_step: "install"
build_script: build
package_manager: pnpm
typecheck-examples:
runs-on: ubuntu-latest
@@ -194,7 +150,7 @@ jobs:
done
- name: Pack provider packages
run: |
for dir in packages/providers/* packages/providers/storage/*; do
for dir in packages/providers/*; do
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
echo "Packing $dir"
pnpm pack --pack-destination ${{ runner.temp }} -C $dir
+3 -1
View File
@@ -1 +1,3 @@
pnpm run lint-staged
pnpm format
pnpm lint
npx lint-staged
+1 -1
View File
@@ -1 +1 @@
22
20
-1
View File
@@ -7,4 +7,3 @@ dist/
.source/
# prttier doesn't support mdx3 we are using
*.mdx
packages/server/server/
-1
View File
@@ -1 +0,0 @@
LlamaIndexTS
+1 -2
View File
@@ -14,6 +14,5 @@
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"prettier.prettierPath": "./node_modules/prettier",
"prettier.configPath": "prettier.config.mjs"
"prettier.prettierPath": "./node_modules/prettier"
}
-92
View File
@@ -1,92 +0,0 @@
# CLAUDE.md
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/workflow/` - Agent workflow orchestration
- `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.
**Data Flow:** Document → NodeParser → Embedding → VectorStore → Retriever → QueryEngine → Response
### Core Components
- **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
+8 -101
View File
@@ -14,145 +14,52 @@ There are some important folders in the repository:
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
Make sure you have Node.js LTS (Long-term Support) installed. You can check your Node.js version by running:
Make sure you have Node.js LIS (Long-term Support) installed. You can check your Node.js version by running:
```shell
node -v
# v22.x.x
# v20.x.x
```
### Use pnpm
```shell
npm install -g pnpm
corepack enable
```
### Install dependencies
```shell
pnpm install
pnpm install -g tsx
```
### Build the packages
To build all packages, run:
```shell
pnpm build
# Build all packages
turbo build --filter "./packages/*"
```
### Start Developing
You can launch the package in dev-mode by running:
```shell
pnpm dev
```
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
```
In another terminal, you can write and run any script needed to quickly test your changes. For example:
```typescript
import { createMemory, staticBlock } from "@llamaindex/core/memory";
// Create memory with predefined context
const memory = createMemory({
memoryBlocks: [
staticBlock({
content:
"The user is a software engineer who loves TypeScript and LlamaIndex.",
messageRole: "system",
}),
],
});
async function main() {
const result = await memory.getLLM();
console.log(result);
}
void main().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
See the [docs](./apps/next/README.md) for more information.
## Adding a new package
Please follow these steps to add a new package:
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.
## Before sending a PR
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
## Changeset
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 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.
Please send a descriptive changeset for each PR.
## Publishing (maintainers only)
+48 -11
View File
@@ -7,10 +7,9 @@
</h3>
[![NPM Version](https://img.shields.io/npm/v/llamaindex)](https://www.npmjs.com/package/llamaindex)
[![NPM License](https://img.shields.io/npm/l/llamaindex)](https://github.com/run-llama/LlamaIndexTS/blob/main/LICENSE)
[![NPM License](https://img.shields.io/npm/l/llamaindex)](https://www.npmjs.com/package/llamaindex)
[![NPM Downloads](https://img.shields.io/npm/dm/llamaindex)](https://www.npmjs.com/package/llamaindex)
[![Discord](https://img.shields.io/discord/1059199217496772688)](https://discord.com/invite/eN6D2HQ4aX)
[![Twitter](https://img.shields.io/twitter/follow/llama_index)](https://x.com/llama_index)
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in JS runtime environments with TypeScript support.
@@ -64,27 +63,65 @@ yarn add llamaindex
### Setup in Node.js, Deno, Bun, TypeScript...?
See our official document: https://ts.llamaindex.ai/docs/llamaindex/getting_started
See our official document: <https://ts.llamaindex.ai/docs/llamaindex/setup/getting-started>
### Adding provider packages
### Tips when using in non-Node.js environments
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.
When you are importing `llamaindex` in a non-Node.js environment(such as Vercel Edge, Cloudflare Workers, etc.)
Some classes are not exported from top-level entry file.
For example, to use the OpenAI LLM, you would install the following package:
The reason is that some classes are only compatible with Node.js runtime,(e.g. `PDFReader`) which uses Node.js specific APIs(like `fs`, `child_process`, `crypto`).
```shell
npm install @llamaindex/openai
pnpm install @llamaindex/openai
yarn add @llamaindex/openai
If you need any of those classes, you have to import them instead directly though their file path in the package.
Here's an example for importing the `PineconeVectorStore` class:
```typescript
import { PineconeVectorStore } from "llamaindex/storage/vectorStore/PineconeVectorStore";
```
As the `PDFReader` is not working with the Edge runtime, here's how to use the `SimpleDirectoryReader` with the `LlamaParseReader` to load PDFs:
```typescript
import { SimpleDirectoryReader } from "llamaindex/readers/SimpleDirectoryReader";
import { LlamaParseReader } from "llamaindex/readers/LlamaParseReader";
export const DATA_DIR = "./data";
export async function getDocuments() {
const reader = new SimpleDirectoryReader();
// Load PDFs using LlamaParseReader
return await reader.loadData({
directoryPath: DATA_DIR,
fileExtToReader: {
pdf: new LlamaParseReader({ resultType: "markdown" }),
},
});
}
```
> _Note_: Reader classes have to be added explictly to the `fileExtToReader` map in the Edge version of the `SimpleDirectoryReader`.
You'll find a complete example with LlamaIndexTS here: https://github.com/run-llama/create_llama_projects/tree/main/nextjs-edge-llamaparse
## Playground
Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
## Core concepts for getting started:
See our documentation: https://ts.llamaindex.ai/docs/llamaindex/getting_started/concepts
- [Document](/packages/llamaindex/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
- [Node](/packages/llamaindex/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/llamaindex/src/embeddings/OpenAIEmbedding.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 question. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/llamaindex/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/llamaindex/src/embeddings)).
- [Indices](/packages/llamaindex/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
- [QueryEngine](/packages/llamaindex/src/engines/query/RetrieverQueryEngine.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. To build a query engine from your Index (recommended), use the [`asQueryEngine`](/packages/llamaindex/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/llamaindex/src/engines/query).
- [ChatEngine](/packages/llamaindex/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/llamaindex/src/engines/chat).
- [SimplePrompt](/packages/llamaindex/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.
## Contributing:
+6
View File
@@ -0,0 +1,6 @@
---
"llamaindex": minor
"docs": minor
---
Add deepseek llm class
+21
View File
@@ -0,0 +1,21 @@
# Dependencies
/node_modules
# Production
/build
# Generated files
.docusaurus
.cache-loader
lib
# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+912
View File
@@ -0,0 +1,912 @@
# docs
## 0.0.117
### Patch Changes
- @llamaindex/examples@0.0.15
## 0.0.116
### Patch Changes
- llamaindex@0.8.12
## 0.0.115
### Patch Changes
- llamaindex@0.8.11
## 0.0.114
### Patch Changes
- Updated dependencies [f066e50]
- llamaindex@0.8.10
- @llamaindex/examples@0.0.14
## 0.0.113
### Patch Changes
- Updated dependencies [4fc001c]
- Updated dependencies [4d4cd8a]
- llamaindex@0.8.9
## 0.0.112
### Patch Changes
- Updated dependencies [ad85bd0]
- llamaindex@0.8.8
- @llamaindex/examples@0.0.13
## 0.0.111
### Patch Changes
- llamaindex@0.8.7
## 0.0.110
### Patch Changes
- Updated dependencies [95a5cc6]
- llamaindex@0.8.6
## 0.0.109
### Patch Changes
- Updated dependencies [14cc9eb]
- Updated dependencies [a6db5dd]
- Updated dependencies [396b1e1]
- llamaindex@0.8.5
## 0.0.108
### Patch Changes
- Updated dependencies [35430d3]
- llamaindex@0.8.4
## 0.0.107
### Patch Changes
- llamaindex@0.8.3
## 0.0.106
### Patch Changes
- @llamaindex/examples@0.0.12
## 0.0.105
### Patch Changes
- Updated dependencies [c7a918c]
- llamaindex@0.8.2
## 0.0.104
### Patch Changes
- llamaindex@0.8.1
## 0.0.103
### Patch Changes
- Updated dependencies [359fd33]
- Updated dependencies [efb7e1b]
- Updated dependencies [98ba1e7]
- Updated dependencies [620c63c]
- llamaindex@0.8.0
- @llamaindex/examples@0.0.11
## 0.0.102
### Patch Changes
- Updated dependencies [9df9a8f]
- llamaindex@0.7.10
## 0.0.101
### Patch Changes
- Updated dependencies [691c5bc]
- llamaindex@0.7.9
## 0.0.100
### Patch Changes
- llamaindex@0.7.8
## 0.0.99
### Patch Changes
- Updated dependencies [2486bd8]
- @llamaindex/examples@0.0.10
- llamaindex@0.7.7
## 0.0.98
### Patch Changes
- Updated dependencies [534d550]
- llamaindex@0.7.6
## 0.0.97
### Patch Changes
- Updated dependencies [e9a111d]
- Updated dependencies [9f22aae]
- llamaindex@0.7.5
## 0.0.96
### Patch Changes
- llamaindex@0.7.4
## 0.0.95
### Patch Changes
- llamaindex@0.7.3
## 0.0.94
### Patch Changes
- llamaindex@0.7.2
## 0.0.93
### Patch Changes
- Updated dependencies [ae49ff4]
- Updated dependencies [4c38c1b]
- Updated dependencies [a75af83]
- Updated dependencies [a75af83]
- llamaindex@0.7.1
## 0.0.92
### Patch Changes
- Updated dependencies [1364e8e]
- Updated dependencies [3b7736f]
- Updated dependencies [96fc69c]
- llamaindex@0.7.0
- @llamaindex/examples@0.0.9
## 0.0.91
### Patch Changes
- Updated dependencies [5729bd9]
- llamaindex@0.6.22
## 0.0.90
### Patch Changes
- Updated dependencies [6f75306]
- Updated dependencies [94cb4ad]
- llamaindex@0.6.21
## 0.0.89
### Patch Changes
- Updated dependencies [6a9a7b1]
- llamaindex@0.6.20
## 0.0.88
### Patch Changes
- Updated dependencies [62cba52]
- Updated dependencies [d265e96]
- Updated dependencies [d30bbf7]
- Updated dependencies [53fd00a]
- llamaindex@0.6.19
## 0.0.87
### Patch Changes
- Updated dependencies [5f67820]
- Updated dependencies [fe08d04]
- llamaindex@0.6.18
## 0.0.86
### Patch Changes
- Updated dependencies [ee697fb]
- llamaindex@0.6.17
## 0.0.85
### Patch Changes
- Updated dependencies [63e9846]
- Updated dependencies [6f3a31c]
- llamaindex@0.6.16
## 0.0.84
### Patch Changes
- Updated dependencies [2a82413]
- llamaindex@0.6.15
## 0.0.83
### Patch Changes
- llamaindex@0.6.14
## 0.0.82
### Patch Changes
- llamaindex@0.6.13
## 0.0.81
### Patch Changes
- Updated dependencies [f7b4e94]
- Updated dependencies [78037a6]
- Updated dependencies [1d9e3b1]
- llamaindex@0.6.12
## 0.0.80
### Patch Changes
- Updated dependencies [df441e2]
- llamaindex@0.6.11
## 0.0.79
### Patch Changes
- Updated dependencies [ebc5105]
- Updated dependencies [6cce3b1]
- llamaindex@0.6.10
## 0.0.78
### Patch Changes
- llamaindex@0.6.9
## 0.0.77
### Patch Changes
- Updated dependencies [8b7fdba]
- llamaindex@0.6.8
## 0.0.76
### Patch Changes
- Updated dependencies [23bcc37]
- llamaindex@0.6.7
## 0.0.75
### Patch Changes
- Updated dependencies [d902cc3]
- Updated dependencies [025ffe6]
- Updated dependencies [a659574]
- llamaindex@0.6.6
## 0.0.74
### Patch Changes
- Updated dependencies [e9714db]
- llamaindex@0.6.5
## 0.0.73
### Patch Changes
- Updated dependencies [b48bcc3]
- llamaindex@0.6.4
## 0.0.72
### Patch Changes
- Updated dependencies [2cd1383]
- Updated dependencies [5c4badb]
- llamaindex@0.6.3
## 0.0.71
### Patch Changes
- Updated dependencies [749b43a]
- llamaindex@0.6.2
## 0.0.70
### Patch Changes
- Updated dependencies [fbd5e01]
- Updated dependencies [6b70c54]
- Updated dependencies [1a6137b]
- Updated dependencies [85c2e19]
- llamaindex@0.6.1
## 0.0.69
### Patch Changes
- Updated dependencies [11feef8]
- llamaindex@0.6.0
- @llamaindex/examples@0.0.8
## 0.0.68
### Patch Changes
- Updated dependencies [7edeb1c]
- llamaindex@0.5.27
## 0.0.67
### Patch Changes
- Updated dependencies [ffe0cd1]
- Updated dependencies [ffe0cd1]
- llamaindex@0.5.26
## 0.0.66
### Patch Changes
- Updated dependencies [4810364]
- Updated dependencies [d3bc663]
- llamaindex@0.5.25
## 0.0.65
### Patch Changes
- llamaindex@0.5.24
## 0.0.64
### Patch Changes
- llamaindex@0.5.23
## 0.0.63
### Patch Changes
- Updated dependencies [4648da6]
- llamaindex@0.5.22
## 0.0.62
### Patch Changes
- Updated dependencies [ae1149f]
- Updated dependencies [2411c9f]
- Updated dependencies [e8f229c]
- Updated dependencies [11b3856]
- Updated dependencies [83d7f41]
- Updated dependencies [0148354]
- Updated dependencies [1711f6d]
- llamaindex@0.5.21
## 0.0.61
### Patch Changes
- Updated dependencies [d9d6c56]
- Updated dependencies [22ff486]
- Updated dependencies [eed0b04]
- llamaindex@0.5.20
## 0.0.60
### Patch Changes
- Updated dependencies [fcbf183]
- llamaindex@0.5.19
## 0.0.59
### Patch Changes
- Updated dependencies [8b66cf4]
- llamaindex@0.5.18
## 0.0.58
### Patch Changes
- Updated dependencies [c654398]
- llamaindex@0.5.17
## 0.0.57
### Patch Changes
- Updated dependencies [58abc57]
- llamaindex@0.5.16
## 0.0.56
### Patch Changes
- Updated dependencies [01c184c]
- Updated dependencies [07a275f]
- llamaindex@0.5.15
## 0.0.55
### Patch Changes
- Updated dependencies [c825a2f]
- llamaindex@0.5.14
## 0.0.54
### Patch Changes
- llamaindex@0.5.13
## 0.0.53
### Patch Changes
- Updated dependencies [345300f]
- Updated dependencies [da5cfc4]
- Updated dependencies [da5cfc4]
- llamaindex@0.5.12
## 0.0.52
### Patch Changes
- 376d29a: feat: added tool calling and agent support for llama3.1 504B
- llamaindex@0.5.11
## 0.0.51
### Patch Changes
- 086b940: feat: add DeepSeek LLM
- 5d5716b: feat: add a reader for JSON data
- Updated dependencies [086b940]
- Updated dependencies [5d5716b]
- Updated dependencies [91d02a4]
- Updated dependencies [fb6db45]
- llamaindex@0.5.10
## 0.0.50
### Patch Changes
- Updated dependencies [15962b3]
- llamaindex@0.5.9
## 0.0.49
### Patch Changes
- Updated dependencies [3d5ba08]
- Updated dependencies [d917cdc]
- llamaindex@0.5.8
## 0.0.48
### Patch Changes
- Updated dependencies [ec59acd]
- llamaindex@0.5.7
## 0.0.47
### Patch Changes
- Updated dependencies [2562244]
- Updated dependencies [325aa51]
- Updated dependencies [ab700ea]
- Updated dependencies [92f0782]
- Updated dependencies [6cf6ae6]
- Updated dependencies [b7cfe5b]
- llamaindex@0.5.6
## 0.0.46
### Patch Changes
- Updated dependencies [b974eea]
- llamaindex@0.5.5
## 0.0.45
### Patch Changes
- Updated dependencies [1a65ead]
- llamaindex@0.5.4
## 0.0.44
### Patch Changes
- Updated dependencies [9bbbc67]
- Updated dependencies [b3681bf]
- llamaindex@0.5.3
## 0.0.43
### Patch Changes
- llamaindex@0.5.2
## 0.0.42
### Patch Changes
- 2774681: Add mixedbread's embeddings and reranking API
- Updated dependencies [2774681]
- Updated dependencies [a0f424e]
- llamaindex@0.5.1
## 0.0.41
### Patch Changes
- 36ddec4: fix: typo in custom page separator parameter for LlamaParse
- Updated dependencies [16ef5dd]
- Updated dependencies [16ef5dd]
- Updated dependencies [36ddec4]
- llamaindex@0.5.0
- @llamaindex/examples@0.0.7
## 0.0.40
### Patch Changes
- llamaindex@0.4.14
## 0.0.39
### Patch Changes
- Updated dependencies [e8f8bea]
- Updated dependencies [304484b]
- llamaindex@0.4.13
## 0.0.38
### Patch Changes
- Updated dependencies [f326ab8]
- llamaindex@0.4.12
## 0.0.37
### Patch Changes
- Updated dependencies [8bf5b4a]
- llamaindex@0.4.11
## 0.0.36
### Patch Changes
- Updated dependencies [7dce3d2]
- llamaindex@0.4.10
## 0.0.35
### Patch Changes
- Updated dependencies [3a96a48]
- llamaindex@0.4.9
## 0.0.34
### Patch Changes
- Updated dependencies [83ebdfb]
- llamaindex@0.4.8
## 0.0.33
### Patch Changes
- Updated dependencies [41fe871]
- Updated dependencies [321c39d]
- Updated dependencies [f7f1af0]
- llamaindex@0.4.7
## 0.0.32
### Patch Changes
- Updated dependencies [1feb23b]
- Updated dependencies [08c55ec]
- llamaindex@0.4.6
## 0.0.31
### Patch Changes
- Updated dependencies [6c3e5d0]
- llamaindex@0.4.5
## 0.0.30
### Patch Changes
- Updated dependencies [42eb73a]
- llamaindex@0.4.4
## 0.0.29
### Patch Changes
- Updated dependencies [2ef62a9]
- llamaindex@0.4.3
- @llamaindex/examples@0.0.6
## 0.0.28
### Patch Changes
- Updated dependencies [a87a4d1]
- Updated dependencies [0730140]
- llamaindex@0.4.2
## 0.0.27
### Patch Changes
- Updated dependencies [3c47910]
- Updated dependencies [ed467a9]
- Updated dependencies [cba5406]
- llamaindex@0.4.1
## 0.0.26
### Patch Changes
- b1a4a74: docs: updated Bedrock Opus region and added a basic README
- Updated dependencies [436bc41]
- Updated dependencies [a44e54f]
- Updated dependencies [a51ed8d]
- Updated dependencies [d3b635b]
- llamaindex@0.4.0
- @llamaindex/examples@0.0.5
## 0.0.25
### Patch Changes
- Updated dependencies [6bc5bdd]
- Updated dependencies [bf25ff6]
- Updated dependencies [e6d6576]
- llamaindex@0.3.17
## 0.0.24
### Patch Changes
- 631f000: feat: DeepInfra LLM implementation
- 8832669: Community bedrock support added
- a29d835: setDocumentHash should be async
- Updated dependencies [11ae926]
- Updated dependencies [631f000]
- Updated dependencies [1378ec4]
- Updated dependencies [6b1ded4]
- Updated dependencies [4d4bd85]
- Updated dependencies [24a9d1e]
- Updated dependencies [45952de]
- Updated dependencies [54230f0]
- Updated dependencies [a29d835]
- Updated dependencies [73819bf]
- llamaindex@0.3.16
## 0.0.23
### Patch Changes
- Updated dependencies [6e156ed]
- Updated dependencies [265976d]
- Updated dependencies [8e26f75]
- llamaindex@0.3.15
## 0.0.22
### Patch Changes
- Updated dependencies [6ff7576]
- Updated dependencies [94543de]
- llamaindex@0.3.14
## 0.0.21
### Patch Changes
- Updated dependencies [1b1081b]
- Updated dependencies [37525df]
- Updated dependencies [660a2b3]
- Updated dependencies [a1f2475]
- llamaindex@0.3.13
## 0.0.20
### Patch Changes
- Updated dependencies [34fb1d8]
- llamaindex@0.3.12
## 0.0.19
### Patch Changes
- Updated dependencies [e072c45]
- Updated dependencies [9e133ac]
- Updated dependencies [447105a]
- Updated dependencies [320be3f]
- llamaindex@0.3.11
## 0.0.18
### Patch Changes
- Updated dependencies [4aba02e]
- llamaindex@0.3.10
## 0.0.17
### Patch Changes
- Updated dependencies [c3747d0]
- llamaindex@0.3.9
## 0.0.16
### Patch Changes
- Updated dependencies [ce94780]
- llamaindex@0.3.8
## 0.0.15
### Patch Changes
- Updated dependencies [b6a6606]
- Updated dependencies [b6a6606]
- llamaindex@0.3.7
## 0.0.14
### Patch Changes
- Updated dependencies [efa326a]
- llamaindex@0.3.6
## 0.0.13
### Patch Changes
- Updated dependencies [bc7a11c]
- Updated dependencies [2fe2b81]
- Updated dependencies [5596e31]
- Updated dependencies [e74fe88]
- Updated dependencies [be5df5b]
- llamaindex@0.3.5
## 0.0.12
### Patch Changes
- Updated dependencies [1dce275]
- Updated dependencies [d10533e]
- Updated dependencies [2008efe]
- Updated dependencies [5e61934]
- Updated dependencies [9e74a43]
- Updated dependencies [ee719a1]
- llamaindex@0.3.4
## 0.0.11
### Patch Changes
- Updated dependencies [e8c41c5]
- llamaindex@0.3.3
## 0.0.10
### Patch Changes
- Updated dependencies [61103b6]
- llamaindex@0.3.2
## 0.0.9
### Patch Changes
- Updated dependencies [46227f2]
- llamaindex@0.3.1
## 0.0.8
### Patch Changes
- Updated dependencies [5016f21]
- llamaindex@0.3.0
## 0.0.7
### Patch Changes
- Updated dependencies [6277105]
- llamaindex@0.2.13
## 0.0.6
### Patch Changes
- Updated dependencies [d8d952d]
- llamaindex@0.2.12
## 0.0.5
### Patch Changes
- Updated dependencies [87142b2]
- Updated dependencies [5a6cc0e]
- Updated dependencies [87142b2]
- llamaindex@0.2.11
## 0.0.4
### Patch Changes
- Updated dependencies [5116ad8]
- @llamaindex/env@0.0.5
## 0.0.3
### Patch Changes
- 09bf27a: Add Groq LLM to LlamaIndex
- Updated dependencies [cf87f84]
- @llamaindex/env@0.0.4
## 0.0.2
### Patch Changes
- 0f64084: docs: update API references
## 0.0.1
### Patch Changes
- 3154f52: chore: add qdrant readme
+47
View File
@@ -0,0 +1,47 @@
# Website
This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator.
### Installation
```
$ pnpm
```
### Local Development
```
$ pnpm start
```
This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server.
However, the searchbar may not function with `yarn start`. Instead, run `yarn build` and launch a server:
```
$ npx http-server ./build
```
### Build
```
$ pnpm build
```
This command generates static content into the `build` directory and can be served using any static contents hosting service.
### Deployment
Using SSH:
```
$ USE_SSH=true pnpm deploy
```
Not using SSH:
```
$ GIT_USER=<Your GitHub username> pnpm deploy
```
If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.
+3
View File
@@ -0,0 +1,3 @@
module.exports = {
presets: [require.resolve("@docusaurus/core/lib/babel/preset")],
};
+493
View File
@@ -0,0 +1,493 @@
---
title: LlamaIndexTS v0.3.0
description: This is my first post on Docusaurus.
slug: welcome-llamaindexts-v0.3
authors:
- name: Alex Yang
title: LlamaIndexTS maintainer, Node.js Member
url: https://github.com/himself65
image_url: https://github.com/himself65.png
tags: [llamaindex, agent]
hide_table_of_contents: false
---
- [What's new in LlamaIndexTS v0.3.0](#whats-new-in-llamaindexts-v030)
- [Improvement in LlamaIndexTS v0.3.0](#improvement-in-llamaindexts-v030)
- [What's the next?](#whats-the-next)
## What's new in LlamaIndexTS v0.3.0
## Agents
In this release, we've not only ported the Agent module from the LlamaIndex Python version but have significantly
enhanced it to be more powerful and user-friendly for JavaScript/TypeScript applications.
Starting from v0.3.0, we are introducing multiple agents specifically designed for RAG applications, including:
- `OpenAIAgent`
- `AnthropicAgent`
- `ReActAgent`:
```ts
import { OpenAIAgent } from "llamaindex";
import { tools } from "./tools";
const agent = new OpenAIAgent({
tools: [...tools],
});
const { response } = await agent.chat({
message: "What is weather today?",
stream: false,
});
console.log(response.message.content);
```
We are also introducing the abstract AgentRunner class, which allows you to create your own agent by simply implementing
the task handler.
```ts
import { AgentRunner, OpenAI } from "llamaindex";
class MyLLM extends OpenAI {}
export class MyAgentWorker extends AgentWorker<MyLLM> {
taskHandler = MyAgent.taskHandler;
}
export class MyAgent extends AgentRunner<MyLLM> {
constructor(params: Params) {
super({
llm: params.llm,
chatHistory: params.chatHistory ?? [],
systemPrompt: params.systemPrompt ?? null,
runner: new MyAgentWorker(),
tools:
"tools" in params
? params.tools
: params.toolRetriever.retrieve.bind(params.toolRetriever),
});
}
// create store is a function to create a store for each task, by default it only includes `messages` and `toolOutputs`
createStore = AgentRunner.defaultCreateStore;
static taskHandler: TaskHandler<Anthropic> = async (step, enqueueOutput) => {
const { llm, stream } = step.context;
// initialize the input
const response = await llm.chat({
stream,
messages: step.context.store.messages,
});
// store the response for next task step
step.context.store.messages = [
...step.context.store.messages,
response.message,
];
// your logic here to decide whether to continue the task
const shouldContinue = Math.random(); /* <-- replace with your logic here */
enqueueOutput({
taskStep: step,
output: response,
isLast: !shouldContinue,
});
if (shouldContinue) {
const content = await someHeavyFunctionCall();
// if you want to continue the task, you can insert your new context for the next task step
step.context.store.messages = [
...step.context.store.messages,
{
content,
role: "user",
},
];
}
};
}
```
### Web Stream API for Streaming response
Web Stream is a web standard utilized in many modern web frameworks and libraries (like React 19, Deno, Node 22). We
have migrated streaming responses to Web Stream to ensure broader compatibility.
For instance, you can use the streaming response in a simple HTTP Server:
```ts
import { createServer } from "http";
import { OpenAIAgent } from "llamaindex";
import { OpenAIStream, streamToResponse } from "ai";
import { tools } from "./tools";
const agent = new OpenAIAgent({
tools: [...tools],
});
const server = createServer(async (req, res) => {
const response = await agent.chat({
message: "What is weather today?",
stream: true,
});
// Transform the response into a string readable stream
const stream: ReadableStream<string> = response.pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
controller.enqueue(chunk.response.delta);
},
}),
);
// Pipe the stream to the response
streamToResponse(stream, res);
});
server.listen(3000);
```
Or it can be integrated into React Server Components (RSC) in Next.js:
```tsx
// app/actions/index.tsx
"use server";
import { createStreamableUI } from "ai/rsc";
import { OpenAIAgent } from "llamaindex";
import type { ChatMessage } from "llamaindex/llm/types";
export async function chatWithAgent(
question: string,
prevMessages: ChatMessage[] = [],
) {
const agent = new OpenAIAgent({
tools: [],
});
const responseStream = await agent.chat({
stream: true,
message: question,
chatHistory: prevMessages,
});
const uiStream = createStreamableUI(<div>loading...</div>);
responseStream
.pipeTo(
new WritableStream({
start: () => {
uiStream.update("response:");
},
write: async (message) => {
uiStream.append(message.response.delta);
},
}),
)
.catch(uiStream.error);
return uiStream.value;
}
```
```tsx
// app/src/page.tsx
"use client";
import { chatWithAgent } from "@/actions";
import type { JSX } from "react";
import { useFormState } from "react-dom";
export const runtime = "edge";
export default function Home() {
const [state, action] = useFormState<JSX.Element | null>(async () => {
return chatWithAgent("hello!", []);
}, null);
return (
<main>
{state}
<form action={action}>
<button>Chat</button>
</form>
</main>
);
}
```
## Improvement in LlamaIndexTS v0.3.0
### Better TypeScript support
We have made significant improvements to the type system to ensure that all code is thoroughly checked before it is
published. This ongoing enhancement has already resulted in better module reliability and developer experience.
For example, we have improved `FunctionTool` type with generic support:
```ts
type Input = {
a: number;
b: number;
};
const sumNumbers = FunctionTool.from<Input>(
({ a, b }) => `${a + b}`, // a and b will be checked as number
// JSON schema will be an error if you type wrong.
{
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"],
},
},
);
```
![type checking](./img/function_tool_example.png)
### Better Next.js, Deno, Cloudflare Worker, and Waku(Vite) support
In addition to Node.js, LlamaIndexTS now offers enhanced support for Next.js, Deno, and Cloudflare Workers, making it
more versatile across different platforms.
For now, you can install llamaindex and directly import it into your existing Next.js, Deno or Cloudflare Worker project
**without any extra configuration**.
#### [Deno](https://deno.com/)
You can use LlamaIndexTS in Deno by installation through JSR:
```sh
jsr add @llamaindex/core
```
#### [Cloudflare Worker](https://developers.cloudflare.com/workers/)
For Cloudflare Workers, here is a starter template:
```typescript
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext,
): Promise<Response> {
const { setEnvs } = await import("@llamaindex/env");
setEnvs(env);
const { OpenAIAgent } = await import("llamaindex");
const agent = new OpenAIAgent({
tools: [],
});
const responseStream = await agent.chat({
stream: true,
message: "Hello? What is the weather today?",
});
const textEncoder = new TextEncoder();
const response = responseStream.pipeThrough(
new TransformStream({
transform: (chunk, controller) => {
controller.enqueue(textEncoder.encode(chunk.response.delta));
},
}),
);
return new Response(response);
},
};
```
### [Waku (Vite)](https://waku.gg/)
Waku powered by Vite is a minimal React framework that supports multiple JS environments, including Deno, Cloudflare, and
Node.js.
You can use LlamaIndexTS with Node.js output to enable full Node.js support with React.
```sh
npm install llamaindex
```
```ts
// file: src/actions.ts
"use server";
import { Document, VectorStoreIndex } from "llamaindex";
import { readFile } from "node:fs/promises";
const path = "node_modules/llamaindex/examples/abramov.txt";
const essay = await readFile(path, "utf-8");
// Create Document object with essay
const document = new Document({ text: essay, id_: path });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
const queryEngine = index.asQueryEngine();
export async function chatWithAI(question: string): Promise<string> {
const { response } = await queryEngine.query({ query: question });
return response;
}
```
```tsx
// file: src/pages/index.tsx
import { chatWithAI } from "./actions";
export default async function HomePage() {
return (
<div>
<Chat askQuestion={chatWithAI} />
</div>
);
}
```
```tsx
// file: src/components/Chat.tsx
"use client";
export type ChatProps = {
askQuestion: (question: string) => Promise<string>;
};
export const Chat = (props: ChatProps) => {
const [response, setResponse] = useState<string | null>(null);
return (
<section className="border-blue-400 -mx-4 mt-4 rounded border border-dashed p-4">
<h2 className="text-lg font-bold">Chat with AI</h2>
{response ? (
<p className="text-sm text-gray-600 max-w-sm">{response}</p>
) : null}
<form
action={async (formData) => {
const question = formData.get("question") as string | null;
if (question) {
setResponse(await props.askQuestion(question));
}
}}
>
<input
type="text"
name="question"
className="border border-gray-400 rounded-sm px-2 py-0.5 text-sm"
/>
<button className="rounded-sm bg-black px-2 py-0.5 text-sm text-white">
Ask
</button>
</form>
</section>
);
};
```
```shell
waku dev # development mode
waku build # build for production
waku start # start the production server
```
Note that not all the modules are supported in all JS environments because of
lack of the file system, network API,
and incompatibility with the Node.js API by upstream dependencies.
But we are trying to make it more compatible with all the environments.
## What's the next?
As we continue to develop LlamaIndexTS, our focus remains on providing more comprehensive and powerful tools for
creating custom agents.
### Align with the Python `llama-index`
We aim to align LlamaIndexTS with the Python version to ensure API consistency and ease of use for developers familiar
with the Python ecosystem.
### Align with the Web Standard and JS development
Not all python APIs are compatible and easy to use in JavaScript/TypeScript.
We are trying to make the API more compatible with the Web Standard and JavaScript modern development.
### More Agents
Future releases will introduce more agents from the Python Llama-Index and explore APIs tailored to real-world use
cases.
### 🧪 `@llamaindex/tool`
We are exploring innovative ways to create tools for agents. The `@llamaindex/tool` library allows you to transform any
function into a tool for an agent, simplifying the development process and reducing runtime costs.
```ts
export function getWeather(city: string) {
return `The weather in ${city} is sunny.`;
}
// you don't need to worry about the shcema with different llm tools
export function getTemperature(city: string) {
return `The temperature in ${city} is 25°C.`;
}
export function getCurrentCity() {
return "New York";
}
```
These functions can be easily integrated into your applications, such as Next.js:
```ts
"use server";
import { OpenAI } from "openai";
import { getTools } from "@llamaindex/tool";
export async function chat(message: string) {
const openai = new OpenAI();
openai.chat.completions.create({
messages: [
{
role: "user",
content: "What is the weather in the current city?",
},
],
tools: getTools("openai"),
});
}
```
```ts
// next.config.js
const withTool = require("@llamaindex/tool/next");
const config = {
// Your original Next.js config
};
module.exports = withTool(config);
```
The functions are automatically transformed into tools for the agent at compile time, which eliminates any extra runtime
costs. This feature is particularly beneficial when you need to debug or deploy your assistant.
For deploying your local functions into OpenAI, you can use a simple command:
```sh
npm install -g @llamaindex/tool
mkai --tools ./src/index.llama.ts
# Successfully created assistant: asst_XXX
# chat with your assistant by `chatai --assistant asst_XXX`
chatai --assistant asst_XXX
# Open your browser and chat with your assistant
# Running at http://localhost:3000
```
This deployment process simplifies the testing and implementation of your custom tools in a live environment.
As this project is still in its early stages, we continue to explore the best ways to create and integrate tools for
agents. For more information and updates, visit the @llamaindex/tool repository.
This release of LlamaIndexTS v0.3.0 marks a significant step forward in our journey to provide developers with robust,
flexible tools for building advanced agents. We are excited to see how our community utilizes these new capabilities to
create innovative solutions and look forward to continuing to support and enhance LlamaIndexTS in future updates.
Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

+1
View File
@@ -0,0 +1 @@
api/

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 49 KiB

Before

Width:  |  Height:  |  Size: 36 KiB

After

Width:  |  Height:  |  Size: 36 KiB

+2
View File
@@ -0,0 +1,2 @@
label: Examples
position: 3
+10
View File
@@ -0,0 +1,10 @@
# Agents
A built-in agent that can take decisions and reasoning based on the tools provided to it.
## OpenAI Agent
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/agent/openai";
<CodeBlock language="ts">{CodeSource}</CodeBlock>
+6
View File
@@ -0,0 +1,6 @@
# Gemini Agent
import CodeBlock from "@theme/CodeBlock";
import CodeSourceGemini from "!raw-loader!../../../../examples/gemini/agent.ts";
<CodeBlock language="ts">{CodeSourceGemini}</CodeBlock>
+12
View File
@@ -0,0 +1,12 @@
---
sidebar_position: 2
---
import CodeBlock from "@theme/CodeBlock";
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.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
@@ -0,0 +1,63 @@
---
sidebar_position: 14
---
# Context-Aware Agent
The Context-Aware Agent enhances the capabilities of standard LLM agents by incorporating relevant context from a retriever for each query. This allows the agent to provide more informed and specific responses based on the available information.
## Usage
Here's a simple example of how to use the Context-Aware Agent:
```typescript
import {
Document,
VectorStoreIndex,
OpenAIContextAwareAgent,
OpenAI,
} from "llamaindex";
async function createContextAwareAgent() {
// Create and index some documents
const documents = [
new Document({
text: "LlamaIndex is a data framework for LLM applications.",
id_: "doc1",
}),
new Document({
text: "The Eiffel Tower is located in Paris, France.",
id_: "doc2",
}),
];
const index = await VectorStoreIndex.fromDocuments(documents);
const retriever = index.asRetriever({ similarityTopK: 1 });
// Create the Context-Aware Agent
const agent = new OpenAIContextAwareAgent({
llm: new OpenAI({ model: "gpt-3.5-turbo" }),
contextRetriever: retriever,
});
// Use the agent to answer queries
const response = await agent.chat({
message: "What is LlamaIndex used for?",
});
console.log("Agent Response:", response.response);
}
createContextAwareAgent().catch(console.error);
```
In this example, the Context-Aware Agent uses the retriever to fetch relevant context for each query, allowing it to provide more accurate and informed responses based on the indexed documents.
## Key Components
- `contextRetriever`: A retriever (e.g., from a VectorStoreIndex) that fetches relevant documents or passages for each query.
## Available Context-Aware Agents
- `OpenAIContextAwareAgent`: A context-aware agent using OpenAI's models.
- `AnthropicContextAwareAgent`: A context-aware agent using Anthropic's models.
@@ -1,8 +1,6 @@
---
title: Local LLMs
---
# Local LLMs
LlamaIndex.TS supports OpenAI and [other remote LLM APIs](/docs/llamaindex/modules/models/llms). You can also run a local LLM on your machine!
LlamaIndex.TS supports OpenAI and [other remote LLM APIs](other_llms). You can also run a local LLM on your machine!
## Using a local model via Ollama
@@ -24,34 +22,17 @@ The first time you run it will also automatically download and install the model
### Switch the LLM in your code
To switch the LLM in your code, you first need to make sure to install the package for the Ollama model provider:
```package-install
npm i @llamaindex/ollama
```
Then, to tell LlamaIndex to use a local LLM, use the `Settings` object:
To tell LlamaIndex to use a local LLM, use the `Settings` object:
```javascript
import { Settings } from "llamaindex";
import { ollama } from "@llamaindex/ollama";
Settings.llm = ollama({
Settings.llm = new Ollama({
model: "mixtral:8x7b",
});
```
### Use local embeddings
If you're doing retrieval-augmented generation, LlamaIndex.TS will also call out to OpenAI to index and embed your data. To be entirely local, you can use a local embedding model from Huggingface like this:
First install the Huggingface model provider package:
```package-install
npm i @llamaindex/huggingface
```
And then set the embedding model in your code:
If you're doing retrieval-augmented generation, LlamaIndex.TS will also call out to OpenAI to index and embed your data. To be entirely local, you can use a local embedding model like this:
```javascript
Settings.embedModel = new HuggingFaceEmbedding({
@@ -1,33 +1,23 @@
---
title: Code examples
sidebar_position: 1
---
# See all examples
Our GitHub repository has a wealth of examples to explore and try out. You can check out our [examples folder](https://github.com/run-llama/LlamaIndexTS/tree/main/examples) to see them all at once, or browse the pages in this section for some selected highlights.
## Use examples locally
## Check out all examples
It may be useful to check out all the examples at once so you can try them out locally. To do this into a folder called `my-new-project`, run these commands:
```bash npm2yarn
npx degit run-llama/LlamaIndexTS/examples my-new-project
cd my-new-project
npm i
npm install
```
Then you can run any example in the folder with `tsx`, e.g.:
```bash npm2yarn
export OPENAI_API_KEY=your-api-key
npx tsx ./agents/agent/openai.ts
npx tsx ./vectorIndex.ts
```
## Try examples online
You can also try the examples online using StackBlitz:
<iframe
className="w-full h-[440px]"
aria-label="LlamaIndex.TS Examples"
aria-description="This is a list of examples for LlamaIndex.TS."
src="https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples?file=README.md"
/>
+41
View File
@@ -0,0 +1,41 @@
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/mistral";
# Using other LLM APIs
By default LlamaIndex.TS uses OpenAI's LLMs and embedding models, but we support [lots of other LLMs](../modules/llms) including models from Mistral (Mistral, Mixtral), Anthropic (Claude) and Google (Gemini).
If you don't want to use an API at all you can [run a local model](../../examples/local_llm)
## Using another LLM
You can specify what LLM LlamaIndex.TS will use on the `Settings` object, like this:
```typescript
import { MistralAI, Settings } from "llamaindex";
Settings.llm = new MistralAI({
model: "mistral-tiny",
apiKey: "<YOUR_API_KEY>",
});
```
You can see examples of other APIs we support by checking out "Available LLMs" in the sidebar of our [LLMs section](../modules/llms).
## Using another embedding model
A frequent gotcha when trying to use a different API as your LLM is that LlamaIndex will also by default index and embed your data using OpenAI's embeddings. To completely switch away from OpenAI you will need to set your embedding model as well, for example:
```typescript
import { MistralAIEmbedding, Settings } from "llamaindex";
Settings.embedModel = new MistralAIEmbedding();
```
We support [many different embeddings](../modules/embeddings).
## Full example
This example uses Mistral's `mistral-tiny` model as the LLM and Mistral for embeddings as well.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
@@ -0,0 +1,10 @@
---
sidebar_position: 4
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/storageContext";
# Save/Load an Index
<CodeBlock language="ts">{CodeSource}</CodeBlock>
+10
View File
@@ -0,0 +1,10 @@
---
sidebar_position: 3
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/summaryIndex";
# Summary Index
<CodeBlock language="ts">{CodeSource}</CodeBlock>
+10
View File
@@ -0,0 +1,10 @@
---
sidebar_position: 2
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
# Vector Index
<CodeBlock language="ts">{CodeSource}</CodeBlock>
@@ -0,0 +1,2 @@
label: Getting Started
position: 1
@@ -1,7 +1,9 @@
---
title: Concepts
sidebar_position: 3
---
# Concepts
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:
@@ -16,7 +18,7 @@ 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
![](/_static/concepts/rag.jpg)
![](../_static/concepts/rag.jpg)
This process is also known as Retrieval Augmented Generation (RAG).
@@ -28,14 +30,14 @@ Let's explore each stage in detail.
LlamaIndex.TS help you prepare the knowledge base with a suite of data connectors and indexes.
![](/_static/concepts/indexing.jpg)
![](../_static/concepts/indexing.jpg)
[**Data Loaders**](/docs/llamaindex/modules/data/readers):
[**Data Loaders**](../modules/data_loaders/index.mdx):
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**](/docs/llamaindex/modules/data): 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.
[**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**](/docs/llamaindex/modules/data/data_index):
[**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.
@@ -54,23 +56,23 @@ LlamaIndex provides composable modules that help you build and integrate RAG pip
These building blocks can be customized to reflect ranking preferences, as well as composed to reason over multiple knowledge bases in a structured way.
![](/_static/concepts/querying.jpg)
![](../_static/concepts/querying.jpg)
#### Building Blocks
[**Retrievers**](/docs/llamaindex/modules/rag/retriever):
[**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 different indices, the most popular being dense retrieval against a vector index.
[**Response Synthesizers**](/docs/llamaindex/modules/rag/response_synthesizer):
[**Response Synthesizers**](../modules/response_synthesizer.md):
A response synthesizer generates a response from an LLM, using a user query and a given set of retrieved text chunks.
#### Pipelines
[**Query Engines**](/docs/llamaindex/modules/rag/query_engines):
[**Query Engines**](../modules/query_engines):
A query engine is an end-to-end pipeline that allow you to ask question over your data.
It takes in a natural language query, and returns a response, along with reference context retrieved and passed to the LLM.
[**Chat Engines**](/docs/llamaindex/modules/rag/chat_engine):
[**Chat Engines**](../modules/chat_engine.md):
A chat engine is an end-to-end pipeline for having a conversation with your data
(multiple back-and-forth instead of a single question & answer).
@@ -0,0 +1,22 @@
---
sidebar_position: 2
---
# Environments
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
## NextJS
If you're using NextJS you'll need to add `withLlamaIndex` to your `next.config.js` file. This will add the necessary configuration for included 3rd-party libraries to your build:
```js
// next.config.js
const withLlamaIndex = require("llamaindex/next");
module.exports = withLlamaIndex({
// your next.js config
});
```
For details, check the latest [withLlamaIndex](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/llamaindex/src/next.ts) implementation.
@@ -0,0 +1,34 @@
---
sidebar_position: 0
---
# Installation and Setup
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
## Installation from NPM
```bash npm2yarn
npm install llamaindex
```
### Environment variables
Our examples use OpenAI by default. You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../examples/local_llm).
To use OpenAI, you'll need to [get an OpenAI API key](https://platform.openai.com/account/api-keys) and then make it available as an environment variable this way:
```bash
export OPENAI_API_KEY="sk-......" # Replace with your key
```
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. GitHub automatically invalidates OpenAI keys checked in by accident.
## What next?
- The easiest way to started is to [build a full-stack chat app with `create-llama`](starter_tutorial/chatbot).
- Try our other [getting started tutorials](starter_tutorial/retrieval_augmented_generation)
- Learn more about the [high level concepts](concepts) behind how LlamaIndex works
- Check out our [many examples](../examples/more_examples) of LlamaIndex.TS in action
@@ -0,0 +1,2 @@
label: Starter Tutorials
position: 1
@@ -0,0 +1,49 @@
---
sidebar_position: 4
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../examples/agent/openai";
# Agent tutorial
We have a comprehensive, step-by-step [guide to building agents in LlamaIndex.TS](../../guides/agents/setup) 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:
```bash npm2yarn
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
<CodeBlock language="ts">{CodeSource}</CodeBlock>
To run the code:
```bash
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
```
@@ -1,7 +1,13 @@
---
title: Create-Llama
sidebar_position: 2
---
# Chatbot tutorial
Once you've mastered basic [retrieval-augment generation](retrieval_augmented_generation) you may want to create an interface to chat with your data. You can do this step-by-step, but we recommend getting started quickly using `create-llama`.
## Using create-llama
`create-llama` is a powerful but easy to use command-line tool that generates a working, full-stack web application that allows you to chat with your data. You can learn more about it on [the `create-llama` README page](https://www.npmjs.com/package/create-llama).
Run it once and it will ask you a series of questions about the kind of application you want to generate. Then you can customize your application to suit your use-case. To get started, run:
@@ -18,9 +24,4 @@ npm run dev
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app, which should look something like this:
![create-llama interface](/images/create_llama.png)
## Learn more
- [Learn more about `create-llama`](https://github.com/run-llama/create-llama)
- [Want to use the same UI components? You can use our React components](https://ui.llamaindex.ai/)
![create-llama interface](./images/create_llama.png)
Binary file not shown.

After

Width:  |  Height:  |  Size: 540 KiB

@@ -1,22 +1,27 @@
---
title: Retrieval Augmented Generation (RAG)
sidebar_position: 1
---
One of the most common use-cases for LlamaIndex is Retrieval-Augmented Generation or RAG, in which your data is indexed and selectively retrieved to be given to an LLM as source material for responding to a query. You can learn more about the [concepts behind RAG](/docs/llamaindex/tutorials/rag/concepts).
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../examples/vectorIndex";
import TSConfigSource from "!!raw-loader!../../../../../examples/tsconfig.json";
# Retrieval Augmented Generation (RAG) Tutorial
One of the most common use-cases for LlamaIndex is Retrieval-Augmented Generation or RAG, in which your data is indexed and selectively retrieved to be given to an LLM as source material for responding to a query. You can learn more about the [concepts behind RAG](../concepts).
## Set up the project
In a new folder, run:
```package-install
```bash npm2yarn
npm init
npm i -D typescript @types/node
npm i llamaindex
npm install -D typescript @types/node
```
Then, check out the [installation](/docs/llamaindex/getting_started/installation) steps to install LlamaIndex.TS and prepare an OpenAI key.
Then, check out the [installation](../installation) steps to install LlamaIndex.TS and prepare an OpenAI key.
You can use [other LLMs](/docs/llamaindex/modules/models/llms) via their APIs; if you would prefer to use local models check out our [local LLM example](/docs/llamaindex/tutorials/local_llm).
You can use [other LLMs](../../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
## Run queries
@@ -27,15 +32,15 @@ Create the file `example.ts`. This code will
- index it (which creates embeddings using OpenAI)
- create a query engine to answer questions about the data
<include cwd>../../examples/index/vectorIndex.ts</include>
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Create a `tsconfig.json` file in the same folder:
<include cwd>../../examples/tsconfig.json</include>
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
Now you can run the code with
```package-install
```bash
npx tsx example.ts
```
@@ -1,19 +1,23 @@
---
title: Structured data extraction
sidebar_position: 3
---
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](/docs/llamaindex/getting_started/installation) guide.
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../examples/jsonExtract";
You can use [other LLMs](/docs/llamaindex/modules/models/llms) via their APIs; if you would prefer to use local models check out our [local LLM example](/docs/llamaindex/tutorials/local_llm).
# Structured data extraction tutorial
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](../installation) guide.
You can use [other LLMs](../../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
## Set up
In a new folder:
```package-install
```bash npm2yarn
npm init
npm i -D typescript @types/node
npm i @llamaindex/openai zod
npm install -D typescript @types/node
```
## Extract data
@@ -24,11 +28,11 @@ Create the file `example.ts`. This code will:
- Give an example of the data structure we wish to generate
- Prompt the LLM with instructions and the example, plus a sample transcript
<include cwd>../../examples/misc/jsonExtract.ts</include>
<CodeBlock language="ts">{CodeSource}</CodeBlock>
To run the code:
```package-install
```bash
npx tsx example.ts
```
+2
View File
@@ -0,0 +1,2 @@
label: Guides
position: 2
@@ -1,26 +1,28 @@
---
title: 1. Setup
sidebar_position: 1
---
# Getting started
In this guide we'll walk you through the process of building an Agent in JavaScript using the LlamaIndex.TS library, starting from nothing and adding complexity in stages.
## What is an Agent?
In LlamaIndex, an agent is a semi-autonomous piece of software powered by an LLM that is given a task and executes a series of steps towards solving that task. It is given a set of tools, which can be anything from arbitrary functions up to full LlamaIndex query engines, and it selects the best available tool to complete each step. When each step is completed, the agent judges whether the task is now complete, in which case it returns a result to the user, or whether it needs to take another step, in which case it loops back to the start.
![agent flow](/images/agent_flow.png)
![agent flow](./images/agent_flow.png)
## Install LlamaIndex.TS
You'll need to have a recent version of [Node.js](https://nodejs.org/en) installed. Then you can install LlamaIndex.TS by running
```package-install
npm i llamaindex @llamaindex/openai @llamaindex/readers @llamaindex/huggingface @llamaindex/workflow
```bash
npm install llamaindex
```
## Choose your model
By default we'll be using OpenAI with GPT-4, as it's a powerful model and easy to get started with. If you'd prefer to run a local model, see [using a local model](3_local_model).
By default we'll be using OpenAI with GPT-4, as it's a powerful model and easy to get started with. If you'd prefer to run a local model, see [using a local model](local_model).
## Get an OpenAI API key
@@ -33,7 +35,7 @@ OPENAI_API_KEY=sk-XXXXXXXXXXXXXXXXXXXXXXXX
We'll use `dotenv` to pull the API key out of that .env file, so also run:
```bash
npm i dotenv
npm install dotenv
```
Now you're ready to [create your agent](2_create_agent).
Now you're ready to [create your agent](create_agent).
@@ -0,0 +1,179 @@
# 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:
```typescript
// 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:
```bash
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
```javascript
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.
```javascript
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).
```javascript
Settings.callbackManager.on("llm-tool-call", (event) => {
console.log(event.detail);
});
Settings.callbackManager.on("llm-tool-result", (event) => {
console.log(event.detail);
});
```
### 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.
```javascript
const sumNumbers = ({ a, b }) => {
return `${a + b}`;
};
```
Note that we're passing in an object with two named parameters, `a` and `b`. This is a little unusual, but important for defining a tool that an LLM can use.
### Turn the function into a tool for the agent
This is the most complicated part of creating an agent. We need to define a `FunctionTool`. We have to pass in:
- The function itself (`sumNumbers`)
- A name for the function, which the LLM will use to call it
- A description of the function. The LLM will read this description to figure out what the tool does, and if it needs to call it
- A schema for function. We tell the LLM that the parameter is an `object`, and we tell it about the two named parameters we gave it, `a` and `b`. We describe each parameter as a `number`, and we say that both are required.
- You can see [more examples of function schemas](https://cookbook.openai.com/examples/how_to_call_functions_with_chat_models).
```javascript
const tool = FunctionTool.from(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "First number to sum",
},
b: {
type: "number",
description: "Second number to sum",
},
},
required: ["a", "b"],
},
});
```
We then wrap up the tools into an array. We could provide lots of tools this way, but for this example we're just using the one.
```javascript
const tools = [tool];
```
### Create the agent
With your LLM already set up and your tools defined, creating an agent is simple:
```javascript
const agent = new OpenAIAgent({ tools });
```
### Ask the agent a question
We can use the `chat` interface to ask our agent a question, and it will use the tools we've defined to find an answer.
```javascript
let response = await agent.chat({
message: "Add 101 and 303",
});
console.log(response);
```
Let's see what running this looks like using `npx tsx agent.ts`
**_Output_**
```javascript
{
toolCall: {
id: 'call_ze6A8C3mOUBG4zmXO8Z4CPB5',
name: 'sumNumbers',
input: { a: 101, b: 303 }
},
toolResult: {
tool: FunctionTool { _fn: [Function: sumNumbers], _metadata: [Object] },
input: { a: 101, b: 303 },
output: '404',
isError: false
}
}
```
```javascript
{
response: {
raw: {
id: 'chatcmpl-9KwauZku3QOvH78MNvxJs81mDvQYK',
object: 'chat.completion',
created: 1714778824,
model: 'gpt-4-turbo-2024-04-09',
choices: [Array],
usage: [Object],
system_fingerprint: 'fp_ea6eb70039'
},
message: {
content: 'The sum of 101 and 303 is 404.',
role: 'assistant',
options: {}
}
},
sources: [Getter]
}
```
We're seeing two pieces of output here. The first is our callback firing when the tool is called. You can see in `toolResult` that the LLM has correctly passed `101` and `303` to our `sumNumbers` function, which adds them up and returns `404`.
The second piece of output is the response from the LLM itself, where the `message.content` key is giving us the answer.
Great! We've built an agent with tool use! Next you can:
- [See the full code](https://github.com/run-llama/ts-agents/blob/main/1_agent/agent.ts)
- [Switch to a local LLM](local_model)
- Move on to [add Retrieval-Augmented Generation to your agent](agentic_rag)
@@ -0,0 +1,90 @@
# Using a local model via Ollama
If you're happy using OpenAI, you can skip this section, but many people are interested in using models they run themselves. The easiest way to do this is via the great work of our friends at [Ollama](https://ollama.com/), who provide a simple to use client that will download, install and run a [growing range of models](https://ollama.com/library) for you.
### Install Ollama
They provide a one-click installer for Mac, Linux and Windows on their [home page](https://ollama.com/).
### Pick and run a model
Since we're going to be doing agentic work, we'll need a very capable model, but the largest models are hard to run on a laptop. We think `mixtral 8x7b` is a good balance between power and resources, but `llama3` is another great option. You can run it simply by running
```bash
ollama run mixtral:8x7b
```
The first time you run it will also automatically download and install the model for you.
### Switch the LLM in your code
There are two changes you need to make to the code we already wrote in `1_agent` to get Mixtral 8x7b to work. First, you need to switch to that model. Replace the call to `Settings.llm` with this:
```javascript
Settings.llm = new Ollama({
model: "mixtral:8x7b",
});
```
### Swap to a ReActAgent
In our original code we used a specific OpenAIAgent, so we'll need to switch to a more generic agent pattern, the ReAct pattern. This is simple: change the `const agent` line in your code to read
```javascript
const agent = new ReActAgent({ tools });
```
(You will also need to bring in `Ollama` and `ReActAgent` in your imports)
### Run your totally local agent
Because your embeddings were already local, your agent can now run entirely locally without making any API calls.
```bash
node agent.mjs
```
Note that your model will probably run a lot slower than OpenAI, so be prepared to wait a while!
**_Output_**
```javascript
{
response: {
message: {
role: 'assistant',
content: ' Thought: I need to use a tool to add the numbers 101 and 303.\n' +
'Action: sumNumbers\n' +
'Action Input: {"a": 101, "b": 303}\n' +
'\n' +
'Observation: 404\n' +
'\n' +
'Thought: I can answer without using any more tools.\n' +
'Answer: The sum of 101 and 303 is 404.'
},
raw: {
model: 'mixtral:8x7b',
created_at: '2024-05-09T00:24:30.339473Z',
message: [Object],
done: true,
total_duration: 64678371209,
load_duration: 57394551334,
prompt_eval_count: 475,
prompt_eval_duration: 4163981000,
eval_count: 94,
eval_duration: 3116692000
}
},
sources: [Getter]
}
```
Tada! You can see all of this in the folder `1a_mixtral`.
### Extending to other examples
You can use a ReActAgent instead of an OpenAIAgent in any of the further examples below, but keep in mind that GPT-4 is a lot more capable than Mixtral 8x7b, so you may see more errors or failures in reasoning if you are using an entirely local setup.
### Next steps
Now you've got a local agent, you can [add Retrieval-Augmented Generation to your agent](agentic_rag).
@@ -1,6 +1,4 @@
---
title: 4. Adding Retrieval-Augmented Generation (RAG)
---
# Adding Retrieval-Augmented Generation (RAG)
While an agent that can perform math is nifty (LLMs are usually not very good at math), LLM-based applications are always more interesting when they work with large amounts of data. In this case, we're going to use a 200-page PDF of the proposed budget of the city of San Francisco for fiscal years 2024-2024 and 2024-2025. It's a great example because it's extremely wordy and full of tables of figures, which present a challenge for humans and LLMs alike.
@@ -13,22 +11,22 @@ To learn more about RAG, we recommend this [introduction](https://docs.llamainde
We're going to start with the same agent we [built in step 1](https://github.com/run-llama/ts-agents/blob/main/1_agent/agent.ts), but make a few changes. You can find the finished version [in the repository](https://github.com/run-llama/ts-agents/blob/main/2_agentic_rag/agent.ts).
## Installation
```package-install
npm i llamaindex @llamaindex/openai @llamaindex/huggingface
```
### New dependencies
We'll be bringing in `SimpleDirectoryReader`, `HuggingFaceEmbedding`, `VectorStoreIndex`, and `QueryEngineTool`, `OpenAIContextAwareAgent` from LlamaIndex.TS, as well as the dependencies we previously used.
```javascript
import { QueryEngineTool, Settings, VectorStoreIndex } from "llamaindex";
import { agent } from "@llamaindex/workflow";
import { openai } from "@llamaindex/openai";
import { HuggingFaceEmbedding } from "@llamaindex/huggingface";
import { SimpleDirectoryReader } from "@llamaindex/readers/directory";
import {
OpenAI,
FunctionTool,
OpenAIAgent,
OpenAIContextAwareAgent,
Settings,
SimpleDirectoryReader,
HuggingFaceEmbedding,
VectorStoreIndex,
QueryEngineTool,
} from "llamaindex";
```
### Add an embedding model
@@ -59,32 +57,67 @@ We will convert our text into embeddings using the `VectorStoreIndex` class thro
const index = await VectorStoreIndex.fromDocuments(documents);
```
### Use index.queryTool
### Configure a retriever
`index.queryTool` creates a `QueryEngineTool` that can be used be an agent to query data from the index:
Before LlamaIndex can send a query to the LLM, it needs to find the most relevant chunks to send. That's the purpose of a `Retriever`. We're going to get `VectorStoreIndex` to act as a retriever for us
```javascript
const retriever = await index.asRetriever();
```
### Configure how many documents to retrieve
By default LlamaIndex will retrieve just the 2 most relevant chunks of text. This document is complex though, so we'll ask for more context.
```javascript
retriever.similarityTopK = 10;
```
### Approach 1: Create a Context-Aware Agent
With the retriever ready, you can create a **context-aware agent**.
```javascript
const agent = new OpenAIContextAwareAgent({
contextRetriever: retriever,
});
// Example query to the context-aware agent
let response = await agent.chat({
message: `What's the budget of San Francisco in 2023-2024?`,
});
console.log(response);
```
**Expected Output:**
```md
The total budget for the City and County of San Francisco for the fiscal year 2023-2024 is $14.6 billion. This represents a $611.8 million, or 4.4 percent, increase over the previous fiscal year's budget. The budget covers various expenditures across different departments and services, including significant allocations to public works, transportation, commerce, public protection, and health services.
```
### Approach 2: Using QueryEngineTool (Alternative Approach)
If you prefer more flexibility and don't mind additional complexity, you can create a `QueryEngineTool`. This approach allows you to define the query logic, providing a more tailored way to interact with the data, but note that it introduces a delay due to the extra tool call.
```javascript
const queryEngine = await index.asQueryEngine({ retriever });
const tools = [
index.queryTool({
new QueryEngineTool({
queryEngine: queryEngine,
metadata: {
name: "san_francisco_budget_tool",
description: `This tool can answer detailed questions about the individual components of the budget of San Francisco in 2023-2024.`,
},
options: { similarityTopK: 10 },
}),
];
```
The `metadata` that we're setting helps the agent to decide when to use the tool.
Note that by default LlamaIndex will retrieve just the 2 most relevant chunks of text. This document is complex though, so we'll ask for more context by setting `similarityTopK` to 10.
Now, we can create an agent using the `QueryEngineTool`:
```javascript
// Create an agent using the tools array
const ragAgent = agent({ tools });
const agent = new OpenAIAgent({ tools });
let toolResponse = await ragAgent.run("What's the budget of San Francisco in 2023-2024?");
let toolResponse = await agent.chat({
message: "What's the budget of San Francisco in 2023-2024?",
});
console.log(toolResponse);
```
@@ -112,4 +145,10 @@ console.log(toolResponse);
Once again we see a `toolResult`. You can see the query the LLM decided to send to the query engine ("total budget"), and the output the engine returned. In `response.message` you see that the LLM has returned the output from the tool almost verbatim, although it trimmed out the bit about 2024-2025 since we didn't ask about that year.
So now we have an agent that can index complicated documents and answer questions about them. Let's [combine our math agent and our RAG agent](5_rag_and_tools)!
### Comparison of Approaches
The `OpenAIContextAwareAgent` approach simplifies the setup by allowing you to directly link the retriever to the agent, making it straightforward to access relevant context for your queries. This is ideal for situations where you want easy integration with existing data sources, like a context chat engine.
On the other hand, using the `QueryEngineTool` offers more flexibility and power. This method allows for customization in how queries are constructed and executed, enabling you to query data from various storages and process them in different ways. However, this added flexibility comes with increased complexity and response time due to the separate tool call and queryEngine generating tool output by LLM that is then passed to the agent.
So now we have an agent that can index complicated documents and answer questions about them. Let's [combine our math agent and our RAG agent](rag_and_tools)!
@@ -1,69 +1,57 @@
---
title: 5. A RAG agent that does math
---
# A RAG agent that does math
In [our third iteration of the agent](https://github.com/run-llama/ts-agents/blob/main/3_rag_and_tools/agent.ts) we've combined the two previous agents, so we've defined both `sumNumbers` and a `QueryEngineTool` and created an array of two tools. The tools support both Zod and JSON Schema for parameter definition:
In [our third iteration of the agent](https://github.com/run-llama/ts-agents/blob/main/3_rag_and_tools/agent.ts) we've combined the two previous agents, so we've defined both `sumNumbers` and a `QueryEngineTool` and created an array of two tools:
```javascript
// define the query engine as a tool
const tools = [
index.queryTool({
new QueryEngineTool({
queryEngine: queryEngine,
metadata: {
name: "san_francisco_budget_tool",
description: `This tool can answer detailed questions about the individual components of the budget of San Francisco in 2023-2024.`,
},
options: { similarityTopK: 10 },
}),
tool({
FunctionTool.from(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: z.object({
a: z.number({
description: "First number to sum",
}),
b: z.number({
description: "Second number to sum",
}),
}),
execute: ({ a, b }) => `${a + b}`,
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "First number to sum",
},
b: {
type: "number",
description: "Second number to sum",
},
},
required: ["a", "b"],
},
}),
];
```
You can also use JSON Schema to define the tool parameters as an alternative to Zod.
```javascript
tool(sumNumbers, {
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: {
type: "object",
properties: {
a: {
type: "number",
description: "First number to sum",
},
b: {
type: "number",
description: "Second number to sum",
},
},
required: ["a", "b"],
},
}),
```
These tool descriptions are identical to the ones we previously defined. Now let's ask it 3 questions in a row:
```javascript
let response = await agent.run("What's the budget of San Francisco for community health in 2023-24?");
let response = await agent.chat({
message:
"What's the budget of San Francisco for community health in 2023-24?",
});
console.log(response);
let response2 = await agent.run("What's the budget of San Francisco for public protection in 2023-24?");
let response2 = await agent.chat({
message:
"What's the budget of San Francisco for public protection in 2023-24?",
});
console.log(response2);
let response3 = await agent.run("What's the combined budget of San Francisco for community health and public protection in 2023-24?");
let response3 = await agent.chat({
message:
"What's the combined budget of San Francisco for community health and public protection in 2023-24?",
});
console.log(response3);
```
@@ -137,4 +125,4 @@ In the final tool call, it used the `sumNumbers` function to add the two budgets
}
```
Great! Now let's improve accuracy by improving our parsing with [LlamaParse](6_llamaparse).
Great! Now let's improve accuracy by improving our parsing with [LlamaParse](llamaparse).
@@ -1,6 +1,4 @@
---
title: 6. Adding LlamaParse
---
# Adding LlamaParse
Complicated PDFs can be very tricky for LLMs to understand. To help with this, LlamaIndex provides LlamaParse, a hosted service that parses complex documents including PDFs. To use it, get a `LLAMA_CLOUD_API_KEY` by [signing up for LlamaCloud](https://cloud.llamaindex.ai/) (it's free for up to 1000 pages/day) and adding it to your `.env` file just as you did for your OpenAI key:
@@ -17,4 +15,4 @@ const documents = await reader.loadData("../data/sf_budget_2023_2024.pdf");
Now you will be able to ask more complicated questions of the same PDF and get better results. You can find this code [in our repo](https://github.com/run-llama/ts-agents/blob/main/4_llamaparse/agent.ts).
Next up, let's persist our embedded data so we don't have to re-parse every time by [using a vector store](7_qdrant).
Next up, let's persist our embedded data so we don't have to re-parse every time by [using a vector store](qdrant).
@@ -1,6 +1,4 @@
---
title: 7. Adding persistent vector storage
---
# Adding persistent vector storage
In the previous examples, we've been loading our data into memory each time we run the agent. This is fine for small datasets, but for larger datasets you'll want to store your embeddings in a database. LlamaIndex.TS provides a `VectorStore` class that can store your embeddings in a variety of databases. We're going to use [Qdrant](https://qdrant.tech/), a popular vector store, for this example.
@@ -65,13 +63,13 @@ Since parsing a PDF can be slow, especially a large one, using the pre-parsed ch
In this guide you've learned how to
- [Create an agent](2_create_agent)
- [Create an agent](create_agent)
- Use remote LLMs like GPT-4
- [Use local LLMs like Mixtral](3_local_model)
- [Create a RAG query engine](4_agentic_rag)
- [Turn functions and query engines into agent tools](5_rag_and_tools)
- [Use local LLMs like Mixtral](local_model)
- [Create a RAG query engine](agentic_rag)
- [Turn functions and query engines into agent tools](rag_and_tools)
- Combine those tools
- [Enhance your parsing with LlamaParse](6_llamaparse)
- [Enhance your parsing with LlamaParse](llamaparse)
- Persist your data in a vector store
The next steps are up to you! Try creating more complex functions and query engines, and set your agent loose on the world.
@@ -0,0 +1,2 @@
label: Agents
position: 1

Before

Width:  |  Height:  |  Size: 236 KiB

After

Width:  |  Height:  |  Size: 236 KiB

+54
View File
@@ -0,0 +1,54 @@
---
sidebar_position: 0
slug: /
---
# What is LlamaIndex?
LlamaIndex is a framework for building LLM-powered applications. LlamaIndex helps you ingest, structure, and access private or domain-specific data. It's available [as a Python package](https://docs.llamaindex.ai/en/stable/) and in TypeScript (this package). LlamaIndex.TS offers the core features of LlamaIndex for popular runtimes like Node.js (official support), Vercel Edge Functions (experimental), and Deno (experimental).
## 🚀 Why LlamaIndex.TS?
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. That data is often distributed across siloed applications and data stores. It's behind APIs, in SQL databases, or trapped in PDFs and slide decks.
LlamaIndex.TS helps you unlock that data and then build powerful applications with it.
## 🦙 What is LlamaIndex for?
LlamaIndex.TS handles several major use cases:
- **Structured Data Extraction**: turning complex, unstructured and semi-structured data into uniform, programmatically accessible formats.
- **Retrieval-Augmented Generation (RAG)**: answering queries across your internal data by providing LLMs with up-to-date, semantically relevant context including Question and Answer systems and chat bots.
- **Autonomous Agents**: building software that is capable of intelligently selecting and using tools to accomplish tasks in an interactive, unsupervised manner.
## 👨‍👩‍👧‍👦 Who is LlamaIndex for?
LlamaIndex targets the "AI Engineer": developers building software in any domain that can be enhanced by LLM-powered functionality, without needing to be an expert in machine learning or natural language processing.
Our high-level API allows beginner users to use LlamaIndex.TS to ingest, index, and query their data in just a few lines of code.
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_tutorial/retrieval_augmented_generation.mdx) 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.
## 🗺️ Ecosystem
To download or contribute, find LlamaIndex on:
- Github: https://github.com/run-llama/LlamaIndexTS
- NPM: https://www.npmjs.com/package/llamaindex
## Community
Need help? Have a feature suggestion? Join the LlamaIndex community:
- Twitter: https://twitter.com/llama_index
- Discord https://discord.gg/dGcwcsnxhU
+3
View File
@@ -0,0 +1,3 @@
label: "Modules"
collapsed: false
position: 5
@@ -0,0 +1,2 @@
label: "Agents"
position: 10
@@ -1,8 +1,4 @@
---
title: Agents
---
**Note**: Agents are deprecated, use [Agent Workflows](/docs/llamaindex/modules/agents/agent_workflow) instead.
# Agents
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:
@@ -21,8 +17,13 @@ LlamaIndex.TS comes with a few built-in agents, but you can also create your own
- ReACT Agent
- Meta3.1 504B via Bedrock (in `@llamaIndex/community`)
## Examples
- [OpenAI Agent](../../examples/agent.mdx)
- [Gemini Agent](../../examples/agent_gemini.mdx)
## Api References
- [OpenAIAgent](/docs/api/classes/OpenAIAgent)
- [AnthropicAgent](/docs/api/classes/AnthropicAgent)
- [ReActAgent](/docs/api/classes/ReActAgent)
- [OpenAIAgent](../../api/classes/OpenAIAgent.md)
- [AnthropicAgent](../../api/classes/AnthropicAgent.md)
- [ReActAgent](../../api/classes/ReActAgent.md)
+30
View File
@@ -0,0 +1,30 @@
---
sidebar_position: 13
---
# ChatEngine
The chat engine is a quick and simple way to chat with the data in your index.
```typescript
const retriever = index.asRetriever();
const chatEngine = new ContextChatEngine({ retriever });
// start chatting
const response = await chatEngine.chat({ message: query });
```
The `chat` function also supports streaming, just add `stream: true` as an option:
```typescript
const stream = await chatEngine.chat({ message: query, stream: true });
for await (const chunk of stream) {
process.stdout.write(chunk.response);
}
```
## Api References
- [ContextChatEngine](../api/classes/ContextChatEngine.md)
- [CondenseQuestionChatEngine](../api/classes/ContextChatEngine.md)
- [SimpleChatEngine](../api/classes/SimpleChatEngine.md)
@@ -1,9 +1,10 @@
---
title: Index
sidebar_position: 12
---
An index is the basic container for organizing your data. Besides managed indexes using [LlamaCloud](/docs/llamaindex/modules/data/data_index/managed), LlamaIndex.TS supports three indexes:
# Index
An index is the basic container and organization for your data. LlamaIndex.TS supports two indexes:
- `VectorStoreIndex` - will send the top-k `Node`s to the LLM when generating a response. The default top-k is 2.
- `SummaryIndex` - will send every `Node` in the index to the LLM in order to generate a response
@@ -19,6 +20,6 @@ const index = await VectorStoreIndex.fromDocuments([document]);
## API Reference
- [SummaryIndex](/docs/api/classes/SummaryIndex)
- [VectorStoreIndex](/docs/api/classes/VectorStoreIndex)
- [KeywordTableIndex](/docs/api/classes/KeywordTableIndex)
- [SummaryIndex](../api/classes/SummaryIndex.md)
- [VectorStoreIndex](../api/classes/VectorStoreIndex.md)
- [KeywordTableIndex](../api/classes/KeywordTableIndex.md)
@@ -0,0 +1,2 @@
label: "Loaders"
position: 1
@@ -1,16 +1,11 @@
---
title: DiscordReader
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../examples/readers/src/discord";
# DiscordReader
DiscordReader is a simple data loader that reads all messages in a given Discord channel and returns them as Document objects.
It uses the [@discordjs/rest](https://github.com/discordjs/discord.js/tree/main/packages/rest) library to fetch the messages.
## Installation
```package-install
npm install @llamaindex/discord
```
## Usage
First step is to create a Discord Application and generating a bot token [here](https://discord.com/developers/applications).
@@ -18,7 +13,7 @@ In your Discord Application, go to the `OAuth2` tab and generate an invite URL b
This will invite the bot with the necessary permissions to read messages.
Copy the URL in your browser and select the server you want your bot to join.
<include cwd>../../examples/readers/discord/reader.ts</include>
<CodeBlock language="ts">{CodeSource}</CodeBlock>
### Params
@@ -36,4 +31,4 @@ Copy the URL in your browser and select the server you want your bot to join.
## API Reference
- [DiscordReader](/docs/api/classes/DiscordReader)
- [DiscordReader](../../api/classes/DiscordReader.md)
@@ -0,0 +1,58 @@
import CodeBlock from "@theme/CodeBlock";
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.
All "basic" data loaders can be seen below, mapped to their respective filetypes in `SimpleDirectoryReader`. More loaders are shown in the sidebar on the left.
Additionally the following loaders exist without separate documentation:
- `AssemblyAIReader` transcribes audio using [AssemblyAI](https://www.assemblyai.com/).
- [AudioTranscriptReader](../../api/classes/AudioTranscriptReader.md): loads entire transcript as a single document.
- [AudioTranscriptParagraphsReader](../../api/classes/AudioTranscriptParagraphsReader.md): creates a document per paragraph.
- [AudioTranscriptSentencesReader](../../api/classes/AudioTranscriptSentencesReader.md): creates a document per sentence.
- [AudioSubtitlesReader](../../api/classes/AudioTranscriptParagraphsReader.md): creates a document containing the subtitles of a transcript.
- [NotionReader](../../api/classes/NotionReader.md) loads [Notion](https://www.notion.so/) pages.
- [SimpleMongoReader](../../api/classes/SimpleMongoReader) loads data from a [MongoDB](https://www.mongodb.com/).
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
## SimpleDirectoryReader
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](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, the following readers are mapped to specific file types:
- [TextFileReader](../../api/classes/TextFileReader.md): `.txt`
- [PDFReader](../../api/classes/PDFReader.md): `.pdf`
- [PapaCSVReader](../../api/classes/PapaCSVReader.md): `.csv`
- [MarkdownReader](../../api/classes/MarkdownReader.md): `.md`
- [DocxReader](../../api/classes/DocxReader.md): `.docx`
- [HTMLReader](../../api/classes/HTMLReader.md): `.htm`, `.html`
- [ImageReader](../../api/classes/ImageReader.md): `.jpg`, `.jpeg`, `.png`, `.gif`
You can modify the reader three different ways:
- `overrideReader` overrides the reader for all file types, including unsupported ones.
- `fileExtToReader` maps a reader to a specific file type. Can override reader for existing file types or add support for new file types.
- `defaultReader` sets a fallback reader for files with unsupported extensions. By default it is `TextFileReader`.
SimpleDirectoryReader supports up to 9 concurrent requests. Use the `numWorkers` option to set the number of concurrent requests. By default it runs in sequential mode, i.e. set to 1.
### Example
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
{CodeSource2}
</CodeBlock>
## API Reference
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
@@ -1,21 +1,13 @@
---
title: JSONReader
---
# JSONReader
A simple JSON data loader with various options.
Either parses the entire string, cleaning it and treat each line as an embedding or performs a recursive depth-first traversal yielding JSON paths.
Supports streaming of large JSON data using [@discoveryjs/json-ext](https://github.com/discoveryjs/json-ext)
## Installation
```package-install
npm i llamaindex @llamaindex/readers
```
## Usage
```ts
import { JSONReader } from "@llamaindex/readers/json";
import { JSONReader } from "llamaindex";
const file = "../../PATH/TO/FILE";
const content = new TextEncoder().encode("JSON_CONTENT");
@@ -47,6 +39,7 @@ Depth-First-Traversal:
#### Examples
<!-- prettier-ignore-start -->
Input:
```json
@@ -149,7 +142,8 @@ Output:
"tweet": "こんにちは世界"
```
<!-- prettier-ignore-end -->
## API Reference
- [JSONReader](/docs/api/classes/JSONReader)
- [JSONReader](../../api/classes/JSONReader.md)
@@ -0,0 +1 @@
label: "LlamaParse"
@@ -1,15 +1,11 @@
---
title: Image Retrieval
sidebar_position: 2
---
# Image Retrieval
LlamaParse `json` mode supports extracting any images found in a page object by using the `getImages` function. They are downloaded to a local folder and can then be sent to a multimodal LLM for further processing.
## Installation
```package-install
npm i llamaindex @llamaindex/cloud @llamaindex/openai
```
## Usage
We use the `getImages` method to input our array of JSON objects, download the images to a specified folder and get a list of ImageNodes.
@@ -25,10 +21,14 @@ const imageDicts = await reader.getImages(jsonObjs, "images");
You can create an index across both text and image nodes by requesting alternative text for the image from a multimodal LLM.
```ts
import { Document, ImageNode, VectorStoreIndex } from "llamaindex";
import { LlamaParseReader } from "@llamaindex/cloud";
import { OpenAI } from "@llamaindex/openai";
import { createMessageContent } from "llamaindex";
import {
Document,
ImageNode,
LlamaParseReader,
OpenAI,
VectorStoreIndex,
} from "llamaindex";
import { createMessageContent } from "llamaindex/synthesizers/utils";
const reader = new LlamaParseReader();
async function main() {
@@ -112,3 +112,6 @@ The returned `imageDocs` have the alt text assigned as text and the image path a
You can see the full example file [here](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/readers/src/llamaparse-json.ts).
## API Reference
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
@@ -1,6 +1,8 @@
---
title: LlamaParse
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../../examples/readers/src/llamaparse";
import CodeSource2 from "!raw-loader!../../../../../../examples/readers/src/simple-directory-reader-with-llamaparse.ts";
# LlamaParse
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
@@ -13,7 +15,7 @@ Official documentation for LlamaParse can be found [here](https://docs.cloud.lla
You can then use the `LlamaParseReader` class to load local files and convert them into a parsed document that can be used by LlamaIndex.
See [reader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/cloud/src/reader.ts) for a list of supported file types:
<include cwd>../../examples/readers/src/llamaparse.ts</include>
<CodeBlock language="ts">{CodeSource}</CodeBlock>
### Params
@@ -32,7 +34,7 @@ They can be divided into two groups.
#### Advanced params:
- `resultType` can be set to `markdown`, `text` or `json`. Defaults to `text`. More information about `json` mode on the next pages.
- `language` primarily helps with OCR recognition. Defaults to `en`.
- `language` primarily helps with OCR recognition. Defaults to `en`. Click [here](../../../api/type-aliases/Language.md) for a list of supported languages.
- `parsingInstructions?` Optional. Can help with complicated document structures. See this [LlamaIndex Blog Post](https://www.llamaindex.ai/blog/launching-the-first-genai-native-document-parsing-platform) for an example.
- `skipDiagonalText?` Optional. Set to true to ignore diagonal text. (Text that is not rotated 0, 90, 180 or 270 degrees)
- `invalidateCache?` Optional. Set to true to ignore the LlamaCloud cache. All document are kept in cache for 48hours after the job was completed to avoid processing the same document twice. Can be useful for testing when trying to re-parse the same document with, e.g. different `parsingInstructions`.
@@ -56,8 +58,9 @@ They can be divided into two groups.
Below a full example of `LlamaParse` integrated in `SimpleDirectoryReader` with additional options.
<include cwd>../../examples/readers/src/simple-directory-reader-with-llamaparse.ts</include>
<CodeBlock language="ts">{CodeSource2}</CodeBlock>
## API Reference
- [SimpleDirectoryReader](/docs/api/classes/SimpleDirectoryReader)
- [SimpleDirectoryReader](../../../api/classes/SimpleDirectoryReader.md)
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
@@ -1,23 +1,17 @@
---
title: JSON Mode
sidebar_position: 1
---
# JSON Mode
In JSON mode, LlamaParse will return a data structure representing the parsed object.
## Installation
```package-install
npm i llamaindex @llamaindex/cloud
```
## Usage
For Json mode, you need to use `loadJson`. The `resultType` is automatically set with this method.
More information about indexing the results on the next page.
```ts
import { LlamaParseReader } from "@llamaindex/cloud";
const reader = new LlamaParseReader();
async function main() {
// Load the file and return an array of json objects
@@ -67,8 +61,7 @@ All Readers share a `loadData` method with `SimpleDirectoryReader` that promises
However, a simple work around is to create a new reader class that extends `LlamaParseReader` and adds a new method or overrides `loadData`, wrapping around JSON mode, extracting the required values, and returning a Document object.
```ts
import { Document } from "llamaindex";
import { LlamaParseReader } from "@llamaindex/cloud";
import { LlamaParseReader, Document } from "llamaindex";
class LlamaParseReaderWithJson extends LlamaParseReader {
// Override the loadData method
@@ -98,4 +91,5 @@ You can assign any other values of the JSON response to the Document as needed.
## API Reference
- [SimpleDirectoryReader](/docs/api/classes/SimpleDirectoryReader)
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
- [SimpleDirectoryReader](../../../api/classes/SimpleDirectoryReader.md)
@@ -0,0 +1,2 @@
label: "Data Stores"
position: 2
@@ -0,0 +1 @@
label: "Chat Stores"
@@ -1,16 +1,13 @@
---
title: Chat Stores
---
# Chat Stores
Chat stores manage chat history by storing sequences of messages in a structured way, ensuring the order of messages is maintained for accurate conversation flow.
## Available Chat Stores
- [SimpleChatStore](/docs/api/classes/SimpleChatStore): A simple in-memory chat store with support for [persisting](/docs/llamaindex/modules/data/stores#local-storage) data to disk.
- [SimpleChatStore](../../../api/classes/SimpleChatStore.md): A simple in-memory chat store with support for [persisting](../index.md#local-storage) data to disk.
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
## API Reference
- [BaseChatStore](/docs/api/classes/BaseChatStore)
- [BaseChatStore](../../../api/interfaces/BaseChatStore.md)
@@ -0,0 +1,2 @@
label: "Document Stores"
position: 2
@@ -0,0 +1,14 @@
# Document Stores
Document stores contain ingested document chunks, i.e. [Node](../../documents_and_nodes/index.md)s.
## Available Document Stores
- [SimpleDocumentStore](../../../api/classes/SimpleDocumentStore.md): A simple in-memory document store with support for [persisting](../index.md#local-storage) data to disk.
- [PostgresDocumentStore](../../../api/classes/PostgresDocumentStore.md): A PostgreSQL document store, see [PostgreSQL Storage](../index.md#postgresql-storage).
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
## API Reference
- [BaseDocumentStore](../../../api/classes/BaseDocumentStore.md)
@@ -0,0 +1,56 @@
# Storage
Storage in LlamaIndex.TS works automatically once you've configured a
`StorageContext` object.
## Local Storage
You can configure the `persistDir` and attach it to an index.
```typescript
import {
Document,
VectorStoreIndex,
storageContextFromDefaults,
} from "llamaindex";
const storageContext = await storageContextFromDefaults({
persistDir: "./storage",
});
const document = new Document({ text: "Test Text" });
const index = await VectorStoreIndex.fromDocuments([document], {
storageContext,
});
```
## PostgreSQL Storage
You can configure the `schemaName`, `tableName`, `namespace`, and
`connectionString`. If a `connectionString` is not
provided, it will use the environment variables `PGHOST`, `PGUSER`,
`PGPASSWORD`, `PGDATABASE` and `PGPORT`.
```typescript
import {
Document,
VectorStoreIndex,
PostgresDocumentStore,
PostgresIndexStore,
storageContextFromDefaults,
} from "llamaindex";
const storageContext = await storageContextFromDefaults({
docStore: new PostgresDocumentStore(),
indexStore: new PostgresIndexStore(),
});
const document = new Document({ text: "Test Text" });
const index = await VectorStoreIndex.fromDocuments([document], {
storageContext,
});
```
## API Reference
- [StorageContext](../../api/interfaces/StorageContext.md)
@@ -0,0 +1,2 @@
label: "Index Stores"
position: 3
@@ -0,0 +1,14 @@
# Index Stores
Index stores are underlying storage components that contain metadata(i.e. information created when indexing) about the [index](../../data_index.md) itself.
## Available Index Stores
- [SimpleIndexStore](../../../api/classes/SimpleIndexStore.md): A simple in-memory index store with support for [persisting](../index.md#local-storage) data to disk.
- [PostgresIndexStore](../../../api/classes/PostgresIndexStore.md): A PostgreSQL index store, , see [PostgreSQL Storage](../index.md#postgresql-storage).
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
## API Reference
- [BaseIndexStore](../../../api/classes/BaseIndexStore.md)
@@ -0,0 +1,2 @@
label: "Key-Value Stores"
position: 4
@@ -0,0 +1,14 @@
# Key-Value Stores
Key-Value Stores represent underlying storage components used in [Document Stores](../doc_stores/index.md) and [Index Stores](../index_stores/index.md)
## Available Key-Value Stores
- [SimpleKVStore](../../../api/classes/SimpleKVStore.md): A simple Key-Value store with support of [persisting](../index.md#local-storage) data to disk.
- [PostgresKVStore](../../../api/classes/PostgresKVStore.md): A PostgreSQL Key-Value store, see [PostgreSQL Storage](../index.md#postgresql-storage).
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
## API Reference
- [BaseKVStore](../../../api/classes/BaseKVStore.md)
@@ -0,0 +1,2 @@
label: "Vector Stores"
position: 1
@@ -0,0 +1,22 @@
# Vector Stores
Vector stores save embedding vectors of your ingested document chunks.
## Available Vector Stores
Available Vector Stores are shown on the sidebar to the left. Additionally the following integrations exist without separate documentation:
- [SimpleVectorStore](../../../api/classes/SimpleVectorStore.md): A simple in-memory vector store with optional [persistance](../index.md#local-storage) to disk.
- [AstraDBVectorStore](../../../api/classes/AstraDBVectorStore.md): A cloud-native, scalable Database-as-a-Service built on Apache Cassandra, see [datastax.com](https://www.datastax.com/products/datastax-astra)
- [ChromaVectorStore](../../../api/classes/ChromaVectorStore.md): An open-source vector database, focused on ease of use and performance, see [trychroma.com](https://www.trychroma.com/)
- [MilvusVectorStore](../../../api/classes/MilvusVectorStore.md): An open-source, high-performance, highly scalable vector database, see [milvus.io](https://milvus.io/)
- [MongoDBAtlasVectorSearch](../../../api/classes/MongoDBAtlasVectorSearch.md): A cloud-based vector search solution for MongoDB, see [mongodb.com](https://www.mongodb.com/products/platform/atlas-vector-search)
- [PGVectorStore](../../../api/classes/PGVectorStore.md): An open-source vector store built on PostgreSQL, see [pgvector Github](https://github.com/pgvector/pgvector)
- [PineconeVectorStore](../../../api/classes/PineconeVectorStore.md): A managed, cloud-native vector database, see [pinecone.io](https://www.pinecone.io/)
- [WeaviateVectorStore](../../../api/classes/WeaviateVectorStore.md): An open-source, ai-native vector database, see [weaviate.io](https://weaviate.io/)
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
## API Reference
- [VectorStoreBase](../../../api/classes/VectorStoreBase.md)
@@ -1,6 +1,4 @@
---
title: Qdrant Vector Store
---
# Qdrant Vector Store
[qdrant.tech](https://qdrant.tech/)
@@ -11,18 +9,11 @@ docker pull qdrant/qdrant
docker run -p 6333:6333 qdrant/qdrant
```
## Installation
```package-install
npm i llamaindex @llamaindex/qdrant
```
## Importing the modules
```ts
import fs from "node:fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
import { QdrantVectorStore } from "@llamaindex/qdrant";
import { Document, VectorStoreIndex, QdrantVectorStore } from "llamaindex";
```
## Load the documents
@@ -44,10 +35,10 @@ const vectorStore = new QdrantVectorStore({
```ts
const document = new Document({ text: essay, id_: path });
const storageContext = await storageContextFromDefaults({ vectorStore });
const index = await VectorStoreIndex.fromDocuments([document], {
storageContext,
});
const index = await VectorStoreIndex.fromDocuments([document], {
vectorStore,
});
```
## Query the index
@@ -67,8 +58,7 @@ console.log(response.toString());
```ts
import fs from "node:fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
import { QdrantVectorStore } from "@llamaindex/qdrant";
import { Document, VectorStoreIndex, QdrantVectorStore } from "llamaindex";
async function main() {
const path = "node_modules/llamaindex/examples/abramov.txt";
@@ -79,16 +69,16 @@ async function main() {
});
const document = new Document({ text: essay, id_: path });
const storageContext = await storageContextFromDefaults({ vectorStore });
const index = await VectorStoreIndex.fromDocuments([document], {
storageContext,
vectorStore,
});
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What did the author do in college?",
}); // Additional filters and params can be passed as options
});
// Output response
console.log(response.toString());
@@ -99,4 +89,4 @@ main().catch(console.error);
## API Reference
- [QdrantVectorStore](/docs/api/classes/QdrantVectorStore)
- [QdrantVectorStore](../../../api/classes/QdrantVectorStore.md)
@@ -0,0 +1,2 @@
label: "Document / Nodes"
position: 0
@@ -0,0 +1,14 @@
# Documents and Nodes
`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.
```typescript
import { Document } from "llamaindex";
document = new Document({ text: "text", metadata: { key: "val" } });
```
## API Reference
- [Document](../../api/classes/Document.md)
- [TextNode](../../api/classes/TextNode.md)
@@ -1,6 +1,4 @@
---
title: Metadata Extraction
---
# Metadata Extraction Usage Pattern
You can use LLMs to automate metadata extraction with our `Metadata Extractor` modules.
@@ -14,8 +12,13 @@ Our metadata extractor modules include the following "feature extractors":
Then you can chain the `Metadata Extractors` with the `IngestionPipeline` to extract metadata from a set of documents.
```ts
import { Document, IngestionPipeline, TitleExtractor, QuestionsAnsweredExtractor } from "llamaindex";
import { OpenAI } from "@llamaindex/openai";
import {
IngestionPipeline,
TitleExtractor,
QuestionsAnsweredExtractor,
Document,
OpenAI,
} from "llamaindex";
async function main() {
const pipeline = new IngestionPipeline({
@@ -43,7 +46,7 @@ main().then(() => console.log("done"));
## API Reference
- [SummaryExtractor](/docs/api/classes/SummaryExtractor)
- [QuestionsAnsweredExtractor](/docs/api/classes/QuestionsAnsweredExtractor)
- [TitleExtractor](/docs/api/classes/TitleExtractor)
- [KeywordExtractor](/docs/api/classes/KeywordExtractor)
- [SummaryExtractor](../../api/classes/SummaryExtractor.md)
- [QuestionsAnsweredExtractor](../../api/classes/QuestionsAnsweredExtractor.md)
- [TitleExtractor](../../api/classes/TitleExtractor.md)
- [KeywordExtractor](../../api/classes/KeywordExtractor.md)
@@ -0,0 +1,2 @@
label: "Embeddings"
position: 6
@@ -0,0 +1 @@
label: "Available Embeddings"
@@ -1,19 +1,15 @@
---
title: DeepInfra
---
# DeepInfra
To use DeepInfra embeddings, you need to import `DeepInfraEmbedding` from llamaindex.
Check out available embedding models [here](https://deepinfra.com/models/embeddings).
## Installation
```package-install
npm i llamaindex @llamaindex/deepinfra
```
```ts
import { Document, Settings, VectorStoreIndex } from "llamaindex";
import { DeepInfraEmbedding } from "@llamaindex/deepinfra";
import {
DeepInfraEmbedding,
Settings,
Document,
VectorStoreIndex,
} from "llamaindex";
// Update Embed Model
Settings.embedModel = new DeepInfraEmbedding();
@@ -35,7 +31,7 @@ By default, DeepInfraEmbedding is using the sentence-transformers/clip-ViT-B-32
For example:
```ts
import { DeepInfraEmbedding } from "@llamaindex/deepinfra";
import { DeepInfraEmbedding } from "llamaindex";
const model = "intfloat/e5-large-v2";
Settings.embedModel = new DeepInfraEmbedding({
@@ -48,8 +44,7 @@ You can also set the `maxRetries` and `timeout` parameters when initializing `De
For example:
```ts
import { Settings } from "llamaindex";
import { DeepInfraEmbedding } from "@llamaindex/deepinfra";
import { DeepInfraEmbedding, Settings } from "llamaindex";
const model = "intfloat/e5-large-v2";
const maxRetries = 5;
@@ -65,7 +60,7 @@ Settings.embedModel = new DeepInfraEmbedding({
Standalone usage:
```ts
import { DeepInfraEmbedding } from "@llamaindex/deepinfra";
import { DeepInfraEmbedding } from "llamaindex";
import { config } from "dotenv";
// For standalone usage, you need to configure DEEPINFRA_API_TOKEN in .env file
config();
@@ -85,4 +80,4 @@ For questions or feedback, please contact us at [feedback@deepinfra.com](mailto:
## API Reference
- [DeepInfraEmbedding](/docs/api/classes/DeepInfraEmbedding)
- [DeepInfraEmbedding](../../../api/classes/DeepInfraEmbedding.md)
@@ -1,18 +1,9 @@
---
title: Gemini
---
# Gemini
To use Gemini embeddings, you need to import `GeminiEmbedding` from `@llamaindex/google`.
## Installation
```package-install
npm i llamaindex @llamaindex/google
```
To use Gemini embeddings, you need to import `GeminiEmbedding` from `llamaindex`.
```ts
import { Document, Settings, VectorStoreIndex } from "llamaindex";
import { GeminiEmbedding, GEMINI_MODEL } from "@llamaindex/google";
import { GeminiEmbedding, Settings } from "llamaindex";
// Update Embed Model
Settings.embedModel = new GeminiEmbedding();
@@ -34,7 +25,7 @@ Per default, `GeminiEmbedding` is using the `gemini-pro` model. You can change t
For example:
```ts
import { GEMINI_MODEL, GeminiEmbedding } from "@llamaindex/google";
import { GEMINI_MODEL, GeminiEmbedding } from "llamaindex";
Settings.embedModel = new GeminiEmbedding({
model: GEMINI_MODEL.GEMINI_PRO_LATEST,
@@ -43,4 +34,4 @@ Settings.embedModel = new GeminiEmbedding({
## API Reference
- [GeminiEmbedding](/docs/api/classes/GeminiEmbedding)
- [GeminiEmbedding](../../../api/classes/GeminiEmbedding.md)
@@ -1,18 +1,9 @@
---
title: HuggingFace
---
# HuggingFace
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `@llamaindex/huggingface`.
## Installation
```package-install
npm i llamaindex @llamaindex/huggingface
```
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
```ts
import { Document, Settings, VectorStoreIndex } from "llamaindex";
import { HuggingFaceEmbedding } from "@llamaindex/huggingface";
import { HuggingFaceEmbedding, Settings } from "llamaindex";
// Update Embed Model
Settings.embedModel = new HuggingFaceEmbedding();
@@ -36,8 +27,6 @@ If you're not using a quantized model, set the `quantized` parameter to `false`.
For example, to use the not quantized `BAAI/bge-small-en-v1.5` model, you can use the following code:
```ts
import { HuggingFaceEmbedding } from "@llamaindex/huggingface";
Settings.embedModel = new HuggingFaceEmbedding({
modelType: "BAAI/bge-small-en-v1.5",
quantized: false,
@@ -46,4 +35,4 @@ Settings.embedModel = new HuggingFaceEmbedding({
## API Reference
- [HuggingFaceEmbedding](/docs/api/classes/HuggingFaceEmbedding)
- [HuggingFaceEmbedding](../../../api/classes/HuggingFaceEmbedding.md)
@@ -1,12 +1,9 @@
---
title: Jina AI
---
# Jina AI
To use Jina AI embeddings, you need to import `JinaAIEmbedding` from `@llamaindex/jinaai`.
To use Jina AI embeddings, you need to import `JinaAIEmbedding` from `llamaindex`.
```ts
import { Settings } from "llamaindex";
import { JinaAIEmbedding } from "@llamaindex/jinaai";
import { JinaAIEmbedding, Settings } from "llamaindex";
Settings.embedModel = new JinaAIEmbedding();
@@ -25,4 +22,4 @@ const results = await queryEngine.query({
## API Reference
- [JinaAIEmbedding](/docs/api/classes/JinaAIEmbedding)
- [JinaAIEmbedding](../../../api/classes/JinaAIEmbedding.md)
@@ -1,18 +1,9 @@
---
title: MistralAI
---
# MistralAI
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `@llamaindex/mistral`.
## Installation
```package-install
npm i llamaindex @llamaindex/mistral
```
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
```ts
import { Document, Settings, VectorStoreIndex } from "llamaindex";
import { MistralAIEmbedding } from "@llamaindex/mistral";
import { MistralAIEmbedding, Settings } from "llamaindex";
// Update Embed Model
Settings.embedModel = new MistralAIEmbedding({
@@ -34,4 +25,4 @@ const results = await queryEngine.query({
## API Reference
- [MistralAIEmbedding](/docs/api/classes/MistralAIEmbedding)
- [MistralAIEmbedding](../../../api/classes/MistralAIEmbedding.md)
@@ -1,6 +1,4 @@
---
title: MixedbreadAI
---
# MixedbreadAI
Welcome to the mixedbread embeddings guide! This guide will help you use the mixedbread ai's API to generate embeddings for your text documents, ensuring you get the most relevant information, just like picking the freshest bread from the bakery.
@@ -14,15 +12,16 @@ To find out more about the latest features, updates, and available models, visit
## Setup
```package-install
npm i llamaindex @llamaindex/mixedbread
First, you will need to install the `llamaindex` package.
```bash
pnpm install llamaindex
```
Next, sign up for an API key at [mixedbread.ai](https://mixedbread.ai/). Once you have your API key, you can import the necessary modules and create a new instance of the `MixedbreadAIEmbeddings` class.
```ts
import { MixedbreadAIEmbeddings } from "@llamaindex/mixedbread";
import { Document, Settings } from "llamaindex";
import { MixedbreadAIEmbeddings, Document, Settings } from "llamaindex";
```
## Usage with LlamaIndex
@@ -102,4 +101,4 @@ console.log(result); // Perfectly customized embeddings, ready to serve.
## API Reference
- [MixedbreadAIEmbeddings](/docs/api/classes/MixedbreadAIEmbeddings)
- [MixedbreadAIEmbeddings](../../../api/classes/MixedbreadAIEmbeddings.md)
@@ -1,8 +1,6 @@
---
title: Ollama
---
# Ollama
To use Ollama embeddings, you need to import `OllamaEmbedding` from `@llamaindex/ollama`.
To use Ollama embeddings, you need to import `OllamaEmbedding` from `llamaindex`.
Note that you need to pull the embedding model first before using it.
@@ -12,15 +10,8 @@ In the example below, we're using the [`nomic-embed-text`](https://ollama.com/li
ollama pull nomic-embed-text
```
## Installation
```package-install
npm i llamaindex @llamaindex/ollama
```
```ts
import { OllamaEmbedding } from "@llamaindex/ollama";
import { Document, Settings, VectorStoreIndex } from "llamaindex";
import { OllamaEmbedding, Settings } from "llamaindex";
Settings.embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
@@ -39,4 +30,4 @@ const results = await queryEngine.query({
## API Reference
- [OllamaEmbedding](/docs/api/classes/OllamaEmbedding)
- [OllamaEmbedding](../../../api/classes/OllamaEmbedding.md)
@@ -1,18 +1,9 @@
---
title: OpenAI
---
# OpenAI
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `@llamaindex/openai`.
## Installation
```package-install
npm i llamaindex @llamaindex/openai
```
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
```ts
import { OpenAIEmbedding } from "@llamaindex/openai";
import { Document, Settings, VectorStoreIndex } from "llamaindex";
import { OpenAIEmbedding, Settings } from "llamaindex";
Settings.embedModel = new OpenAIEmbedding();
@@ -31,4 +22,4 @@ const results = await queryEngine.query({
## API Reference
- [OpenAIEmbedding](/docs/api/classes/OpenAIEmbedding)
- [OpenAIEmbedding](../../../api/classes/OpenAIEmbedding.md)
@@ -1,12 +1,9 @@
---
title: Together
---
# Together
To use together embeddings, you need to import `TogetherEmbedding` from `@llamaindex/together`.
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
```ts
import { Settings } from "llamaindex";
import { TogetherEmbedding } from "@llamaindex/together";
import { TogetherEmbedding, Settings } from "llamaindex";
Settings.embedModel = new TogetherEmbedding({
apiKey: "<YOUR_API_KEY>",
@@ -27,4 +24,4 @@ const results = await queryEngine.query({
## API Reference
- [TogetherEmbedding](/docs/api/classes/TogetherEmbedding)
- [TogetherEmbedding](../../../api/classes/TogetherEmbedding.md)
@@ -0,0 +1,31 @@
# Embedding
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 updated through `Settings`
```typescript
import { OpenAIEmbedding, Settings } from "llamaindex";
Settings.embedModel = new OpenAIEmbedding({
model: "text-embedding-ada-002",
});
```
## Local Embedding
For local embeddings, you can use the [HuggingFace](./available_embeddings/huggingface.md) embedding model.
## Available Embeddings
Most available embeddings are listed in the sidebar on the left.
Additionally the following integrations exist without separate documentation:
- [ClipEmbedding](../../api/classes/ClipEmbedding.md) using `@xenova/transformers`
- [FireworksEmbedding](../../api/classes/FireworksEmbedding.md) see [fireworks.ai](https://fireworks.ai/)
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
## API Reference
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
@@ -0,0 +1,2 @@
label: "Evaluating"
position: 9
@@ -1,6 +1,4 @@
---
title: Evaluating
---
# Evaluating
## Concept
@@ -29,6 +27,6 @@ These evaluation modules are in the following forms:
## Usage
- [Correctness Evaluator](/docs/llamaindex/modules/evaluation/correctness)
- [Faithfulness Evaluator](/docs/llamaindex/modules/evaluation/faithfulness)
- [Relevancy Evaluator](/docs/llamaindex/modules/evaluation/relevancy)
- [Correctness Evaluator](./modules/correctness.md)
- [Faithfulness Evaluator](./modules/faithfulness.md)
- [Relevancy Evaluator](./modules/relevancy.md)
@@ -0,0 +1 @@
label: "Modules"

Some files were not shown because too many files have changed in this diff Show More