mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-04 03:40:26 -04:00
Compare commits
133 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 469e438741 | |||
| 56fabbb4f5 | |||
| dfd8cc1ba4 | |||
| cba54061a2 | |||
| ed467a9889 | |||
| 3c4791007f | |||
| 8f16a179c3 | |||
| ce3a4cac6c | |||
| be46044b98 | |||
| 154c7f8e36 | |||
| 8b6c2b45a6 | |||
| b1a4a74270 | |||
| d7fb095fbd | |||
| 58791d4bdd | |||
| d3b635b193 | |||
| 436bc41f82 | |||
| 834f49275a | |||
| a44e54f9ec | |||
| a51ed8dd70 | |||
| c8cfc6c06d | |||
| 83b2f0b0af | |||
| 1a6abb38bc | |||
| 6bc5bddb59 | |||
| e6d6576b2f | |||
| bf25ff6104 | |||
| 32ad0992cf | |||
| af650343d9 | |||
| f6f4ca44bd | |||
| 9aa918f026 | |||
| 00a92cd125 | |||
| 73819bf19d | |||
| d10cca28fc | |||
| 1378ec4e50 | |||
| 24a9d1e816 | |||
| b100684bad | |||
| c375cd5c6b | |||
| 45952dee59 | |||
| 6db7f23ec7 | |||
| 0721a84900 | |||
| 4d4bd85448 | |||
| 11ae9267ae | |||
| 174cb3e6da | |||
| 5ab5e5191d | |||
| 54230f0477 | |||
| 3d484da1c5 | |||
| 631f0001ef | |||
| 060b700e09 | |||
| 83c24f4d50 | |||
| 883266939e | |||
| a29d8351c8 | |||
| da1f025229 | |||
| 6b1ded41a9 | |||
| e01cc053e3 | |||
| 6e156edb11 | |||
| 0b519958e9 | |||
| 265976df12 | |||
| 7e1b96a2db | |||
| 8e26f753b7 | |||
| 31e3251435 | |||
| 058c275a72 | |||
| 6ff7576eb9 | |||
| 94543decad | |||
| b963782137 | |||
| 52c47cada3 | |||
| 9216312b11 | |||
| 660a2b3495 | |||
| 6d21092805 | |||
| fb2c1fa917 | |||
| 37525df529 | |||
| a1f24753d9 | |||
| aa0f586330 | |||
| ff03139799 | |||
| 1b1081b9c9 | |||
| 047ae07e74 | |||
| d8aa29a115 | |||
| 34fb1d8992 | |||
| c517f35526 | |||
| e072c45393 | |||
| 51241865f8 | |||
| 10c83485d2 | |||
| 1e6a18ad2d | |||
| 9e133ac10d | |||
| ba217eec2c | |||
| 64ef70b735 | |||
| 6615aaa4ab | |||
| 447105a6dc | |||
| 320be3fab6 | |||
| bbd9f85a45 | |||
| 5f29ba5e2c | |||
| 4aba02eb82 | |||
| 75736ad01b | |||
| 68a508fcd0 | |||
| 6281fc8c91 | |||
| c3747d092a | |||
| 24a39aefb8 | |||
| 0b1299036d | |||
| 2c8d7941f0 | |||
| a1a72ab223 | |||
| b99ab056d1 | |||
| 1a45b44307 | |||
| 804c57519f | |||
| ce94780b95 | |||
| 645fcf6c24 | |||
| e37fa5d9ca | |||
| 97e4ecd5b8 | |||
| b6a660651b | |||
| 456d3fb0b3 | |||
| efa326a871 | |||
| 5765b637ce | |||
| 72687b4f69 | |||
| 0c67e1f8f3 | |||
| 4a0619758a | |||
| bc7a11cdbe | |||
| 5596e31947 | |||
| 2fe2b813ba | |||
| be5df5b01b | |||
| e74fe88342 | |||
| f1862ccab1 | |||
| 9e74a4327f | |||
| 5e61934d5a | |||
| 2008efe0ee | |||
| ee719a1fda | |||
| 1dce275a7c | |||
| d10533ef77 | |||
| 8aeb8ae690 | |||
| e8c41c5c27 | |||
| 051b4ddfa2 | |||
| 61103b677b | |||
| e69cac672a | |||
| 94246a3ca8 | |||
| b440a008e5 | |||
| 46227f2a70 | |||
| 77f0298f6f |
+4
-1
@@ -1,3 +1,5 @@
|
||||
const { join } = require("node:path");
|
||||
|
||||
module.exports = {
|
||||
root: true,
|
||||
extends: [
|
||||
@@ -6,7 +8,7 @@ module.exports = {
|
||||
"plugin:@typescript-eslint/recommended-type-checked-only",
|
||||
],
|
||||
parserOptions: {
|
||||
project: true,
|
||||
project: join(__dirname, "tsconfig.eslint.json"),
|
||||
__tsconfigRootDir: __dirname,
|
||||
},
|
||||
settings: {
|
||||
@@ -23,6 +25,7 @@ module.exports = {
|
||||
ignoreIIFE: true,
|
||||
},
|
||||
],
|
||||
"no-debugger": "error",
|
||||
"@typescript-eslint/await-thenable": "off",
|
||||
"@typescript-eslint/ban-ts-comment": "off",
|
||||
"@typescript-eslint/ban-types": "off",
|
||||
|
||||
@@ -31,6 +31,6 @@ jobs:
|
||||
|
||||
- name: Publish @llamaindex/core
|
||||
run: npx jsr publish --allow-slow-types
|
||||
working-directory: packages/core
|
||||
working-directory: packages/llamaindex
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -26,12 +26,12 @@ jobs:
|
||||
- name: Build tarball
|
||||
run: |
|
||||
pnpm pack
|
||||
working-directory: packages/core
|
||||
working-directory: packages/llamaindex
|
||||
|
||||
- name: Create release
|
||||
uses: ncipollo/release-action@v1
|
||||
with:
|
||||
artifacts: "packages/core/llamaindex-*.tgz"
|
||||
artifacts: "packages/llamaindex/llamaindex-*.tgz"
|
||||
name: Release ${{ github.ref }}
|
||||
bodyFile: "packages/core/CHANGELOG.md"
|
||||
bodyFile: "packages/llamaindex/CHANGELOG.md"
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
+12
-12
@@ -69,31 +69,31 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter llamaindex
|
||||
run: pnpm run build
|
||||
- name: Use Build For Examples
|
||||
run: pnpm link ../packages/core/
|
||||
run: 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
|
||||
working-directory: ./packages/core
|
||||
run: pnpm dlx turbo run circular-check
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: failure()
|
||||
with:
|
||||
name: typecheck-build-dist
|
||||
path: ./packages/core/dist
|
||||
path: ./packages/llamaindex/dist
|
||||
if-no-files-found: error
|
||||
e2e-core-examples:
|
||||
e2e-llamaindex-examples:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
packages:
|
||||
- cloudflare-worker-agent
|
||||
- nextjs-agent
|
||||
- nextjs-edge-runtime
|
||||
- waku-query-engine
|
||||
# - waku-query-engine
|
||||
runs-on: ubuntu-latest
|
||||
name: Build Core Example (${{ matrix.packages }})
|
||||
name: Build LlamaIndex Example (${{ matrix.packages }})
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: pnpm/action-setup@v3
|
||||
@@ -105,10 +105,10 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build llamaindex
|
||||
run: pnpm run build --filter llamaindex
|
||||
run: pnpm run build
|
||||
- name: Build ${{ matrix.packages }}
|
||||
run: pnpm run build
|
||||
working-directory: packages/core/e2e/examples/${{ matrix.packages }}
|
||||
working-directory: packages/llamaindex/e2e/examples/${{ matrix.packages }}
|
||||
|
||||
typecheck-examples:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -124,7 +124,7 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
- name: Build
|
||||
run: pnpm run build --filter llamaindex
|
||||
run: pnpm run build
|
||||
- name: Copy examples
|
||||
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
|
||||
- name: Pack @llamaindex/env
|
||||
@@ -132,7 +132,7 @@ jobs:
|
||||
working-directory: packages/env
|
||||
- name: Pack llamaindex
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/core
|
||||
working-directory: packages/llamaindex
|
||||
- name: Install
|
||||
run: npm add ${{ runner.temp }}/*.tgz
|
||||
working-directory: ${{ runner.temp }}/examples
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
pnpm format:write
|
||||
pnpm format
|
||||
pnpm lint
|
||||
npx lint-staged
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@ To run them, run
|
||||
pnpm run test
|
||||
```
|
||||
|
||||
To write new test cases write them in [packages/core/src/tests](/packages/core/src/tests)
|
||||
To write new test cases write them in [packages/core/src/tests](/packages/llamaindex/src/tests)
|
||||
|
||||
We use Jest https://jestjs.io/ to write our test cases. Jest comes with a bunch of built in assertions using the expect function: https://jestjs.io/docs/expect
|
||||
|
||||
|
||||
@@ -78,6 +78,17 @@ node --import tsx ./main.ts
|
||||
|
||||
### Next.js
|
||||
|
||||
First, you will need to add a llamaindex plugin to your Next.js project.
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
const withLlamaIndex = require("llamaindex/next");
|
||||
|
||||
module.exports = withLlamaIndex({
|
||||
// your next.js config
|
||||
});
|
||||
```
|
||||
|
||||
You can combine `ai` with `llamaindex` in Next.js with RSC (React Server Components).
|
||||
|
||||
```tsx
|
||||
@@ -183,19 +194,19 @@ Check out our NextJS playground at https://llama-playground.vercel.app/. The sou
|
||||
|
||||
## Core concepts for getting started:
|
||||
|
||||
- [Document](/packages/core/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
- [Document](/packages/llamaindex/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
|
||||
- [Node](/packages/core/src/Node.ts): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
|
||||
- [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/core/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 quesiton. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/core/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/core/src/embeddings)).
|
||||
- [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 quesiton. 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/core/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
|
||||
- [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/core/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/core/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/core/src/engines/query).
|
||||
- [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/core/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/core/src/engines/chat).
|
||||
- [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/core/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
|
||||
- [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.
|
||||
|
||||
## Tips when using in non-Node.js environments
|
||||
|
||||
|
||||
@@ -1,5 +1,178 @@
|
||||
# docs
|
||||
|
||||
## 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
|
||||
|
||||
@@ -72,12 +72,8 @@ export class MyAgent extends AgentRunner<MyLLM> {
|
||||
// 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) => {
|
||||
const { input } = step;
|
||||
static taskHandler: TaskHandler<Anthropic> = async (step, enqueueOutput) => {
|
||||
const { llm, stream } = step.context;
|
||||
if (input) {
|
||||
step.context.store.messages = [...step.context.store.messages, input];
|
||||
}
|
||||
// initialize the input
|
||||
const response = await llm.chat({
|
||||
stream,
|
||||
@@ -90,27 +86,21 @@ export class MyAgent extends AgentRunner<MyLLM> {
|
||||
];
|
||||
// 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: "INSERT MY NEW DATA",
|
||||
content,
|
||||
role: "user",
|
||||
},
|
||||
];
|
||||
return {
|
||||
taskStep: step,
|
||||
output: response,
|
||||
isLast: false,
|
||||
};
|
||||
} else {
|
||||
// if you want to end the task, you can return the response with `isLast: true`
|
||||
return {
|
||||
taskStep: step,
|
||||
output: response,
|
||||
isLast: true,
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -263,6 +253,9 @@ const sumNumbers = FunctionTool.from<Input>(
|
||||
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:
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: Examples
|
||||
position: 2
|
||||
position: 3
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# Local LLMs
|
||||
|
||||
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
|
||||
|
||||
The easiest way to run a local LLM 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 Mixtral 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
|
||||
|
||||
To tell LlamaIndex to use a local LLM, use the `Settings` object:
|
||||
|
||||
```javascript
|
||||
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 like this:
|
||||
|
||||
```javascript
|
||||
Settings.embedModel = new HuggingFaceEmbedding({
|
||||
modelType: "BAAI/bge-small-en-v1.5",
|
||||
quantized: false,
|
||||
});
|
||||
```
|
||||
|
||||
The first time this runs it will download the embedding model to run it.
|
||||
|
||||
### Try it out
|
||||
|
||||
With a local LLM and local embeddings in place, you can perform RAG as usual and everything will happen on your machine without calling an API:
|
||||
|
||||
```typescript
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await fs.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]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
|
||||
You can see the [full example file](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/vectorIndexLocal.ts).
|
||||
@@ -1,7 +1,23 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# More examples
|
||||
# See all examples
|
||||
|
||||
You can check out more examples in the [examples](https://github.com/run-llama/LlamaIndexTS/tree/main/examples) folder of the repository.
|
||||
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.
|
||||
|
||||
## 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 install
|
||||
```
|
||||
|
||||
Then you can run any example in the folder with `tsx`, e.g.:
|
||||
|
||||
```bash npm2yarn
|
||||
npx tsx ./vectorIndex.ts
|
||||
```
|
||||
|
||||
@@ -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>
|
||||
@@ -4,7 +4,7 @@ sidebar_position: 2
|
||||
|
||||
# Environments
|
||||
|
||||
LlamaIndex currently officially supports NodeJS 18 and NodeJS 20.
|
||||
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
|
||||
|
||||
## NextJS App Router
|
||||
|
||||
|
||||
@@ -4,45 +4,7 @@ sidebar_position: 0
|
||||
|
||||
# Installation and Setup
|
||||
|
||||
Make sure you have NodeJS v18 or higher.
|
||||
|
||||
## Using create-llama
|
||||
|
||||
The easiest way to get started with LlamaIndex is by using `create-llama`. This CLI tool enables you to quickly start building a new LlamaIndex application, with everything set up for you.
|
||||
|
||||
Just run
|
||||
|
||||
<Tabs>
|
||||
<TabItem value="1" label="npm" default>
|
||||
|
||||
```bash
|
||||
npx create-llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="2" label="Yarn">
|
||||
|
||||
```bash
|
||||
yarn create llama
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
<TabItem value="3" label="pnpm">
|
||||
|
||||
```bash
|
||||
pnpm create llama@latest
|
||||
```
|
||||
|
||||
</TabItem>
|
||||
</Tabs>
|
||||
|
||||
to get started. Once your app is generated, run
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app
|
||||
We support Node.JS versions 18, 20 and 22, with experimental support for Deno, Bun and Vercel Edge functions.
|
||||
|
||||
## Installation from NPM
|
||||
|
||||
@@ -52,12 +14,21 @@ npm install llamaindex
|
||||
|
||||
### Environment variables
|
||||
|
||||
Our examples use OpenAI by default. You'll need to set up your Open AI key like so:
|
||||
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 from https://platform.openai.com/account/api-keys
|
||||
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.
|
||||
**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
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
|
||||
import TSConfigSource from "!!raw-loader!../../../../examples/tsconfig.json";
|
||||
|
||||
# Starter Tutorial
|
||||
|
||||
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
|
||||
|
||||
## From scratch(node.js + TypeScript):
|
||||
|
||||
In a new folder:
|
||||
|
||||
```bash npm2yarn
|
||||
npm init
|
||||
npm install -D typescript @types/node
|
||||
```
|
||||
|
||||
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Create a `tsconfig.json` file in the same folder:
|
||||
|
||||
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
|
||||
|
||||
Now you can run the code with
|
||||
|
||||
```bash
|
||||
npx tsx example.ts
|
||||
```
|
||||
|
||||
Also, you can clone our examples and try them out:
|
||||
|
||||
```bash npm2yarn
|
||||
npx degit run-llama/LlamaIndexTS/examples my-new-project
|
||||
cd my-new-project
|
||||
npm install
|
||||
npx tsx ./vectorIndex.ts
|
||||
```
|
||||
|
||||
## From scratch (Next.js + TypeScript):
|
||||
|
||||
You just need one command to create a new Next.js project:
|
||||
|
||||
```bash npm2yarn
|
||||
npx create-llama@latest
|
||||
```
|
||||
@@ -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
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
---
|
||||
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:
|
||||
|
||||
```bash npm2yarn
|
||||
npx create-llama@latest
|
||||
```
|
||||
|
||||
Once your app is generated, `cd` into your app directory and run
|
||||
|
||||
```bash npm2yarn
|
||||
npm run dev
|
||||
```
|
||||
|
||||
to start the development server. You can then visit [http://localhost:3000](http://localhost:3000) to see your app, which should look something like this:
|
||||
|
||||

|
||||
Binary file not shown.
|
After Width: | Height: | Size: 540 KiB |
@@ -0,0 +1,58 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
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:
|
||||
|
||||
```bash npm2yarn
|
||||
npm init
|
||||
npm install -D typescript @types/node
|
||||
```
|
||||
|
||||
Then, check out the [installation](../installation) steps to install LlamaIndex.TS and prepare an OpenAI key.
|
||||
|
||||
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
|
||||
|
||||
Create the file `example.ts`. This code will
|
||||
|
||||
- load an example file
|
||||
- convert it into a Document object
|
||||
- index it (which creates embeddings using OpenAI)
|
||||
- create a query engine to answer questions about the data
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Create a `tsconfig.json` file in the same folder:
|
||||
|
||||
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
|
||||
|
||||
Now you can run the code with
|
||||
|
||||
```bash
|
||||
npx tsx example.ts
|
||||
```
|
||||
|
||||
You should expect output something like:
|
||||
|
||||
```
|
||||
In college, the author studied subjects like linear algebra and physics, but did not find them particularly interesting. They started slacking off, skipping lectures, and eventually stopped attending classes altogether. They also had a negative experience with their English classes, where they were required to pay for catch-up training despite getting verbal approval to skip most of the classes. Ultimately, the author lost motivation for college due to their job as a software developer and stopped attending classes, only returning years later to pick up their papers.
|
||||
|
||||
0: Score: 0.8305309270895813 - I started this decade as a first-year college stud...
|
||||
|
||||
|
||||
1: Score: 0.8286388215713089 - A short digression. I’m not saying colleges are wo...
|
||||
```
|
||||
|
||||
Once you've mastered basic RAG, you may want to consider [chatting with your data](chatbot).
|
||||
@@ -0,0 +1,52 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../../examples/jsonExtract";
|
||||
|
||||
# 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:
|
||||
|
||||
```bash npm2yarn
|
||||
npm init
|
||||
npm install -D typescript @types/node
|
||||
```
|
||||
|
||||
## Extract data
|
||||
|
||||
Create the file `example.ts`. This code will:
|
||||
|
||||
- Set up an LLM connection to GPT-4
|
||||
- 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:
|
||||
|
||||
```json
|
||||
{
|
||||
"summary": "Sarah from XYZ Company called John to introduce the XYZ Widget, a tool designed to automate tasks and improve productivity. John expressed interest and requested case studies and a product demo. Sarah agreed to send the information and follow up to schedule the demo.",
|
||||
"products": ["XYZ Widget"],
|
||||
"rep_name": "Sarah",
|
||||
"prospect_name": "John",
|
||||
"action_items": [
|
||||
"Send case studies and additional product information to John",
|
||||
"Follow up with John to schedule a product demo"
|
||||
]
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: Guides
|
||||
position: 2
|
||||
@@ -0,0 +1,41 @@
|
||||
---
|
||||
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.
|
||||
|
||||

|
||||
|
||||
## 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
|
||||
|
||||
```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](local_model).
|
||||
|
||||
## Get an OpenAI API key
|
||||
|
||||
If you don't already have one, you can sign up for an [OpenAI API key](https://platform.openai.com/api-keys). You should then put the key in a `.env` file in the root of the project; the file should look like
|
||||
|
||||
```
|
||||
OPENAI_API_KEY=sk-XXXXXXXXXXXXXXXXXXXXXXXX
|
||||
```
|
||||
|
||||
We'll use `dotenv` to pull the API key out of that .env file, so also run:
|
||||
|
||||
```bash
|
||||
npm install dotenv
|
||||
```
|
||||
|
||||
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.payload);
|
||||
});
|
||||
Settings.callbackManager.on("llm-tool-result", (event) => {
|
||||
console.log(event.detail.payload);
|
||||
});
|
||||
```
|
||||
|
||||
### Create a function
|
||||
|
||||
We're going to create a very simple function that adds two numbers together. This will be the tool we ask our agent to use.
|
||||
|
||||
```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).
|
||||
@@ -0,0 +1,165 @@
|
||||
# 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.
|
||||
|
||||
To learn more about RAG, we recommend this [introduction](https://docs.llamaindex.ai/en/stable/getting_started/concepts/) from our Python docs. We'll assume you know the basics:
|
||||
|
||||
- You need to parse your source data into chunks of text
|
||||
- You need to encode that text as numbers, called embeddings
|
||||
- You need to search your embeddings for the most relevant chunks of text
|
||||
- You feed your relevant chunks and a query to an LLM to answer a question
|
||||
|
||||
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).
|
||||
|
||||
### New dependencies
|
||||
|
||||
We'll be bringing in `SimpleDirectoryReader`, `HuggingFaceEmbedding`, `VectorStoreIndex`, and `QueryEngineTool` from LlamaIndex.TS, as well as the dependencies we previously used.
|
||||
|
||||
```javascript
|
||||
import {
|
||||
OpenAI,
|
||||
FunctionTool,
|
||||
OpenAIAgent,
|
||||
Settings,
|
||||
SimpleDirectoryReader,
|
||||
HuggingFaceEmbedding,
|
||||
VectorStoreIndex,
|
||||
QueryEngineTool,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
### Add an embedding model
|
||||
|
||||
To encode our text into embeddings, we'll need an embedding model. We could use OpenAI for this but to save on API calls we're going to use a local embedding model from HuggingFace.
|
||||
|
||||
```javascript
|
||||
Settings.embedModel = new HuggingFaceEmbedding({
|
||||
modelType: "BAAI/bge-small-en-v1.5",
|
||||
quantized: false,
|
||||
});
|
||||
```
|
||||
|
||||
### Load data using SimpleDirectoryReader
|
||||
|
||||
SimpleDirectoryReader is a flexible tool that can read a variety of file formats. We're going to point it at our data directory, which contains just the single PDF file, and get it to return a set of documents.
|
||||
|
||||
```javascript
|
||||
const reader = new SimpleDirectoryReader();
|
||||
const documents = await reader.loadData("../data");
|
||||
```
|
||||
|
||||
### Index our data
|
||||
|
||||
Now we turn our text into embeddings. The `VectorStoreIndex` class takes care of this for us when we use the `fromDocuments` method (it uses the embedding model we defined in `Settings` earlier).
|
||||
|
||||
```javascript
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
```
|
||||
|
||||
### Configure a retriever
|
||||
|
||||
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;
|
||||
```
|
||||
|
||||
### Create a query engine
|
||||
|
||||
And our final step in creating a RAG pipeline is to create a query engine that will use the retriever to find the most relevant chunks of text, and then use the LLM to answer the question.
|
||||
|
||||
```javascript
|
||||
const queryEngine = await index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
```
|
||||
|
||||
### Define the query engine as a tool
|
||||
|
||||
Just as before we created a `FunctionTool`, we're going to create a `QueryEngineTool` that uses our `queryEngine`.
|
||||
|
||||
```javascript
|
||||
const tools = [
|
||||
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.`,
|
||||
},
|
||||
}),
|
||||
];
|
||||
```
|
||||
|
||||
As before, we've created an array of tools with just one tool in it. The metadata is slightly different: we don't need to define our parameters, we just give the tool a name and a natural-language description.
|
||||
|
||||
### Create the agent as before
|
||||
|
||||
Creating the agent and asking a question is exactly the same as before, but we'll ask a different question.
|
||||
|
||||
```javascript
|
||||
// create the agent
|
||||
const agent = new OpenAIAgent({ tools });
|
||||
|
||||
let response = await agent.chat({
|
||||
message: "What's the budget of San Francisco in 2023-2024?",
|
||||
});
|
||||
|
||||
console.log(response);
|
||||
```
|
||||
|
||||
Once again we'll run `npx tsx agent.ts` and see what we get:
|
||||
|
||||
**_Output_**
|
||||
|
||||
```javascript
|
||||
{
|
||||
toolCall: {
|
||||
id: 'call_iNo6rTK4pOpOBbO8FanfWLI9',
|
||||
name: 'san_francisco_budget_tool',
|
||||
input: { query: 'total budget' }
|
||||
},
|
||||
toolResult: {
|
||||
tool: QueryEngineTool {
|
||||
queryEngine: [RetrieverQueryEngine],
|
||||
metadata: [Object]
|
||||
},
|
||||
input: { query: 'total budget' },
|
||||
output: 'The total budget for the City and County of San Francisco for Fiscal Year (FY) 2023-24 is $14.6 billion, which represents a $611.8 million, or 4.4 percent, increase over the FY 2022-23 budget. For FY 2024-25, the total budget is also projected to be $14.6 billion, reflecting a $40.5 million, or 0.3 percent, decrease from the FY 2023-24 proposed budget. This budget includes various expenditures across different departments and services, with significant allocations to public works, transportation, commerce, public protection, and health services.',
|
||||
isError: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```javascript
|
||||
{
|
||||
response: {
|
||||
raw: {
|
||||
id: 'chatcmpl-9KxUkwizVCYCmxwFQcZFSHrInzNFU',
|
||||
object: 'chat.completion',
|
||||
created: 1714782286,
|
||||
model: 'gpt-4-turbo-2024-04-09',
|
||||
choices: [Array],
|
||||
usage: [Object],
|
||||
system_fingerprint: 'fp_ea6eb70039'
|
||||
},
|
||||
message: {
|
||||
content: "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.",
|
||||
role: 'assistant',
|
||||
options: {}
|
||||
}
|
||||
},
|
||||
sources: [Getter]
|
||||
}
|
||||
```
|
||||
|
||||
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](rag_and_tools)!
|
||||
@@ -0,0 +1,128 @@
|
||||
# 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:
|
||||
|
||||
```javascript
|
||||
// define the query engine as a tool
|
||||
const tools = [
|
||||
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.`,
|
||||
},
|
||||
}),
|
||||
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"],
|
||||
},
|
||||
}),
|
||||
];
|
||||
```
|
||||
|
||||
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.chat({
|
||||
message:
|
||||
"What's the budget of San Francisco for community health in 2023-24?",
|
||||
});
|
||||
console.log(response);
|
||||
|
||||
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.chat({
|
||||
message:
|
||||
"What's the combined budget of San Francisco for community health and public protection in 2023-24?",
|
||||
});
|
||||
console.log(response3);
|
||||
```
|
||||
|
||||
We'll abbreviate the output, but here are the important things to spot:
|
||||
|
||||
```javascript
|
||||
{
|
||||
toolCall: {
|
||||
id: 'call_ZA1LPx03gO4ABre1r6XowLWq',
|
||||
name: 'san_francisco_budget_tool',
|
||||
input: { query: 'community health budget 2023-2024' }
|
||||
},
|
||||
toolResult: {
|
||||
tool: QueryEngineTool {
|
||||
queryEngine: [RetrieverQueryEngine],
|
||||
metadata: [Object]
|
||||
},
|
||||
input: { query: 'community health budget 2023-2024' },
|
||||
output: 'The proposed Fiscal Year (FY) 2023-24 budget for the Department of Public Health is $3.2 billion
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This is the first tool call, where it used the query engine to get the public health budget.
|
||||
|
||||
```javascript
|
||||
{
|
||||
toolCall: {
|
||||
id: 'call_oHu1KjEvA47ER6HYVfFIq9yp',
|
||||
name: 'san_francisco_budget_tool',
|
||||
input: { query: 'public protection budget 2023-2024' }
|
||||
},
|
||||
toolResult: {
|
||||
tool: QueryEngineTool {
|
||||
queryEngine: [RetrieverQueryEngine],
|
||||
metadata: [Object]
|
||||
},
|
||||
input: { query: 'public protection budget 2023-2024' },
|
||||
output: "The budget for Public Protection in San Francisco for Fiscal Year (FY) 2023-24 is $2,012.5 million."
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the second tool call, it got the police budget also from the query engine.
|
||||
|
||||
```javascript
|
||||
{
|
||||
toolCall: {
|
||||
id: 'call_SzG4yGUnLbv1T7IyaLAOqg3t',
|
||||
name: 'sumNumbers',
|
||||
input: { a: 3200, b: 2012.5 }
|
||||
},
|
||||
toolResult: {
|
||||
tool: FunctionTool { _fn: [Function: sumNumbers], _metadata: [Object] },
|
||||
input: { a: 3200, b: 2012.5 },
|
||||
output: '5212.5',
|
||||
isError: false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In the final tool call, it used the `sumNumbers` function to add the two budgets together. Perfect! This leads to the final answer:
|
||||
|
||||
```javascript
|
||||
{
|
||||
message: {
|
||||
content: 'The combined budget of San Francisco for community health and public protection in Fiscal Year (FY) 2023-24 is $5,212.5 million.',
|
||||
role: 'assistant',
|
||||
options: {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Great! Now let's improve accuracy by improving our parsing with [LlamaParse](llamaparse).
|
||||
@@ -0,0 +1,18 @@
|
||||
# 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:
|
||||
|
||||
```bash
|
||||
LLAMA_CLOUD_API_KEY=llx-XXXXXXXXXXXXXXXX
|
||||
```
|
||||
|
||||
Then replace `SimpleDirectoryReader` with `LlamaParseReader`:
|
||||
|
||||
```javascript
|
||||
const reader = new LlamaParseReader({ resultType: "markdown" });
|
||||
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](qdrant).
|
||||
@@ -0,0 +1,75 @@
|
||||
# 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.
|
||||
|
||||
We can get a local instance of Qdrant running very simply with Docker (make sure you [install Docker](https://www.docker.com/products/docker-desktop/) first):
|
||||
|
||||
```bash
|
||||
docker pull qdrant/qdrant
|
||||
docker run -p 6333:6333 qdrant/qdrant
|
||||
```
|
||||
|
||||
And in our code we initialize a `VectorStore` with the Qdrant URL:
|
||||
|
||||
```javascript
|
||||
// initialize qdrant vector store
|
||||
const vectorStore = new QdrantVectorStore({
|
||||
url: "http://localhost:6333",
|
||||
});
|
||||
```
|
||||
|
||||
Now once we have loaded our documents, we can instantiate an index with the vector store:
|
||||
|
||||
```javascript
|
||||
// create a query engine from our documents
|
||||
const index = await VectorStoreIndex.fromDocuments(documents, { vectorStore });
|
||||
```
|
||||
|
||||
In [the final iteration](https://github.com/run-llama/ts-agents/blob/main/5_qdrant/agent.ts) you can see that we have also implemented a very naive caching mechanism to avoid re-parsing the PDF each time we run the agent:
|
||||
|
||||
```javascript
|
||||
// load cache.json and parse it
|
||||
let cache = {};
|
||||
let cacheExists = false;
|
||||
try {
|
||||
await fs.access(PARSING_CACHE, fs.constants.F_OK);
|
||||
cacheExists = true;
|
||||
} catch (e) {
|
||||
console.log("No cache found");
|
||||
}
|
||||
if (cacheExists) {
|
||||
cache = JSON.parse(await fs.readFile(PARSING_CACHE, "utf-8"));
|
||||
}
|
||||
|
||||
const filesToParse = ["../data/sf_budget_2023_2024.pdf"];
|
||||
|
||||
// load our data, reading only files we haven't seen before
|
||||
let documents = [];
|
||||
const reader = new LlamaParseReader({ resultType: "markdown" });
|
||||
for (let file of filesToParse) {
|
||||
if (!cache[file]) {
|
||||
documents = documents.concat(await reader.loadData(file));
|
||||
cache[file] = true;
|
||||
}
|
||||
}
|
||||
|
||||
// write the cache back to disk
|
||||
await fs.writeFile(PARSING_CACHE, JSON.stringify(cache));
|
||||
```
|
||||
|
||||
Since parsing a PDF can be slow, especially a large one, using the pre-parsed chunks in Qdrant can significantly speed up your agent.
|
||||
|
||||
## Next steps
|
||||
|
||||
In this guide you've learned how to
|
||||
|
||||
- [Create an agent](create_agent)
|
||||
- Use remote LLMs like GPT-4
|
||||
- [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](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
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 236 KiB |
@@ -3,33 +3,31 @@ sidebar_position: 0
|
||||
slug: /
|
||||
---
|
||||
|
||||
# What is LlamaIndex.TS?
|
||||
# What is LlamaIndex?
|
||||
|
||||
LlamaIndex.TS is a data framework for LLM applications to ingest, structure, and access private or domain-specific data. While a python package is also available (see [here](https://docs.llamaindex.ai/en/stable/)), LlamaIndex.TS offers core features in a simple package, optimized for usage with TypeScript.
|
||||
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?
|
||||
|
||||
At their core, LLMs offer a natural language interface between humans and inferred data. Widely available models come pre-trained on huge amounts of publicly available data, from Wikipedia and mailing lists to textbooks and source code.
|
||||
LLMs offer a natural language interface between humans and inferred data. Widely available models come pre-trained on huge amounts of publicly available data, from Wikipedia and mailing lists to textbooks and source code.
|
||||
|
||||
Applications built on top of LLMs often require augmenting these models with private or domain-specific data. Unfortunately, that data can be distributed across siloed applications and data stores. It's behind APIs, in SQL databases, or trapped in PDFs and slide decks.
|
||||
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.
|
||||
|
||||
That's where **LlamaIndex.TS** comes in.
|
||||
LlamaIndex.TS helps you unlock that data and then build powerful applications with it.
|
||||
|
||||
## 🦙 How can LlamaIndex.TS help?
|
||||
## 🦙 What is LlamaIndex for?
|
||||
|
||||
LlamaIndex.TS provides the following tools:
|
||||
LlamaIndex.TS handles several major use cases:
|
||||
|
||||
- **Data loading** ingest your existing `.txt`, `.pdf`, `.csv`, `.md` and `.docx` data directly
|
||||
- **Data indexes** structure your data in intermediate representations that are easy and performant for LLMs to consume.
|
||||
- **Engines** provide natural language access to your data. For example:
|
||||
- Query engines are powerful retrieval interfaces for knowledge-augmented output.
|
||||
- Chat engines are conversational interfaces for multi-message, "back and forth" interactions with your data.
|
||||
- **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 interative, unsupervised manner.
|
||||
|
||||
## 👨👩👧👦 Who is LlamaIndex for?
|
||||
|
||||
LlamaIndex.TS provides a core set of tools, essential for anyone building LLM apps with JavaScript and TypeScript.
|
||||
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 and query their data.
|
||||
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.
|
||||
|
||||
@@ -37,7 +35,7 @@ For more complex applications, our lower-level APIs allow advanced users to cust
|
||||
|
||||
`npm install llamaindex`
|
||||
|
||||
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.mdx) to build your first application.
|
||||
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.
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ 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";
|
||||
import CodeSource3 from "!raw-loader!../../../../examples/readers/src/llamaparse";
|
||||
import CodeSource4 from "!raw-loader!../../../../examples/readers/src/simple-directory-reader-with-llamaparse.ts";
|
||||
|
||||
# Loader
|
||||
|
||||
@@ -21,11 +22,13 @@ It is a simple reader that reads all files from a directory and its subdirectori
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Currently, it supports reading `.csv`, `.docx`, `.html`, `.md` and `.pdf` files,
|
||||
but support for other file types is planned.
|
||||
Currently, it supports reading `.txt`, `.pdf`, `.csv`, `.md`, `.docx`, `.htm`, `.html`, `.jpg`, `.jpeg`, `.png` and `.gif` files, but support for other file types is planned.
|
||||
|
||||
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions.
|
||||
Or pass new readers for `fileExtToReader` to support more file types.
|
||||
You can override the default reader for all file types, inlcuding unsupported ones, with the `overrideReader` option.
|
||||
Additionally, you can override the default reader for specific file types or add support for additional file types with the `fileExtToReader` option.
|
||||
Also, you can provide a `defaultReader` as a fallback 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.
|
||||
|
||||
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
|
||||
{CodeSource2}
|
||||
@@ -35,14 +38,31 @@ Or pass new readers for `fileExtToReader` to support more file types.
|
||||
|
||||
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
|
||||
|
||||
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key in the environment variable `LLAMA_CLOUD_API_KEY`.
|
||||
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key as `apiKey` parameter or in the environment variable `LLAMA_CLOUD_API_KEY`.
|
||||
|
||||
Then, you can use the `LlamaParseReader` class to read a local PDF file and convert it into a markdown document that can be used by LlamaIndex:
|
||||
Then, you can use the `LlamaParseReader` class to local files and convert them into a parsed document that can be used by LlamaIndex.
|
||||
See [LlamaParseReader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/core/src/readers/LlamaParseReader.ts#L6) for a list of supported file types:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource3}</CodeBlock>
|
||||
|
||||
Alternatively, you can set the [`resultType`](../api/classes/LlamaParseReader.md#resulttype) option to `text` to get the parsed document as a text string.
|
||||
Additional options can be set with the `LlamaParseReader` constructor:
|
||||
|
||||
- `resultType` can be set to `markdown`, `text` or `.json`. Defaults to `text`
|
||||
- `language` primarly helps with OCR recognition. Defaults to `en`. See [../readers/type.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/core/src/readers/type.ts#L20) for a list of supported languages.
|
||||
- `parsingInstructions` 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` set to true to ignore diagonal text.
|
||||
- `invalidateCache` 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`.
|
||||
- `gpt4oMode` set to true to use GPT-4o to extract content.
|
||||
- `gpt4oApiKey` set the GPT-4o API key. Optional. Lowers the cost of parsing by using your own API key. Your OpenAI account will be charged. Can also be set in the environment variable `LLAMA_CLOUD_GPT4O_API_KEY`.
|
||||
- `numWorkers` as in the python version, is set in `SimpleDirectoryReader`. Default is 1.
|
||||
|
||||
## LlamaParse with SimpleDirectoryReader
|
||||
|
||||
Below a full example of `LlamaParse` integrated in `SimpleDirectoryReader` with additional options.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource4}</CodeBlock>
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
|
||||
- [LlamaParseReader](../api/classes/LlamaParseReader.md)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
# DeepInfra
|
||||
|
||||
To use DeepInfra embeddings, you need to import `DeepInfraEmbedding` from llamaindex.
|
||||
Check out available embedding models [here](https://deepinfra.com/models/embeddings).
|
||||
|
||||
```ts
|
||||
import {
|
||||
DeepInfraEmbedding,
|
||||
Settings,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update Embed Model
|
||||
Settings.embedModel = new DeepInfraEmbedding();
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
By default, DeepInfraEmbedding is using the sentence-transformers/clip-ViT-B-32 model. You can change the model by passing the model parameter to the constructor.
|
||||
For example:
|
||||
|
||||
```ts
|
||||
import { DeepInfraEmbedding } from "llamaindex";
|
||||
|
||||
const model = "intfloat/e5-large-v2";
|
||||
Settings.embedModel = new DeepInfraEmbedding({
|
||||
model,
|
||||
});
|
||||
```
|
||||
|
||||
You can also set the `maxRetries` and `timeout` parameters when initializing `DeepInfraEmbedding` for better control over the request behavior.
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
import { DeepInfraEmbedding, Settings } from "llamaindex";
|
||||
|
||||
const model = "intfloat/e5-large-v2";
|
||||
const maxRetries = 5;
|
||||
const timeout = 5000; // 5 seconds
|
||||
|
||||
Settings.embedModel = new DeepInfraEmbedding({
|
||||
model,
|
||||
maxRetries,
|
||||
timeout,
|
||||
});
|
||||
```
|
||||
|
||||
Standalone usage:
|
||||
|
||||
```ts
|
||||
import { DeepInfraEmbedding } from "llamaindex";
|
||||
import { config } from "dotenv";
|
||||
// For standalone usage, you need to configure DEEPINFRA_API_TOKEN in .env file
|
||||
config();
|
||||
|
||||
const main = async () => {
|
||||
const model = "intfloat/e5-large-v2";
|
||||
const embeddings = new DeepInfraEmbedding({ model });
|
||||
const text = "What is the meaning of life?";
|
||||
const response = await embeddings.embed([text]);
|
||||
console.log(response);
|
||||
};
|
||||
|
||||
main();
|
||||
```
|
||||
|
||||
For questions or feedback, please contact us at [feedback@deepinfra.com](mailto:feedback@deepinfra.com)
|
||||
@@ -21,7 +21,7 @@ export OPENAI_API_KEY=your-api-key
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import { CorrectnessEvaluator, OpenAI, Settings } from "llamaindex";
|
||||
import { CorrectnessEvaluator, OpenAI, Settings, Response } from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
@@ -45,7 +45,7 @@ const evaluator = new CorrectnessEvaluator();
|
||||
|
||||
const result = await evaluator.evaluateResponse({
|
||||
query,
|
||||
response,
|
||||
response: new Response(response),
|
||||
});
|
||||
|
||||
console.log(
|
||||
|
||||
@@ -21,7 +21,13 @@ export OPENAI_API_KEY=your-api-key
|
||||
Import the required modules:
|
||||
|
||||
```ts
|
||||
import { RelevancyEvaluator, OpenAI, Settings } from "llamaindex";
|
||||
import {
|
||||
RelevancyEvaluator,
|
||||
OpenAI,
|
||||
Settings,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
Let's setup gpt-4 for better results:
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# Bedrock
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { BEDROCK_MODELS, Bedrock } from "@llamaindex/community";
|
||||
|
||||
Settings.llm = new Bedrock({
|
||||
model: BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_HAIKU,
|
||||
region: "us-east-1", // can be provided via env AWS_REGION
|
||||
credentials: {
|
||||
accessKeyId: "...", // optional and can be provided via env AWS_ACCESS_KEY_ID
|
||||
secretAccessKey: "...", // optional and can be provided via env AWS_SECRET_ACCESS_KEY
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Currently only supports Anthropic models:
|
||||
|
||||
```ts
|
||||
ANTHROPIC_CLAUDE_INSTANT_1 = "anthropic.claude-instant-v1";
|
||||
ANTHROPIC_CLAUDE_2 = "anthropic.claude-v2";
|
||||
ANTHROPIC_CLAUDE_2_1 = "anthropic.claude-v2:1";
|
||||
ANTHROPIC_CLAUDE_3_SONNET = "anthropic.claude-3-sonnet-20240229-v1:0";
|
||||
ANTHROPIC_CLAUDE_3_HAIKU = "anthropic.claude-3-haiku-20240307-v1:0";
|
||||
ANTHROPIC_CLAUDE_3_OPUS = "anthropic.claude-3-opus-20240229-v1:0"; // available on us-west-2
|
||||
ANTHROPIC_CLAUDE_3_5_SONNET = "anthropic.claude-3-5-sonnet-20240620-v1:0";
|
||||
```
|
||||
|
||||
Sonnet, Haiku and Opus are multimodal, image_url only supports base64 data url format, e.g. `data:image/jpeg;base64,SGVsbG8sIFdvcmxkIQ==`
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { BEDROCK_MODELS, Bedrock } from "llamaindex";
|
||||
|
||||
Settings.llm = new Bedrock({
|
||||
model: BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_HAIKU,
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
# DeepInfra
|
||||
|
||||
Check out available LLMs [here](https://deepinfra.com/models/text-generation).
|
||||
|
||||
```ts
|
||||
import { DeepInfra, Settings } from "llamaindex";
|
||||
|
||||
// Get the API key from `DEEPINFRA_API_TOKEN` environment variable
|
||||
import { config } from "dotenv";
|
||||
config();
|
||||
Settings.llm = new DeepInfra();
|
||||
|
||||
// Set the API key
|
||||
apiKey = "YOUR_API_KEY";
|
||||
Settings.llm = new DeepInfra({ apiKey });
|
||||
```
|
||||
|
||||
You can setup the apiKey on the environment variables, like:
|
||||
|
||||
```bash
|
||||
export DEEPINFRA_API_TOKEN="<YOUR_API_KEY>"
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { DeepInfra, Document, VectorStoreIndex, Settings } from "llamaindex";
|
||||
|
||||
// Use custom LLM
|
||||
const model = "meta-llama/Meta-Llama-3-8B-Instruct";
|
||||
Settings.llm = new DeepInfra({ model, temperature: 0 });
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
|
||||
## Feedback
|
||||
|
||||
If you have any feedback, please reach out to us at [feedback@deepinfra.com](mailto:feedback@deepinfra.com)
|
||||
@@ -10,6 +10,36 @@ Settings.llm = new Gemini({
|
||||
});
|
||||
```
|
||||
|
||||
### Usage with Vertex AI
|
||||
|
||||
To use Gemini via Vertex AI you can use `GeminiVertexSession`.
|
||||
|
||||
GeminiVertexSession accepts the env variables: `GOOGLE_VERTEX_LOCATION` and `GOOGLE_VERTEX_PROJECT`
|
||||
|
||||
```ts
|
||||
import { Gemini, GEMINI_MODEL, GeminiVertexSession } from "llamaindex";
|
||||
|
||||
const gemini = new Gemini({
|
||||
model: GEMINI_MODEL.GEMINI_PRO,
|
||||
session: new GeminiVertexSession({
|
||||
location: "us-central1", // optional if provided by GOOGLE_VERTEX_LOCATION env variable
|
||||
project: "project1", // optional if provided by GOOGLE_VERTEX_PROJECT env variable
|
||||
googleAuthOptions: {...}, // optional, but useful for production. It accepts all values from `GoogleAuthOptions`
|
||||
}),
|
||||
});
|
||||
```
|
||||
|
||||
[GoogleAuthOptions](https://github.com/googleapis/google-auth-library-nodejs/blob/main/src/auth/googleauth.ts)
|
||||
|
||||
To authenticate for local development:
|
||||
|
||||
```bash
|
||||
npm install @google-cloud/vertexai
|
||||
gcloud auth application-default login
|
||||
```
|
||||
|
||||
To authenticate for production you'll have to use a [service account](https://cloud.google.com/docs/authentication/). `googleAuthOptions` has `credentials` which might be useful for you.
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, Settings } from "llamaindex";
|
||||
import { MistralAI, Settings } from "llamaindex";
|
||||
|
||||
Settings.llm = new MistralAI({
|
||||
model: "mistral-tiny",
|
||||
|
||||
@@ -167,7 +167,7 @@ const config = {
|
||||
[
|
||||
"docusaurus-plugin-typedoc",
|
||||
{
|
||||
entryPoints: ["../../packages/core/src/index.ts"],
|
||||
entryPoints: ["../../packages/llamaindex/src/index.ts"],
|
||||
tsconfig: "../../tsconfig.json",
|
||||
readme: "none",
|
||||
sourceLinkTemplate:
|
||||
|
||||
+1
-1
@@ -271,7 +271,7 @@ custom_edit_url: null
|
||||
|
||||
### setDocumentHash
|
||||
|
||||
▸ `Abstract` **setDocumentHash**(`docId`, `docHash`): `void`
|
||||
▸ `Abstract` **setDocumentHash**(`docId`, `docHash`): `Promise`<`void`\>
|
||||
|
||||
#### Parameters
|
||||
|
||||
|
||||
+1
-1
@@ -271,7 +271,7 @@ custom_edit_url: null
|
||||
|
||||
### setDocumentHash
|
||||
|
||||
▸ `Abstract` **setDocumentHash**(`docId`, `docHash`): `void`
|
||||
▸ `Abstract` **setDocumentHash**(`docId`, `docHash`): `Promise`<`void`\>
|
||||
|
||||
#### Parameters
|
||||
|
||||
|
||||
+1
-1
@@ -271,7 +271,7 @@ custom_edit_url: null
|
||||
|
||||
### setDocumentHash
|
||||
|
||||
▸ `Abstract` **setDocumentHash**(`docId`, `docHash`): `void`
|
||||
▸ `Abstract` **setDocumentHash**(`docId`, `docHash`): `Promise`<`void`\>
|
||||
|
||||
#### Parameters
|
||||
|
||||
|
||||
+14
-14
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "docs",
|
||||
"version": "0.0.8",
|
||||
"version": "0.0.27",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"docusaurus": "docusaurus",
|
||||
@@ -15,29 +15,29 @@
|
||||
"typecheck": "tsc"
|
||||
},
|
||||
"dependencies": {
|
||||
"@docusaurus/core": "^3.2.1",
|
||||
"@docusaurus/remark-plugin-npm2yarn": "^3.2.1",
|
||||
"@docusaurus/core": "^3.3.2",
|
||||
"@docusaurus/remark-plugin-npm2yarn": "^3.3.2",
|
||||
"@llamaindex/examples": "workspace:*",
|
||||
"@mdx-js/react": "^3.0.1",
|
||||
"clsx": "^2.1.0",
|
||||
"clsx": "^2.1.1",
|
||||
"llamaindex": "workspace:*",
|
||||
"postcss": "^8.4.38",
|
||||
"prism-react-renderer": "^2.3.1",
|
||||
"raw-loader": "^4.0.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@docusaurus/module-type-aliases": "3.2.0",
|
||||
"@docusaurus/preset-classic": "^3.2.1",
|
||||
"@docusaurus/theme-classic": "^3.2.1",
|
||||
"@docusaurus/types": "^3.2.1",
|
||||
"@docusaurus/module-type-aliases": "3.3.2",
|
||||
"@docusaurus/preset-classic": "^3.3.2",
|
||||
"@docusaurus/theme-classic": "^3.3.2",
|
||||
"@docusaurus/types": "^3.3.2",
|
||||
"@tsconfig/docusaurus": "^2.0.3",
|
||||
"@types/node": "^20.12.7",
|
||||
"docusaurus-plugin-typedoc": "^0.22.0",
|
||||
"@types/node": "^20.12.11",
|
||||
"docusaurus-plugin-typedoc": "^1.0.1",
|
||||
"typedoc": "^0.25.13",
|
||||
"typedoc-plugin-markdown": "^3.17.1",
|
||||
"typescript": "^5.4.4"
|
||||
"typedoc-plugin-markdown": "^4.0.1",
|
||||
"typescript": "^5.5.2"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
DEBUG=llamaindex
|
||||
@@ -1,5 +1,15 @@
|
||||
# examples
|
||||
|
||||
## 0.0.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [436bc41]
|
||||
- Updated dependencies [a44e54f]
|
||||
- Updated dependencies [a51ed8d]
|
||||
- Updated dependencies [d3b635b]
|
||||
- llamaindex@0.4.0
|
||||
|
||||
## 0.0.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { FunctionTool, OpenAI, OpenAIAgent } from "llamaindex";
|
||||
|
||||
const csvData =
|
||||
"TITLE,RELEASE_YEAR,SCORE,NUMBER_OF_VOTES,DURATION,MAIN_GENRE,MAIN_PRODUCTION\nDavid Attenborough: A Life on Our Planet,2020,9,31180,83,documentary,GB\nInception,2010,8.8,2268288,148,scifi,GB\nForrest Gump,1994,8.8,1994599,142,drama,US\nAnbe Sivam,2003,8.7,20595,160,comedy,IN\nBo Burnham: Inside,2021,8.7,44074,87,comedy,US\nSaving Private Ryan,1998,8.6,1346020,169,drama,US\nDjango Unchained,2012,8.4,1472668,165,western,US\nDangal,2016,8.4,180247,161,action,IN\nBo Burnham: Make Happy,2016,8.4,14356,60,comedy,US\nLouis C.K.: Hilarious,2010,8.4,11973,84,comedy,US\nDave Chappelle: Sticks & Stones,2019,8.4,25687,65,comedy,US\n3 Idiots,2009,8.4,385782,170,comedy,IN\nBlack Friday,2004,8.4,20611,143,crime,IN\nSuper Deluxe,2019,8.4,13680,176,thriller,IN\nWinter on Fire: Ukraine's Fight for Freedom,2015,8.3,17710,98,documentary,UA\nOnce Upon a Time in America,1984,8.3,342335,229,drama,US\nTaxi Driver,1976,8.3,795222,113,crime,US\nLike Stars on Earth,2007,8.3,188234,165,drama,IN\nBo Burnham: What.,2013,8.3,11488,60,comedy,US\nFull Metal Jacket,1987,8.3,723306,116,drama,GB\nWarrior,2011,8.2,463276,140,drama,US\nDrishyam,2015,8.2,79075,163,thriller,IN\nQueen,2014,8.2,64805,146,drama,IN\nPaan Singh Tomar,2012,8.2,35888,135,drama,IN";
|
||||
|
||||
const userQuestion = "which are the best comedies after 2010?";
|
||||
|
||||
(async () => {
|
||||
// The agent will succeed if we increase `maxTokens` to 1024
|
||||
const llm = new OpenAI({ model: "gpt-4-turbo", maxTokens: 256 });
|
||||
|
||||
type Input = {
|
||||
code: string;
|
||||
};
|
||||
// initiate fake code interpreter
|
||||
const interpreterTool = FunctionTool.from<Input>(
|
||||
({ code }) => {
|
||||
console.log(
|
||||
`To answer the user's question, call the following code:\n${code}`,
|
||||
);
|
||||
return code;
|
||||
},
|
||||
{
|
||||
name: "interpreter",
|
||||
description:
|
||||
"Execute python code in a Jupyter notebook cell and return any result, stdout, stderr, display_data, and error.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
code: {
|
||||
type: "string",
|
||||
description: "The python code to execute in a single cell.",
|
||||
},
|
||||
},
|
||||
required: ["code"],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const systemPrompt =
|
||||
"You are a Python interpreter.\n - You are given tasks to complete and you run python code to solve them.\n - The python code runs in a Jupyter notebook. Every time you call $(interpreter) tool, the python code is executed in a separate cell. It's okay to make multiple calls to $(interpreter).\n - Display visualizations using matplotlib or any other visualization library directly in the notebook. Shouldn't save the visualizations to a file, just return the base64 encoded data.\n - You can install any pip package (if it exists) if you need to but the usual packages for data analysis are already preinstalled.\n - You can run any python code you want in a secure environment.";
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
llm,
|
||||
tools: [interpreterTool],
|
||||
systemPrompt,
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
console.log(`User question: ${userQuestion}\n`);
|
||||
|
||||
await agent.chat({
|
||||
message: [
|
||||
{
|
||||
type: "text",
|
||||
text: userQuestion,
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: `Use data from following CSV raw contents:\n${csvData}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,74 @@
|
||||
import { FunctionTool, OpenAI, ToolCallOptions } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
// The tool call will generate a partial JSON for `gpt-4-turbo`
|
||||
// See thread: https://community.openai.com/t/gpt-4o-doesnt-consistently-respect-json-schema-on-tool-use/751125/7
|
||||
|
||||
const models = ["gpt-4o", "gpt-4-turbo"];
|
||||
for (const model of models) {
|
||||
const validJSON = await callLLM({ model });
|
||||
console.log(
|
||||
`LLM call resulting in large tool input with '${model}': LLM generates ${validJSON ? "valid" : "invalid"} JSON.`,
|
||||
);
|
||||
}
|
||||
})();
|
||||
|
||||
async function callLLM(init: Partial<OpenAI>) {
|
||||
const csvData =
|
||||
"Country,Average Height (cm)\nNetherlands,156\nDenmark,158\nNorway,160";
|
||||
|
||||
const userQuestion = "Describe data in this csv";
|
||||
|
||||
// fake code interpreter tool
|
||||
const interpreterTool = FunctionTool.from(
|
||||
({ code }: { code: string }) => code,
|
||||
{
|
||||
name: "interpreter",
|
||||
description:
|
||||
"Execute python code in a Jupyter notebook cell and return any result, stdout, stderr, display_data, and error.",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
code: {
|
||||
type: "string",
|
||||
description: "The python code to execute in a single cell.",
|
||||
},
|
||||
},
|
||||
required: ["code"],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const systemPrompt =
|
||||
"You are a Python interpreter.\n- You are given tasks to complete and you run python code to solve them.\n- The python code runs in a Jupyter notebook. Every time you call $(interpreter) tool, the python code is executed in a separate cell. It's okay to make multiple calls to $(interpreter).\n- Display visualizations using matplotlib or any other visualization library directly in the notebook. Shouldn't save the visualizations to a file, just return the base64 encoded data.\n- You can install any pip package (if it exists) if you need to but the usual packages for data analysis are already preinstalled.\n- You can run any python code you want in a secure environment.";
|
||||
|
||||
const llm = new OpenAI(init);
|
||||
const response = await llm.chat({
|
||||
tools: [interpreterTool],
|
||||
messages: [
|
||||
{ role: "system", content: systemPrompt },
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: userQuestion,
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: `Use data from following CSV raw contents:\n${csvData}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const options = response.message?.options as ToolCallOptions;
|
||||
const input = options.toolCall[0].input as string;
|
||||
try {
|
||||
JSON.parse(input);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { ChatResponseChunk, OpenAIAgent } from "llamaindex";
|
||||
import { ReadableStream } from "node:stream/web";
|
||||
import {
|
||||
getCurrentIDTool,
|
||||
getUserInfoTool,
|
||||
getWeatherTool,
|
||||
} from "./utils/tools";
|
||||
|
||||
async function main() {
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [getCurrentIDTool, getUserInfoTool, getWeatherTool],
|
||||
});
|
||||
|
||||
const task = await agent.createTask(
|
||||
"What is my current address weather based on my profile?",
|
||||
true,
|
||||
);
|
||||
|
||||
for await (const stepOutput of task) {
|
||||
const stream = stepOutput.output as ReadableStream<ChatResponseChunk>;
|
||||
if (stepOutput.isLast) {
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.delta);
|
||||
}
|
||||
process.stdout.write("\n");
|
||||
} else {
|
||||
// handing function call
|
||||
console.log("handling function call...");
|
||||
for await (const chunk of stream) {
|
||||
console.log("debug:", JSON.stringify(chunk.raw));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -53,7 +53,7 @@ async function main() {
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
console.log(response.message);
|
||||
}
|
||||
|
||||
void main().then(() => {
|
||||
|
||||
@@ -29,15 +29,16 @@ async function main() {
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
message: "What was his first salary?",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
console.log(response.response);
|
||||
}
|
||||
|
||||
void main().then(() => {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { ChatResponseChunk, ReActAgent } from "llamaindex";
|
||||
import { ReadableStream } from "node:stream/web";
|
||||
import {
|
||||
getCurrentIDTool,
|
||||
getUserInfoTool,
|
||||
getWeatherTool,
|
||||
} from "./utils/tools";
|
||||
|
||||
async function main() {
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new ReActAgent({
|
||||
tools: [getCurrentIDTool, getUserInfoTool, getWeatherTool],
|
||||
});
|
||||
|
||||
const task = await agent.createTask(
|
||||
"What is my current address weather based on my profile?",
|
||||
true,
|
||||
);
|
||||
|
||||
for await (const stepOutput of task) {
|
||||
const stream = stepOutput.output as ReadableStream<ChatResponseChunk>;
|
||||
if (stepOutput.isLast) {
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.delta);
|
||||
}
|
||||
process.stdout.write("\n");
|
||||
} else {
|
||||
// handing function call
|
||||
console.log("handling function call...");
|
||||
for await (const chunk of stream) {
|
||||
console.log("debug:", JSON.stringify(chunk.raw));
|
||||
}
|
||||
}
|
||||
console.log("---");
|
||||
}
|
||||
}
|
||||
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -68,7 +68,7 @@ async function main() {
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const { response } = await agent.chat({
|
||||
const response = await agent.chat({
|
||||
message: "Divide 16 by 2 then add 20",
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
import {
|
||||
FunctionTool,
|
||||
MetadataMode,
|
||||
NodeWithScore,
|
||||
OpenAIAgent,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
const retriever = vectorIndex.asRetriever({ similarityTopK: 3 });
|
||||
|
||||
const retrieverTool = FunctionTool.from(
|
||||
async ({ query }: { query: string }) => {
|
||||
const nodesWithScores = await retriever.retrieve({
|
||||
query,
|
||||
});
|
||||
return nodesWithScores
|
||||
.map((nodeWithScore: NodeWithScore) =>
|
||||
nodeWithScore.node.getContent(MetadataMode.NONE),
|
||||
)
|
||||
.join("\n");
|
||||
},
|
||||
{
|
||||
name: "get_abramov_info",
|
||||
description: "Get information about the Abramov documents",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
query: {
|
||||
type: "string",
|
||||
description: "The query about Abramov",
|
||||
},
|
||||
},
|
||||
required: ["query"],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [retrieverTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "What was his first salary?",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(response.response);
|
||||
}
|
||||
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -1,97 +0,0 @@
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
import { ReadableStream } from "node:stream/web";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a + b}`;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }) {
|
||||
return `${a / b}`;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
} as const;
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
} as const;
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const functionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const functionTool2 = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [functionTool, functionTool2],
|
||||
});
|
||||
|
||||
// Create a task to sum and divide numbers
|
||||
const task = await agent.createTask("How much is 5 + 5? then divide by 2");
|
||||
|
||||
let count = 0;
|
||||
|
||||
for await (const stepOutput of task) {
|
||||
console.log(`Runnning step ${count++}`);
|
||||
console.log(`======== OUTPUT ==========`);
|
||||
const output = stepOutput.output;
|
||||
if (output instanceof ReadableStream) {
|
||||
for await (const chunk of output) {
|
||||
process.stdout.write(chunk.delta);
|
||||
}
|
||||
} else {
|
||||
console.log(output);
|
||||
}
|
||||
console.log(`==========================`);
|
||||
|
||||
if (stepOutput.isLast) {
|
||||
if (stepOutput.output instanceof ReadableStream) {
|
||||
for await (const chunk of stepOutput.output) {
|
||||
process.stdout.write(chunk.delta);
|
||||
}
|
||||
} else {
|
||||
console.log(stepOutput.output);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -31,7 +31,7 @@ async function main() {
|
||||
tools: [queryEngineTool],
|
||||
});
|
||||
|
||||
const { response } = await agent.chat({
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
|
||||
@@ -68,9 +68,7 @@ async function main() {
|
||||
|
||||
console.log("Response:");
|
||||
|
||||
for await (const {
|
||||
response: { delta },
|
||||
} of stream) {
|
||||
for await (const { delta } of stream) {
|
||||
process.stdout.write(delta);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { FunctionTool } from "llamaindex";
|
||||
|
||||
export const getCurrentIDTool = FunctionTool.from(
|
||||
() => {
|
||||
console.log("Getting user id...");
|
||||
return crypto.randomUUID();
|
||||
},
|
||||
{
|
||||
name: "get_user_id",
|
||||
description: "Get a random user id",
|
||||
},
|
||||
);
|
||||
|
||||
export const getUserInfoTool = FunctionTool.from(
|
||||
({ userId }: { userId: string }) => {
|
||||
console.log("Getting user info...", userId);
|
||||
return `Name: Alex; Address: 1234 Main St, CA; User ID: ${userId}`;
|
||||
},
|
||||
{
|
||||
name: "get_user_info",
|
||||
description: "Get user info",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
userId: {
|
||||
type: "string",
|
||||
description: "The user id",
|
||||
},
|
||||
},
|
||||
required: ["userId"],
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
export const getWeatherTool = FunctionTool.from(
|
||||
({ address }: { address: string }) => {
|
||||
console.log("Getting weather...", address);
|
||||
return `${address} is in a sunny location!`;
|
||||
},
|
||||
{
|
||||
name: "get_weather",
|
||||
description: "Get the current weather for a location",
|
||||
parameters: {
|
||||
type: "object",
|
||||
properties: {
|
||||
address: {
|
||||
type: "string",
|
||||
description: "The address",
|
||||
},
|
||||
},
|
||||
required: ["address"],
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -16,9 +16,7 @@ async function main() {
|
||||
stream: true,
|
||||
});
|
||||
|
||||
for await (const {
|
||||
response: { delta },
|
||||
} of response) {
|
||||
for await (const { delta } of response) {
|
||||
process.stdout.write(delta);
|
||||
}
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -0,0 +1,19 @@
|
||||
import { DeepInfra } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
if (!process.env.DEEPINFRA_API_TOKEN) {
|
||||
throw new Error("Please set the DEEPINFRA_API_TOKEN environment variable.");
|
||||
}
|
||||
const deepinfra = new DeepInfra({});
|
||||
const result = await deepinfra.chat({
|
||||
messages: [
|
||||
{ content: "You want to talk in rhymes.", role: "system" },
|
||||
{
|
||||
content:
|
||||
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
console.log(result);
|
||||
})();
|
||||
@@ -0,0 +1,17 @@
|
||||
import { DeepInfraEmbedding } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// API token can be provided as an environment variable too
|
||||
// using DEEPINFRA_API_TOKEN variable
|
||||
const apiToken = "YOUR_API_TOKEN" ?? process.env.DEEPINFRA_API_TOKEN;
|
||||
const model = "BAAI/bge-large-en-v1.5";
|
||||
const embedModel = new DeepInfraEmbedding({
|
||||
model,
|
||||
apiToken,
|
||||
});
|
||||
const texts = ["hello", "world"];
|
||||
const embeddings = await embedModel.getTextEmbeddingsBatch(texts);
|
||||
console.log(`\nWe have ${embeddings.length} embeddings`);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Gemini, GEMINI_MODEL, GeminiVertexSession } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
const gemini = new Gemini({
|
||||
model: GEMINI_MODEL.GEMINI_PRO,
|
||||
session: new GeminiVertexSession(),
|
||||
});
|
||||
const result = await gemini.chat({
|
||||
messages: [
|
||||
{ content: "You want to talk in rhymes.", role: "system" },
|
||||
{
|
||||
content:
|
||||
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
console.log(result);
|
||||
})();
|
||||
+1
-1
@@ -35,4 +35,4 @@ async function main() {
|
||||
console.log(response.response);
|
||||
}
|
||||
|
||||
await main();
|
||||
main().catch(console.error);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { HuggingFaceInferenceAPI } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
if (!process.env.HUGGING_FACE_TOKEN) {
|
||||
throw new Error("Please set the HUGGING_FACE_TOKEN environment variable.");
|
||||
}
|
||||
const hf = new HuggingFaceInferenceAPI({
|
||||
accessToken: process.env.HUGGING_FACE_TOKEN,
|
||||
model: "mistralai/Mixtral-8x7B-Instruct-v0.1",
|
||||
});
|
||||
const result = await hf.chat({
|
||||
messages: [
|
||||
{ content: "You want to talk in rhymes.", role: "system" },
|
||||
{
|
||||
content:
|
||||
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
console.log(result);
|
||||
})();
|
||||
@@ -0,0 +1,16 @@
|
||||
import { HuggingFaceLLM } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
const hf = new HuggingFaceLLM();
|
||||
const result = await hf.chat({
|
||||
messages: [
|
||||
{ content: "You want to talk in rhymes.", role: "system" },
|
||||
{
|
||||
content:
|
||||
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
|
||||
role: "user",
|
||||
},
|
||||
],
|
||||
});
|
||||
console.log(result);
|
||||
})();
|
||||
@@ -0,0 +1,54 @@
|
||||
// call pnpm tsx multimodal/load.ts first to init the storage
|
||||
import {
|
||||
ContextChatEngine,
|
||||
NodeWithScore,
|
||||
ObjectType,
|
||||
OpenAI,
|
||||
RetrievalEndEvent,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
import { getStorageContext } from "./storage";
|
||||
|
||||
// Update chunk size and overlap
|
||||
Settings.chunkSize = 512;
|
||||
Settings.chunkOverlap = 20;
|
||||
|
||||
// Update llm
|
||||
Settings.llm = new OpenAI({ model: "gpt-4-turbo", maxTokens: 512 });
|
||||
|
||||
// Update callbackManager
|
||||
Settings.callbackManager.on("retrieve-end", (event: RetrievalEndEvent) => {
|
||||
const { nodes, query } = event.detail.payload;
|
||||
const imageNodes = nodes.filter(
|
||||
(node: NodeWithScore) => node.node.type === ObjectType.IMAGE_DOCUMENT,
|
||||
);
|
||||
const textNodes = nodes.filter(
|
||||
(node: NodeWithScore) => node.node.type === ObjectType.TEXT,
|
||||
);
|
||||
console.log(
|
||||
`Retrieved ${textNodes.length} text nodes and ${imageNodes.length} image nodes for query: ${query}`,
|
||||
);
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const storageContext = await getStorageContext();
|
||||
const index = await VectorStoreIndex.init({
|
||||
storageContext,
|
||||
});
|
||||
// topK for text is 0 and for image 1 => we only retrieve one image and no text based on the query
|
||||
const retriever = index.asRetriever({ topK: { TEXT: 0, IMAGE: 1 } });
|
||||
// NOTE: we set the contextRole to "user" (default is "system"). The reason is that GPT-4 does not support
|
||||
// images in a system message
|
||||
const chatEngine = new ContextChatEngine({ retriever, contextRole: "user" });
|
||||
|
||||
// the ContextChatEngine will use the Clip embedding to retrieve the closest image
|
||||
// (the lady in the chair) and use it in the context for the query
|
||||
const response = await chatEngine.chat({
|
||||
message: "What is the name of the painting with the lady in the chair?",
|
||||
});
|
||||
|
||||
console.log(response.response, "\n");
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,11 +1,6 @@
|
||||
import {
|
||||
Settings,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
import * as path from "path";
|
||||
import { Settings, SimpleDirectoryReader, VectorStoreIndex } from "llamaindex";
|
||||
import path from "path";
|
||||
import { getStorageContext } from "./storage";
|
||||
|
||||
// Update chunk size and overlap
|
||||
Settings.chunkSize = 512;
|
||||
@@ -25,10 +20,7 @@ async function generateDatasource() {
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: path.join("multimodal", "data"),
|
||||
});
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "storage",
|
||||
storeImages: true,
|
||||
});
|
||||
const storageContext = await getStorageContext();
|
||||
await VectorStoreIndex.fromDocuments(documents, {
|
||||
storageContext,
|
||||
});
|
||||
|
||||
+15
-26
@@ -1,12 +1,11 @@
|
||||
import {
|
||||
CallbackManager,
|
||||
ImageType,
|
||||
MultiModalResponseSynthesizer,
|
||||
OpenAI,
|
||||
RetrievalEndEvent,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { getStorageContext } from "./storage";
|
||||
|
||||
// Update chunk size and overlap
|
||||
Settings.chunkSize = 512;
|
||||
@@ -16,40 +15,30 @@ Settings.chunkOverlap = 20;
|
||||
Settings.llm = new OpenAI({ model: "gpt-4-turbo", maxTokens: 512 });
|
||||
|
||||
// Update callbackManager
|
||||
Settings.callbackManager = new CallbackManager({
|
||||
onRetrieve: ({ query, nodes }) => {
|
||||
console.log(`Retrieved ${nodes.length} nodes for query: ${query}`);
|
||||
},
|
||||
Settings.callbackManager.on("retrieve-end", (event: RetrievalEndEvent) => {
|
||||
const { nodes, query } = event.detail.payload;
|
||||
console.log(`Retrieved ${nodes.length} nodes for query: ${query}`);
|
||||
});
|
||||
|
||||
export async function createIndex() {
|
||||
// set up vector store index with two vector stores, one for text, the other for images
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "storage",
|
||||
storeImages: true,
|
||||
});
|
||||
return await VectorStoreIndex.init({
|
||||
async function main() {
|
||||
const storageContext = await getStorageContext();
|
||||
const index = await VectorStoreIndex.init({
|
||||
nodes: [],
|
||||
storageContext,
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const images: ImageType[] = [];
|
||||
|
||||
const index = await createIndex();
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
responseSynthesizer: new MultiModalResponseSynthesizer(),
|
||||
retriever: index.asRetriever({ similarityTopK: 3, imageSimilarityTopK: 1 }),
|
||||
retriever: index.asRetriever({ topK: { TEXT: 3, IMAGE: 1 } }),
|
||||
});
|
||||
const result = await queryEngine.query({
|
||||
const stream = await queryEngine.query({
|
||||
query: "Tell me more about Vincent van Gogh's famous paintings",
|
||||
stream: true,
|
||||
});
|
||||
console.log(result.response, "\n");
|
||||
images.forEach((image) =>
|
||||
console.log(`Image retrieved and used in inference: ${image.toString()}`),
|
||||
);
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
process.stdout.write("\n");
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
|
||||
@@ -1,31 +1,18 @@
|
||||
import {
|
||||
ImageNode,
|
||||
Settings,
|
||||
TextNode,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
import { ImageNode, Settings, TextNode, VectorStoreIndex } from "llamaindex";
|
||||
import { getStorageContext } from "./storage";
|
||||
|
||||
// Update chunk size and overlap
|
||||
Settings.chunkSize = 512;
|
||||
Settings.chunkOverlap = 20;
|
||||
|
||||
export async function createIndex() {
|
||||
// set up vector store index with two vector stores, one for text, the other for images
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "storage",
|
||||
storeImages: true,
|
||||
});
|
||||
return await VectorStoreIndex.init({
|
||||
async function main() {
|
||||
// retrieve documents using the index
|
||||
const storageContext = await getStorageContext();
|
||||
const index = await VectorStoreIndex.init({
|
||||
nodes: [],
|
||||
storageContext,
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// retrieve documents using the index
|
||||
const index = await createIndex();
|
||||
const retriever = index.asRetriever({ similarityTopK: 3 });
|
||||
const retriever = index.asRetriever({ topK: { TEXT: 1, IMAGE: 3 } });
|
||||
const results = await retriever.retrieve({
|
||||
query: "what are Vincent van Gogh's famous paintings",
|
||||
});
|
||||
@@ -40,7 +27,7 @@ async function main() {
|
||||
console.log("Text:", (node as TextNode).text.substring(0, 128));
|
||||
}
|
||||
console.log(`ID: ${node.id_}`);
|
||||
console.log(`Similarity: ${result.score}`);
|
||||
console.log(`Similarity: ${result.score}\n`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { storageContextFromDefaults } from "llamaindex";
|
||||
|
||||
// set up store context with two vector stores, one for text, the other for images
|
||||
export async function getStorageContext() {
|
||||
return await storageContextFromDefaults({
|
||||
persistDir: "storage",
|
||||
storeImages: true,
|
||||
// if storeImages is true, the following vector store will be added
|
||||
// vectorStores: {
|
||||
// IMAGE: SimpleVectorStore.fromPersistDir(
|
||||
// `${persistDir}/images`,
|
||||
// fs,
|
||||
// new ClipEmbedding(),
|
||||
// ),
|
||||
// },
|
||||
});
|
||||
}
|
||||
+6
-1
@@ -2,7 +2,12 @@ import { OllamaEmbedding } from "llamaindex";
|
||||
import { Ollama } from "llamaindex/llm/ollama";
|
||||
|
||||
(async () => {
|
||||
const llm = new Ollama({ model: "llama3" });
|
||||
const llm = new Ollama({
|
||||
model: "llama3",
|
||||
config: {
|
||||
host: "http://localhost:11434",
|
||||
},
|
||||
});
|
||||
const embedModel = new OllamaEmbedding({ model: "nomic-embed-text" });
|
||||
{
|
||||
const response = await llm.chat({
|
||||
|
||||
+11
-11
@@ -1,26 +1,26 @@
|
||||
{
|
||||
"name": "@llamaindex/examples",
|
||||
"private": true,
|
||||
"version": "0.0.4",
|
||||
"version": "0.0.5",
|
||||
"dependencies": {
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@datastax/astra-db-ts": "^1.0.1",
|
||||
"@datastax/astra-db-ts": "^1.2.1",
|
||||
"@notionhq/client": "^2.2.15",
|
||||
"@pinecone-database/pinecone": "^1.1.3",
|
||||
"@zilliz/milvus2-sdk-node": "^2.4.1",
|
||||
"@pinecone-database/pinecone": "^2.2.2",
|
||||
"@zilliz/milvus2-sdk-node": "^2.4.2",
|
||||
"chromadb": "^1.8.1",
|
||||
"commander": "^11.1.0",
|
||||
"commander": "^12.1.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"js-tiktoken": "^1.0.11",
|
||||
"llamaindex": "*",
|
||||
"mongodb": "^6.5.0",
|
||||
"js-tiktoken": "^1.0.12",
|
||||
"llamaindex": "^0.4.0",
|
||||
"mongodb": "^6.7.0",
|
||||
"pathe": "^1.1.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.12.7",
|
||||
"@types/node": "^20.14.1",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsx": "^4.7.2",
|
||||
"typescript": "^5.4.5"
|
||||
"tsx": "^4.15.6",
|
||||
"typescript": "^5.5.2"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint ."
|
||||
|
||||
@@ -11,14 +11,15 @@
|
||||
"start:pdf": "node --import tsx ./src/pdf.ts",
|
||||
"start:llamaparse": "node --import tsx ./src/llamaparse.ts",
|
||||
"start:notion": "node --import tsx ./src/notion.ts",
|
||||
"start:llamaparse2": "node --import tsx ./src/llamaparse_2.ts"
|
||||
"start:llamaparse-dir": "node --import tsx ./src/simple-directory-reader-with-llamaparse.ts",
|
||||
"start:llamaparse-json": "node --import tsx ./src/llamaparse-json.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"llamaindex": "*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.12.7",
|
||||
"tsx": "^4.7.2",
|
||||
"typescript": "^5.4.5"
|
||||
"@types/node": "^20.12.11",
|
||||
"tsx": "^4.15.6",
|
||||
"typescript": "^5.5.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import type { BaseReader, Document, Metadata } from "llamaindex";
|
||||
import type { Document, Metadata } from "llamaindex";
|
||||
import { FileReader } from "llamaindex";
|
||||
import {
|
||||
FILE_EXT_TO_READER,
|
||||
SimpleDirectoryReader,
|
||||
} from "llamaindex/readers/SimpleDirectoryReader";
|
||||
import { TextFileReader } from "llamaindex/readers/TextFileReader";
|
||||
|
||||
class ZipReader implements BaseReader {
|
||||
loadData(...args: any[]): Promise<Document<Metadata>[]> {
|
||||
class ZipReader extends FileReader {
|
||||
loadDataAsContent(fileContent: Buffer): Promise<Document<Metadata>[]> {
|
||||
throw new Error("Implement me");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import fs from "fs/promises";
|
||||
import { LlamaParseReader } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load PDF using LlamaParse json mode
|
||||
const reader = new LlamaParseReader({ resultType: "json" });
|
||||
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
|
||||
|
||||
// Write the JSON objects to a file
|
||||
try {
|
||||
await fs.writeFile("jsonObjs.json", JSON.stringify(jsonObjs, null, 4));
|
||||
console.log("Array of JSON objects has been written to jsonObjs.json");
|
||||
} catch (e) {
|
||||
console.error("Error writing jsonObjs.json", e);
|
||||
}
|
||||
|
||||
const jsonList = jsonObjs[0]["pages"];
|
||||
|
||||
// Write the list of JSON objects as a single array to a file
|
||||
try {
|
||||
await fs.writeFile("jsonList.json", JSON.stringify(jsonList, null, 4));
|
||||
console.log(
|
||||
"List of JSON objects as single array has been written to jsonList.json",
|
||||
);
|
||||
} catch (e) {
|
||||
console.error("Error writing jsonList.json", e);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,26 +0,0 @@
|
||||
import fs from "fs/promises";
|
||||
import { LlamaParseReader } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load PDF using LlamaParse. set apiKey here or in environment variable LLAMA_CLOUD_API_KEY
|
||||
const reader = new LlamaParseReader({
|
||||
resultType: "markdown",
|
||||
language: "en",
|
||||
parsingInstruction:
|
||||
"The provided document is a manga comic book. Most pages do NOT have title. It does not contain tables. Try to reconstruct the dialogue happening in a cohesive way. Output any math equation in LATEX markdown (between $$)",
|
||||
});
|
||||
const documents = await reader.loadData("../data/manga.pdf"); // The manga.pdf in the data folder is just a copy of the TOS, due to copyright laws. You have to place your own. I used "The Manga Guide to Calculus" by Hiroyuki Kojima
|
||||
|
||||
// Assuming documents contain an array of pages or sections
|
||||
const parsedManga = documents.map((page) => page.text).join("\n---\n");
|
||||
|
||||
// Output the parsed manga to .md file. Will be placed in ../example/readers/
|
||||
try {
|
||||
await fs.writeFile("./parsedManga.md", parsedManga);
|
||||
console.log("Output successfully written to parsedManga.md");
|
||||
} catch (err) {
|
||||
console.error("Error writing to file:", err);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,35 @@
|
||||
import {
|
||||
LlamaParseReader,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const reader = new SimpleDirectoryReader();
|
||||
|
||||
const docs = await reader.loadData({
|
||||
directoryPath: "../data/parallel", // brk-2022.pdf split into 6 parts
|
||||
numWorkers: 2,
|
||||
// set LlamaParse as the default reader for all file types. Set apiKey here or in environment variable LLAMA_CLOUD_API_KEY
|
||||
overrideReader: new LlamaParseReader({
|
||||
language: "en",
|
||||
resultType: "markdown",
|
||||
parsingInstruction:
|
||||
"The provided files is Berkshire Hathaway's 2022 Annual Report. They contain figures, tables and raw data. Capture the data in a structured format. Mathematical equation should be put out as LATEX markdown (between $$).",
|
||||
}),
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments(docs);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query:
|
||||
"What is the general strategy for shareholder safety outlined in the report? Use a concrete example with numbers",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
OpenAI,
|
||||
OpenAIEmbedding,
|
||||
ResponseSynthesizer,
|
||||
RetrieverQueryEngine,
|
||||
Settings,
|
||||
@@ -28,6 +29,7 @@ class PineconeVectorStore<T extends RecordMetadata = RecordMetadata>
|
||||
{
|
||||
storesText = true;
|
||||
isEmbeddingQuery = false;
|
||||
embedModel = new OpenAIEmbedding();
|
||||
|
||||
indexName!: string;
|
||||
pineconeClient!: Pinecone;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
HuggingFaceEmbedding,
|
||||
Ollama,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
Settings.llm = new Ollama({
|
||||
model: "mixtral:8x7b",
|
||||
});
|
||||
|
||||
Settings.embedModel = new HuggingFaceEmbedding({
|
||||
modelType: "BAAI/bge-small-en-v1.5",
|
||||
quantized: false,
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
const essay = await fs.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]);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
+15
-14
@@ -2,8 +2,8 @@
|
||||
"name": "@llamaindex/monorepo",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"build": "turbo run build",
|
||||
"build:release": "turbo run build lint test --filter=\"!docs\" --filter=\"!*-test\"",
|
||||
"build": "turbo run build --filter=\"!docs\" --filter=\"!*-test\" --filter=\"!*-example\"",
|
||||
"build:release": "turbo run build lint test --filter=\"!docs\" --filter=\"!*-test\" --filter=\"!*-example\"",
|
||||
"dev": "turbo run dev",
|
||||
"format": "prettier --ignore-unknown --cache --check .",
|
||||
"format:write": "prettier --ignore-unknown --write .",
|
||||
@@ -14,24 +14,25 @@
|
||||
"type-check": "tsc -b --diagnostics",
|
||||
"release": "pnpm run check-minor-version && pnpm run build:release && changeset publish",
|
||||
"release-snapshot": "pnpm run check-minor-version && pnpm run build:release && changeset publish --tag snapshot",
|
||||
"check-minor-version": "node ./scripts/check-minor-version",
|
||||
"new-version": "changeset version && pnpm run check-minor-version && pnpm run build:release",
|
||||
"check-minor-version": "node ./scripts/check-minor-version.mjs",
|
||||
"new-version": "changeset version && pnpm run check-minor-version && pnpm format:write && pnpm install && pnpm run build:release",
|
||||
"new-snapshot": "pnpm run build:release && changeset version --snapshot"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.27.1",
|
||||
"@typescript-eslint/eslint-plugin": "^7.7.0",
|
||||
"@changesets/cli": "^2.27.5",
|
||||
"@typescript-eslint/eslint-plugin": "^7.13.1",
|
||||
"eslint": "^8.57.0",
|
||||
"eslint-config-next": "^13.5.6",
|
||||
"eslint-config-prettier": "^8.10.0",
|
||||
"eslint-config-turbo": "^1.13.2",
|
||||
"eslint-plugin-react": "7.28.0",
|
||||
"eslint-config-next": "^14.2.4",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-config-turbo": "^1.13.4",
|
||||
"eslint-plugin-react": "7.34.1",
|
||||
"husky": "^9.0.11",
|
||||
"lint-staged": "^15.2.2",
|
||||
"prettier": "^3.2.5",
|
||||
"lint-staged": "^15.2.7",
|
||||
"madge": "^7.0.0",
|
||||
"prettier": "^3.3.2",
|
||||
"prettier-plugin-organize-imports": "^3.2.4",
|
||||
"turbo": "^1.13.2",
|
||||
"typescript": "^5.4.5"
|
||||
"turbo": "^1.13.4",
|
||||
"typescript": "^5.5.2"
|
||||
},
|
||||
"packageManager": "pnpm@9.0.5",
|
||||
"pnpm": {
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# @llamaindex/autotool
|
||||
|
||||
## 1.0.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [436bc41]
|
||||
- Updated dependencies [a44e54f]
|
||||
- Updated dependencies [a51ed8d]
|
||||
- Updated dependencies [d3b635b]
|
||||
- llamaindex@0.4.0
|
||||
@@ -0,0 +1,83 @@
|
||||
# @llamaindex/autotool
|
||||
|
||||
> Auto transpile your JS function to LLM Agent compatible
|
||||
|
||||
## Usage
|
||||
|
||||
First, Install the package
|
||||
|
||||
```shell
|
||||
npm install @llamaindex/autotool
|
||||
pnpm add @llamaindex/autotool
|
||||
yarn add @llamaindex/autotool
|
||||
```
|
||||
|
||||
Second, Add the plugin/loader to your configuration:
|
||||
|
||||
### Next.js
|
||||
|
||||
```javascript
|
||||
import { withNext } from "@llamaindex/autotool/next";
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {};
|
||||
|
||||
export default withNext(nextConfig);
|
||||
```
|
||||
|
||||
### Node.js
|
||||
|
||||
```shell
|
||||
node --import @llamaindex/autotool/node ./path/to/your/script.js
|
||||
```
|
||||
|
||||
Third, add `"use tool"` on top of your tool file or change to `.tool.ts`.
|
||||
|
||||
```typescript
|
||||
"use tool";
|
||||
|
||||
export function getWeather(city: string) {
|
||||
// ...
|
||||
}
|
||||
// ...
|
||||
```
|
||||
|
||||
Finally, export a chat handler function to the frontend using `llamaindex` Agent
|
||||
|
||||
```typescript
|
||||
"use server";
|
||||
|
||||
// imports ...
|
||||
|
||||
export async function chatWithAI(message: string): Promise<JSX.Element> {
|
||||
const agent = new OpenAIAgent({
|
||||
tools: convertTools("llamaindex"),
|
||||
});
|
||||
const uiStream = createStreamableUI();
|
||||
agent
|
||||
.chat({
|
||||
stream: true,
|
||||
message,
|
||||
})
|
||||
.then(async (responseStream) => {
|
||||
return responseStream.pipeTo(
|
||||
new WritableStream({
|
||||
start: () => {
|
||||
uiStream.append("\n");
|
||||
},
|
||||
write: async (message) => {
|
||||
uiStream.append(message.response.delta);
|
||||
},
|
||||
close: () => {
|
||||
uiStream.done();
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
return uiStream.value;
|
||||
}
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,66 @@
|
||||
# @llamaindex/autotool-01-node-example
|
||||
|
||||
## null
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [6e156ed]
|
||||
- Updated dependencies [265976d]
|
||||
- Updated dependencies [8e26f75]
|
||||
- llamaindex@0.3.15
|
||||
- @llamaindex/autotool@0.0.1
|
||||
|
||||
## null
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [6ff7576]
|
||||
- Updated dependencies [94543de]
|
||||
- llamaindex@0.3.14
|
||||
- @llamaindex/autotool@0.0.1
|
||||
|
||||
## null
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [1b1081b]
|
||||
- Updated dependencies [37525df]
|
||||
- Updated dependencies [660a2b3]
|
||||
- Updated dependencies [a1f2475]
|
||||
- llamaindex@0.3.13
|
||||
- @llamaindex/autotool@0.0.1
|
||||
|
||||
## null
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [34fb1d8]
|
||||
- llamaindex@0.3.12
|
||||
- @llamaindex/autotool@0.0.1
|
||||
|
||||
## null
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [e072c45]
|
||||
- Updated dependencies [9e133ac]
|
||||
- Updated dependencies [447105a]
|
||||
- Updated dependencies [320be3f]
|
||||
- llamaindex@0.3.11
|
||||
- @llamaindex/autotool@0.0.1
|
||||
|
||||
## null
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [4aba02e]
|
||||
- llamaindex@0.3.10
|
||||
- @llamaindex/autotool@0.0.1
|
||||
|
||||
## null
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [c3747d0]
|
||||
- llamaindex@0.3.9
|
||||
- @llamaindex/autotool@0.0.1
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "@llamaindex/autotool-01-node-example",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@llamaindex/autotool": "workspace:*",
|
||||
"llamaindex": "workspace:*",
|
||||
"openai": "^4.52.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tsx": "^4.15.6"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node --import tsx --import @llamaindex/autotool/node ./src/index.ts"
|
||||
},
|
||||
"version": null
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { getWeather } from "./utils.js";
|
||||
|
||||
/**
|
||||
* Get current location
|
||||
*/
|
||||
export function getCurrentLocation() {
|
||||
console.log("Getting current location");
|
||||
return "London";
|
||||
}
|
||||
|
||||
export { getWeather };
|
||||
@@ -0,0 +1,23 @@
|
||||
import { convertTools } from "@llamaindex/autotool";
|
||||
import { OpenAI } from "openai";
|
||||
import "./index.tool.js";
|
||||
|
||||
const openai = new OpenAI();
|
||||
{
|
||||
const response = await openai.chat.completions.create({
|
||||
model: "gpt-3.5-turbo",
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: "What's my current weather?",
|
||||
},
|
||||
],
|
||||
tools: convertTools("openai"),
|
||||
stream: false,
|
||||
});
|
||||
|
||||
const toolCalls = response.choices[0].message.tool_calls ?? [];
|
||||
for (const toolCall of toolCalls) {
|
||||
toolCall.function.name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Get the weather for a city
|
||||
* @param city The city to get the weather for
|
||||
* @returns The weather for the city, e.g. "Sunny", "Rainy", etc.
|
||||
*/
|
||||
export function getWeather(city: string) {
|
||||
return `The weather in ${city} is sunny!`;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user