mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-01 22:14:03 -04:00
Compare commits
99 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c168cd531 | |||
| 62cba5236d | |||
| d265e96420 | |||
| d30bbf799f | |||
| 53fd00a7c3 | |||
| 83f2848d47 | |||
| 313071e9cd | |||
| 5f6782038a | |||
| fe08d0451b | |||
| 59c5e5c3d4 | |||
| ee697fb1b3 | |||
| cf3320a4ea | |||
| f2ed69f2f8 | |||
| 3489e7de84 | |||
| 468bda594e | |||
| 6f3a31caf6 | |||
| 63e9846e97 | |||
| b7382b0d24 | |||
| 2a8241328d | |||
| 0b20ff9f17 | |||
| 1fc26046e3 | |||
| b17d439d6d | |||
| 040160c360 | |||
| 981811efd1 | |||
| d563b45a27 | |||
| 2774e80234 | |||
| 449274ca5a | |||
| 78037a664c | |||
| 1d9e3b1000 | |||
| df83e32107 | |||
| f7b4e94231 | |||
| 4c07a2655d | |||
| 5c0c8b2ec4 | |||
| e5e18688a6 | |||
| b6fb10eba8 | |||
| df441e28f4 | |||
| a4e05ec7ab | |||
| 96f72ad86e | |||
| f3556c011c | |||
| ebc510582b | |||
| f3bfdc29e3 | |||
| 6cce3b12ea | |||
| 0273e9739a | |||
| 7c8b883448 | |||
| c2bb418542 | |||
| ed6acbead0 | |||
| 976cce40d7 | |||
| e4fd4158bb | |||
| 31d5dffcef | |||
| d12edee802 | |||
| ac41ed3aae | |||
| d8c1159032 | |||
| c856c5becb | |||
| 50e6b57be0 | |||
| 8b7fdba544 | |||
| 22ae8d0166 | |||
| 23bcc379a8 | |||
| bdc4bfe7b0 | |||
| 025ffe6b50 | |||
| a6595747fa | |||
| d902cc3e7e | |||
| 726eb41359 | |||
| e9714dbfcd | |||
| a3618e761e | |||
| 24eabe7f35 | |||
| ecfa939ea6 | |||
| b48bcc3add | |||
| fa01fa2051 | |||
| fb36eff5e1 | |||
| d24d3d1e8c | |||
| 5c4badbcca | |||
| 2cd1383dc8 | |||
| 72440c101f | |||
| 423d66b07a | |||
| b42adebd51 | |||
| 749b43a3b1 | |||
| 8daaef44ee | |||
| ac07e3cbe6 | |||
| 1a6137b323 | |||
| 85c2e198a4 | |||
| 01263c4cfd | |||
| fbd5e0174d | |||
| 70ccb4ae65 | |||
| 7eb331774d | |||
| 24a3f058a3 | |||
| 84c28f95f9 | |||
| 7af57982fe | |||
| 6b70c5408f | |||
| 74fc725f37 | |||
| a0a74aed60 | |||
| 11feef8c82 | |||
| 9c5ff164ac | |||
| 7edeb1c2d7 | |||
| 8b95abdc85 | |||
| ffe0cd1ef1 | |||
| 5d2111a19f | |||
| 68ac7fd57f | |||
| 7320d96a36 | |||
| ee17fb475b |
+35
-26
@@ -12,6 +12,12 @@ concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
POSTGRES_HOST_AUTH_METHOD: trust
|
||||
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
|
||||
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
|
||||
TURBO_REMOTE_ONLY: true
|
||||
|
||||
jobs:
|
||||
e2e:
|
||||
strategy:
|
||||
@@ -19,17 +25,20 @@ jobs:
|
||||
matrix:
|
||||
node-version: [18.x, 20.x, 22.x]
|
||||
name: E2E on Node.js ${{ matrix.node-version }}
|
||||
|
||||
env: POSTGRES_DB=vectordb
|
||||
POSTGRES_USER=testuser
|
||||
POSTGRES_PASSWORD=testpwd
|
||||
POSTGRES_HOST_AUTH_METHOD=trust
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
database: llamaindex_node_test
|
||||
dev-files: true
|
||||
- run: |
|
||||
cd /tmp
|
||||
git clone --branch v0.7.0 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
make
|
||||
sudo make install
|
||||
- uses: pnpm/action-setup@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -47,19 +56,8 @@ jobs:
|
||||
node-version: [18.x, 20.x, 22.x]
|
||||
name: Test on Node.js ${{ matrix.node-version }}
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: ankane/setup-postgres@v1
|
||||
with:
|
||||
database: llamaindex_node_test
|
||||
dev-files: true
|
||||
- run: |
|
||||
cd /tmp
|
||||
git clone --branch v0.7.0 https://github.com/pgvector/pgvector.git
|
||||
cd pgvector
|
||||
make
|
||||
sudo make install
|
||||
- uses: pnpm/action-setup@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -91,13 +89,7 @@ jobs:
|
||||
- name: Run Type Check
|
||||
run: pnpm run type-check
|
||||
- name: Run Circular Dependency Check
|
||||
run: pnpm dlx turbo run circular-check
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: failure()
|
||||
with:
|
||||
name: typecheck-build-dist
|
||||
path: ./packages/llamaindex/dist
|
||||
if-no-files-found: error
|
||||
run: pnpm run circular-check
|
||||
e2e-llamaindex-examples:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
@@ -107,7 +99,8 @@ jobs:
|
||||
- nextjs-agent
|
||||
- nextjs-edge-runtime
|
||||
- nextjs-node-runtime
|
||||
# - waku-query-engine
|
||||
- waku-query-engine
|
||||
- llama-parse-browser
|
||||
runs-on: ubuntu-latest
|
||||
name: Build LlamaIndex Example (${{ matrix.packages }})
|
||||
steps:
|
||||
@@ -146,6 +139,15 @@ jobs:
|
||||
- name: Pack @llamaindex/cloud
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/cloud
|
||||
- name: Pack @llamaindex/openai
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/llm/openai
|
||||
- name: Pack @llamaindex/groq
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/llm/groq
|
||||
- name: Pack @llamaindex/ollama
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/llm/ollama
|
||||
- name: Pack @llamaindex/core
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/core
|
||||
@@ -161,3 +163,10 @@ jobs:
|
||||
- name: Run Type Check
|
||||
run: npx tsc --project ./tsconfig.json
|
||||
working-directory: ${{ runner.temp }}/examples
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: build-dist
|
||||
path: |
|
||||
${{ runner.temp }}/*.tgz
|
||||
if-no-files-found: error
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
LlamaIndex is a data framework for your LLM application.
|
||||
|
||||
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in Typescript and Javascript.
|
||||
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in JS runtime environments with TypeScript support.
|
||||
|
||||
Documentation: https://ts.llamaindex.ai/
|
||||
|
||||
@@ -19,17 +19,36 @@ Try examples online:
|
||||
|
||||
LlamaIndex.TS aims to be a lightweight, easy to use set of libraries to help you integrate large language models into your applications with your own data.
|
||||
|
||||
## Multiple JS Environment Support
|
||||
## Compatibility
|
||||
|
||||
### Multiple JS Environment Support
|
||||
|
||||
LlamaIndex.TS supports multiple JS environments, including:
|
||||
|
||||
- Node.js (18, 20, 22) ✅
|
||||
- Deno ✅
|
||||
- Bun ✅
|
||||
- React Server Components (Next.js) ✅
|
||||
- Nitro ✅
|
||||
- Vercel Edge Runtime ✅ (with some limitations)
|
||||
- Cloudflare Workers ✅ (with some limitations)
|
||||
|
||||
For now, browser support is limited due to the lack of support for [AsyncLocalStorage-like APIs](https://github.com/tc39/proposal-async-context)
|
||||
|
||||
### Supported LLMs:
|
||||
|
||||
- OpenAI LLms
|
||||
- Anthropic LLms
|
||||
- Groq LLMs
|
||||
- Llama2, Llama3, Llama3.1 LLMs
|
||||
- MistralAI LLMs
|
||||
- Fireworks LLMs
|
||||
- DeepSeek LLMs
|
||||
- ReplicateAI LLMs
|
||||
- TogetherAI LLMs
|
||||
- HuggingFace LLms
|
||||
- DeepInfra LLMs
|
||||
- Gemini LLMs
|
||||
|
||||
## Getting started
|
||||
|
||||
```shell
|
||||
@@ -77,7 +96,7 @@ See more about [moduleResolution](https://www.typescriptlang.org/docs/handbook/m
|
||||
### Node.js
|
||||
|
||||
```ts
|
||||
import fs from "fs/promises";
|
||||
import fs from "node:fs/promises";
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
@@ -111,9 +130,9 @@ main();
|
||||
node --import tsx ./main.ts
|
||||
```
|
||||
|
||||
### React Server Component (Next.js, Waku, Redwood.JS...)
|
||||
### Next.js
|
||||
|
||||
First, you will need to add a llamaindex plugin to your Next.js project.
|
||||
You will need to add a llamaindex plugin to your Next.js project.
|
||||
|
||||
```js
|
||||
// next.config.js
|
||||
@@ -124,20 +143,18 @@ module.exports = withLlamaIndex({
|
||||
});
|
||||
```
|
||||
|
||||
You can combine `ai` with `llamaindex` in Next.js with RSC (React Server Components).
|
||||
### React Server Actions
|
||||
|
||||
You can combine `ai` with `llamaindex` in Next.js, Waku or Redwood.js with RSC (React Server Components).
|
||||
|
||||
```tsx
|
||||
// src/apps/page.tsx
|
||||
"use client";
|
||||
import { chatWithAgent } from "@/actions";
|
||||
import type { JSX } from "react";
|
||||
import { useFormState } from "react-dom";
|
||||
|
||||
// You can use the Edge runtime in Next.js by adding this line:
|
||||
// export const runtime = "edge";
|
||||
import { useActionState } from "react";
|
||||
|
||||
export default function Home() {
|
||||
const [ui, action] = useFormState<JSX.Element | null>(async () => {
|
||||
const [ui, action] = useActionState<JSX.Element | null>(async () => {
|
||||
return chatWithAgent("hello!", []);
|
||||
}, null);
|
||||
return (
|
||||
@@ -167,11 +184,13 @@ export async function chatWithAgent(
|
||||
// ... adding your tools here
|
||||
],
|
||||
});
|
||||
const responseStream = await agent.chat({
|
||||
stream: true,
|
||||
message: question,
|
||||
chatHistory: prevMessages,
|
||||
});
|
||||
const responseStream = await agent.chat(
|
||||
{
|
||||
message: question,
|
||||
chatHistory: prevMessages,
|
||||
},
|
||||
true,
|
||||
);
|
||||
const uiStream = createStreamableUI(<div>loading...</div>);
|
||||
responseStream
|
||||
.pipeTo(
|
||||
@@ -189,29 +208,66 @@ export async function chatWithAgent(
|
||||
}
|
||||
```
|
||||
|
||||
## Playground
|
||||
### Cloudflare Workers
|
||||
|
||||
Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
|
||||
> [!TIP]
|
||||
> Some modules are not supported in Cloudflare Workers which require Node.js APIs.
|
||||
|
||||
## Core concepts for getting started:
|
||||
```ts
|
||||
// add `OPENAI_API_KEY` to the `.dev.vars` file
|
||||
interface Env {
|
||||
OPENAI_API_KEY: string;
|
||||
}
|
||||
|
||||
- [Document](/packages/llamaindex/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
export default {
|
||||
async fetch(
|
||||
request: Request,
|
||||
env: Env,
|
||||
ctx: ExecutionContext,
|
||||
): Promise<Response> {
|
||||
const { OpenAIAgent, OpenAI } = await import("@llamaindex/openai");
|
||||
const text = await request.text();
|
||||
const agent = new OpenAIAgent({
|
||||
llm: new OpenAI({
|
||||
apiKey: env.OPENAI_API_KEY,
|
||||
}),
|
||||
tools: [],
|
||||
});
|
||||
const responseStream = await agent.chat({
|
||||
stream: true,
|
||||
message: text,
|
||||
});
|
||||
const textEncoder = new TextEncoder();
|
||||
const response = responseStream.pipeThrough<Uint8Array>(
|
||||
new TransformStream({
|
||||
transform: (chunk, controller) => {
|
||||
controller.enqueue(textEncoder.encode(chunk.delta));
|
||||
},
|
||||
}),
|
||||
);
|
||||
return new Response(response);
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
- [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.
|
||||
### Vite
|
||||
|
||||
- [Embedding](/packages/llamaindex/src/embeddings/OpenAIEmbedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that question. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/llamaindex/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/llamaindex/src/embeddings)).
|
||||
We have some wasm dependencies for better performance. You can use `vite-plugin-wasm` to load them.
|
||||
|
||||
- [Indices](/packages/llamaindex/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
|
||||
```ts
|
||||
import wasm from "vite-plugin-wasm";
|
||||
|
||||
- [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).
|
||||
export default {
|
||||
plugins: [wasm()],
|
||||
ssr: {
|
||||
external: ["tiktoken"],
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
- [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).
|
||||
### Tips when using in non-Node.js environments
|
||||
|
||||
- [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
|
||||
|
||||
When you are importing `llamaindex` in a non-Node.js environment(such as React Server Components, Cloudflare Workers, etc.)
|
||||
When you are importing `llamaindex` in a non-Node.js environment(such as Vercel Edge, Cloudflare Workers, etc.)
|
||||
Some classes are not exported from top-level entry file.
|
||||
|
||||
The reason is that some classes are only compatible with Node.js runtime,(e.g. `PDFReader`) which uses Node.js specific APIs(like `fs`, `child_process`, `crypto`).
|
||||
@@ -247,19 +303,31 @@ export async function getDocuments() {
|
||||
|
||||
You'll find a complete example with LlamaIndexTS here: https://github.com/run-llama/create_llama_projects/tree/main/nextjs-edge-llamaparse
|
||||
|
||||
## Supported LLMs:
|
||||
## Playground
|
||||
|
||||
- OpenAI GPT-3.5-turbo and GPT-4
|
||||
- Anthropic Claude 3 (Opus, Sonnet, and Haiku) and the legacy models (Claude 2 and Instant)
|
||||
- Groq LLMs
|
||||
- Llama2/3 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- MistralAI Chat LLMs
|
||||
- Fireworks Chat LLMs
|
||||
Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
|
||||
|
||||
## Core concepts for getting started:
|
||||
|
||||
- [Document](/packages/llamaindex/src/Node.ts): A document represents a text file, PDF file or other contiguous piece of data.
|
||||
|
||||
- [Node](/packages/llamaindex/src/Node.ts): The basic data building block. Most commonly, these are parts of the document split into manageable pieces that are small enough to be fed into an embedding model and LLM.
|
||||
|
||||
- [Embedding](/packages/llamaindex/src/embeddings/OpenAIEmbedding.ts): Embeddings are sets of floating point numbers which represent the data in a Node. By comparing the similarity of embeddings, we can derive an understanding of the similarity of two pieces of data. One use case is to compare the embedding of a question with the embeddings of our Nodes to see which Nodes may contain the data needed to answer that question. Because the default service context is OpenAI, the default embedding is `OpenAIEmbedding`. If using different models, say through Ollama, use this [Embedding](/packages/llamaindex/src/embeddings/OllamaEmbedding.ts) (see all [here](/packages/llamaindex/src/embeddings)).
|
||||
|
||||
- [Indices](/packages/llamaindex/src/indices/): Indices store the Nodes and the embeddings of those nodes. QueryEngines retrieve Nodes from these Indices using embedding similarity.
|
||||
|
||||
- [QueryEngine](/packages/llamaindex/src/engines/query/RetrieverQueryEngine.ts): Query engines are what generate the query you put in and give you back the result. Query engines generally combine a pre-built prompt with selected Nodes from your Index to give the LLM the context it needs to answer your query. To build a query engine from your Index (recommended), use the [`asQueryEngine`](/packages/llamaindex/src/indices/BaseIndex.ts) method on your Index. See all query engines [here](/packages/llamaindex/src/engines/query).
|
||||
|
||||
- [ChatEngine](/packages/llamaindex/src/engines/chat/SimpleChatEngine.ts): A ChatEngine helps you build a chatbot that will interact with your Indices. See all chat engines [here](/packages/llamaindex/src/engines/chat).
|
||||
|
||||
- [SimplePrompt](/packages/llamaindex/src/Prompt.ts): A simple standardized function call definition that takes in inputs and formats them in a template literal. SimplePrompts can be specialized using currying and combined using other SimplePrompt functions.
|
||||
|
||||
## Contributing:
|
||||
|
||||
We are in the very early days of LlamaIndex.TS. If you’re interested in hacking on it with us check out our [contributing guide](/CONTRIBUTING.md)
|
||||
Please see our [contributing guide](CONTRIBUTING.md) for more information.
|
||||
You are highly encouraged to contribute to LlamaIndex.TS!
|
||||
|
||||
## Bugs? Questions?
|
||||
## Community
|
||||
|
||||
Please join our Discord! https://discord.com/invite/eN6D2HQ4aX
|
||||
|
||||
@@ -1,5 +1,172 @@
|
||||
# docs
|
||||
|
||||
## 0.0.88
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [62cba52]
|
||||
- Updated dependencies [d265e96]
|
||||
- Updated dependencies [d30bbf7]
|
||||
- Updated dependencies [53fd00a]
|
||||
- llamaindex@0.6.19
|
||||
|
||||
## 0.0.87
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [5f67820]
|
||||
- Updated dependencies [fe08d04]
|
||||
- llamaindex@0.6.18
|
||||
|
||||
## 0.0.86
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ee697fb]
|
||||
- llamaindex@0.6.17
|
||||
|
||||
## 0.0.85
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [63e9846]
|
||||
- Updated dependencies [6f3a31c]
|
||||
- llamaindex@0.6.16
|
||||
|
||||
## 0.0.84
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2a82413]
|
||||
- llamaindex@0.6.15
|
||||
|
||||
## 0.0.83
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.14
|
||||
|
||||
## 0.0.82
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.13
|
||||
|
||||
## 0.0.81
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [f7b4e94]
|
||||
- Updated dependencies [78037a6]
|
||||
- Updated dependencies [1d9e3b1]
|
||||
- llamaindex@0.6.12
|
||||
|
||||
## 0.0.80
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [df441e2]
|
||||
- llamaindex@0.6.11
|
||||
|
||||
## 0.0.79
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ebc5105]
|
||||
- Updated dependencies [6cce3b1]
|
||||
- llamaindex@0.6.10
|
||||
|
||||
## 0.0.78
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.9
|
||||
|
||||
## 0.0.77
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [8b7fdba]
|
||||
- llamaindex@0.6.8
|
||||
|
||||
## 0.0.76
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [23bcc37]
|
||||
- llamaindex@0.6.7
|
||||
|
||||
## 0.0.75
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d902cc3]
|
||||
- Updated dependencies [025ffe6]
|
||||
- Updated dependencies [a659574]
|
||||
- llamaindex@0.6.6
|
||||
|
||||
## 0.0.74
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [e9714db]
|
||||
- llamaindex@0.6.5
|
||||
|
||||
## 0.0.73
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [b48bcc3]
|
||||
- llamaindex@0.6.4
|
||||
|
||||
## 0.0.72
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2cd1383]
|
||||
- Updated dependencies [5c4badb]
|
||||
- llamaindex@0.6.3
|
||||
|
||||
## 0.0.71
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [749b43a]
|
||||
- llamaindex@0.6.2
|
||||
|
||||
## 0.0.70
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [fbd5e01]
|
||||
- Updated dependencies [6b70c54]
|
||||
- Updated dependencies [1a6137b]
|
||||
- Updated dependencies [85c2e19]
|
||||
- llamaindex@0.6.1
|
||||
|
||||
## 0.0.69
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [11feef8]
|
||||
- llamaindex@0.6.0
|
||||
- @llamaindex/examples@0.0.8
|
||||
|
||||
## 0.0.68
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [7edeb1c]
|
||||
- llamaindex@0.5.27
|
||||
|
||||
## 0.0.67
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ffe0cd1]
|
||||
- Updated dependencies [ffe0cd1]
|
||||
- llamaindex@0.5.26
|
||||
|
||||
## 0.0.66
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Agents"
|
||||
position: 3
|
||||
position: 10
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
sidebar_position: 13
|
||||
---
|
||||
|
||||
# ChatEngine
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
sidebar_position: 12
|
||||
---
|
||||
|
||||
# Index
|
||||
@@ -8,6 +8,7 @@ An index is the basic container and organization for your data. LlamaIndex.TS su
|
||||
|
||||
- `VectorStoreIndex` - will send the top-k `Node`s to the LLM when generating a response. The default top-k is 2.
|
||||
- `SummaryIndex` - will send every `Node` in the index to the LLM in order to generate a response
|
||||
- `KeywordTableIndex` extracts and provides keywords from `Node`s to the LLM
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
@@ -6,6 +6,19 @@ import CodeSource2 from "!raw-loader!../../../../../examples/readers/src/custom-
|
||||
|
||||
Before you can start indexing your documents, you need to load them into memory.
|
||||
|
||||
All "basic" data loaders can be seen below, mapped to their respective filetypes in `SimpleDirectoryReader`. More loaders are shown in the sidebar on the left.
|
||||
Additionally the following loaders exist without separate documentation:
|
||||
|
||||
- `AssemblyAIReader` transcribes audio using [AssemblyAI](https://www.assemblyai.com/).
|
||||
- [AudioTranscriptReader](../../api/classes/AudioTranscriptReader.md): loads entire transcript as a single document.
|
||||
- [AudioTranscriptParagraphsReader](../../api/classes/AudioTranscriptParagraphsReader.md): creates a document per paragraph.
|
||||
- [AudioTranscriptSentencesReader](../../api/classes/AudioTranscriptSentencesReader.md): creates a document per sentence.
|
||||
- [AudioSubtitlesReader](../../api/classes/AudioTranscriptParagraphsReader.md): creates a document containing the subtitles of a transcript.
|
||||
- [NotionReader](../../api/classes/NotionReader.md) loads [Notion](https://www.notion.so/) pages.
|
||||
- [SimpleMongoReader](../../api/classes/SimpleMongoReader) loads data from a [MongoDB](https://www.mongodb.com/).
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## SimpleDirectoryReader
|
||||
|
||||
[](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
|
||||
|
||||
@@ -13,7 +13,7 @@ Official documentation for LlamaParse can be found [here](https://docs.cloud.lla
|
||||
## Usage
|
||||
|
||||
You can then use the `LlamaParseReader` class to load local files and convert them into a parsed document that can be used by LlamaIndex.
|
||||
See [LlamaParseReader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/llamaindex/src/readers/LlamaParseReader.ts) for a list of supported file types:
|
||||
See [reader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/cloud/src/reader.ts) for a list of supported file types:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Data Stores"
|
||||
position: 2
|
||||
@@ -0,0 +1 @@
|
||||
label: "Chat Stores"
|
||||
@@ -0,0 +1,13 @@
|
||||
# Chat Stores
|
||||
|
||||
Chat stores manage chat history by storing sequences of messages in a structured way, ensuring the order of messages is maintained for accurate conversation flow.
|
||||
|
||||
## Available Chat Stores
|
||||
|
||||
- [SimpleChatStore](../../../api/classes/SimpleChatStore.md): A simple in-memory chat store with support for [persisting](../index.md#local-storage) data to disk.
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [BaseChatStore](../../../api/interfaces/BaseChatStore.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Document Stores"
|
||||
position: 2
|
||||
@@ -0,0 +1,14 @@
|
||||
# Document Stores
|
||||
|
||||
Document stores contain ingested document chunks, i.e. [Node](../../documents_and_nodes/index.md)s.
|
||||
|
||||
## Available Document Stores
|
||||
|
||||
- [SimpleDocumentStore](../../../api/classes/SimpleDocumentStore.md): A simple in-memory document store with support for [persisting](../index.md#local-storage) data to disk.
|
||||
- [PostgresDocumentStore](../../../api/classes/PostgresDocumentStore.md): A PostgreSQL document store, see [PostgreSQL Storage](../index.md#postgresql-storage).
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [BaseDocumentStore](../../../api/classes/BaseDocumentStore.md)
|
||||
@@ -0,0 +1,56 @@
|
||||
# Storage
|
||||
|
||||
Storage in LlamaIndex.TS works automatically once you've configured a
|
||||
`StorageContext` object.
|
||||
|
||||
## Local Storage
|
||||
|
||||
You can configure the `persistDir` and attach it to an index.
|
||||
|
||||
```typescript
|
||||
import {
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
|
||||
const document = new Document({ text: "Test Text" });
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
## PostgreSQL Storage
|
||||
|
||||
You can configure the `schemaName`, `tableName`, `namespace`, and
|
||||
`connectionString`. If a `connectionString` is not
|
||||
provided, it will use the environment variables `PGHOST`, `PGUSER`,
|
||||
`PGPASSWORD`, `PGDATABASE` and `PGPORT`.
|
||||
|
||||
```typescript
|
||||
import {
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
PostgresDocumentStore,
|
||||
PostgresIndexStore,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
docStore: new PostgresDocumentStore(),
|
||||
indexStore: new PostgresIndexStore(),
|
||||
});
|
||||
|
||||
const document = new Document({ text: "Test Text" });
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [StorageContext](../../api/interfaces/StorageContext.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Index Stores"
|
||||
position: 3
|
||||
@@ -0,0 +1,14 @@
|
||||
# Index Stores
|
||||
|
||||
Index stores are underlying storage components that contain metadata(i.e. information created when indexing) about the [index](../../data_index.md) itself.
|
||||
|
||||
## Available Index Stores
|
||||
|
||||
- [SimpleIndexStore](../../../api/classes/SimpleIndexStore.md): A simple in-memory index store with support for [persisting](../index.md#local-storage) data to disk.
|
||||
- [PostgresIndexStore](../../../api/classes/PostgresIndexStore.md): A PostgreSQL index store, , see [PostgreSQL Storage](../index.md#postgresql-storage).
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [BaseIndexStore](../../../api/classes/BaseIndexStore.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Key-Value Stores"
|
||||
position: 4
|
||||
@@ -0,0 +1,14 @@
|
||||
# Key-Value Stores
|
||||
|
||||
Key-Value Stores represent underlying storage components used in [Document Stores](../doc_stores/index.md) and [Index Stores](../index_stores/index.md)
|
||||
|
||||
## Available Key-Value Stores
|
||||
|
||||
- [SimpleKVStore](../../../api/classes/SimpleKVStore.md): A simple Key-Value store with support of [persisting](../index.md#local-storage) data to disk.
|
||||
- [PostgresKVStore](../../../api/classes/PostgresKVStore.md): A PostgreSQL Key-Value store, see [PostgreSQL Storage](../index.md#postgresql-storage).
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [BaseKVStore](../../../api/classes/BaseKVStore.md)
|
||||
@@ -0,0 +1,22 @@
|
||||
# Vector Stores
|
||||
|
||||
Vector stores save embedding vectors of your ingested document chunks.
|
||||
|
||||
## Available Vector Stores
|
||||
|
||||
Available Vector Stores are shown on the sidebar to the left. Additionally the following integrations exist without separate documentation:
|
||||
|
||||
- [SimpleVectorStore](../../../api/classes/SimpleVectorStore.md): A simple in-memory vector store with optional [persistance](../index.md#local-storage) to disk.
|
||||
- [AstraDBVectorStore](../../../api/classes/AstraDBVectorStore.md): A cloud-native, scalable Database-as-a-Service built on Apache Cassandra, see [datastax.com](https://www.datastax.com/products/datastax-astra)
|
||||
- [ChromaVectorStore](../../../api/classes/ChromaVectorStore.md): An open-source vector database, focused on ease of use and performance, see [trychroma.com](https://www.trychroma.com/)
|
||||
- [MilvusVectorStore](../../../api/classes/MilvusVectorStore.md): An open-source, high-performance, highly scalable vector database, see [milvus.io](https://milvus.io/)
|
||||
- [MongoDBAtlasVectorSearch](../../../api/classes/MongoDBAtlasVectorSearch.md): A cloud-based vector search solution for MongoDB, see [mongodb.com](https://www.mongodb.com/products/platform/atlas-vector-search)
|
||||
- [PGVectorStore](../../../api/classes/PGVectorStore.md): An open-source vector store built on PostgreSQL, see [pgvector Github](https://github.com/pgvector/pgvector)
|
||||
- [PineconeVectorStore](../../../api/classes/PineconeVectorStore.md): A managed, cloud-native vector database, see [pinecone.io](https://www.pinecone.io/)
|
||||
- [WeaviateVectorStore](../../../api/classes/WeaviateVectorStore.md): An open-source, ai-native vector database, see [weaviate.io](https://weaviate.io/)
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [VectorStoreBase](../../../api/classes/VectorStoreBase.md)
|
||||
+3
-1
@@ -1,5 +1,7 @@
|
||||
# Qdrant Vector Store
|
||||
|
||||
[qdrant.tech](https://qdrant.tech/)
|
||||
|
||||
To run this example, you need to have a Qdrant instance running. You can run it with Docker:
|
||||
|
||||
```bash
|
||||
@@ -87,4 +89,4 @@ main().catch(console.error);
|
||||
|
||||
## API Reference
|
||||
|
||||
- [QdrantVectorStore](../../api/classes/QdrantVectorStore.md)
|
||||
- [QdrantVectorStore](../../../api/classes/QdrantVectorStore.md)
|
||||
@@ -1,7 +1,3 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# Documents and Nodes
|
||||
|
||||
`Document`s and `Node`s are the basic building blocks of any index. While the API for these objects is similar, `Document` objects represent entire files, while `Node`s are smaller pieces of that original document, that are suitable for an LLM and Q&A.
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Embeddings"
|
||||
position: 3
|
||||
position: 6
|
||||
|
||||
@@ -7,7 +7,7 @@ To find out more about the latest features, updates, and available models, visit
|
||||
## Table of Contents
|
||||
|
||||
1. [Setup](#setup)
|
||||
2. [Usage with LlamaIndex](#integration-with-llamaindex)
|
||||
2. [Usage with LlamaIndex](#usage-with-llamaindex)
|
||||
3. [Embeddings with Custom Parameters](#embeddings-with-custom-parameters)
|
||||
|
||||
## Setup
|
||||
|
||||
@@ -16,6 +16,16 @@ Settings.embedModel = new OpenAIEmbedding({
|
||||
|
||||
For local embeddings, you can use the [HuggingFace](./available_embeddings/huggingface.md) embedding model.
|
||||
|
||||
## Available Embeddings
|
||||
|
||||
Most available embeddings are listed in the sidebar on the left.
|
||||
Additionally the following integrations exist without separate documentation:
|
||||
|
||||
- [ClipEmbedding](../../api/classes/ClipEmbedding.md) using `@xenova/transformers`
|
||||
- [FireworksEmbedding](../../api/classes/FireworksEmbedding.md) see [fireworks.ai](https://fireworks.ai/)
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Evaluating"
|
||||
position: 3
|
||||
position: 9
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Ingestion Pipeline"
|
||||
position: 2
|
||||
position: 4
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "LLMs"
|
||||
position: 3
|
||||
position: 5
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Fireworks LLM
|
||||
|
||||
Fireworks.ai focus on production use cases for open source LLMs, offering speed and quality.
|
||||
[Fireworks.ai](https://fireworks.ai/) focus on production use cases for open source LLMs, offering speed and quality.
|
||||
|
||||
## Usage
|
||||
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Large Language Models (LLMs)
|
||||
|
||||
The LLM is responsible for reading text and generating natural language responses to queries. By default, LlamaIndex.TS uses `gpt-3.5-turbo`.
|
||||
@@ -30,6 +26,15 @@ export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
|
||||
|
||||
For local LLMs, currently we recommend the use of [Ollama](./available_llms/ollama.md) LLM.
|
||||
|
||||
## Available LLMs
|
||||
|
||||
Most available LLMs are listed in the sidebar on the left. Additionally the following integrations exist without separate documentation:
|
||||
|
||||
- [HuggingFaceLLM](../../api/classes/HuggingFaceLLM.md) and [HuggingFaceInferenceAPI](../../api/classes/HuggingFaceInferenceAPI.md).
|
||||
- [ReplicateLLM](../../api/classes/ReplicateLLM.md) see [replicate.com](https://replicate.com/)
|
||||
|
||||
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAI](../../api/classes/OpenAI.md)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
sidebar_position: 11
|
||||
---
|
||||
|
||||
# NodeParser
|
||||
|
||||
@@ -107,3 +107,4 @@ const filteredNodes = processor.postprocessNodes(nodes);
|
||||
## API Reference
|
||||
|
||||
- [SimilarityPostprocessor](../../api/classes/SimilarityPostprocessor.md)
|
||||
- [MetadataReplacementPostProcessor](../../api/classes/MetadataReplacementPostProcessor.md)
|
||||
|
||||
@@ -7,7 +7,7 @@ To find out more about the latest features and updates, visit the [mixedbread.ai
|
||||
## Table of Contents
|
||||
|
||||
1. [Setup](#setup)
|
||||
2. [Usage with LlamaIndex](#integration-with-llamaindex)
|
||||
2. [Usage with LlamaIndex](#usage-with-llamaindex)
|
||||
3. [Simple Reranking Guide](#simple-reranking-guide)
|
||||
4. [Reranking with Objects](#reranking-with-objects)
|
||||
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Prompts"
|
||||
position: 0
|
||||
position: 7
|
||||
|
||||
@@ -73,6 +73,5 @@ const response = await queryEngine.query({
|
||||
|
||||
## API Reference
|
||||
|
||||
- [TextQaPrompt](../../api/type-aliases/TextQaPrompt.md)
|
||||
- [ResponseSynthesizer](../../api/classes/ResponseSynthesizer.md)
|
||||
- [CompactAndRefine](../../api/classes/CompactAndRefine.md)
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
label: "Query Engines"
|
||||
position: 2
|
||||
position: 8
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 6
|
||||
sidebar_position: 15
|
||||
---
|
||||
|
||||
# ResponseSynthesizer
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 5
|
||||
sidebar_position: 14
|
||||
---
|
||||
|
||||
# Retriever
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
---
|
||||
sidebar_position: 7
|
||||
---
|
||||
|
||||
# Storage
|
||||
|
||||
Storage in LlamaIndex.TS works automatically once you've configured a `StorageContext` object. Just configure the `persistDir` and attach it to an index.
|
||||
|
||||
Right now, only saving and loading from disk is supported, with future integrations planned!
|
||||
|
||||
```typescript
|
||||
import { Document, VectorStoreIndex, storageContextFromDefaults } from "./src";
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
|
||||
const document = new Document({ text: "Test Text" });
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
storageContext,
|
||||
});
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [StorageContext](../api/interfaces/StorageContext.md)
|
||||
@@ -0,0 +1,168 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/workflow/joke.ts";
|
||||
|
||||
# Workflows
|
||||
|
||||
A `Workflow` in LlamaIndexTS is an event-driven abstraction used to chain together several events. Workflows are made up of `steps`, with each step responsible for handling certain event types and emitting new events.
|
||||
|
||||
Workflows in LlamaIndexTS work by defining step functions that handle specific event types and emit new events.
|
||||
|
||||
When a step function is added to a workflow, you need to specify the input and optionally the output event types (used for validation). The specification of the input events ensures each step only runs when an accepted event is ready.
|
||||
|
||||
You can create a `Workflow` to do anything! Build an agent, a RAG flow, an extraction flow, or anything else you want.
|
||||
|
||||
## Getting Started
|
||||
|
||||
As an illustrative example, let's consider a naive workflow where a joke is generated and then critiqued.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
There's a few moving pieces here, so let's go through this piece by piece.
|
||||
|
||||
### Defining Workflow Events
|
||||
|
||||
```typescript
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
```
|
||||
|
||||
Events are user-defined classes that extend `WorkflowEvent` and contain arbitrary data provided as template argument. In this case, our workflow relies on a single user-defined event, the `JokeEvent` with a `joke` attribute of type `string`.
|
||||
|
||||
### Setting up the Workflow Class
|
||||
|
||||
```typescript
|
||||
const llm = new OpenAI();
|
||||
...
|
||||
const jokeFlow = new Workflow({ verbose: true });
|
||||
```
|
||||
|
||||
Our workflow is implemented by initiating the `Workflow` class. For simplicity, we created a `OpenAI` llm instance.
|
||||
|
||||
### Workflow Entry Points
|
||||
|
||||
```typescript
|
||||
const generateJoke = async (_context: Context, ev: StartEvent) => {
|
||||
const prompt = `Write your best joke about ${ev.data.input}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
```
|
||||
|
||||
Here, we come to the entry-point of our workflow. While events are user-defined, there are two special-case events, the `StartEvent` and the `StopEvent`. Here, the `StartEvent` signifies where to send the initial workflow input.
|
||||
|
||||
The `StartEvent` is a bit of a special object since it can hold arbitrary attributes. Here, we accessed the topic with `ev.data.input`.
|
||||
|
||||
At this point, you may have noticed that we haven't explicitly told the workflow what events are handled by which steps.
|
||||
|
||||
To do so, we use the `addStep` method which adds a step to the workflow. The first argument is the event type that the step will handle, and the second argument is the previously defined step function:
|
||||
|
||||
```typescript
|
||||
jokeFlow.addStep(StartEvent, generateJoke);
|
||||
```
|
||||
|
||||
### Workflow Exit Points
|
||||
|
||||
```typescript
|
||||
const critiqueJoke = async (_context: Context, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent({ result: response.text });
|
||||
};
|
||||
```
|
||||
|
||||
Here, we have our second, and last step, in the workflow. We know its the last step because the special `StopEvent` is returned. When the workflow encounters a returned `StopEvent`, it immediately stops the workflow and returns whatever the result was.
|
||||
|
||||
In this case, the result is a string, but it could be a map, array, or any other object.
|
||||
|
||||
Don't forget to add the step to the workflow:
|
||||
|
||||
```typescript
|
||||
jokeFlow.addStep(JokeEvent, critiqueJoke);
|
||||
```
|
||||
|
||||
### Running the Workflow
|
||||
|
||||
```typescript
|
||||
const result = await jokeFlow.run("pirates");
|
||||
console.log(result.data.result);
|
||||
```
|
||||
|
||||
Lastly, we run the workflow. The `.run()` method is async, so we use await here to wait for the result.
|
||||
|
||||
### Validating Workflows
|
||||
|
||||
To tell the workflow what events are produced by each step, you can optionally provide a third argument to `addStep` to specify the output event type:
|
||||
|
||||
```typescript
|
||||
jokeFlow.addStep(StartEvent, generateJoke, { outputs: JokeEvent });
|
||||
jokeFlow.addStep(JokeEvent, critiqueJoke, { outputs: StopEvent });
|
||||
```
|
||||
|
||||
To validate a workflow, you need to call the `validate` method:
|
||||
|
||||
```typescript
|
||||
jokeFlow.validate();
|
||||
```
|
||||
|
||||
To automatically validate a workflow when you run it, you can set the `validate` flag to `true` at initialization:
|
||||
|
||||
```typescript
|
||||
const jokeFlow = new Workflow({ verbose: true, validate: true });
|
||||
```
|
||||
|
||||
## Working with Global Context/State
|
||||
|
||||
Optionally, you can choose to use global context between steps. For example, maybe multiple steps access the original `query` input from the user. You can store this in global context so that every step has access.
|
||||
|
||||
```typescript
|
||||
import { Context } from "@llamaindex/core/workflow";
|
||||
|
||||
const query = async (context: Context, ev: MyEvent) => {
|
||||
// get the query from the context
|
||||
const query = context.get("query");
|
||||
// do something with context and event
|
||||
const val = ...
|
||||
const result = ...
|
||||
// store in context
|
||||
context.set("key", val);
|
||||
|
||||
return new StopEvent({ result });
|
||||
};
|
||||
```
|
||||
|
||||
## Waiting for Multiple Events
|
||||
|
||||
The context does more than just hold data, it also provides utilities to buffer and wait for multiple events.
|
||||
|
||||
For example, you might have a step that waits for a query and retrieved nodes before synthesizing a response:
|
||||
|
||||
```typescript
|
||||
const synthesize = async (context: Context, ev: QueryEvent | RetrieveEvent) => {
|
||||
const events = context.collectEvents(ev, [QueryEvent | RetrieveEvent]);
|
||||
if (!events) {
|
||||
return;
|
||||
}
|
||||
const prompt = events
|
||||
.map((event) => {
|
||||
if (event instanceof QueryEvent) {
|
||||
return `Answer this query using the context provided: ${event.data.query}`;
|
||||
} else if (event instanceof RetrieveEvent) {
|
||||
return `Context: ${event.data.context}`;
|
||||
}
|
||||
return "";
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent({ result: response.text });
|
||||
};
|
||||
```
|
||||
|
||||
Using `ctx.collectEvents()` we can buffer and wait for ALL expected events to arrive. This function will only return events (in the requested order) once all events have arrived.
|
||||
|
||||
## Manually Triggering Events
|
||||
|
||||
Normally, events are triggered by returning another event during a step. However, events can also be manually dispatched using the `ctx.sendEvent(event)` method within a workflow.
|
||||
|
||||
## Examples
|
||||
|
||||
You can find many useful examples of using workflows in the [examples folder](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/workflow).
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "docs",
|
||||
"version": "0.0.66",
|
||||
"version": "0.0.88",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"docusaurus": "docusaurus",
|
||||
@@ -37,7 +37,7 @@
|
||||
"docusaurus-plugin-typedoc": "1.0.5",
|
||||
"typedoc": "0.26.6",
|
||||
"typedoc-plugin-markdown": "4.2.6",
|
||||
"typescript": "^5.5.4"
|
||||
"typescript": "^5.6.2"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": ["//"],
|
||||
"tasks": {
|
||||
"build": {
|
||||
"outputs": ["build/**", ".docusaurus/**"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
# examples
|
||||
|
||||
## 0.0.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 11feef8: Add workflows
|
||||
- Updated dependencies [11feef8]
|
||||
- @llamaindex/core@0.2.0
|
||||
- llamaindex@0.6.0
|
||||
|
||||
## 0.0.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -13,7 +13,7 @@ import { FunctionTool, OpenAI, ToolCallOptions } from "llamaindex";
|
||||
}
|
||||
})();
|
||||
|
||||
async function callLLM(init: Partial<OpenAI>) {
|
||||
async function callLLM(init: { model: string }) {
|
||||
const csvData =
|
||||
"Country,Average Height (cm)\nNetherlands,156\nDenmark,158\nNorway,160";
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Anthropic, SimpleChatEngine, SimpleChatHistory } from "llamaindex";
|
||||
import { Anthropic, ChatMemoryBuffer, SimpleChatEngine } from "llamaindex";
|
||||
import { stdin as input, stdout as output } from "node:process";
|
||||
import readline from "node:readline/promises";
|
||||
|
||||
@@ -8,8 +8,8 @@ import readline from "node:readline/promises";
|
||||
model: "claude-3-opus",
|
||||
});
|
||||
// chatHistory will store all the messages in the conversation
|
||||
const chatHistory = new SimpleChatHistory({
|
||||
messages: [
|
||||
const chatHistory = new ChatMemoryBuffer({
|
||||
chatHistory: [
|
||||
{
|
||||
content: "You want to talk in rhymes.",
|
||||
role: "system",
|
||||
@@ -18,7 +18,7 @@ import readline from "node:readline/promises";
|
||||
});
|
||||
const chatEngine = new SimpleChatEngine({
|
||||
llm,
|
||||
chatHistory,
|
||||
memory: chatHistory,
|
||||
});
|
||||
const rl = readline.createInterface({ input, output });
|
||||
|
||||
|
||||
@@ -2,10 +2,10 @@ import { stdin as input, stdout as output } from "node:process";
|
||||
import readline from "node:readline/promises";
|
||||
|
||||
import {
|
||||
ChatSummaryMemoryBuffer,
|
||||
OpenAI,
|
||||
Settings,
|
||||
SimpleChatEngine,
|
||||
SummaryChatHistory,
|
||||
} from "llamaindex";
|
||||
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
@@ -18,7 +18,7 @@ async function main() {
|
||||
// Set maxTokens to 75% of the context window size of 4096
|
||||
// This will trigger the summarizer once the chat history reaches 25% of the context window size (1024 tokens)
|
||||
const llm = new OpenAI({ model: "gpt-3.5-turbo", maxTokens: 4096 * 0.75 });
|
||||
const chatHistory = new SummaryChatHistory({ llm });
|
||||
const chatHistory = new ChatSummaryMemoryBuffer({ llm });
|
||||
const chatEngine = new SimpleChatEngine({ llm });
|
||||
const rl = readline.createInterface({ input, output });
|
||||
|
||||
|
||||
+12
-1
@@ -1,12 +1,23 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import { Document, Groq, Settings, VectorStoreIndex } from "llamaindex";
|
||||
import {
|
||||
Document,
|
||||
Groq,
|
||||
HuggingFaceEmbedding,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update llm to use Groq
|
||||
Settings.llm = new Groq({
|
||||
apiKey: process.env.GROQ_API_KEY,
|
||||
});
|
||||
|
||||
// Use HuggingFace for embeddings
|
||||
Settings.embedModel = new HuggingFaceEmbedding({
|
||||
modelType: "Xenova/all-mpnet-base-v2",
|
||||
});
|
||||
|
||||
async function main() {
|
||||
// Load essay from abramov.txt in Node
|
||||
const path = "node_modules/llamaindex/examples/abramov.txt";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
Document,
|
||||
getResponseSynthesizer,
|
||||
NodeWithScore,
|
||||
ResponseSynthesizer,
|
||||
SentenceSplitter,
|
||||
TextNode,
|
||||
} from "llamaindex";
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
|
||||
console.log(nodes);
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer();
|
||||
const responseSynthesizer = getResponseSynthesizer("compact");
|
||||
|
||||
const nodesWithScore: NodeWithScore[] = [
|
||||
{
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
const stream = await responseSynthesizer.synthesize(
|
||||
{
|
||||
query: "What age am I?",
|
||||
nodesWithScore,
|
||||
nodes: nodesWithScore,
|
||||
},
|
||||
true,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
Document,
|
||||
MetadataFilters,
|
||||
Settings,
|
||||
SimpleDocumentStore,
|
||||
VectorStoreIndex,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function getDataSource() {
|
||||
const docs = [
|
||||
new Document({ text: "The dog is brown", metadata: { dogId: "1" } }),
|
||||
new Document({ text: "The dog is yellow", metadata: { dogId: "2" } }),
|
||||
];
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./cache",
|
||||
});
|
||||
const numberOfDocs = Object.keys(
|
||||
(storageContext.docStore as SimpleDocumentStore).toDict(),
|
||||
).length;
|
||||
if (numberOfDocs === 0) {
|
||||
return await VectorStoreIndex.fromDocuments(docs, { storageContext });
|
||||
}
|
||||
return await VectorStoreIndex.init({
|
||||
storageContext,
|
||||
});
|
||||
}
|
||||
|
||||
Settings.callbackManager.on("retrieve-end", (event) => {
|
||||
const { nodes, query } = event.detail;
|
||||
console.log(`${query.query} - Number of retrieved nodes:`, nodes.length);
|
||||
});
|
||||
|
||||
async function main() {
|
||||
const index = await getDataSource();
|
||||
const filters: MetadataFilters = {
|
||||
filters: [{ key: "dogId", value: "2", operator: "==" }],
|
||||
};
|
||||
|
||||
const retriever = index.asRetriever({ similarityTopK: 3, filters });
|
||||
const queryEngine = index.asQueryEngine({
|
||||
similarityTopK: 3,
|
||||
preFilters: filters,
|
||||
});
|
||||
|
||||
console.log("Retriever and query engine should only retrieve 1 node:");
|
||||
await retriever.retrieve({ query: "Retriever: get dog" });
|
||||
await queryEngine.query({ query: "QueryEngine: get dog" });
|
||||
}
|
||||
|
||||
void main();
|
||||
@@ -1,4 +1,5 @@
|
||||
// call pnpm tsx multimodal/load.ts first to init the storage
|
||||
import { extractText } from "@llamaindex/core/utils";
|
||||
import {
|
||||
ContextChatEngine,
|
||||
NodeWithScore,
|
||||
@@ -25,8 +26,9 @@ Settings.callbackManager.on("retrieve-end", (event) => {
|
||||
const textNodes = nodes.filter(
|
||||
(node: NodeWithScore) => node.node.type === ObjectType.TEXT,
|
||||
);
|
||||
const text = extractText(query);
|
||||
console.log(
|
||||
`Retrieved ${textNodes.length} text nodes and ${imageNodes.length} image nodes for query: ${query}`,
|
||||
`Retrieved ${textNodes.length} text nodes and ${imageNodes.length} image nodes for query: ${text}`,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { extractText } from "@llamaindex/core/utils";
|
||||
import {
|
||||
MultiModalResponseSynthesizer,
|
||||
getResponseSynthesizer,
|
||||
OpenAI,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
@@ -16,7 +17,8 @@ Settings.llm = new OpenAI({ model: "gpt-4-turbo", maxTokens: 512 });
|
||||
// Update callbackManager
|
||||
Settings.callbackManager.on("retrieve-end", (event) => {
|
||||
const { nodes, query } = event.detail;
|
||||
console.log(`Retrieved ${nodes.length} nodes for query: ${query}`);
|
||||
const text = extractText(query);
|
||||
console.log(`Retrieved ${nodes.length} nodes for query: ${text}`);
|
||||
});
|
||||
|
||||
async function main() {
|
||||
@@ -27,7 +29,7 @@ async function main() {
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
responseSynthesizer: new MultiModalResponseSynthesizer(),
|
||||
responseSynthesizer: getResponseSynthesizer("multi_modal"),
|
||||
retriever: index.asRetriever({ topK: { TEXT: 3, IMAGE: 1 } }),
|
||||
});
|
||||
const stream = await queryEngine.query({
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { OpenAI } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
const llm = new OpenAI({ model: "o1-preview", temperature: 1 });
|
||||
|
||||
const prompt = `What are three compounds we should consider investigating to advance research
|
||||
into new antibiotics? Why should we consider them?
|
||||
`;
|
||||
|
||||
// complete api
|
||||
const response = await llm.complete({ prompt });
|
||||
console.log(response.text);
|
||||
})();
|
||||
@@ -1,27 +1,29 @@
|
||||
{
|
||||
"name": "@llamaindex/examples",
|
||||
"private": true,
|
||||
"version": "0.0.7",
|
||||
"version": "0.0.8",
|
||||
"dependencies": {
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@azure/identity": "^4.4.1",
|
||||
"@datastax/astra-db-ts": "^1.4.1",
|
||||
"@llamaindex/core": "^0.1.0",
|
||||
"@llamaindex/core": "^0.2.0",
|
||||
"@notionhq/client": "^2.2.15",
|
||||
"@pinecone-database/pinecone": "^3.0.2",
|
||||
"@vercel/postgres": "^0.10.0",
|
||||
"@zilliz/milvus2-sdk-node": "^2.4.6",
|
||||
"chromadb": "^1.8.1",
|
||||
"commander": "^12.1.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"js-tiktoken": "^1.0.14",
|
||||
"llamaindex": "^0.5.0",
|
||||
"llamaindex": "^0.6.0",
|
||||
"mongodb": "^6.7.0",
|
||||
"pathe": "^1.1.2"
|
||||
"pathe": "^1.1.2",
|
||||
"postgres": "^3.4.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.5.1",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.5.4"
|
||||
"typescript": "^5.6.2"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint ."
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import {
|
||||
Document,
|
||||
getResponseSynthesizer,
|
||||
PromptTemplate,
|
||||
ResponseSynthesizer,
|
||||
TreeSummarize,
|
||||
TreeSummarizePrompt,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
@@ -27,9 +26,7 @@ async function main() {
|
||||
|
||||
const query = "The quick brown fox jumps over the lazy dog";
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new TreeSummarize(),
|
||||
});
|
||||
const responseSynthesizer = getResponseSynthesizer("tree_summarize");
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
responseSynthesizer,
|
||||
|
||||
@@ -39,6 +39,12 @@ async function main() {
|
||||
dogId: "2",
|
||||
},
|
||||
}),
|
||||
new Document({
|
||||
text: "The dog is black",
|
||||
metadata: {
|
||||
dogId: "3",
|
||||
},
|
||||
}),
|
||||
];
|
||||
console.log("Creating QdrantDB vector store");
|
||||
const qdrantVs = new QdrantVectorStore({ url: qdrantUrl, collectionName });
|
||||
@@ -73,6 +79,42 @@ async function main() {
|
||||
query: "What is the color of the dog?",
|
||||
});
|
||||
console.log("Filter with dogId 2 response:", response.toString());
|
||||
|
||||
console.log("Querying index with dogId !=2: Expected output: Not red");
|
||||
const queryEngineNotDogId2 = index.asQueryEngine({
|
||||
preFilters: {
|
||||
filters: [
|
||||
{
|
||||
key: "dogId",
|
||||
value: "2",
|
||||
operator: "!=",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const responseNotDogId2 = await queryEngineNotDogId2.query({
|
||||
query: "What is the color of the dog?",
|
||||
});
|
||||
console.log(responseNotDogId2.toString());
|
||||
|
||||
console.log(
|
||||
"Querying index with dogId 2 or 3: Expected output: Red, Black",
|
||||
);
|
||||
const queryEngineIn = index.asQueryEngine({
|
||||
preFilters: {
|
||||
filters: [
|
||||
{
|
||||
key: "dogId",
|
||||
value: ["2", "3"],
|
||||
operator: "in",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const responseIn = await queryEngineIn.query({
|
||||
query: "List all dogs",
|
||||
});
|
||||
console.log(responseIn.toString());
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
@@ -23,6 +23,6 @@
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.5.1",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.5.4"
|
||||
"typescript": "^5.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import {
|
||||
CompactAndRefine,
|
||||
getResponseSynthesizer,
|
||||
OpenAI,
|
||||
PromptTemplate,
|
||||
ResponseSynthesizer,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
@@ -29,8 +28,8 @@ Given the CSV file, generate me Typescript code to answer the question: {query}.
|
||||
`,
|
||||
});
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new CompactAndRefine(undefined, csvPrompt),
|
||||
const responseSynthesizer = getResponseSynthesizer("compact", {
|
||||
textQATemplate: csvPrompt,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine({ responseSynthesizer });
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createMessageContent } from "@llamaindex/core/response-synthesizers";
|
||||
import {
|
||||
Document,
|
||||
ImageNode,
|
||||
@@ -6,7 +7,6 @@ import {
|
||||
PromptTemplate,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
import { createMessageContent } from "llamaindex/synthesizers/utils";
|
||||
|
||||
const reader = new LlamaParseReader();
|
||||
async function main() {
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# neon template
|
||||
PGHOST=
|
||||
PGDATABASE=
|
||||
PGUSER=
|
||||
PGPASSWORD=
|
||||
ENDPOINT_ID=
|
||||
|
||||
# vercel template
|
||||
POSTGRES_URL=
|
||||
@@ -1,11 +1,11 @@
|
||||
// load-docs.ts
|
||||
import fs from "fs/promises";
|
||||
import {
|
||||
PGVectorStore,
|
||||
SimpleDirectoryReader,
|
||||
storageContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
async function getSourceFilenames(sourceDir: string) {
|
||||
return await fs
|
||||
@@ -40,7 +40,11 @@ async function main(args: any) {
|
||||
const rdr = new SimpleDirectoryReader(callback);
|
||||
const docs = await rdr.loadData({ directoryPath: sourceDir });
|
||||
|
||||
const pgvs = new PGVectorStore();
|
||||
const pgvs = new PGVectorStore({
|
||||
clientConfig: {
|
||||
connectionString: process.env.PG_CONNECTION_STRING,
|
||||
},
|
||||
});
|
||||
pgvs.setCollection(sourceDir);
|
||||
await pgvs.clearCollection();
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/* eslint-disable turbo/no-undeclared-env-vars */
|
||||
import dotenv from "dotenv";
|
||||
import { Document, PGVectorStore, VectorStoreQueryMode } from "llamaindex";
|
||||
import postgres from "postgres";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
const { PGHOST, PGDATABASE, PGUSER, ENDPOINT_ID } = process.env;
|
||||
const PGPASSWORD = decodeURIComponent(process.env.PGPASSWORD!);
|
||||
|
||||
const sql = postgres({
|
||||
host: PGHOST,
|
||||
database: PGDATABASE,
|
||||
username: PGUSER,
|
||||
password: PGPASSWORD,
|
||||
port: 5432,
|
||||
ssl: "require",
|
||||
connection: {
|
||||
options: `project=${ENDPOINT_ID}`,
|
||||
},
|
||||
});
|
||||
|
||||
await sql`CREATE EXTENSION IF NOT EXISTS vector`;
|
||||
|
||||
const vectorStore = new PGVectorStore({
|
||||
dimensions: 3,
|
||||
client: sql,
|
||||
});
|
||||
|
||||
await vectorStore.add([
|
||||
new Document({
|
||||
text: "hello, world",
|
||||
embedding: [1, 2, 3],
|
||||
}),
|
||||
]);
|
||||
|
||||
const results = await vectorStore.query({
|
||||
mode: VectorStoreQueryMode.DEFAULT,
|
||||
similarityTopK: 1,
|
||||
queryEmbedding: [1, 2, 3],
|
||||
});
|
||||
|
||||
console.log("result", results);
|
||||
|
||||
await sql.end();
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "pg-vector-store",
|
||||
"type": "module",
|
||||
"private": true
|
||||
}
|
||||
@@ -7,7 +7,11 @@ async function main() {
|
||||
});
|
||||
|
||||
try {
|
||||
const pgvs = new PGVectorStore();
|
||||
const pgvs = new PGVectorStore({
|
||||
clientConfig: {
|
||||
connectionString: process.env.PG_CONNECTION_STRING,
|
||||
},
|
||||
});
|
||||
// Optional - set your collection name, default is no filter on this field.
|
||||
// pgvs.setCollection();
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["./**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// https://vercel.com/docs/storage/vercel-postgres/sdk
|
||||
import { sql } from "@vercel/postgres";
|
||||
import dotenv from "dotenv";
|
||||
import { Document, PGVectorStore, VectorStoreQueryMode } from "llamaindex";
|
||||
|
||||
dotenv.config();
|
||||
|
||||
await sql`CREATE EXTENSION IF NOT EXISTS vector`;
|
||||
|
||||
const vectorStore = new PGVectorStore({
|
||||
dimensions: 3,
|
||||
client: sql,
|
||||
});
|
||||
|
||||
await vectorStore.add([
|
||||
new Document({
|
||||
text: "hello, world",
|
||||
embedding: [1, 2, 3],
|
||||
}),
|
||||
]);
|
||||
|
||||
const results = await vectorStore.query({
|
||||
mode: VectorStoreQueryMode.DEFAULT,
|
||||
similarityTopK: 1,
|
||||
queryEmbedding: [1, 2, 3],
|
||||
});
|
||||
|
||||
console.log("result", results);
|
||||
|
||||
await sql.end();
|
||||
@@ -2,12 +2,10 @@ import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Anthropic,
|
||||
CompactAndRefine,
|
||||
Document,
|
||||
ResponseSynthesizer,
|
||||
Settings,
|
||||
VectorStoreIndex,
|
||||
anthropicTextQaPrompt,
|
||||
getResponseSynthesizer,
|
||||
} from "llamaindex";
|
||||
|
||||
// Update llm to use Anthropic
|
||||
@@ -23,9 +21,7 @@ async function main() {
|
||||
const document = new Document({ text: essay, id_: path });
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new CompactAndRefine(undefined, anthropicTextQaPrompt),
|
||||
});
|
||||
const responseSynthesizer = getResponseSynthesizer("compact");
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
|
||||
@@ -25,12 +25,9 @@ async function main() {
|
||||
similarityCutoff: 0.7,
|
||||
});
|
||||
// TODO: cannot pass responseSynthesizer into retriever query engine
|
||||
const queryEngine = new RetrieverQueryEngine(
|
||||
retriever,
|
||||
undefined,
|
||||
undefined,
|
||||
[nodePostprocessor],
|
||||
);
|
||||
const queryEngine = new RetrieverQueryEngine(retriever, undefined, [
|
||||
nodePostprocessor,
|
||||
]);
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do growing up?",
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import {
|
||||
getResponseSynthesizer,
|
||||
OpenAI,
|
||||
OpenAIEmbedding,
|
||||
ResponseSynthesizer,
|
||||
RetrieverQueryEngine,
|
||||
Settings,
|
||||
TextNode,
|
||||
TreeSummarize,
|
||||
VectorIndexRetriever,
|
||||
VectorStore,
|
||||
VectorStoreIndex,
|
||||
@@ -165,13 +164,8 @@ async function main() {
|
||||
similarityTopK: 500,
|
||||
});
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new TreeSummarize(),
|
||||
});
|
||||
|
||||
return new RetrieverQueryEngine(retriever, responseSynthesizer, {
|
||||
filter,
|
||||
});
|
||||
const responseSynthesizer = getResponseSynthesizer("tree_summarize");
|
||||
return new RetrieverQueryEngine(retriever, responseSynthesizer);
|
||||
};
|
||||
|
||||
// whatever is a key from your metadata
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
# Workflow Examples
|
||||
|
||||
These examples demonstrate LlamaIndexTS's workflow system. Check out [its documentation](https://ts.llamaindex.ai/modules/workflows) for more information.
|
||||
|
||||
## Running the Examples
|
||||
|
||||
To run the examples, make sure to run them from the parent folder called `examples`). For example, to run the joke workflow, run `npx tsx workflow/joke.ts`.
|
||||
@@ -0,0 +1,122 @@
|
||||
import {
|
||||
Context,
|
||||
StartEvent,
|
||||
StopEvent,
|
||||
Workflow,
|
||||
WorkflowEvent,
|
||||
} from "@llamaindex/core/workflow";
|
||||
import { OpenAI } from "llamaindex";
|
||||
|
||||
const MAX_REVIEWS = 3;
|
||||
|
||||
// Using the o1-preview model (see https://platform.openai.com/docs/guides/reasoning?reasoning-prompt-examples=coding-planning)
|
||||
const llm = new OpenAI({ model: "o1-preview", temperature: 1 });
|
||||
|
||||
// example specification from https://platform.openai.com/docs/guides/reasoning?reasoning-prompt-examples=coding-planning
|
||||
const specification = `Python app that takes user questions and looks them up in a
|
||||
database where they are mapped to answers. If there is a close match, it retrieves
|
||||
the matched answer. If there isn't, it asks the user to provide an answer and
|
||||
stores the question/answer pair in the database.`;
|
||||
|
||||
// Create custom event types
|
||||
export class MessageEvent extends WorkflowEvent<{ msg: string }> {}
|
||||
export class CodeEvent extends WorkflowEvent<{ code: string }> {}
|
||||
export class ReviewEvent extends WorkflowEvent<{
|
||||
review: string;
|
||||
code: string;
|
||||
}> {}
|
||||
|
||||
// Helper function to truncate long strings
|
||||
const truncate = (str: string) => {
|
||||
const MAX_LENGTH = 60;
|
||||
if (str.length <= MAX_LENGTH) return str;
|
||||
return str.slice(0, MAX_LENGTH) + "...";
|
||||
};
|
||||
|
||||
// the architect is responsible for writing the structure and the initial code based on the specification
|
||||
const architect = async (context: Context, ev: StartEvent) => {
|
||||
// get the specification from the start event and save it to context
|
||||
context.set("specification", ev.data.input);
|
||||
const spec = context.get("specification");
|
||||
// write a message to send an update to the user
|
||||
context.writeEventToStream(
|
||||
new MessageEvent({
|
||||
msg: `Writing app using this specification: ${truncate(spec)}`,
|
||||
}),
|
||||
);
|
||||
const prompt = `Build an app for this specification: <spec>${spec}</spec>. Make a plan for the directory structure you'll need, then return each file in full. Don't supply any reasoning, just code.`;
|
||||
const code = await llm.complete({ prompt });
|
||||
return new CodeEvent({ code: code.text });
|
||||
};
|
||||
|
||||
// the coder is responsible for updating the code based on the review
|
||||
const coder = async (context: Context, ev: ReviewEvent) => {
|
||||
// get the specification from the context
|
||||
const spec = context.get("specification");
|
||||
// get the latest review and code
|
||||
const { review, code } = ev.data;
|
||||
// write a message to send an update to the user
|
||||
context.writeEventToStream(
|
||||
new MessageEvent({
|
||||
msg: `Update code based on review: ${truncate(review)}`,
|
||||
}),
|
||||
);
|
||||
const prompt = `We need to improve code that should implement this specification: <spec>${spec}</spec>. Here is the current code: <code>${code}</code>. And here is a review of the code: <review>${review}</review>. Improve the code based on the review, keep the specification in mind, and return the full updated code. Don't supply any reasoning, just code.`;
|
||||
const updatedCode = await llm.complete({ prompt });
|
||||
return new CodeEvent({ code: updatedCode.text });
|
||||
};
|
||||
|
||||
// the reviewer is responsible for reviewing the code and providing feedback
|
||||
const reviewer = async (context: Context, ev: CodeEvent) => {
|
||||
// get the specification from the context
|
||||
const spec = context.get("specification");
|
||||
// get latest code from the event
|
||||
const { code } = ev.data;
|
||||
// update and check the number of reviews
|
||||
const numberReviews = context.get("numberReviews", 0) + 1;
|
||||
context.set("numberReviews", numberReviews);
|
||||
if (numberReviews > MAX_REVIEWS) {
|
||||
// the we've done this too many times - return the code
|
||||
context.writeEventToStream(
|
||||
new MessageEvent({
|
||||
msg: `Already reviewed ${numberReviews - 1} times, stopping!`,
|
||||
}),
|
||||
);
|
||||
return new StopEvent({ result: code });
|
||||
}
|
||||
// write a message to send an update to the user
|
||||
context.writeEventToStream(
|
||||
new MessageEvent({ msg: `Review #${numberReviews}: ${truncate(code)}` }),
|
||||
);
|
||||
const prompt = `Review this code: <code>${code}</code>. Check if the code quality and whether it correctly implements this specification: <spec>${spec}</spec>. If you're satisfied, just return 'Looks great', nothing else. If not, return a review with a list of changes you'd like to see.`;
|
||||
const review = (await llm.complete({ prompt })).text;
|
||||
if (review.includes("Looks great")) {
|
||||
// the reviewer is satisfied with the code, let's return the review
|
||||
context.writeEventToStream(
|
||||
new MessageEvent({
|
||||
msg: `Reviewer says: ${review}`,
|
||||
}),
|
||||
);
|
||||
return new StopEvent({ result: code });
|
||||
}
|
||||
|
||||
return new ReviewEvent({ review, code });
|
||||
};
|
||||
|
||||
const codeAgent = new Workflow({ validate: true });
|
||||
codeAgent.addStep(StartEvent, architect, { outputs: CodeEvent });
|
||||
codeAgent.addStep(ReviewEvent, coder, { outputs: CodeEvent });
|
||||
codeAgent.addStep(CodeEvent, reviewer, { outputs: ReviewEvent });
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
const run = codeAgent.run(specification);
|
||||
for await (const event of codeAgent.streamEvents()) {
|
||||
const msg = (event as MessageEvent).data.msg;
|
||||
console.log(`${msg}\n`);
|
||||
}
|
||||
const result = await run;
|
||||
console.log("Final code:\n", result.data.result);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
Context,
|
||||
StartEvent,
|
||||
StopEvent,
|
||||
Workflow,
|
||||
WorkflowEvent,
|
||||
} from "@llamaindex/core/workflow";
|
||||
import { OpenAI } from "llamaindex";
|
||||
|
||||
// Create LLM instance
|
||||
const llm = new OpenAI();
|
||||
|
||||
// Create custom event types
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
export class CritiqueEvent extends WorkflowEvent<{ critique: string }> {}
|
||||
export class AnalysisEvent extends WorkflowEvent<{ analysis: string }> {}
|
||||
|
||||
const generateJoke = async (_context: Context, ev: StartEvent) => {
|
||||
const prompt = `Write your best joke about ${ev.data.input}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
|
||||
const critiqueJoke = async (_context: Context, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new CritiqueEvent({ critique: response.text });
|
||||
};
|
||||
|
||||
const analyzeJoke = async (_context: Context, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough analysis of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new AnalysisEvent({ analysis: response.text });
|
||||
};
|
||||
|
||||
const reportJoke = async (
|
||||
context: Context,
|
||||
ev: AnalysisEvent | CritiqueEvent,
|
||||
) => {
|
||||
const events = context.collectEvents(ev, [AnalysisEvent, CritiqueEvent]);
|
||||
if (!events) {
|
||||
return;
|
||||
}
|
||||
const subPrompts = events.map((event) => {
|
||||
if (event instanceof AnalysisEvent) {
|
||||
return `Analysis: ${event.data.analysis}`;
|
||||
} else if (event instanceof CritiqueEvent) {
|
||||
return `Critique: ${event.data.critique}`;
|
||||
}
|
||||
return "";
|
||||
});
|
||||
|
||||
const prompt = `Based on the following information about a joke:\n${subPrompts.join("\n")}\nProvide a comprehensive report on the joke's quality and impact.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent({ result: response.text });
|
||||
};
|
||||
|
||||
const jokeFlow = new Workflow();
|
||||
jokeFlow.addStep(StartEvent, generateJoke);
|
||||
jokeFlow.addStep(JokeEvent, critiqueJoke);
|
||||
jokeFlow.addStep(JokeEvent, analyzeJoke);
|
||||
jokeFlow.addStep([AnalysisEvent, CritiqueEvent], reportJoke);
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
const result = await jokeFlow.run("pirates");
|
||||
console.log(result.data.result);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
Context,
|
||||
StartEvent,
|
||||
StopEvent,
|
||||
Workflow,
|
||||
WorkflowEvent,
|
||||
} from "@llamaindex/core/workflow";
|
||||
import { OpenAI } from "llamaindex";
|
||||
|
||||
// Create LLM instance
|
||||
const llm = new OpenAI();
|
||||
|
||||
// Create a custom event type
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
|
||||
const generateJoke = async (_context: Context, ev: StartEvent) => {
|
||||
const prompt = `Write your best joke about ${ev.data.input}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
|
||||
const critiqueJoke = async (_context: Context, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent({ result: response.text });
|
||||
};
|
||||
|
||||
const jokeFlow = new Workflow({ verbose: true });
|
||||
jokeFlow.addStep(StartEvent, generateJoke);
|
||||
jokeFlow.addStep(JokeEvent, critiqueJoke);
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
const result = await jokeFlow.run("pirates");
|
||||
console.log(result.data.result);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
Context,
|
||||
StartEvent,
|
||||
StopEvent,
|
||||
Workflow,
|
||||
WorkflowEvent,
|
||||
} from "@llamaindex/core/workflow";
|
||||
import { OpenAI } from "llamaindex";
|
||||
|
||||
// Create LLM instance
|
||||
const llm = new OpenAI();
|
||||
|
||||
// Create custom event types
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
export class MessageEvent extends WorkflowEvent<{ msg: string }> {}
|
||||
|
||||
const generateJoke = async (context: Context, ev: StartEvent) => {
|
||||
context.writeEventToStream(
|
||||
new MessageEvent({ msg: `Generating a joke about: ${ev.data.input}` }),
|
||||
);
|
||||
const prompt = `Write your best joke about ${ev.data.input}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
|
||||
const critiqueJoke = async (context: Context, ev: JokeEvent) => {
|
||||
context.writeEventToStream(
|
||||
new MessageEvent({ msg: `Write a critique of this joke: ${ev.data.joke}` }),
|
||||
);
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent({ result: response.text });
|
||||
};
|
||||
|
||||
const jokeFlow = new Workflow();
|
||||
jokeFlow.addStep(StartEvent, generateJoke);
|
||||
jokeFlow.addStep(JokeEvent, critiqueJoke);
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
const run = jokeFlow.run("pirates");
|
||||
for await (const event of jokeFlow.streamEvents()) {
|
||||
console.log((event as MessageEvent).data.msg);
|
||||
}
|
||||
const result = await run;
|
||||
console.log(result.data.result);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,37 @@
|
||||
import {
|
||||
Context,
|
||||
StartEvent,
|
||||
StopEvent,
|
||||
Workflow,
|
||||
} from "@llamaindex/core/workflow";
|
||||
|
||||
const longRunning = async (_context: Context, ev: StartEvent) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000)); // Wait for 2 seconds
|
||||
return new StopEvent({ result: "We waited 2 seconds" });
|
||||
};
|
||||
|
||||
async function timeout() {
|
||||
const workflow = new Workflow({ verbose: true, timeout: 1 });
|
||||
workflow.addStep(StartEvent, longRunning);
|
||||
// This will timeout
|
||||
try {
|
||||
await workflow.run("Let's start");
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function notimeout() {
|
||||
// Increase timeout to 3 seconds - no timeout
|
||||
const workflow = new Workflow({ verbose: true, timeout: 3 });
|
||||
workflow.addStep(StartEvent, longRunning);
|
||||
const result = await workflow.run("Let's start");
|
||||
console.log(result.data.result);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
await timeout();
|
||||
await notimeout();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
Context,
|
||||
StartEvent,
|
||||
StopEvent,
|
||||
Workflow,
|
||||
WorkflowEvent,
|
||||
} from "@llamaindex/core/workflow";
|
||||
import { OpenAI } from "llamaindex";
|
||||
|
||||
// Create LLM instance
|
||||
const llm = new OpenAI();
|
||||
|
||||
// Create a custom event type
|
||||
export class JokeEvent extends WorkflowEvent<{ joke: string }> {}
|
||||
|
||||
const generateJoke = async (_context: Context, ev: StartEvent) => {
|
||||
const prompt = `Write your best joke about ${ev.data.input}.`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new JokeEvent({ joke: response.text });
|
||||
};
|
||||
|
||||
const critiqueJoke = async (_context: Context, ev: JokeEvent) => {
|
||||
const prompt = `Give a thorough critique of the following joke: ${ev.data.joke}`;
|
||||
const response = await llm.complete({ prompt });
|
||||
return new StopEvent({ result: response.text });
|
||||
};
|
||||
|
||||
async function validateFails() {
|
||||
try {
|
||||
const jokeFlow = new Workflow({ verbose: true, validate: true });
|
||||
jokeFlow.addStep(StartEvent, generateJoke, { outputs: StopEvent });
|
||||
jokeFlow.addStep(JokeEvent, critiqueJoke, { outputs: StopEvent });
|
||||
await jokeFlow.run("pirates");
|
||||
} catch (e) {
|
||||
console.error("Validation failed:", e);
|
||||
}
|
||||
}
|
||||
|
||||
async function validate() {
|
||||
const jokeFlow = new Workflow({ verbose: true, validate: true });
|
||||
jokeFlow.addStep(StartEvent, generateJoke, { outputs: JokeEvent });
|
||||
jokeFlow.addStep(JokeEvent, critiqueJoke, { outputs: StopEvent });
|
||||
const result = await jokeFlow.run("pirates");
|
||||
console.log(result.data.result);
|
||||
}
|
||||
|
||||
// Usage
|
||||
async function main() {
|
||||
await validateFails();
|
||||
await validate();
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
+6
-5
@@ -2,9 +2,9 @@
|
||||
"name": "@llamaindex/monorepo",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"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",
|
||||
"build": "turbo run build",
|
||||
"build:release": "turbo run build --filter=\"./packages/*\"",
|
||||
"dev": "turbo run dev --filter=\"./packages/*\"",
|
||||
"format": "prettier --ignore-unknown --cache --check .",
|
||||
"format:write": "prettier --ignore-unknown --write .",
|
||||
"lint": "turbo run lint",
|
||||
@@ -12,6 +12,7 @@
|
||||
"e2e": "turbo run e2e",
|
||||
"test": "turbo run test",
|
||||
"type-check": "tsc -b --diagnostics",
|
||||
"circular-check": "madge --circular ./packages/**/**/dist/index.js",
|
||||
"release": "pnpm run build:release && changeset publish",
|
||||
"release-snapshot": "pnpm run build:release && changeset publish --tag snapshot",
|
||||
"new-version": "changeset version && pnpm format:write && pnpm run build:release",
|
||||
@@ -30,8 +31,8 @@
|
||||
"madge": "^8.0.0",
|
||||
"prettier": "^3.3.3",
|
||||
"prettier-plugin-organize-imports": "^4.0.0",
|
||||
"turbo": "^2.1.0",
|
||||
"typescript": "^5.5.4"
|
||||
"turbo": "^2.1.2",
|
||||
"typescript": "^5.6.2"
|
||||
},
|
||||
"packageManager": "pnpm@9.5.0",
|
||||
"pnpm": {
|
||||
|
||||
@@ -1,5 +1,161 @@
|
||||
# @llamaindex/autotool
|
||||
|
||||
## 3.0.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [62cba52]
|
||||
- Updated dependencies [d265e96]
|
||||
- Updated dependencies [d30bbf7]
|
||||
- Updated dependencies [53fd00a]
|
||||
- llamaindex@0.6.19
|
||||
|
||||
## 3.0.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [5f67820]
|
||||
- Updated dependencies [fe08d04]
|
||||
- llamaindex@0.6.18
|
||||
|
||||
## 3.0.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ee697fb]
|
||||
- llamaindex@0.6.17
|
||||
|
||||
## 3.0.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [63e9846]
|
||||
- Updated dependencies [6f3a31c]
|
||||
- llamaindex@0.6.16
|
||||
|
||||
## 3.0.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2a82413]
|
||||
- llamaindex@0.6.15
|
||||
|
||||
## 3.0.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.14
|
||||
|
||||
## 3.0.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.13
|
||||
|
||||
## 3.0.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [f7b4e94]
|
||||
- Updated dependencies [78037a6]
|
||||
- Updated dependencies [1d9e3b1]
|
||||
- llamaindex@0.6.12
|
||||
|
||||
## 3.0.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- df441e2: fix: consoleLogger is missing from `@llamaindex/env`
|
||||
- Updated dependencies [df441e2]
|
||||
- llamaindex@0.6.11
|
||||
|
||||
## 3.0.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ebc5105]
|
||||
- Updated dependencies [6cce3b1]
|
||||
- llamaindex@0.6.10
|
||||
|
||||
## 3.0.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.9
|
||||
|
||||
## 3.0.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [8b7fdba]
|
||||
- llamaindex@0.6.8
|
||||
|
||||
## 3.0.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [23bcc37]
|
||||
- llamaindex@0.6.7
|
||||
|
||||
## 3.0.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d902cc3]
|
||||
- Updated dependencies [025ffe6]
|
||||
- Updated dependencies [a659574]
|
||||
- llamaindex@0.6.6
|
||||
|
||||
## 3.0.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [e9714db]
|
||||
- llamaindex@0.6.5
|
||||
|
||||
## 3.0.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [b48bcc3]
|
||||
- llamaindex@0.6.4
|
||||
|
||||
## 3.0.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2cd1383]
|
||||
- Updated dependencies [5c4badb]
|
||||
- llamaindex@0.6.3
|
||||
|
||||
## 3.0.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [749b43a]
|
||||
- llamaindex@0.6.2
|
||||
|
||||
## 3.0.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 1a6137b: feat: experimental support for browser
|
||||
|
||||
If you see bundler issue in next.js edge runtime, please bump to `next@14` latest version.
|
||||
|
||||
- Updated dependencies [fbd5e01]
|
||||
- Updated dependencies [6b70c54]
|
||||
- Updated dependencies [1a6137b]
|
||||
- Updated dependencies [85c2e19]
|
||||
- llamaindex@0.6.1
|
||||
|
||||
## 3.0.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [11feef8]
|
||||
- llamaindex@0.6.0
|
||||
|
||||
## 2.0.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,5 +1,193 @@
|
||||
# @llamaindex/autotool-01-node-example
|
||||
|
||||
## 0.0.28
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [62cba52]
|
||||
- Updated dependencies [d265e96]
|
||||
- Updated dependencies [d30bbf7]
|
||||
- Updated dependencies [53fd00a]
|
||||
- llamaindex@0.6.19
|
||||
- @llamaindex/autotool@3.0.19
|
||||
|
||||
## 0.0.27
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [5f67820]
|
||||
- Updated dependencies [fe08d04]
|
||||
- llamaindex@0.6.18
|
||||
- @llamaindex/autotool@3.0.18
|
||||
|
||||
## 0.0.26
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ee697fb]
|
||||
- llamaindex@0.6.17
|
||||
- @llamaindex/autotool@3.0.17
|
||||
|
||||
## 0.0.25
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [63e9846]
|
||||
- Updated dependencies [6f3a31c]
|
||||
- llamaindex@0.6.16
|
||||
- @llamaindex/autotool@3.0.16
|
||||
|
||||
## 0.0.24
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2a82413]
|
||||
- llamaindex@0.6.15
|
||||
- @llamaindex/autotool@3.0.15
|
||||
|
||||
## 0.0.23
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.14
|
||||
- @llamaindex/autotool@3.0.14
|
||||
|
||||
## 0.0.22
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.13
|
||||
- @llamaindex/autotool@3.0.13
|
||||
|
||||
## 0.0.21
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [f7b4e94]
|
||||
- Updated dependencies [78037a6]
|
||||
- Updated dependencies [1d9e3b1]
|
||||
- llamaindex@0.6.12
|
||||
- @llamaindex/autotool@3.0.12
|
||||
|
||||
## 0.0.20
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [df441e2]
|
||||
- @llamaindex/autotool@3.0.11
|
||||
- llamaindex@0.6.11
|
||||
|
||||
## 0.0.19
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ebc5105]
|
||||
- Updated dependencies [6cce3b1]
|
||||
- llamaindex@0.6.10
|
||||
- @llamaindex/autotool@3.0.10
|
||||
|
||||
## 0.0.18
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.9
|
||||
- @llamaindex/autotool@3.0.9
|
||||
|
||||
## 0.0.17
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [8b7fdba]
|
||||
- llamaindex@0.6.8
|
||||
- @llamaindex/autotool@3.0.8
|
||||
|
||||
## 0.0.16
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [23bcc37]
|
||||
- llamaindex@0.6.7
|
||||
- @llamaindex/autotool@3.0.7
|
||||
|
||||
## 0.0.15
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d902cc3]
|
||||
- Updated dependencies [025ffe6]
|
||||
- Updated dependencies [a659574]
|
||||
- llamaindex@0.6.6
|
||||
- @llamaindex/autotool@3.0.6
|
||||
|
||||
## 0.0.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [e9714db]
|
||||
- llamaindex@0.6.5
|
||||
- @llamaindex/autotool@3.0.5
|
||||
|
||||
## 0.0.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [b48bcc3]
|
||||
- llamaindex@0.6.4
|
||||
- @llamaindex/autotool@3.0.4
|
||||
|
||||
## 0.0.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2cd1383]
|
||||
- Updated dependencies [5c4badb]
|
||||
- llamaindex@0.6.3
|
||||
- @llamaindex/autotool@3.0.3
|
||||
|
||||
## 0.0.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [749b43a]
|
||||
- llamaindex@0.6.2
|
||||
- @llamaindex/autotool@3.0.2
|
||||
|
||||
## 0.0.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [fbd5e01]
|
||||
- Updated dependencies [6b70c54]
|
||||
- Updated dependencies [1a6137b]
|
||||
- Updated dependencies [85c2e19]
|
||||
- llamaindex@0.6.1
|
||||
- @llamaindex/autotool@3.0.1
|
||||
|
||||
## 0.0.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [11feef8]
|
||||
- llamaindex@0.6.0
|
||||
- @llamaindex/autotool@3.0.0
|
||||
|
||||
## 0.0.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [7edeb1c]
|
||||
- llamaindex@0.5.27
|
||||
- @llamaindex/autotool@2.0.1
|
||||
|
||||
## 0.0.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ffe0cd1]
|
||||
- Updated dependencies [ffe0cd1]
|
||||
- llamaindex@0.5.26
|
||||
- @llamaindex/autotool@2.0.1
|
||||
|
||||
## 0.0.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -13,5 +13,5 @@
|
||||
"scripts": {
|
||||
"start": "node --import tsx --import @llamaindex/autotool/node ./src/index.ts"
|
||||
},
|
||||
"version": "0.0.6"
|
||||
"version": "0.0.28"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,193 @@
|
||||
# @llamaindex/autotool-02-next-example
|
||||
|
||||
## 0.1.72
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [62cba52]
|
||||
- Updated dependencies [d265e96]
|
||||
- Updated dependencies [d30bbf7]
|
||||
- Updated dependencies [53fd00a]
|
||||
- llamaindex@0.6.19
|
||||
- @llamaindex/autotool@3.0.19
|
||||
|
||||
## 0.1.71
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [5f67820]
|
||||
- Updated dependencies [fe08d04]
|
||||
- llamaindex@0.6.18
|
||||
- @llamaindex/autotool@3.0.18
|
||||
|
||||
## 0.1.70
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ee697fb]
|
||||
- llamaindex@0.6.17
|
||||
- @llamaindex/autotool@3.0.17
|
||||
|
||||
## 0.1.69
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [63e9846]
|
||||
- Updated dependencies [6f3a31c]
|
||||
- llamaindex@0.6.16
|
||||
- @llamaindex/autotool@3.0.16
|
||||
|
||||
## 0.1.68
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2a82413]
|
||||
- llamaindex@0.6.15
|
||||
- @llamaindex/autotool@3.0.15
|
||||
|
||||
## 0.1.67
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.14
|
||||
- @llamaindex/autotool@3.0.14
|
||||
|
||||
## 0.1.66
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.13
|
||||
- @llamaindex/autotool@3.0.13
|
||||
|
||||
## 0.1.65
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [f7b4e94]
|
||||
- Updated dependencies [78037a6]
|
||||
- Updated dependencies [1d9e3b1]
|
||||
- llamaindex@0.6.12
|
||||
- @llamaindex/autotool@3.0.12
|
||||
|
||||
## 0.1.64
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [df441e2]
|
||||
- @llamaindex/autotool@3.0.11
|
||||
- llamaindex@0.6.11
|
||||
|
||||
## 0.1.63
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ebc5105]
|
||||
- Updated dependencies [6cce3b1]
|
||||
- llamaindex@0.6.10
|
||||
- @llamaindex/autotool@3.0.10
|
||||
|
||||
## 0.1.62
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- llamaindex@0.6.9
|
||||
- @llamaindex/autotool@3.0.9
|
||||
|
||||
## 0.1.61
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [8b7fdba]
|
||||
- llamaindex@0.6.8
|
||||
- @llamaindex/autotool@3.0.8
|
||||
|
||||
## 0.1.60
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [23bcc37]
|
||||
- llamaindex@0.6.7
|
||||
- @llamaindex/autotool@3.0.7
|
||||
|
||||
## 0.1.59
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d902cc3]
|
||||
- Updated dependencies [025ffe6]
|
||||
- Updated dependencies [a659574]
|
||||
- llamaindex@0.6.6
|
||||
- @llamaindex/autotool@3.0.6
|
||||
|
||||
## 0.1.58
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [e9714db]
|
||||
- llamaindex@0.6.5
|
||||
- @llamaindex/autotool@3.0.5
|
||||
|
||||
## 0.1.57
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [b48bcc3]
|
||||
- llamaindex@0.6.4
|
||||
- @llamaindex/autotool@3.0.4
|
||||
|
||||
## 0.1.56
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2cd1383]
|
||||
- Updated dependencies [5c4badb]
|
||||
- llamaindex@0.6.3
|
||||
- @llamaindex/autotool@3.0.3
|
||||
|
||||
## 0.1.55
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [749b43a]
|
||||
- llamaindex@0.6.2
|
||||
- @llamaindex/autotool@3.0.2
|
||||
|
||||
## 0.1.54
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [fbd5e01]
|
||||
- Updated dependencies [6b70c54]
|
||||
- Updated dependencies [1a6137b]
|
||||
- Updated dependencies [85c2e19]
|
||||
- llamaindex@0.6.1
|
||||
- @llamaindex/autotool@3.0.1
|
||||
|
||||
## 0.1.53
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [11feef8]
|
||||
- llamaindex@0.6.0
|
||||
- @llamaindex/autotool@3.0.0
|
||||
|
||||
## 0.1.52
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [7edeb1c]
|
||||
- llamaindex@0.5.27
|
||||
- @llamaindex/autotool@2.0.1
|
||||
|
||||
## 0.1.51
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ffe0cd1]
|
||||
- Updated dependencies [ffe0cd1]
|
||||
- llamaindex@0.5.26
|
||||
- @llamaindex/autotool@2.0.1
|
||||
|
||||
## 0.1.50
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -5,9 +5,9 @@ import { runWithStreamableUI } from "@/context";
|
||||
import "@/tool";
|
||||
import { convertTools } from "@llamaindex/autotool";
|
||||
import { createStreamableUI } from "ai/rsc";
|
||||
import type { JSX } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export async function chatWithAI(message: string): Promise<JSX.Element> {
|
||||
export async function chatWithAI(message: string): Promise<ReactNode> {
|
||||
const agent = new OpenAIAgent({
|
||||
tools: convertTools("llamaindex"),
|
||||
});
|
||||
@@ -25,7 +25,7 @@ export async function chatWithAI(message: string): Promise<JSX.Element> {
|
||||
uiStream.append("\n");
|
||||
},
|
||||
write: async (message) => {
|
||||
uiStream.append(message.response.delta);
|
||||
uiStream.append(message.response);
|
||||
},
|
||||
close: () => {
|
||||
uiStream.done();
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@llamaindex/autotool-02-next-example",
|
||||
"private": true,
|
||||
"version": "0.1.50",
|
||||
"version": "0.1.72",
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
@@ -32,6 +32,6 @@
|
||||
"cross-env": "^7.0.3",
|
||||
"postcss": "^8.4.41",
|
||||
"tailwindcss": "^3.4.10",
|
||||
"typescript": "^5.5.4"
|
||||
"typescript": "^5.6.2"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@llamaindex/autotool",
|
||||
"type": "module",
|
||||
"version": "2.0.1",
|
||||
"version": "3.0.19",
|
||||
"description": "auto transpile your JS function to LLM Agent compatible",
|
||||
"files": [
|
||||
"dist",
|
||||
@@ -51,7 +51,7 @@
|
||||
"unplugin": "^1.12.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"llamaindex": "^0.5.25",
|
||||
"llamaindex": "workspace:*",
|
||||
"openai": "^4",
|
||||
"typescript": "^4"
|
||||
},
|
||||
@@ -72,10 +72,10 @@
|
||||
"@types/node": "^22.5.1",
|
||||
"bunchee": "5.3.2",
|
||||
"llamaindex": "workspace:*",
|
||||
"next": "14.2.7",
|
||||
"next": "14.2.11",
|
||||
"rollup": "^4.21.2",
|
||||
"tsx": "^4.19.0",
|
||||
"typescript": "^5.5.4",
|
||||
"typescript": "^5.6.2",
|
||||
"vitest": "^2.0.5",
|
||||
"webpack": "^5.94.0"
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import td from "typedoc";
|
||||
import type { SourceMapCompact } from "unplugin";
|
||||
import type { InfoString } from "./internal";
|
||||
|
||||
export const isToolFile = (url: string) => /tool\.[jt]sx?$/.test(url);
|
||||
export const isToolFile = (url: string) => /\.tool\.[jt]sx?$/.test(url);
|
||||
export const isJSorTS = (url: string) => /\.m?[jt]sx?$/.test(url);
|
||||
|
||||
async function parseRoot(entryPoint: string) {
|
||||
@@ -28,7 +28,7 @@ async function parseRoot(entryPoint: string) {
|
||||
if (project) {
|
||||
return app.serializer.projectToObject(project, process.cwd());
|
||||
}
|
||||
throw new Error("Failed to parse root");
|
||||
throw new Error(`Failed to parse root ${entryPoint}`);
|
||||
}
|
||||
|
||||
export async function transformAutoTool(
|
||||
|
||||
@@ -1,5 +1,90 @@
|
||||
# @llamaindex/cloud
|
||||
|
||||
## 0.2.14
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [5f67820]
|
||||
- @llamaindex/core@0.2.12
|
||||
|
||||
## 0.2.13
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ee697fb]
|
||||
- @llamaindex/core@0.2.11
|
||||
|
||||
## 0.2.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3489e7d]
|
||||
- Updated dependencies [468bda5]
|
||||
- @llamaindex/core@0.2.10
|
||||
|
||||
## 0.2.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 0b20ff9: fix: package.json format
|
||||
|
||||
## 0.2.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 981811e: fix(cloud): llama parse reader save image incorrectly
|
||||
|
||||
## 0.2.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- df441e2: fix: consoleLogger is missing from `@llamaindex/env`
|
||||
- Updated dependencies [df441e2]
|
||||
- @llamaindex/core@0.2.8
|
||||
- @llamaindex/env@0.1.13
|
||||
|
||||
## 0.2.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- ac41ed3: feat: bump cloud sdk version
|
||||
|
||||
## 0.2.7
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- fb36eff: fix: backport for node.js 18
|
||||
|
||||
There could have one missing API in the node.js 18, so we need to backport it to make it work.
|
||||
|
||||
- d24d3d1: fix: print warning when llama parse reader has error
|
||||
- Updated dependencies [2cd1383]
|
||||
- @llamaindex/core@0.2.3
|
||||
|
||||
## 0.2.6
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- b42adeb: fix: get job result in llama parse reader
|
||||
- Updated dependencies [749b43a]
|
||||
- @llamaindex/core@0.2.2
|
||||
|
||||
## 0.2.5
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 85c2e19: feat: `@llamaindex/cloud` package update
|
||||
|
||||
- Bump to latest openapi schema
|
||||
- Move LlamaParse class from llamaindex, this will allow you use llamaparse in more non-node.js environment
|
||||
|
||||
- Updated dependencies [ac07e3c]
|
||||
- Updated dependencies [70ccb4a]
|
||||
- Updated dependencies [1a6137b]
|
||||
- Updated dependencies [ac07e3c]
|
||||
- @llamaindex/core@0.2.1
|
||||
- @llamaindex/env@0.1.11
|
||||
|
||||
## 0.2.4
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": "./dist/index.js",
|
||||
"private": true
|
||||
}
|
||||
+9687
-4356
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@llamaindex/cloud",
|
||||
"version": "0.2.4",
|
||||
"version": "0.2.14",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
@@ -9,33 +9,57 @@
|
||||
},
|
||||
"files": [
|
||||
"openapi.json",
|
||||
"dist"
|
||||
"./api",
|
||||
"./reader"
|
||||
],
|
||||
"exports": {
|
||||
"./openapi.json": "./openapi.json",
|
||||
"./api": {
|
||||
"require": {
|
||||
"types": "./dist/api.d.cts",
|
||||
"default": "./dist/api.cjs"
|
||||
"types": "./api/dist/index.d.cts",
|
||||
"default": "./api/dist/index.cjs"
|
||||
},
|
||||
"import": {
|
||||
"types": "./dist/api.d.ts",
|
||||
"default": "./dist/api.js"
|
||||
"types": "./api/dist/index.d.ts",
|
||||
"default": "./api/dist/index.js"
|
||||
},
|
||||
"default": {
|
||||
"types": "./dist/api.d.ts",
|
||||
"default": "./dist/api.js"
|
||||
"types": "./api/dist/index.d.ts",
|
||||
"default": "./api/dist/index.js"
|
||||
}
|
||||
},
|
||||
"./reader": {
|
||||
"require": {
|
||||
"types": "./reader/dist/index.d.cts",
|
||||
"default": "./reader/dist/index.cjs"
|
||||
},
|
||||
"import": {
|
||||
"types": "./reader/dist/index.d.ts",
|
||||
"default": "./reader/dist/index.js"
|
||||
},
|
||||
"default": {
|
||||
"types": "./reader/dist/index.d.ts",
|
||||
"default": "./reader/dist/index.js"
|
||||
}
|
||||
}
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/himself65/LlamaIndexTS.git",
|
||||
"url": "https://github.com/run-llama/LlamaIndexTS.git",
|
||||
"directory": "packages/cloud"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@hey-api/client-fetch": "^0.2.4",
|
||||
"@hey-api/openapi-ts": "^0.53.0",
|
||||
"@llamaindex/core": "workspace:*",
|
||||
"@llamaindex/env": "workspace:*",
|
||||
"bunchee": "5.3.2"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@llamaindex/core": "workspace:*",
|
||||
"@llamaindex/env": "workspace:*"
|
||||
},
|
||||
"dependencies": {
|
||||
"magic-bytes.js": "^1.10.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"type": "module",
|
||||
"main": "./dist/index.cjs",
|
||||
"module": "./dist/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": "./dist/index.js",
|
||||
"private": true
|
||||
}
|
||||
+194
-223
@@ -1,92 +1,17 @@
|
||||
import { type Client, createClient, createConfig } from "@hey-api/client-fetch";
|
||||
import { Document, FileReader } from "@llamaindex/core/schema";
|
||||
import { fs, getEnv } from "@llamaindex/env";
|
||||
import { fs, getEnv, path } from "@llamaindex/env";
|
||||
import { filetypeinfo } from "magic-bytes.js";
|
||||
import {
|
||||
type Body_upload_file_api_v1_parsing_upload_post,
|
||||
type ParserLanguages,
|
||||
ParsingService,
|
||||
} from "./api";
|
||||
import { sleep } from "./utils";
|
||||
|
||||
export type Language = ParserLanguages;
|
||||
|
||||
export type ResultType = "text" | "markdown" | "json";
|
||||
export type Language =
|
||||
| "abq"
|
||||
| "ady"
|
||||
| "af"
|
||||
| "ang"
|
||||
| "ar"
|
||||
| "as"
|
||||
| "ava"
|
||||
| "az"
|
||||
| "be"
|
||||
| "bg"
|
||||
| "bh"
|
||||
| "bho"
|
||||
| "bn"
|
||||
| "bs"
|
||||
| "ch_sim"
|
||||
| "ch_tra"
|
||||
| "che"
|
||||
| "cs"
|
||||
| "cy"
|
||||
| "da"
|
||||
| "dar"
|
||||
| "de"
|
||||
| "en"
|
||||
| "es"
|
||||
| "et"
|
||||
| "fa"
|
||||
| "fr"
|
||||
| "ga"
|
||||
| "gom"
|
||||
| "hi"
|
||||
| "hr"
|
||||
| "hu"
|
||||
| "id"
|
||||
| "inh"
|
||||
| "is"
|
||||
| "it"
|
||||
| "ja"
|
||||
| "kbd"
|
||||
| "kn"
|
||||
| "ko"
|
||||
| "ku"
|
||||
| "la"
|
||||
| "lbe"
|
||||
| "lez"
|
||||
| "lt"
|
||||
| "lv"
|
||||
| "mah"
|
||||
| "mai"
|
||||
| "mi"
|
||||
| "mn"
|
||||
| "mr"
|
||||
| "ms"
|
||||
| "mt"
|
||||
| "ne"
|
||||
| "new"
|
||||
| "nl"
|
||||
| "no"
|
||||
| "oc"
|
||||
| "pi"
|
||||
| "pl"
|
||||
| "pt"
|
||||
| "ro"
|
||||
| "ru"
|
||||
| "rs_cyrillic"
|
||||
| "rs_latin"
|
||||
| "sck"
|
||||
| "sk"
|
||||
| "sl"
|
||||
| "sq"
|
||||
| "sv"
|
||||
| "sw"
|
||||
| "ta"
|
||||
| "tab"
|
||||
| "te"
|
||||
| "th"
|
||||
| "tjk"
|
||||
| "tl"
|
||||
| "tr"
|
||||
| "ug"
|
||||
| "uk"
|
||||
| "ur"
|
||||
| "uz"
|
||||
| "vi";
|
||||
|
||||
const SUPPORT_FILE_EXT: string[] = [
|
||||
".pdf",
|
||||
@@ -181,6 +106,15 @@ const SUPPORT_FILE_EXT: string[] = [
|
||||
".tsv",
|
||||
];
|
||||
|
||||
//todo: should move into @llamaindex/env
|
||||
type WriteStream = {
|
||||
write: (text: string) => void;
|
||||
};
|
||||
|
||||
// Do not modify this variable or cause type errors
|
||||
// eslint-disable-next-line no-var
|
||||
var process: any;
|
||||
|
||||
/**
|
||||
* Represents a reader for parsing files using the LlamaParse API.
|
||||
* See https://github.com/run-llama/llama_parse
|
||||
@@ -188,8 +122,8 @@ const SUPPORT_FILE_EXT: string[] = [
|
||||
export class LlamaParseReader extends FileReader {
|
||||
// The API key for the LlamaParse API. Can be set as an environment variable: LLAMA_CLOUD_API_KEY
|
||||
apiKey: string;
|
||||
// The base URL of the Llama Parsing API.
|
||||
baseUrl: string = "https://api.cloud.llamaindex.ai/api/parsing";
|
||||
// The base URL of the Llama Cloud Platform.
|
||||
baseUrl: string = "https://api.cloud.llamaindex.ai";
|
||||
// The result type for the parser.
|
||||
resultType: ResultType = "text";
|
||||
// The interval in seconds to check if the parsing is done.
|
||||
@@ -199,7 +133,7 @@ export class LlamaParseReader extends FileReader {
|
||||
// Whether to print the progress of the parsing.
|
||||
verbose = true;
|
||||
// The language of the text to parse.
|
||||
language: Language = "en";
|
||||
language: ParserLanguages[] = ["en"];
|
||||
// The parsing instruction for the parser. Backend default is an empty string.
|
||||
parsingInstruction?: string | undefined;
|
||||
// Wether to ignore diagonal text (when the text rotation in degrees is not 0, 90, 180 or 270, so not a horizontal or vertical text). Backend default is false.
|
||||
@@ -236,22 +170,48 @@ export class LlamaParseReader extends FileReader {
|
||||
vendorMultimodalModelName?: string | undefined;
|
||||
// The API key for the multimodal API. Can also be set as an env variable: LLAMA_CLOUD_VENDOR_MULTIMODAL_API_KEY
|
||||
vendorMultimodalApiKey?: string | undefined;
|
||||
|
||||
webhookUrl?: string | undefined;
|
||||
premiumMode?: boolean | undefined;
|
||||
takeScreenshot?: boolean | undefined;
|
||||
disableOcr?: boolean | undefined;
|
||||
disableReconstruction?: boolean | undefined;
|
||||
inputS3Path?: string | undefined;
|
||||
outputS3PathPrefix?: string | undefined;
|
||||
|
||||
// numWorkers is implemented in SimpleDirectoryReader
|
||||
stdout?: WriteStream | undefined;
|
||||
|
||||
readonly #client: Client;
|
||||
|
||||
constructor(
|
||||
params: Partial<LlamaParseReader> & {
|
||||
params: Partial<Omit<LlamaParseReader, "language" | "apiKey">> & {
|
||||
language?: ParserLanguages | ParserLanguages[] | undefined;
|
||||
apiKey?: string | undefined;
|
||||
} = {},
|
||||
) {
|
||||
super();
|
||||
Object.assign(this, params);
|
||||
params.apiKey = params.apiKey ?? getEnv("LLAMA_CLOUD_API_KEY");
|
||||
if (!params.apiKey) {
|
||||
this.language = Array.isArray(this.language)
|
||||
? this.language
|
||||
: [this.language];
|
||||
this.stdout =
|
||||
(params.stdout ?? typeof process !== "undefined")
|
||||
? process!.stdout
|
||||
: undefined;
|
||||
const apiKey = params.apiKey ?? getEnv("LLAMA_CLOUD_API_KEY");
|
||||
if (!apiKey) {
|
||||
throw new Error(
|
||||
"API Key is required for LlamaParseReader. Please pass the apiKey parameter or set the LLAMA_CLOUD_API_KEY environment variable.",
|
||||
);
|
||||
}
|
||||
this.apiKey = params.apiKey;
|
||||
this.apiKey = apiKey;
|
||||
if (this.baseUrl.endsWith("/")) {
|
||||
this.baseUrl = this.baseUrl.slice(0, -"/".length);
|
||||
}
|
||||
if (this.baseUrl.endsWith("/api/parsing")) {
|
||||
this.baseUrl = this.baseUrl.slice(0, -"/api/parsing".length);
|
||||
}
|
||||
|
||||
if (params.gpt4oMode) {
|
||||
params.gpt4oApiKey =
|
||||
@@ -266,126 +226,145 @@ export class LlamaParseReader extends FileReader {
|
||||
|
||||
this.vendorMultimodalApiKey = params.vendorMultimodalApiKey;
|
||||
}
|
||||
|
||||
this.#client = createClient(
|
||||
createConfig({
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
baseUrl: this.baseUrl,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// Create a job for the LlamaParse API
|
||||
private async createJob(
|
||||
data: Uint8Array,
|
||||
fileName?: string,
|
||||
): Promise<string> {
|
||||
private async createJob(data: Uint8Array): Promise<string> {
|
||||
// Load data, set the mime type
|
||||
const { mime, extension } = await LlamaParseReader.getMimeType(data);
|
||||
const { mime } = await LlamaParseReader.getMimeType(data);
|
||||
|
||||
if (this.verbose) {
|
||||
const name = fileName ? fileName : extension;
|
||||
console.log(`Starting load for ${name} file`);
|
||||
console.log("Started uploading the file");
|
||||
}
|
||||
|
||||
const body = new FormData();
|
||||
body.set("file", new Blob([data], { type: mime }), fileName);
|
||||
|
||||
const LlamaParseBodyParams = {
|
||||
const body = {
|
||||
file: new Blob([data], {
|
||||
type: mime,
|
||||
}),
|
||||
language: this.language,
|
||||
parsing_instruction: this.parsingInstruction,
|
||||
skip_diagonal_text: this.skipDiagonalText?.toString(),
|
||||
invalidate_cache: this.invalidateCache?.toString(),
|
||||
do_not_cache: this.doNotCache?.toString(),
|
||||
fast_mode: this.fastMode?.toString(),
|
||||
do_not_unroll_columns: this.doNotUnrollColumns?.toString(),
|
||||
skip_diagonal_text: this.skipDiagonalText,
|
||||
invalidate_cache: this.invalidateCache,
|
||||
do_not_cache: this.doNotCache,
|
||||
fast_mode: this.fastMode,
|
||||
do_not_unroll_columns: this.doNotUnrollColumns,
|
||||
page_separator: this.pageSeparator,
|
||||
page_prefix: this.pagePrefix,
|
||||
page_suffix: this.pageSuffix,
|
||||
gpt4o_mode: this.gpt4oMode?.toString(),
|
||||
gpt4o_mode: this.gpt4oMode,
|
||||
gpt4o_api_key: this.gpt4oApiKey,
|
||||
bounding_box: this.boundingBox,
|
||||
target_pages: this.targetPages,
|
||||
use_vendor_multimodal_model: this.useVendorMultimodalModel?.toString(),
|
||||
use_vendor_multimodal_model: this.useVendorMultimodalModel,
|
||||
vendor_multimodal_model_name: this.vendorMultimodalModelName,
|
||||
vendor_multimodal_api_key: this.vendorMultimodalApiKey,
|
||||
};
|
||||
premium_mode: this.premiumMode,
|
||||
webhook_url: this.webhookUrl,
|
||||
take_screenshot: this.takeScreenshot,
|
||||
disable_ocr: this.disableOcr,
|
||||
disable_reconstruction: this.disableReconstruction,
|
||||
input_s3_path: this.inputS3Path,
|
||||
output_s3_path_prefix: this.outputS3PathPrefix,
|
||||
} satisfies {
|
||||
[Key in keyof Body_upload_file_api_v1_parsing_upload_post]-?:
|
||||
| Body_upload_file_api_v1_parsing_upload_post[Key]
|
||||
| undefined;
|
||||
} as unknown as Body_upload_file_api_v1_parsing_upload_post;
|
||||
|
||||
// Filter out params with invalid values that would cause issues on the backend.
|
||||
const filteredParams = this.filterSpecificParams(LlamaParseBodyParams, [
|
||||
"page_separator",
|
||||
"page_prefix",
|
||||
"page_suffix",
|
||||
"bounding_box",
|
||||
"target_pages",
|
||||
]);
|
||||
|
||||
// Appends body with any defined LlamaParseBodyParams
|
||||
Object.entries(filteredParams).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
body.append(key, value);
|
||||
}
|
||||
});
|
||||
|
||||
const headers = {
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
};
|
||||
|
||||
// Send the request, start job
|
||||
const url = `${this.baseUrl}/upload`;
|
||||
const response = await fetch(url, {
|
||||
const response = await ParsingService.uploadFileApiV1ParsingUploadPost({
|
||||
client: this.#client,
|
||||
throwOnError: true,
|
||||
signal: AbortSignal.timeout(this.maxTimeout * 1000),
|
||||
method: "POST",
|
||||
body,
|
||||
headers,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to parse the file: ${await response.text()}`);
|
||||
}
|
||||
const jsonResponse = await response.json();
|
||||
return jsonResponse.id;
|
||||
|
||||
return response.data.id;
|
||||
}
|
||||
|
||||
// Get the result of the job
|
||||
private async getJobResult(jobId: string, resultType: string): Promise<any> {
|
||||
const resultUrl = `${this.baseUrl}/job/${jobId}/result/${resultType}`;
|
||||
const statusUrl = `${this.baseUrl}/job/${jobId}`;
|
||||
const headers = { Authorization: `Bearer ${this.apiKey}` };
|
||||
|
||||
private async getJobResult(
|
||||
jobId: string,
|
||||
resultType: "text" | "json" | "markdown",
|
||||
): Promise<any> {
|
||||
const signal = AbortSignal.timeout(this.maxTimeout * 1000);
|
||||
let tries = 0;
|
||||
while (true) {
|
||||
await new Promise((resolve) =>
|
||||
setTimeout(resolve, this.checkInterval * 1000),
|
||||
);
|
||||
await sleep(this.checkInterval * 1000);
|
||||
|
||||
// Check the job status. If unsuccessful response, checks if maximum timeout has been reached. If reached, throws an error
|
||||
const statusResponse = await fetch(statusUrl, {
|
||||
headers,
|
||||
const result = await ParsingService.getJobApiV1ParsingJobJobIdGet({
|
||||
client: this.#client,
|
||||
throwOnError: true,
|
||||
path: {
|
||||
job_id: jobId,
|
||||
},
|
||||
signal,
|
||||
});
|
||||
if (!statusResponse.ok) {
|
||||
signal.throwIfAborted();
|
||||
if (this.verbose && tries % 10 === 0) {
|
||||
process.stdout.write(".");
|
||||
}
|
||||
tries++;
|
||||
continue;
|
||||
}
|
||||
const { data } = result;
|
||||
|
||||
// If response is succesful, check status of job. Allowed values "PENDING", "SUCCESS", "ERROR", "CANCELED"
|
||||
const statusJson = await statusResponse.json();
|
||||
const status = statusJson.status;
|
||||
const status = (data as Record<string, unknown>)["status"];
|
||||
// If job has completed, return the result
|
||||
if (status === "SUCCESS") {
|
||||
const resultResponse = await fetch(resultUrl, {
|
||||
headers,
|
||||
signal,
|
||||
});
|
||||
if (!resultResponse.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch result: ${await resultResponse.text()}`,
|
||||
);
|
||||
let result;
|
||||
switch (resultType) {
|
||||
case "json": {
|
||||
result =
|
||||
await ParsingService.getJobJsonResultApiV1ParsingJobJobIdResultJsonGet(
|
||||
{
|
||||
client: this.#client,
|
||||
throwOnError: true,
|
||||
path: {
|
||||
job_id: jobId,
|
||||
},
|
||||
signal,
|
||||
},
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "markdown": {
|
||||
result =
|
||||
await ParsingService.getJobResultApiV1ParsingJobJobIdResultMarkdownGet(
|
||||
{
|
||||
client: this.#client,
|
||||
throwOnError: true,
|
||||
path: {
|
||||
job_id: jobId,
|
||||
},
|
||||
signal,
|
||||
},
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "text": {
|
||||
result =
|
||||
await ParsingService.getJobTextResultApiV1ParsingJobJobIdResultTextGet(
|
||||
{
|
||||
client: this.#client,
|
||||
throwOnError: true,
|
||||
path: {
|
||||
job_id: jobId,
|
||||
},
|
||||
signal,
|
||||
},
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return resultResponse.json();
|
||||
return result.data;
|
||||
// If job is still pending, check if maximum timeout has been reached. If reached, throws an error
|
||||
} else if (status === "PENDING") {
|
||||
signal.throwIfAborted();
|
||||
if (this.verbose && tries % 10 === 0) {
|
||||
process.stdout.write(".");
|
||||
this.stdout?.write(".");
|
||||
}
|
||||
tries++;
|
||||
} else {
|
||||
@@ -401,43 +380,38 @@ export class LlamaParseReader extends FileReader {
|
||||
* To be used with resultType = "text" and "markdown"
|
||||
*
|
||||
* @param {Uint8Array} fileContent - The content of the file to be loaded.
|
||||
* @param {string} [fileName] - The optional name of the file to be loaded.
|
||||
* @return {Promise<Document[]>} A Promise object that resolves to an array of Document objects.
|
||||
*/
|
||||
async loadDataAsContent(
|
||||
fileContent: Uint8Array,
|
||||
fileName?: string,
|
||||
): Promise<Document[]> {
|
||||
let jobId;
|
||||
try {
|
||||
// Creates a job for the file
|
||||
jobId = await this.createJob(fileContent, fileName);
|
||||
if (this.verbose) {
|
||||
console.log(`Started parsing the file under job id ${jobId}`);
|
||||
}
|
||||
async loadDataAsContent(fileContent: Uint8Array): Promise<Document[]> {
|
||||
return this.createJob(fileContent)
|
||||
.then(async (jobId) => {
|
||||
if (this.verbose) {
|
||||
console.log(`Started parsing the file under job id ${jobId}`);
|
||||
}
|
||||
|
||||
// Return results as Document objects
|
||||
const jobResults = await this.getJobResult(jobId, this.resultType);
|
||||
const resultText = jobResults[this.resultType];
|
||||
// Return results as Document objects
|
||||
const jobResults = await this.getJobResult(jobId, this.resultType);
|
||||
const resultText = jobResults[this.resultType];
|
||||
|
||||
// Split the text by separator if splitByPage is true
|
||||
if (this.splitByPage) {
|
||||
return this.splitTextBySeparator(resultText);
|
||||
}
|
||||
// Split the text by separator if splitByPage is true
|
||||
if (this.splitByPage) {
|
||||
return this.splitTextBySeparator(resultText);
|
||||
}
|
||||
|
||||
return [
|
||||
new Document({
|
||||
text: resultText,
|
||||
}),
|
||||
];
|
||||
} catch (e) {
|
||||
console.error(`Error while parsing file under job id ${jobId}`, e);
|
||||
if (this.ignoreErrors) {
|
||||
return [];
|
||||
} else {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
return [
|
||||
new Document({
|
||||
text: resultText,
|
||||
}),
|
||||
];
|
||||
})
|
||||
.catch((error) => {
|
||||
if (this.ignoreErrors) {
|
||||
console.warn(`Error while parsing the file: ${error.message}`);
|
||||
return [];
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Loads data from a file and returns an array of JSON objects.
|
||||
@@ -467,8 +441,8 @@ export class LlamaParseReader extends FileReader {
|
||||
resultJson.file_path = isFilePath ? filePathOrContent : undefined;
|
||||
return [resultJson];
|
||||
} catch (e) {
|
||||
console.error(`Error while parsing the file under job id ${jobId}`, e);
|
||||
if (this.ignoreErrors) {
|
||||
console.error(`Error while parsing the file under job id ${jobId}`, e);
|
||||
return [];
|
||||
} else {
|
||||
throw e;
|
||||
@@ -536,14 +510,7 @@ export class LlamaParseReader extends FileReader {
|
||||
jobId: string,
|
||||
imageName: string,
|
||||
): Promise<string> {
|
||||
// Get the full path
|
||||
let imagePath = `${downloadPath}/${jobId}-${imageName}`;
|
||||
// Get a valid image path
|
||||
if (!imagePath.endsWith(".png") && !imagePath.endsWith(".jpg")) {
|
||||
imagePath += ".png";
|
||||
}
|
||||
|
||||
return imagePath;
|
||||
return path.join(downloadPath, `${jobId}-${imageName}`);
|
||||
}
|
||||
|
||||
private async fetchAndSaveImage(
|
||||
@@ -551,18 +518,22 @@ export class LlamaParseReader extends FileReader {
|
||||
imagePath: string,
|
||||
jobId: string,
|
||||
): Promise<void> {
|
||||
const headers = { Authorization: `Bearer ${this.apiKey}` };
|
||||
// Construct the image URL
|
||||
const imageUrl = `${this.baseUrl}/job/${jobId}/result/image/${imageName}`;
|
||||
const response = await fetch(imageUrl, { headers });
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to download image: ${await response.text()}`);
|
||||
const response =
|
||||
await ParsingService.getJobImageResultApiV1ParsingJobJobIdResultImageNameGet(
|
||||
{
|
||||
client: this.#client,
|
||||
path: {
|
||||
job_id: jobId,
|
||||
name: imageName,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (response.error) {
|
||||
throw new Error(`Failed to download image: ${response.error.detail}`);
|
||||
}
|
||||
// Convert the response to an ArrayBuffer and then to a Buffer
|
||||
const arrayBuffer = await response.arrayBuffer();
|
||||
const buffer = new Uint8Array(arrayBuffer);
|
||||
const blob = (await response.data) as Blob;
|
||||
// Write the image buffer to the specified imagePath
|
||||
await fs.writeFile(imagePath, buffer);
|
||||
await fs.writeFile(imagePath, new Uint8Array(await blob.arrayBuffer()));
|
||||
}
|
||||
|
||||
// Filters out invalid values (null, undefined, empty string) of specific params.
|
||||
@@ -0,0 +1,3 @@
|
||||
export async function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
@@ -8,8 +8,17 @@
|
||||
"moduleResolution": "Bundler",
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"lib": ["DOM", "ESNext"]
|
||||
"lib": ["DOM", "ESNext"],
|
||||
"types": []
|
||||
},
|
||||
"include": ["./src"],
|
||||
"exclude": ["node_modules"]
|
||||
"exclude": ["node_modules"],
|
||||
"references": [
|
||||
{
|
||||
"path": "../core/tsconfig.json"
|
||||
},
|
||||
{
|
||||
"path": "../env/tsconfig.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": ["//"],
|
||||
"tasks": {
|
||||
"build": {
|
||||
"outputs": ["**/dist/**", "src/client/**"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,111 @@
|
||||
# @llamaindex/community
|
||||
|
||||
## 0.0.47
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [5f67820]
|
||||
- @llamaindex/core@0.2.12
|
||||
|
||||
## 0.0.46
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ee697fb]
|
||||
- @llamaindex/core@0.2.11
|
||||
|
||||
## 0.0.45
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [3489e7d]
|
||||
- Updated dependencies [468bda5]
|
||||
- @llamaindex/core@0.2.10
|
||||
|
||||
## 0.0.44
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [b17d439]
|
||||
- @llamaindex/core@0.2.9
|
||||
|
||||
## 0.0.43
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 2774e80: feat: added meta3.2 support via Bedrock including vision, tool call and inference region support
|
||||
|
||||
## 0.0.42
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- df441e2: fix: consoleLogger is missing from `@llamaindex/env`
|
||||
- Updated dependencies [df441e2]
|
||||
- @llamaindex/core@0.2.8
|
||||
- @llamaindex/env@0.1.13
|
||||
|
||||
## 0.0.41
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [6cce3b1]
|
||||
- @llamaindex/core@0.2.7
|
||||
|
||||
## 0.0.40
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 50e6b57: feat: add Amazon Bedrock Retriever
|
||||
- Updated dependencies [8b7fdba]
|
||||
- @llamaindex/core@0.2.6
|
||||
|
||||
## 0.0.39
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [d902cc3]
|
||||
- @llamaindex/core@0.2.5
|
||||
|
||||
## 0.0.38
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [b48bcc3]
|
||||
- @llamaindex/core@0.2.4
|
||||
- @llamaindex/env@0.1.12
|
||||
|
||||
## 0.0.37
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [2cd1383]
|
||||
- @llamaindex/core@0.2.3
|
||||
|
||||
## 0.0.36
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [749b43a]
|
||||
- @llamaindex/core@0.2.2
|
||||
|
||||
## 0.0.35
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [ac07e3c]
|
||||
- Updated dependencies [70ccb4a]
|
||||
- Updated dependencies [1a6137b]
|
||||
- Updated dependencies [ac07e3c]
|
||||
- @llamaindex/core@0.2.1
|
||||
- @llamaindex/env@0.1.11
|
||||
|
||||
## 0.0.34
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [11feef8]
|
||||
- @llamaindex/core@0.2.0
|
||||
|
||||
## 0.0.33
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -5,8 +5,11 @@
|
||||
## Current Features:
|
||||
|
||||
- Bedrock support for the Anthropic Claude Models [usage](https://ts.llamaindex.ai/modules/llms/available_llms/bedrock)
|
||||
- Bedrock support for the Meta LLama 2, 3 and 3.1 Models [usage](https://ts.llamaindex.ai/modules/llms/available_llms/bedrock)
|
||||
- Meta LLama3.1 405b tool call support
|
||||
- Bedrock support for the Meta LLama 2, 3, 3.1 and 3.2 Models [usage](https://ts.llamaindex.ai/modules/llms/available_llms/bedrock)
|
||||
- Meta LLama3.1 405b and Llama3.2 tool call support
|
||||
- Meta 3.2 11B and 90B vision support
|
||||
- Bedrock support for querying Knowledge Base
|
||||
- Bedrock: [Supported Regions and models for cross-region inference](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference-support.html)
|
||||
|
||||
## LICENSE
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@llamaindex/community",
|
||||
"description": "Community package for LlamaIndexTS",
|
||||
"version": "0.0.33",
|
||||
"version": "0.0.47",
|
||||
"type": "module",
|
||||
"types": "dist/type/index.d.ts",
|
||||
"main": "dist/cjs/index.js",
|
||||
@@ -47,6 +47,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-bedrock-runtime": "^3.642.0",
|
||||
"@aws-sdk/client-bedrock-agent-runtime": "^3.642.0",
|
||||
"@llamaindex/core": "workspace:*",
|
||||
"@llamaindex/env": "workspace:*"
|
||||
}
|
||||
|
||||
@@ -2,4 +2,7 @@ export {
|
||||
BEDROCK_MODELS,
|
||||
BEDROCK_MODEL_MAX_TOKENS,
|
||||
Bedrock,
|
||||
INFERENCE_BEDROCK_MODELS,
|
||||
INFERENCE_TO_BEDROCK_MAP,
|
||||
} from "./llm/bedrock/index.js";
|
||||
export { AmazonKnowledgeBaseRetriever } from "./retrievers/bedrock.js";
|
||||
|
||||
@@ -6,7 +6,10 @@ import type {
|
||||
MessageContentDetail,
|
||||
ToolCallLLMMessageOptions,
|
||||
} from "@llamaindex/core/llms";
|
||||
import { mapMessageContentToMessageContentDetails } from "../utils";
|
||||
import {
|
||||
extractDataUrlComponents,
|
||||
mapMessageContentToMessageContentDetails,
|
||||
} from "../utils";
|
||||
import type {
|
||||
AnthropicContent,
|
||||
AnthropicImageContent,
|
||||
@@ -143,27 +146,6 @@ export const mapTextContent = (text: string): AnthropicTextContent => {
|
||||
return { type: "text", text };
|
||||
};
|
||||
|
||||
export const extractDataUrlComponents = (
|
||||
dataUrl: string,
|
||||
): {
|
||||
mimeType: string;
|
||||
base64: string;
|
||||
} => {
|
||||
const parts = dataUrl.split(";base64,");
|
||||
|
||||
if (parts.length !== 2 || !parts[0]!.startsWith("data:")) {
|
||||
throw new Error("Invalid data URL");
|
||||
}
|
||||
|
||||
const mimeType = parts[0]!.slice(5);
|
||||
const base64 = parts[1]!;
|
||||
|
||||
return {
|
||||
mimeType,
|
||||
base64,
|
||||
};
|
||||
};
|
||||
|
||||
export const mapImageContent = (imageUrl: string): AnthropicImageContent => {
|
||||
if (!imageUrl.startsWith("data:"))
|
||||
throw new Error(
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
ToolCallLLM,
|
||||
type ToolCallLLMMessageOptions,
|
||||
} from "@llamaindex/core/llms";
|
||||
import { streamConverter, wrapLLMEvent } from "@llamaindex/core/utils";
|
||||
import { streamConverter } from "@llamaindex/core/utils";
|
||||
import {
|
||||
type BedrockAdditionalChatOptions,
|
||||
type BedrockChatStreamResponse,
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
} from "./provider";
|
||||
import { mapMessageContentToMessageContentDetails } from "./utils";
|
||||
|
||||
import { wrapLLMEvent } from "@llamaindex/core/decorator";
|
||||
import { AnthropicProvider } from "./anthropic/provider";
|
||||
import { MetaProvider } from "./meta/provider";
|
||||
|
||||
@@ -46,35 +47,96 @@ export type BedrockChatParamsNonStreaming = LLMChatParamsNonStreaming<
|
||||
export type BedrockChatNonStreamResponse =
|
||||
ChatResponse<ToolCallLLMMessageOptions>;
|
||||
|
||||
export enum BEDROCK_MODELS {
|
||||
AMAZON_TITAN_TG1_LARGE = "amazon.titan-tg1-large",
|
||||
AMAZON_TITAN_TEXT_EXPRESS_V1 = "amazon.titan-text-express-v1",
|
||||
AI21_J2_GRANDE_INSTRUCT = "ai21.j2-grande-instruct",
|
||||
AI21_J2_JUMBO_INSTRUCT = "ai21.j2-jumbo-instruct",
|
||||
AI21_J2_MID = "ai21.j2-mid",
|
||||
AI21_J2_MID_V1 = "ai21.j2-mid-v1",
|
||||
AI21_J2_ULTRA = "ai21.j2-ultra",
|
||||
AI21_J2_ULTRA_V1 = "ai21.j2-ultra-v1",
|
||||
COHERE_COMMAND_TEXT_V14 = "cohere.command-text-v14",
|
||||
ANTHROPIC_CLAUDE_INSTANT_1 = "anthropic.claude-instant-v1",
|
||||
ANTHROPIC_CLAUDE_1 = "anthropic.claude-v1", // EOF: No longer supported
|
||||
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",
|
||||
ANTHROPIC_CLAUDE_3_5_SONNET = "anthropic.claude-3-5-sonnet-20240620-v1:0",
|
||||
META_LLAMA2_13B_CHAT = "meta.llama2-13b-chat-v1",
|
||||
META_LLAMA2_70B_CHAT = "meta.llama2-70b-chat-v1",
|
||||
META_LLAMA3_8B_INSTRUCT = "meta.llama3-8b-instruct-v1:0",
|
||||
META_LLAMA3_70B_INSTRUCT = "meta.llama3-70b-instruct-v1:0",
|
||||
META_LLAMA3_1_8B_INSTRUCT = "meta.llama3-1-8b-instruct-v1:0",
|
||||
META_LLAMA3_1_70B_INSTRUCT = "meta.llama3-1-70b-instruct-v1:0",
|
||||
META_LLAMA3_1_405B_INSTRUCT = "meta.llama3-1-405b-instruct-v1:0",
|
||||
MISTRAL_7B_INSTRUCT = "mistral.mistral-7b-instruct-v0:2",
|
||||
MISTRAL_MIXTRAL_7B_INSTRUCT = "mistral.mixtral-8x7b-instruct-v0:1",
|
||||
MISTRAL_MIXTRAL_LARGE_2402 = "mistral.mistral-large-2402-v1:0",
|
||||
}
|
||||
export const BEDROCK_MODELS = {
|
||||
AMAZON_TITAN_TG1_LARGE: "amazon.titan-tg1-large",
|
||||
AMAZON_TITAN_TEXT_EXPRESS_V1: "amazon.titan-text-express-v1",
|
||||
AI21_J2_GRANDE_INSTRUCT: "ai21.j2-grande-instruct",
|
||||
AI21_J2_JUMBO_INSTRUCT: "ai21.j2-jumbo-instruct",
|
||||
AI21_J2_MID: "ai21.j2-mid",
|
||||
AI21_J2_MID_V1: "ai21.j2-mid-v1",
|
||||
AI21_J2_ULTRA: "ai21.j2-ultra",
|
||||
AI21_J2_ULTRA_V1: "ai21.j2-ultra-v1",
|
||||
COHERE_COMMAND_TEXT_V14: "cohere.command-text-v14",
|
||||
ANTHROPIC_CLAUDE_INSTANT_1: "anthropic.claude-instant-v1",
|
||||
ANTHROPIC_CLAUDE_1: "anthropic.claude-v1", // EOF: No longer supported
|
||||
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",
|
||||
ANTHROPIC_CLAUDE_3_5_SONNET: "anthropic.claude-3-5-sonnet-20240620-v1:0",
|
||||
META_LLAMA2_13B_CHAT: "meta.llama2-13b-chat-v1",
|
||||
META_LLAMA2_70B_CHAT: "meta.llama2-70b-chat-v1",
|
||||
META_LLAMA3_8B_INSTRUCT: "meta.llama3-8b-instruct-v1:0",
|
||||
META_LLAMA3_70B_INSTRUCT: "meta.llama3-70b-instruct-v1:0",
|
||||
META_LLAMA3_1_8B_INSTRUCT: "meta.llama3-1-8b-instruct-v1:0",
|
||||
META_LLAMA3_1_70B_INSTRUCT: "meta.llama3-1-70b-instruct-v1:0",
|
||||
META_LLAMA3_1_405B_INSTRUCT: "meta.llama3-1-405b-instruct-v1:0",
|
||||
META_LLAMA3_2_1B_INSTRUCT: "meta.llama3-2-1b-instruct-v1:0",
|
||||
META_LLAMA3_2_3B_INSTRUCT: "meta.llama3-2-3b-instruct-v1:0",
|
||||
META_LLAMA3_2_11B_INSTRUCT: "meta.llama3-2-11b-instruct-v1:0",
|
||||
META_LLAMA3_2_90B_INSTRUCT: "meta.llama3-2-90b-instruct-v1:0",
|
||||
MISTRAL_7B_INSTRUCT: "mistral.mistral-7b-instruct-v0:2",
|
||||
MISTRAL_MIXTRAL_7B_INSTRUCT: "mistral.mixtral-8x7b-instruct-v0:1",
|
||||
MISTRAL_MIXTRAL_LARGE_2402: "mistral.mistral-large-2402-v1:0",
|
||||
};
|
||||
export type BEDROCK_MODELS =
|
||||
(typeof BEDROCK_MODELS)[keyof typeof BEDROCK_MODELS];
|
||||
|
||||
export const INFERENCE_BEDROCK_MODELS = {
|
||||
US_ANTHROPIC_CLAUDE_3_HAIKU: "us.anthropic.claude-3-haiku-20240307-v1:0",
|
||||
US_ANTHROPIC_CLAUDE_3_OPUS: "us.anthropic.claude-3-opus-20240229-v1:0",
|
||||
US_ANTHROPIC_CLAUDE_3_SONNET: "us.anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
US_ANTHROPIC_CLAUDE_3_5_SONNET:
|
||||
"us.anthropic.claude-3-5-sonnet-20240620-v1:0",
|
||||
US_META_LLAMA_3_2_1B_INSTRUCT: "us.meta.llama3-2-1b-instruct-v1:0",
|
||||
US_META_LLAMA_3_2_3B_INSTRUCT: "us.meta.llama3-2-3b-instruct-v1:0",
|
||||
US_META_LLAMA_3_2_11B_INSTRUCT: "us.meta.llama3-2-11b-instruct-v1:0",
|
||||
US_META_LLAMA_3_2_90B_INSTRUCT: "us.meta.llama3-2-90b-instruct-v1:0",
|
||||
|
||||
EU_ANTHROPIC_CLAUDE_3_HAIKU: "eu.anthropic.claude-3-haiku-20240307-v1:0",
|
||||
EU_ANTHROPIC_CLAUDE_3_SONNET: "eu.anthropic.claude-3-sonnet-20240229-v1:0",
|
||||
EU_ANTHROPIC_CLAUDE_3_5_SONNET:
|
||||
"eu.anthropic.claude-3-5-sonnet-20240620-v1:0",
|
||||
EU_META_LLAMA_3_2_1B_INSTRUCT: "eu.meta.llama3-2-1b-instruct-v1:0",
|
||||
EU_META_LLAMA_3_2_3B_INSTRUCT: "eu.meta.llama3-2-3b-instruct-v1:0",
|
||||
};
|
||||
|
||||
export type INFERENCE_BEDROCK_MODELS =
|
||||
(typeof INFERENCE_BEDROCK_MODELS)[keyof typeof INFERENCE_BEDROCK_MODELS];
|
||||
|
||||
export const INFERENCE_TO_BEDROCK_MAP: Record<
|
||||
INFERENCE_BEDROCK_MODELS,
|
||||
BEDROCK_MODELS
|
||||
> = {
|
||||
[INFERENCE_BEDROCK_MODELS.US_ANTHROPIC_CLAUDE_3_HAIKU]:
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_HAIKU,
|
||||
[INFERENCE_BEDROCK_MODELS.US_ANTHROPIC_CLAUDE_3_OPUS]:
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_OPUS,
|
||||
[INFERENCE_BEDROCK_MODELS.US_ANTHROPIC_CLAUDE_3_SONNET]:
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_SONNET,
|
||||
[INFERENCE_BEDROCK_MODELS.US_ANTHROPIC_CLAUDE_3_5_SONNET]:
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_5_SONNET,
|
||||
[INFERENCE_BEDROCK_MODELS.US_META_LLAMA_3_2_1B_INSTRUCT]:
|
||||
BEDROCK_MODELS.META_LLAMA3_2_1B_INSTRUCT,
|
||||
[INFERENCE_BEDROCK_MODELS.US_META_LLAMA_3_2_3B_INSTRUCT]:
|
||||
BEDROCK_MODELS.META_LLAMA3_2_3B_INSTRUCT,
|
||||
[INFERENCE_BEDROCK_MODELS.US_META_LLAMA_3_2_11B_INSTRUCT]:
|
||||
BEDROCK_MODELS.META_LLAMA3_2_11B_INSTRUCT,
|
||||
[INFERENCE_BEDROCK_MODELS.US_META_LLAMA_3_2_90B_INSTRUCT]:
|
||||
BEDROCK_MODELS.META_LLAMA3_2_90B_INSTRUCT,
|
||||
|
||||
[INFERENCE_BEDROCK_MODELS.EU_ANTHROPIC_CLAUDE_3_HAIKU]:
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_HAIKU,
|
||||
[INFERENCE_BEDROCK_MODELS.EU_ANTHROPIC_CLAUDE_3_SONNET]:
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_SONNET,
|
||||
[INFERENCE_BEDROCK_MODELS.EU_ANTHROPIC_CLAUDE_3_5_SONNET]:
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_5_SONNET,
|
||||
[INFERENCE_BEDROCK_MODELS.EU_META_LLAMA_3_2_1B_INSTRUCT]:
|
||||
BEDROCK_MODELS.META_LLAMA3_2_1B_INSTRUCT,
|
||||
[INFERENCE_BEDROCK_MODELS.EU_META_LLAMA_3_2_3B_INSTRUCT]:
|
||||
BEDROCK_MODELS.META_LLAMA3_2_3B_INSTRUCT,
|
||||
};
|
||||
|
||||
/*
|
||||
* Values taken from https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html#model-parameters-claude
|
||||
@@ -108,6 +170,10 @@ const CHAT_ONLY_MODELS = {
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_8B_INSTRUCT]: 128000,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_70B_INSTRUCT]: 128000,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_405B_INSTRUCT]: 128000,
|
||||
[BEDROCK_MODELS.META_LLAMA3_2_1B_INSTRUCT]: 131000,
|
||||
[BEDROCK_MODELS.META_LLAMA3_2_3B_INSTRUCT]: 131000,
|
||||
[BEDROCK_MODELS.META_LLAMA3_2_11B_INSTRUCT]: 128000,
|
||||
[BEDROCK_MODELS.META_LLAMA3_2_90B_INSTRUCT]: 128000,
|
||||
[BEDROCK_MODELS.MISTRAL_7B_INSTRUCT]: 32000,
|
||||
[BEDROCK_MODELS.MISTRAL_MIXTRAL_7B_INSTRUCT]: 32000,
|
||||
[BEDROCK_MODELS.MISTRAL_MIXTRAL_LARGE_2402]: 32000,
|
||||
@@ -138,17 +204,25 @@ export const STREAMING_MODELS = new Set([
|
||||
BEDROCK_MODELS.META_LLAMA3_1_8B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_1_70B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_1_405B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_2_1B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_2_3B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_2_11B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_2_90B_INSTRUCT,
|
||||
BEDROCK_MODELS.MISTRAL_7B_INSTRUCT,
|
||||
BEDROCK_MODELS.MISTRAL_MIXTRAL_7B_INSTRUCT,
|
||||
BEDROCK_MODELS.MISTRAL_MIXTRAL_LARGE_2402,
|
||||
]);
|
||||
|
||||
export const TOOL_CALL_MODELS = [
|
||||
export const TOOL_CALL_MODELS: BEDROCK_MODELS[] = [
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_SONNET,
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_HAIKU,
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_OPUS,
|
||||
BEDROCK_MODELS.ANTHROPIC_CLAUDE_3_5_SONNET,
|
||||
BEDROCK_MODELS.META_LLAMA3_1_405B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_2_1B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_2_3B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_2_11B_INSTRUCT,
|
||||
BEDROCK_MODELS.META_LLAMA3_2_90B_INSTRUCT,
|
||||
];
|
||||
|
||||
const getProvider = (model: string): Provider => {
|
||||
@@ -165,7 +239,7 @@ const getProvider = (model: string): Provider => {
|
||||
};
|
||||
|
||||
export type BedrockModelParams = {
|
||||
model: keyof typeof BEDROCK_FOUNDATION_LLMS;
|
||||
model: BEDROCK_MODELS | INFERENCE_BEDROCK_MODELS;
|
||||
temperature?: number;
|
||||
topP?: number;
|
||||
maxTokens?: number;
|
||||
@@ -184,6 +258,10 @@ export const BEDROCK_MODEL_MAX_TOKENS: Partial<Record<BEDROCK_MODELS, number>> =
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_8B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_70B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_1_405B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_2_1B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_2_3B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_2_11B_INSTRUCT]: 2048,
|
||||
[BEDROCK_MODELS.META_LLAMA3_2_90B_INSTRUCT]: 2048,
|
||||
};
|
||||
|
||||
const DEFAULT_BEDROCK_PARAMS = {
|
||||
@@ -192,14 +270,15 @@ const DEFAULT_BEDROCK_PARAMS = {
|
||||
maxTokens: 1024, // required by anthropic
|
||||
};
|
||||
|
||||
export type BedrockParams = BedrockModelParams & BedrockRuntimeClientConfig;
|
||||
export type BedrockParams = BedrockRuntimeClientConfig & BedrockModelParams;
|
||||
|
||||
/**
|
||||
* ToolCallLLM for Bedrock
|
||||
*/
|
||||
export class Bedrock extends ToolCallLLM<BedrockAdditionalChatOptions> {
|
||||
private client: BedrockRuntimeClient;
|
||||
model: keyof typeof BEDROCK_FOUNDATION_LLMS;
|
||||
protected actualModel: BEDROCK_MODELS | INFERENCE_BEDROCK_MODELS;
|
||||
model: BEDROCK_MODELS;
|
||||
temperature: number;
|
||||
topP: number;
|
||||
maxTokens?: number;
|
||||
@@ -216,8 +295,8 @@ export class Bedrock extends ToolCallLLM<BedrockAdditionalChatOptions> {
|
||||
...params
|
||||
}: BedrockParams) {
|
||||
super();
|
||||
|
||||
this.model = model;
|
||||
this.actualModel = model;
|
||||
this.model = INFERENCE_TO_BEDROCK_MAP[model] ?? model;
|
||||
this.provider = getProvider(this.model);
|
||||
this.maxTokens = maxTokens ?? DEFAULT_BEDROCK_PARAMS.maxTokens;
|
||||
this.temperature = temperature ?? DEFAULT_BEDROCK_PARAMS.temperature;
|
||||
@@ -240,7 +319,7 @@ export class Bedrock extends ToolCallLLM<BedrockAdditionalChatOptions> {
|
||||
temperature: this.temperature,
|
||||
topP: this.topP,
|
||||
maxTokens: this.maxTokens,
|
||||
contextWindow: BEDROCK_FOUNDATION_LLMS[this.model],
|
||||
contextWindow: BEDROCK_FOUNDATION_LLMS[this.model] ?? 128000,
|
||||
tokenizer: undefined,
|
||||
};
|
||||
}
|
||||
@@ -255,6 +334,8 @@ export class Bedrock extends ToolCallLLM<BedrockAdditionalChatOptions> {
|
||||
params.additionalChatOptions,
|
||||
);
|
||||
const command = new InvokeModelCommand(input);
|
||||
command.input.modelId = this.actualModel;
|
||||
|
||||
const response = await this.client.send(command);
|
||||
let options: ToolCallLLMMessageOptions = {};
|
||||
if (this.supportToolCall) {
|
||||
@@ -286,6 +367,8 @@ export class Bedrock extends ToolCallLLM<BedrockAdditionalChatOptions> {
|
||||
params.additionalChatOptions,
|
||||
);
|
||||
const command = new InvokeModelWithResponseStreamCommand(input);
|
||||
command.input.modelId = this.actualModel;
|
||||
|
||||
const response = await this.client.send(command);
|
||||
|
||||
if (response.body) yield* this.provider.reduceStream(response.body);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user