Compare commits

..

31 Commits

Author SHA1 Message Date
Marcus Schiesser 951f215723 Merge branch 'main' into feat/build-wasm-with-extism 2024-09-16 15:40:17 +07:00
Thuc Pham 9447654332 Create shy-bottles-shop.md 2024-09-12 14:42:33 +07:00
Thuc Pham 3293c22ade Merge branch 'main' into feat/build-wasm-with-extism 2024-09-12 14:41:43 +07:00
Thuc Pham 33d57d1caf update test 2024-09-12 14:24:10 +07:00
Thuc Pham 92d0d098ab add todo tool example 2024-09-12 14:14:18 +07:00
Thuc Pham f76abceb8f refactor: remove enum 2024-09-12 14:09:34 +07:00
Thuc Pham 191986b337 refactor: create tool class params 2024-09-12 13:59:17 +07:00
Thuc Pham d718f4334e fix: upgrade extism to fix worker bug 2024-09-12 13:47:57 +07:00
Thuc Pham f34ea4563a Merge branch 'main' into feat/build-wasm-with-extism 2024-09-11 09:45:52 +07:00
Thuc Pham fda48fae63 fix: wrong path ts config.json 2024-09-09 18:43:14 +07:00
Thuc Pham 660eab8045 fix: e2e 2024-09-09 18:41:50 +07:00
Thuc Pham d95ed78ca4 fix: lint depend on build 2024-09-09 18:36:05 +07:00
Thuc Pham 8a73dac583 test wiki 2024-09-09 18:32:24 +07:00
Thuc Pham f7b666e24a refactor: add package.json to examples 2024-09-09 18:24:39 +07:00
Thuc Pham d48724fa1e fix: update doc 2024-09-09 17:28:01 +07:00
Thuc Pham 879c15f951 fix: lint 2024-09-09 17:22:34 +07:00
Thuc Pham 6cc8595d44 fix: typo and use same d.ts file for all tools 2024-09-09 17:20:22 +07:00
Thuc Pham 7710d9669f add getMetadata to wiki python example 2024-09-09 12:18:29 +07:00
Thuc Pham 1eddb6e8f3 export type 2024-09-09 12:13:04 +07:00
Thuc Pham 54abd709b2 feat: example with agent 2024-09-09 12:10:15 +07:00
Thuc Pham 507012a0c9 feat: ExtismToolFactory 2024-09-09 12:01:36 +07:00
Thuc Pham 4b74096fb6 update readme 2024-09-06 17:59:02 +07:00
Thuc Pham dfb6c2563a feat: add js example 2024-09-06 17:55:14 +07:00
Thuc Pham 9df0d63821 feat: make agent example 2024-09-06 17:42:11 +07:00
Thuc Pham 5c34d3a9cc create abstract ExtismTool 2024-09-06 17:08:13 +07:00
Thuc Pham fbb5ece07e fix: install extism for all tests 2024-09-06 16:39:05 +07:00
Thuc Pham de4d8ffb1d install extism for all actions 2024-09-06 16:34:42 +07:00
Thuc Pham efbd61f124 install extism-js 2024-09-06 16:30:15 +07:00
Thuc Pham ecc54cb540 fix: lock 2024-09-06 16:09:42 +07:00
Thuc Pham 02c81989c6 feat: detach packages for extism 2024-09-06 16:07:55 +07:00
Thuc Pham ccfc11c8cb feat: build wasm with extism 2024-09-06 12:39:28 +07:00
403 changed files with 14918 additions and 26093 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"llamaindex": patch
---
feat: update JinaAIEmbedding, support embedding v3
+5
View File
@@ -0,0 +1,5 @@
---
"@llamaindex/extism-tools": patch
---
Build WASM tools with extism
@@ -19,6 +19,10 @@ jobs:
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install Extism
run: |
curl -O https://raw.githubusercontent.com/extism/js-pdk/main/install.sh
sh install.sh
- name: Install dependencies
run: pnpm install
- name: Run lint
+6 -1
View File
@@ -18,6 +18,11 @@ jobs:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install Extism
run: |
curl -O https://raw.githubusercontent.com/extism/js-pdk/main/install.sh
sh install.sh
- name: Install dependencies
run: pnpm install
@@ -25,4 +30,4 @@ jobs:
run: pnpm run build
- name: Pre Release
run: pnpx pkg-pr-new publish ./packages/* ./packages/providers/*
run: pnpx pkg-pr-new publish ./packages/*
+5
View File
@@ -23,6 +23,11 @@ jobs:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install Extism
run: |
curl -O https://raw.githubusercontent.com/extism/js-pdk/main/install.sh
sh install.sh
- name: Install dependencies
run: pnpm install
+43 -32
View File
@@ -13,10 +13,8 @@ concurrency:
cancel-in-progress: true
env:
POSTGRES_USER: runneradmin
POSTGRES_HOST_AUTH_METHOD: trust
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_TEAM: ${{ vars.TURBO_TEAM }}
TURBO_REMOTE_ONLY: true
jobs:
e2e:
@@ -44,6 +42,10 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
- name: Install Extism
run: |
curl -O https://raw.githubusercontent.com/extism/js-pdk/main/install.sh
sh install.sh
- name: Install dependencies
run: pnpm install
- name: Run E2E Tests
@@ -64,6 +66,10 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
cache: "pnpm"
- name: Install Extism
run: |
curl -O https://raw.githubusercontent.com/extism/js-pdk/main/install.sh
sh install.sh
- name: Install dependencies
run: pnpm install
- name: Run tests
@@ -79,6 +85,10 @@ jobs:
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install Extism
run: |
curl -O https://raw.githubusercontent.com/extism/js-pdk/main/install.sh
sh install.sh
- name: Install dependencies
run: pnpm install
- name: Build
@@ -89,7 +99,13 @@ jobs:
- name: Run Type Check
run: pnpm run type-check
- name: Run Circular Dependency Check
run: pnpm run circular-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
e2e-llamaindex-examples:
strategy:
fail-fast: false
@@ -100,7 +116,6 @@ jobs:
- nextjs-edge-runtime
- nextjs-node-runtime
- waku-query-engine
- llama-parse-browser
runs-on: ubuntu-latest
name: Build LlamaIndex Example (${{ matrix.packages }})
steps:
@@ -111,6 +126,10 @@ jobs:
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install Extism
run: |
curl -O https://raw.githubusercontent.com/extism/js-pdk/main/install.sh
sh install.sh
- name: Install dependencies
run: pnpm install
- name: Build llamaindex
@@ -130,42 +149,34 @@ jobs:
with:
node-version-file: ".nvmrc"
cache: "pnpm"
- name: Install Extism
run: |
curl -O https://raw.githubusercontent.com/extism/js-pdk/main/install.sh
sh install.sh
- name: Install dependencies
run: pnpm install
- name: Build
run: pnpm run build
- name: Copy examples
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
- name: Pack packages
run: |
for dir in packages/*; do
if [ -d "$dir" ] && [ -f "$dir/package.json" ] && [[ ! "$dir" =~ autotool ]]; then
echo "Packing $dir"
pnpm pack --pack-destination ${{ runner.temp }} -C $dir
else
echo "Skipping $dir, no package.json found"
fi
done
- name: Pack provider packages
run: |
for dir in packages/providers/*; do
if [ -d "$dir" ] && [ -f "$dir/package.json" ]; then
echo "Packing $dir"
pnpm pack --pack-destination ${{ runner.temp }} -C $dir
else
echo "Skipping $dir, no package.json found"
fi
done
- 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/core
run: pnpm pack --pack-destination ${{ runner.temp }}
working-directory: packages/core
- name: Pack @llamaindex/env
run: pnpm pack --pack-destination ${{ runner.temp }}
working-directory: packages/env
- name: Pack llamaindex
run: pnpm pack --pack-destination ${{ runner.temp }}
working-directory: packages/llamaindex
- name: Install
run: npm add ${{ runner.temp }}/*.tgz
working-directory: ${{ runner.temp }}/examples
- 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
+49 -102
View File
@@ -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 JS runtime environments with TypeScript support.
Use your own data with large language models (LLMs, OpenAI ChatGPT and others) in Typescript and Javascript.
Documentation: https://ts.llamaindex.ai/
@@ -19,36 +19,17 @@ 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.
## Compatibility
### Multiple JS Environment Support
## Multiple JS Environment Support
LlamaIndex.TS supports multiple JS environments, including:
- Node.js (18, 20, 22) ✅
- Deno ✅
- Bun ✅
- Nitro
- Vercel Edge Runtime ✅ (with some limitations)
- Cloudflare Workers ✅ (with some limitations)
- React Server Components (Next.js)
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
@@ -96,7 +77,7 @@ See more about [moduleResolution](https://www.typescriptlang.org/docs/handbook/m
### Node.js
```ts
import fs from "node:fs/promises";
import fs from "fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
async function main() {
@@ -130,9 +111,9 @@ main();
node --import tsx ./main.ts
```
### Next.js
### React Server Component (Next.js, Waku, Redwood.JS...)
You will need to add a llamaindex plugin to your Next.js project.
First, you will need to add a llamaindex plugin to your Next.js project.
```js
// next.config.js
@@ -143,18 +124,20 @@ module.exports = withLlamaIndex({
});
```
### React Server Actions
You can combine `ai` with `llamaindex` in Next.js, Waku or Redwood.js with RSC (React Server Components).
You can combine `ai` with `llamaindex` in Next.js with RSC (React Server Components).
```tsx
// src/apps/page.tsx
"use client";
import { chatWithAgent } from "@/actions";
import type { JSX } from "react";
import { useActionState } from "react";
import { useFormState } from "react-dom";
// You can use the Edge runtime in Next.js by adding this line:
// export const runtime = "edge";
export default function Home() {
const [ui, action] = useActionState<JSX.Element | null>(async () => {
const [ui, action] = useFormState<JSX.Element | null>(async () => {
return chatWithAgent("hello!", []);
}, null);
return (
@@ -184,13 +167,11 @@ export async function chatWithAgent(
// ... adding your tools here
],
});
const responseStream = await agent.chat(
{
message: question,
chatHistory: prevMessages,
},
true,
);
const responseStream = await agent.chat({
stream: true,
message: question,
chatHistory: prevMessages,
});
const uiStream = createStreamableUI(<div>loading...</div>);
responseStream
.pipeTo(
@@ -208,48 +189,6 @@ export async function chatWithAgent(
}
```
### Cloudflare Workers
> [!TIP]
> Some modules are not supported in Cloudflare Workers which require Node.js APIs.
```ts
// add `OPENAI_API_KEY` to the `.dev.vars` file
interface Env {
OPENAI_API_KEY: string;
}
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);
},
};
```
### Vite
We have some wasm dependencies for better performance. You can use `vite-plugin-wasm` to load them.
@@ -265,9 +204,29 @@ export default {
};
```
### Tips when using in non-Node.js environments
## Playground
When you are importing `llamaindex` in a non-Node.js environment(such as Vercel Edge, Cloudflare Workers, etc.)
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.
## 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.)
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`).
@@ -303,31 +262,19 @@ 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
## Playground
## Supported 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.
- 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
## Contributing:
Please see our [contributing guide](CONTRIBUTING.md) for more information.
You are highly encouraged to contribute to LlamaIndex.TS!
We are in the very early days of LlamaIndex.TS. If youre interested in hacking on it with us check out our [contributing guide](/CONTRIBUTING.md)
## Community
## Bugs? Questions?
Please join our Discord! https://discord.com/invite/eN6D2HQ4aX
-186
View File
@@ -1,191 +1,5 @@
# docs
## 0.0.93
### Patch Changes
- Updated dependencies [ae49ff4]
- Updated dependencies [4c38c1b]
- Updated dependencies [a75af83]
- Updated dependencies [a75af83]
- llamaindex@0.7.1
## 0.0.92
### Patch Changes
- Updated dependencies [1364e8e]
- Updated dependencies [3b7736f]
- Updated dependencies [96fc69c]
- llamaindex@0.7.0
- @llamaindex/examples@0.0.9
## 0.0.91
### Patch Changes
- Updated dependencies [5729bd9]
- llamaindex@0.6.22
## 0.0.90
### Patch Changes
- Updated dependencies [6f75306]
- Updated dependencies [94cb4ad]
- llamaindex@0.6.21
## 0.0.89
### Patch Changes
- Updated dependencies [6a9a7b1]
- llamaindex@0.6.20
## 0.0.88
### Patch Changes
- Updated dependencies [62cba52]
- Updated dependencies [d265e96]
- Updated dependencies [d30bbf7]
- Updated dependencies [53fd00a]
- llamaindex@0.6.19
## 0.0.87
### Patch Changes
- Updated dependencies [5f67820]
- Updated dependencies [fe08d04]
- llamaindex@0.6.18
## 0.0.86
### Patch Changes
- Updated dependencies [ee697fb]
- llamaindex@0.6.17
## 0.0.85
### Patch Changes
- Updated dependencies [63e9846]
- Updated dependencies [6f3a31c]
- llamaindex@0.6.16
## 0.0.84
### Patch Changes
- Updated dependencies [2a82413]
- llamaindex@0.6.15
## 0.0.83
### Patch Changes
- llamaindex@0.6.14
## 0.0.82
### Patch Changes
- llamaindex@0.6.13
## 0.0.81
### Patch Changes
- Updated dependencies [f7b4e94]
- Updated dependencies [78037a6]
- Updated dependencies [1d9e3b1]
- llamaindex@0.6.12
## 0.0.80
### Patch Changes
- Updated dependencies [df441e2]
- llamaindex@0.6.11
## 0.0.79
### Patch Changes
- Updated dependencies [ebc5105]
- Updated dependencies [6cce3b1]
- llamaindex@0.6.10
## 0.0.78
### Patch Changes
- llamaindex@0.6.9
## 0.0.77
### Patch Changes
- Updated dependencies [8b7fdba]
- llamaindex@0.6.8
## 0.0.76
### Patch Changes
- Updated dependencies [23bcc37]
- llamaindex@0.6.7
## 0.0.75
### Patch Changes
- Updated dependencies [d902cc3]
- Updated dependencies [025ffe6]
- Updated dependencies [a659574]
- llamaindex@0.6.6
## 0.0.74
### Patch Changes
- Updated dependencies [e9714db]
- llamaindex@0.6.5
## 0.0.73
### Patch Changes
- Updated dependencies [b48bcc3]
- llamaindex@0.6.4
## 0.0.72
### Patch Changes
- Updated dependencies [2cd1383]
- Updated dependencies [5c4badb]
- llamaindex@0.6.3
## 0.0.71
### Patch Changes
- Updated dependencies [749b43a]
- llamaindex@0.6.2
## 0.0.70
### Patch Changes
- Updated dependencies [fbd5e01]
- Updated dependencies [6b70c54]
- Updated dependencies [1a6137b]
- Updated dependencies [85c2e19]
- llamaindex@0.6.1
## 0.0.69
### Patch Changes
@@ -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 [reader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/cloud/src/reader.ts) for a list of supported file types:
See [LlamaParseReader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/llamaindex/src/readers/LlamaParseReader.ts) for a list of supported file types:
<CodeBlock language="ts">{CodeSource}</CodeBlock>
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "docs",
"version": "0.0.93",
"version": "0.0.69",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
-8
View File
@@ -1,8 +0,0 @@
{
"extends": ["//"],
"tasks": {
"build": {
"outputs": ["build/**", ".docusaurus/**"]
}
}
}
-11
View File
@@ -1,16 +1,5 @@
# examples
## 0.0.9
### Patch Changes
- Updated dependencies [1364e8e]
- Updated dependencies [96fc69c]
- Updated dependencies [3b7736f]
- Updated dependencies [96fc69c]
- llamaindex@0.7.0
- @llamaindex/core@0.3.0
## 0.0.8
### Patch Changes
+1 -1
View File
@@ -13,7 +13,7 @@ import { FunctionTool, OpenAI, ToolCallOptions } from "llamaindex";
}
})();
async function callLLM(init: { model: string }) {
async function callLLM(init: Partial<OpenAI>) {
const csvData =
"Country,Average Height (cm)\nNetherlands,156\nDenmark,158\nNorway,160";
+4 -4
View File
@@ -1,4 +1,4 @@
import { Anthropic, ChatMemoryBuffer, SimpleChatEngine } from "llamaindex";
import { Anthropic, SimpleChatEngine, SimpleChatHistory } 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 ChatMemoryBuffer({
chatHistory: [
const chatHistory = new SimpleChatHistory({
messages: [
{
content: "You want to talk in rhymes.",
role: "system",
@@ -18,7 +18,7 @@ import readline from "node:readline/promises";
});
const chatEngine = new SimpleChatEngine({
llm,
memory: chatHistory,
chatHistory,
});
const rl = readline.createInterface({ input, output });
+2 -5
View File
@@ -1,7 +1,6 @@
import {
AstraDBVectorStore,
Document,
MetadataFilters,
storageContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
@@ -43,10 +42,8 @@ async function main() {
const index = await VectorStoreIndex.fromDocuments(docs, {
storageContext: ctx,
});
const preFilters: MetadataFilters = {
filters: [{ key: "id", operator: "in", value: [123, 789] }],
}; // try changing the filters to see the different results
const queryEngine = index.asQueryEngine({ preFilters });
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "Describe AstraDB.",
});
+2 -2
View File
@@ -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 ChatSummaryMemoryBuffer({ llm });
const chatHistory = new SummaryChatHistory({ llm });
const chatEngine = new SimpleChatEngine({ llm });
const rl = readline.createInterface({ input, output });
+39 -65
View File
@@ -1,83 +1,57 @@
import {
ChromaVectorStore,
Document,
MetadataFilters,
VectorStoreIndex,
storageContextFromDefaults,
} from "llamaindex";
const collectionName = "dogs_with_color";
const collectionName = "dog_colors";
async function main() {
try {
const docs = [
new Document({
text: "The dog is brown",
metadata: {
dogId: "1",
},
}),
new Document({
text: "The dog is red",
metadata: {
dogId: "2",
},
}),
];
console.log("Creating ChromaDB vector store");
const chromaVS = new ChromaVectorStore({ collectionName });
const index = await VectorStoreIndex.fromVectorStore(chromaVS);
const ctx = await storageContextFromDefaults({ vectorStore: chromaVS });
const queryFn = async (filters?: MetadataFilters) => {
console.log("\nQuerying dogs by filters: ", JSON.stringify(filters));
const query = "List all colors of dogs";
const queryEngine = index.asQueryEngine({
preFilters: filters,
similarityTopK: 3,
});
const response = await queryEngine.query({ query });
console.log(response.toString());
};
console.log("Embedding documents and adding to index");
const index = await VectorStoreIndex.fromDocuments(docs, {
storageContext: ctx,
});
await queryFn(); // red, brown, yellow
await queryFn({ filters: [{ key: "dogId", value: "1", operator: "==" }] }); // brown
await queryFn({ filters: [{ key: "dogId", value: "1", operator: "!=" }] }); // red, yellow
await queryFn({
filters: [
{ key: "dogId", value: "1", operator: "==" },
{ key: "dogId", value: "3", operator: "==" },
],
condition: "or",
}); // brown, yellow
await queryFn({
filters: [{ key: "dogId", value: ["1", "2"], operator: "in" }],
}); // red, brown
console.log("Querying index");
const queryEngine = index.asQueryEngine({
preFilters: {
filters: [
{
key: "dogId",
value: "2",
operator: "==",
},
],
},
});
const response = await queryEngine.query({
query: "What is the color of the dog?",
});
console.log(response.toString());
} catch (e) {
console.error(e);
}
}
async function generate() {
const docs = [
new Document({
id_: "doc1",
text: "The dog is brown",
metadata: {
dogId: "1",
},
}),
new Document({
id_: "doc2",
text: "The dog is red",
metadata: {
dogId: "2",
},
}),
new Document({
id_: "doc3",
text: "The dog is yellow",
metadata: {
dogId: "3",
},
}),
];
console.log("Creating ChromaDB vector store");
const chromaVS = new ChromaVectorStore({ collectionName });
const ctx = await storageContextFromDefaults({ vectorStore: chromaVS });
console.log("Embedding documents and adding to index");
await VectorStoreIndex.fromDocuments(docs, {
storageContext: ctx,
});
}
(async () => {
await generate();
await main();
})();
void main();
+1 -12
View File
@@ -1,23 +1,12 @@
import fs from "node:fs/promises";
import {
Document,
Groq,
HuggingFaceEmbedding,
Settings,
VectorStoreIndex,
} from "llamaindex";
import { Document, Groq, 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";
+3 -3
View File
@@ -1,7 +1,7 @@
import {
Document,
getResponseSynthesizer,
NodeWithScore,
ResponseSynthesizer,
SentenceSplitter,
TextNode,
} from "llamaindex";
@@ -14,7 +14,7 @@ import {
console.log(nodes);
const responseSynthesizer = getResponseSynthesizer("compact");
const responseSynthesizer = new ResponseSynthesizer();
const nodesWithScore: NodeWithScore[] = [
{
@@ -30,7 +30,7 @@ import {
const stream = await responseSynthesizer.synthesize(
{
query: "What age am I?",
nodes: nodesWithScore,
nodesWithScore,
},
true,
);
-51
View File
@@ -1,51 +0,0 @@
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 -3
View File
@@ -1,5 +1,4 @@
// call pnpm tsx multimodal/load.ts first to init the storage
import { extractText } from "@llamaindex/core/utils";
import {
ContextChatEngine,
NodeWithScore,
@@ -26,9 +25,8 @@ 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: ${text}`,
`Retrieved ${textNodes.length} text nodes and ${imageNodes.length} image nodes for query: ${query}`,
);
});
+3 -5
View File
@@ -1,6 +1,5 @@
import { extractText } from "@llamaindex/core/utils";
import {
getResponseSynthesizer,
MultiModalResponseSynthesizer,
OpenAI,
Settings,
VectorStoreIndex,
@@ -17,8 +16,7 @@ Settings.llm = new OpenAI({ model: "gpt-4-turbo", maxTokens: 512 });
// Update callbackManager
Settings.callbackManager.on("retrieve-end", (event) => {
const { nodes, query } = event.detail;
const text = extractText(query);
console.log(`Retrieved ${nodes.length} nodes for query: ${text}`);
console.log(`Retrieved ${nodes.length} nodes for query: ${query}`);
});
async function main() {
@@ -29,7 +27,7 @@ async function main() {
});
const queryEngine = index.asQueryEngine({
responseSynthesizer: getResponseSynthesizer("multi_modal"),
responseSynthesizer: new MultiModalResponseSynthesizer(),
retriever: index.asRetriever({ topK: { TEXT: 3, IMAGE: 1 } }),
});
const stream = await queryEngine.query({
+4 -6
View File
@@ -1,24 +1,22 @@
{
"name": "@llamaindex/examples",
"private": true,
"version": "0.0.9",
"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.3.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.7.0",
"llamaindex": "^0.6.0",
"mongodb": "^6.7.0",
"pathe": "^1.1.2",
"postgres": "^3.4.4"
"pathe": "^1.1.2"
},
"devDependencies": {
"@types/node": "^22.5.1",
@@ -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,11 +40,7 @@ async function main(args: any) {
const rdr = new SimpleDirectoryReader(callback);
const docs = await rdr.loadData({ directoryPath: sourceDir });
const pgvs = new PGVectorStore({
clientConfig: {
connectionString: process.env.PG_CONNECTION_STRING,
},
});
const pgvs = new PGVectorStore();
pgvs.setCollection(sourceDir);
await pgvs.clearCollection();
@@ -7,11 +7,7 @@ async function main() {
});
try {
const pgvs = new PGVectorStore({
clientConfig: {
connectionString: process.env.PG_CONNECTION_STRING,
},
});
const pgvs = new PGVectorStore();
// Optional - set your collection name, default is no filter on this field.
// pgvs.setCollection();
+5 -2
View File
@@ -1,7 +1,8 @@
import {
Document,
getResponseSynthesizer,
PromptTemplate,
ResponseSynthesizer,
TreeSummarize,
TreeSummarizePrompt,
VectorStoreIndex,
} from "llamaindex";
@@ -26,7 +27,9 @@ async function main() {
const query = "The quick brown fox jumps over the lazy dog";
const responseSynthesizer = getResponseSynthesizer("tree_summarize");
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new TreeSummarize(),
});
const queryEngine = index.asQueryEngine({
responseSynthesizer,
-42
View File
@@ -39,12 +39,6 @@ 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 });
@@ -79,42 +73,6 @@ 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);
}
+4 -3
View File
@@ -1,7 +1,8 @@
import {
getResponseSynthesizer,
CompactAndRefine,
OpenAI,
PromptTemplate,
ResponseSynthesizer,
Settings,
VectorStoreIndex,
} from "llamaindex";
@@ -28,8 +29,8 @@ Given the CSV file, generate me Typescript code to answer the question: {query}.
`,
});
const responseSynthesizer = getResponseSynthesizer("compact", {
textQATemplate: csvPrompt,
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new CompactAndRefine(undefined, csvPrompt),
});
const queryEngine = index.asQueryEngine({ responseSynthesizer });
+1 -1
View File
@@ -1,4 +1,3 @@
import { createMessageContent } from "@llamaindex/core/response-synthesizers";
import {
Document,
ImageNode,
@@ -7,6 +6,7 @@ import {
PromptTemplate,
VectorStoreIndex,
} from "llamaindex";
import { createMessageContent } from "llamaindex/synthesizers/utils";
const reader = new LlamaParseReader();
async function main() {
-9
View File
@@ -1,9 +0,0 @@
# neon template
PGHOST=
PGDATABASE=
PGUSER=
PGPASSWORD=
ENDPOINT_ID=
# vercel template
POSTGRES_URL=
-45
View File
@@ -1,45 +0,0 @@
/* 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();
-5
View File
@@ -1,5 +0,0 @@
{
"name": "pg-vector-store",
"type": "module",
"private": true
}
-9
View File
@@ -1,9 +0,0 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"types": ["node"],
"skipLibCheck": true
},
"include": ["./**/*.ts"]
}
-30
View File
@@ -1,30 +0,0 @@
// 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();
+6 -2
View File
@@ -2,10 +2,12 @@ import fs from "node:fs/promises";
import {
Anthropic,
CompactAndRefine,
Document,
ResponseSynthesizer,
Settings,
VectorStoreIndex,
getResponseSynthesizer,
anthropicTextQaPrompt,
} from "llamaindex";
// Update llm to use Anthropic
@@ -21,7 +23,9 @@ async function main() {
const document = new Document({ text: essay, id_: path });
// Split text and create embeddings. Store them in a VectorStoreIndex
const responseSynthesizer = getResponseSynthesizer("compact");
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new CompactAndRefine(undefined, anthropicTextQaPrompt),
});
const index = await VectorStoreIndex.fromDocuments([document]);
+6 -3
View File
@@ -25,9 +25,12 @@ async function main() {
similarityCutoff: 0.7,
});
// TODO: cannot pass responseSynthesizer into retriever query engine
const queryEngine = new RetrieverQueryEngine(retriever, undefined, [
nodePostprocessor,
]);
const queryEngine = new RetrieverQueryEngine(
retriever,
undefined,
undefined,
[nodePostprocessor],
);
const response = await queryEngine.query({
query: "What did the author do growing up?",
+11 -5
View File
@@ -1,12 +1,13 @@
import {
BaseVectorStore,
getResponseSynthesizer,
OpenAI,
OpenAIEmbedding,
ResponseSynthesizer,
RetrieverQueryEngine,
Settings,
TextNode,
TreeSummarize,
VectorIndexRetriever,
VectorStore,
VectorStoreIndex,
VectorStoreQuery,
VectorStoreQueryResult,
@@ -24,7 +25,7 @@ Settings.llm = new OpenAI({
* Please do not use this class in production; it's only for demonstration purposes.
*/
class PineconeVectorStore<T extends RecordMetadata = RecordMetadata>
implements BaseVectorStore
implements VectorStore
{
storesText = true;
isEmbeddingQuery = false;
@@ -164,8 +165,13 @@ async function main() {
similarityTopK: 500,
});
const responseSynthesizer = getResponseSynthesizer("tree_summarize");
return new RetrieverQueryEngine(retriever, responseSynthesizer);
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new TreeSummarize(),
});
return new RetrieverQueryEngine(retriever, responseSynthesizer, {
filter,
});
};
// whatever is a key from your metadata
+1 -2
View File
@@ -12,7 +12,6 @@
"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",
@@ -31,7 +30,7 @@
"madge": "^8.0.0",
"prettier": "^3.3.3",
"prettier-plugin-organize-imports": "^4.0.0",
"turbo": "^2.1.2",
"turbo": "^2.1.0",
"typescript": "^5.6.2"
},
"packageManager": "pnpm@9.5.0",
-191
View File
@@ -1,196 +1,5 @@
# @llamaindex/autotool
## 4.0.1
### Patch Changes
- a75af83: refactor: move some llm and embedding to single package
- Updated dependencies [ae49ff4]
- Updated dependencies [4c38c1b]
- Updated dependencies [a75af83]
- Updated dependencies [a75af83]
- llamaindex@0.7.1
## 4.0.0
### Patch Changes
- Updated dependencies [1364e8e]
- Updated dependencies [3b7736f]
- Updated dependencies [96fc69c]
- llamaindex@0.7.0
## 3.0.22
### Patch Changes
- Updated dependencies [5729bd9]
- llamaindex@0.6.22
## 3.0.21
### Patch Changes
- Updated dependencies [6f75306]
- Updated dependencies [94cb4ad]
- llamaindex@0.6.21
## 3.0.20
### Patch Changes
- Updated dependencies [6a9a7b1]
- llamaindex@0.6.20
## 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
@@ -1,214 +1,5 @@
# @llamaindex/autotool-01-node-example
## 0.0.33
### Patch Changes
- Updated dependencies [ae49ff4]
- Updated dependencies [4c38c1b]
- Updated dependencies [a75af83]
- Updated dependencies [a75af83]
- llamaindex@0.7.1
- @llamaindex/autotool@4.0.1
## 0.0.32
### Patch Changes
- Updated dependencies [1364e8e]
- Updated dependencies [3b7736f]
- Updated dependencies [96fc69c]
- llamaindex@0.7.0
- @llamaindex/autotool@4.0.0
## 0.0.31
### Patch Changes
- Updated dependencies [5729bd9]
- llamaindex@0.6.22
- @llamaindex/autotool@3.0.22
## 0.0.30
### Patch Changes
- Updated dependencies [6f75306]
- Updated dependencies [94cb4ad]
- llamaindex@0.6.21
- @llamaindex/autotool@3.0.21
## 0.0.29
### Patch Changes
- Updated dependencies [6a9a7b1]
- llamaindex@0.6.20
- @llamaindex/autotool@3.0.20
## 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
@@ -13,5 +13,5 @@
"scripts": {
"start": "node --import tsx --import @llamaindex/autotool/node ./src/index.ts"
},
"version": "0.0.33"
"version": "0.0.9"
}
@@ -1,214 +1,5 @@
# @llamaindex/autotool-02-next-example
## 0.1.77
### Patch Changes
- Updated dependencies [ae49ff4]
- Updated dependencies [4c38c1b]
- Updated dependencies [a75af83]
- Updated dependencies [a75af83]
- llamaindex@0.7.1
- @llamaindex/autotool@4.0.1
## 0.1.76
### Patch Changes
- Updated dependencies [1364e8e]
- Updated dependencies [3b7736f]
- Updated dependencies [96fc69c]
- llamaindex@0.7.0
- @llamaindex/autotool@4.0.0
## 0.1.75
### Patch Changes
- Updated dependencies [5729bd9]
- llamaindex@0.6.22
- @llamaindex/autotool@3.0.22
## 0.1.74
### Patch Changes
- Updated dependencies [6f75306]
- Updated dependencies [94cb4ad]
- llamaindex@0.6.21
- @llamaindex/autotool@3.0.21
## 0.1.73
### Patch Changes
- Updated dependencies [6a9a7b1]
- llamaindex@0.6.20
- @llamaindex/autotool@3.0.20
## 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
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/autotool-02-next-example",
"private": true,
"version": "0.1.77",
"version": "0.1.53",
"scripts": {
"dev": "next dev",
"build": "next build",
+3 -3
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/autotool",
"type": "module",
"version": "4.0.1",
"version": "3.0.0",
"description": "auto transpile your JS function to LLM Agent compatible",
"files": [
"dist",
@@ -70,9 +70,9 @@
"@swc/types": "^0.1.12",
"@types/json-schema": "^7.0.15",
"@types/node": "^22.5.1",
"bunchee": "5.5.1",
"bunchee": "5.3.2",
"llamaindex": "workspace:*",
"next": "14.2.11",
"next": "14.2.7",
"rollup": "^4.21.2",
"tsx": "^4.19.0",
"typescript": "^5.6.2",
-105
View File
@@ -1,110 +1,5 @@
# @llamaindex/cloud
## 1.0.1
### Patch Changes
- 4c38c1b: fix(cloud): do not detect file type in llama parse
- 24d065f: Log Parse Job Errors when verbose is enabled
- a75af83: refactor: move some llm and embedding to single package
- Updated dependencies [ae49ff4]
- Updated dependencies [a75af83]
- @llamaindex/env@0.1.14
- @llamaindex/core@0.3.1
## 1.0.0
### Patch Changes
- Updated dependencies [1364e8e]
- Updated dependencies [96fc69c]
- @llamaindex/core@0.3.0
## 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
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
+4155 -9486
View File
File diff suppressed because it is too large Load Diff
+10 -31
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/cloud",
"version": "1.0.1",
"version": "0.2.4",
"type": "module",
"license": "MIT",
"scripts": {
@@ -9,54 +9,33 @@
},
"files": [
"openapi.json",
"./api",
"./reader"
"dist"
],
"exports": {
"./openapi.json": "./openapi.json",
"./api": {
"require": {
"types": "./api/dist/index.d.cts",
"default": "./api/dist/index.cjs"
"types": "./dist/api.d.cts",
"default": "./dist/api.cjs"
},
"import": {
"types": "./api/dist/index.d.ts",
"default": "./api/dist/index.js"
"types": "./dist/api.d.ts",
"default": "./dist/api.js"
},
"default": {
"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"
"types": "./dist/api.d.ts",
"default": "./dist/api.js"
}
}
},
"repository": {
"type": "git",
"url": "https://github.com/run-llama/LlamaIndexTS.git",
"url": "https://github.com/himself65/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.5.1"
},
"peerDependencies": {
"@llamaindex/core": "workspace:*",
"@llamaindex/env": "workspace:*"
"bunchee": "5.3.2"
}
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-3
View File
@@ -1,3 +0,0 @@
export async function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
+2 -11
View File
@@ -8,17 +8,8 @@
"moduleResolution": "Bundler",
"skipLibCheck": true,
"strict": true,
"lib": ["DOM", "ESNext"],
"types": []
"lib": ["DOM", "ESNext"]
},
"include": ["./src"],
"exclude": ["node_modules"],
"references": [
{
"path": "../core/tsconfig.json"
},
{
"path": "../env/tsconfig.json"
}
]
"exclude": ["node_modules"]
}
-8
View File
@@ -1,8 +0,0 @@
{
"extends": ["//"],
"tasks": {
"build": {
"outputs": ["**/dist/**", "src/client/**"]
}
}
}
-117
View File
@@ -1,122 +1,5 @@
# @llamaindex/community
## 0.0.49
### Patch Changes
- a75af83: refactor: move some llm and embedding to single package
- Updated dependencies [ae49ff4]
- Updated dependencies [a75af83]
- @llamaindex/env@0.1.14
- @llamaindex/core@0.3.1
## 0.0.48
### Patch Changes
- Updated dependencies [1364e8e]
- Updated dependencies [96fc69c]
- @llamaindex/core@0.3.0
## 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
+2 -5
View File
@@ -5,11 +5,8 @@
## 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, 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)
- 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
## LICENSE
+2 -3
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/community",
"description": "Community package for LlamaIndexTS",
"version": "0.0.49",
"version": "0.0.34",
"type": "module",
"types": "dist/type/index.d.ts",
"main": "dist/cjs/index.js",
@@ -43,10 +43,9 @@
},
"devDependencies": {
"@types/node": "^22.5.1",
"bunchee": "5.5.1"
"bunchee": "5.3.2"
},
"dependencies": {
"@aws-sdk/client-bedrock-agent-runtime": "^3.642.0",
"@aws-sdk/client-bedrock-runtime": "^3.642.0",
"@llamaindex/core": "workspace:*",
"@llamaindex/env": "workspace:*"
-3
View File
@@ -2,7 +2,4 @@ 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,10 +6,7 @@ import type {
MessageContentDetail,
ToolCallLLMMessageOptions,
} from "@llamaindex/core/llms";
import {
extractDataUrlComponents,
mapMessageContentToMessageContentDetails,
} from "../utils";
import { mapMessageContentToMessageContentDetails } from "../utils";
import type {
AnthropicContent,
AnthropicImageContent,
@@ -146,6 +143,27 @@ 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(
+37 -120
View File
@@ -16,7 +16,7 @@ import {
ToolCallLLM,
type ToolCallLLMMessageOptions,
} from "@llamaindex/core/llms";
import { streamConverter } from "@llamaindex/core/utils";
import { streamConverter, wrapLLMEvent } from "@llamaindex/core/utils";
import {
type BedrockAdditionalChatOptions,
type BedrockChatStreamResponse,
@@ -24,7 +24,6 @@ import {
} from "./provider";
import { mapMessageContentToMessageContentDetails } from "./utils";
import { wrapLLMEvent } from "@llamaindex/core/decorator";
import { AnthropicProvider } from "./anthropic/provider";
import { MetaProvider } from "./meta/provider";
@@ -47,96 +46,35 @@ export type BedrockChatParamsNonStreaming = LLMChatParamsNonStreaming<
export type BedrockChatNonStreamResponse =
ChatResponse<ToolCallLLMMessageOptions>;
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,
};
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",
}
/*
* Values taken from https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html#model-parameters-claude
@@ -170,10 +108,6 @@ 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,
@@ -204,25 +138,17 @@ 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: BEDROCK_MODELS[] = [
export const TOOL_CALL_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 => {
@@ -239,7 +165,7 @@ const getProvider = (model: string): Provider => {
};
export type BedrockModelParams = {
model: BEDROCK_MODELS | INFERENCE_BEDROCK_MODELS;
model: keyof typeof BEDROCK_FOUNDATION_LLMS;
temperature?: number;
topP?: number;
maxTokens?: number;
@@ -258,10 +184,6 @@ 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 = {
@@ -270,15 +192,14 @@ const DEFAULT_BEDROCK_PARAMS = {
maxTokens: 1024, // required by anthropic
};
export type BedrockParams = BedrockRuntimeClientConfig & BedrockModelParams;
export type BedrockParams = BedrockModelParams & BedrockRuntimeClientConfig;
/**
* ToolCallLLM for Bedrock
*/
export class Bedrock extends ToolCallLLM<BedrockAdditionalChatOptions> {
private client: BedrockRuntimeClient;
protected actualModel: BEDROCK_MODELS | INFERENCE_BEDROCK_MODELS;
model: BEDROCK_MODELS;
model: keyof typeof BEDROCK_FOUNDATION_LLMS;
temperature: number;
topP: number;
maxTokens?: number;
@@ -295,8 +216,8 @@ export class Bedrock extends ToolCallLLM<BedrockAdditionalChatOptions> {
...params
}: BedrockParams) {
super();
this.actualModel = model;
this.model = INFERENCE_TO_BEDROCK_MAP[model] ?? model;
this.model = model;
this.provider = getProvider(this.model);
this.maxTokens = maxTokens ?? DEFAULT_BEDROCK_PARAMS.maxTokens;
this.temperature = temperature ?? DEFAULT_BEDROCK_PARAMS.temperature;
@@ -319,7 +240,7 @@ export class Bedrock extends ToolCallLLM<BedrockAdditionalChatOptions> {
temperature: this.temperature,
topP: this.topP,
maxTokens: this.maxTokens,
contextWindow: BEDROCK_FOUNDATION_LLMS[this.model] ?? 128000,
contextWindow: BEDROCK_FOUNDATION_LLMS[this.model],
tokenizer: undefined,
};
}
@@ -334,8 +255,6 @@ 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) {
@@ -367,8 +286,6 @@ 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);
@@ -67,26 +67,21 @@ export class MetaProvider extends Provider<MetaStreamEvent> {
for await (const response of stream) {
const event = this.getStreamingEventResponse(response);
const delta = this.getTextFromStreamResponse(response);
// odd quirk of llama3.1, start token is \n\n
if (
!toolId &&
!event?.generation.trim() &&
event?.generation_token_count === 1 &&
event?.prompt_token_count !== null
event.prompt_token_count !== null
)
continue;
if (delta.startsWith(TOKENS.TOOL_CALL)) {
if (delta === TOKENS.TOOL_CALL) {
toolId = randomUUID();
const parts = delta.split(TOKENS.TOOL_CALL).filter((part) => part);
collecting.push(...parts);
continue;
}
let options: undefined | ToolCallLLMMessageOptions = undefined;
if (toolId && event?.stop_reason === "stop") {
if (delta) collecting.push(delta);
const tool = JSON.parse(collecting.join(""));
options = {
toolCall: [
@@ -115,18 +110,11 @@ export class MetaProvider extends Provider<MetaStreamEvent> {
getRequestBody<T extends ChatMessage>(
metadata: LLMMetadata,
messages: T[],
tools: BaseTool[] = [],
tools?: BaseTool[],
): InvokeModelCommandInput | InvokeModelWithResponseStreamCommandInput {
let prompt: string = "";
let images: string[] = [];
if (metadata.model.startsWith("meta.llama3")) {
const mapped = mapChatMessagesToMetaLlama3Messages({
messages,
tools,
model: metadata.model,
});
prompt = mapped.prompt;
images = mapped.images;
prompt = mapChatMessagesToMetaLlama3Messages(messages, tools);
} else if (metadata.model.startsWith("meta.llama2")) {
prompt = mapChatMessagesToMetaLlama2Messages(messages);
} else {
@@ -139,7 +127,6 @@ export class MetaProvider extends Provider<MetaStreamEvent> {
accept: "application/json",
body: JSON.stringify({
prompt,
images: images.length ? images : undefined,
max_gen_len: metadata.maxTokens,
temperature: metadata.temperature,
top_p: metadata.topP,
@@ -1,12 +1,9 @@
import type {
BaseTool,
ChatMessage,
LLMMetadata,
MessageContentTextDetail,
ToolCallLLMMessageOptions,
} from "@llamaindex/core/llms";
import { extractDataUrlComponents } from "../utils";
import { TOKENS } from "./constants";
import type { MetaMessage } from "./types";
const getToolCallInstructionString = (tool: BaseTool): string => {
@@ -27,7 +24,7 @@ const getToolCallParametersString = (tool: BaseTool): string => {
// ported from https://github.com/meta-llama/llama-agentic-system/blob/main/llama_agentic_system/system_prompt.py
// NOTE: using json instead of the above xml style tool calling works more reliability
export const getToolsPrompt_3_1 = (tools?: BaseTool[]) => {
export const getToolsPrompt = (tools?: BaseTool[]) => {
if (!tools?.length) return "";
const customToolParams = tools.map((tool) => {
@@ -80,46 +77,6 @@ Reminder:
`;
};
export const getToolsPrompt_3_2 = (tools?: BaseTool[]) => {
if (!tools?.length) return "";
return `
You are an expert in composing functions. You are given a question and a set of possible functions.
Based on the question, you will need to make one or more function/tool calls to achieve the purpose.
If none of the function can be used, point it out. If the given question lacks the parameters required by the function,
also point it out. You should only return the function call in tools call sections.
If you decide to invoke any of the function(s), you MUST put it in the format of and start with the token: ${TOKENS.TOOL_CALL}:
{
"name": function_name,
"parameters": parameters,
}
where
{
"name": function_name,
"parameters": parameters, => a JSON dict with the function argument name as key and function argument value as value.
}
Here is an example,
{
"name": "example_function_name",
"parameters": {"example_name": "example_value"}
}
Reminder:
- Function calls MUST follow the specified format
- Required parameters MUST be specified
- Only call one function at a time
- You SHOULD NOT include any other text in the response
- Put the entire function call reply on one line
Here is a list of functions in JSON format that you can invoke.
${JSON.stringify(tools)}
`;
};
export const mapChatRoleToMetaRole = (
role: ChatMessage["role"],
): MetaMessage["role"] => {
@@ -168,46 +125,16 @@ export const mapChatMessagesToMetaMessages = <
/**
* Documentation at https://llama.meta.com/docs/model-cards-and-prompt-formats/meta-llama-3
*/
export const mapChatMessagesToMetaLlama3Messages = <T extends ChatMessage>({
messages,
model,
tools,
}: {
messages: T[];
model: LLMMetadata["model"];
tools?: BaseTool[];
}): { prompt: string; images: string[] } => {
const images: string[] = [];
const textMessages: T[] = [];
messages.forEach((message) => {
if (Array.isArray(message.content)) {
message.content.forEach((content) => {
if (content.type === "image_url") {
const { base64 } = extractDataUrlComponents(content.image_url.url);
images.push(base64);
} else {
textMessages.push(message);
}
});
} else {
textMessages.push(message);
}
});
export const mapChatMessagesToMetaLlama3Messages = <T extends ChatMessage>(
messages: T[],
tools?: BaseTool[],
): string => {
const parts: string[] = [];
let toolsPrompt = "";
if (model.startsWith("meta.llama3-2")) {
toolsPrompt = getToolsPrompt_3_2(tools);
} else if (model.startsWith("meta.llama3-1")) {
toolsPrompt = getToolsPrompt_3_1(tools);
}
if (toolsPrompt) {
if (tools?.length) {
parts.push(
"<|begin_of_text|>",
"<|start_header_id|>system<|end_header_id|>",
toolsPrompt,
getToolsPrompt(tools),
"<|eot_id|>",
);
}
@@ -227,9 +154,7 @@ export const mapChatMessagesToMetaLlama3Messages = <T extends ChatMessage>({
...mapped,
"<|start_header_id|>assistant<|end_header_id|>",
);
const prompt = parts.join("\n");
return { prompt, images };
return parts.join("\n");
};
/**
@@ -11,24 +11,3 @@ export const mapMessageContentToMessageContentDetails = (
export const toUtf8 = (input: Uint8Array): string =>
new TextDecoder("utf-8").decode(input);
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,
};
};
@@ -1,165 +0,0 @@
import type { KnowledgeBaseVectorSearchConfiguration } from "@aws-sdk/client-bedrock-agent-runtime";
import {
BedrockAgentRuntimeClient,
type BedrockAgentRuntimeClientConfig,
type RetrievalFilter,
RetrieveCommand,
type SearchType,
} from "@aws-sdk/client-bedrock-agent-runtime";
import type { QueryBundle } from "@llamaindex/core/query-engine";
import { BaseRetriever } from "@llamaindex/core/retriever";
import { Document, type NodeWithScore } from "@llamaindex/core/schema";
import { extractText } from "@llamaindex/core/utils";
/**
* Interface for the arguments required to initialize an
* AmazonKnowledgeBaseRetriever instance.
*/
export interface AmazonKnowledgeBaseRetrieverArgs {
knowledgeBaseId: string;
topK: number;
region: string;
clientOptions?: BedrockAgentRuntimeClientConfig;
filter?: RetrievalFilter;
overrideSearchType?: SearchType;
}
/**
* Class for interacting with Amazon Bedrock Knowledge Bases, a RAG workflow oriented service
* Extends the BaseRetriever class.
* @example
* ```typescript
* const retriever = new AmazonKnowledgeBaseRetriever({
* topK: 10,
* knowledgeBaseId: "YOUR_KNOWLEDGE_BASE_ID",
* region: "us-east-2",
* clientOptions: {
* credentials: {
* accessKeyId: "YOUR_ACCESS_KEY_ID",
* secretAccessKey: "YOUR_SECRET_ACCESS_KEY",
* },
* },
* });
*
* const docs = await retriever.retrieve({query: "How are clouds formed?"});
* ```
*/
export class AmazonKnowledgeBaseRetriever extends BaseRetriever {
static lc_name() {
return "AmazonKnowledgeBaseRetriever";
}
lc_namespace = ["llamaindex", "retrievers", "amazon_bedrock_knowledge_base"];
knowledgeBaseId: string;
topK: number;
bedrockAgentRuntimeClient: BedrockAgentRuntimeClient;
filter: RetrievalFilter | undefined;
overrideSearchType: SearchType | undefined;
constructor({
knowledgeBaseId,
topK = 10,
clientOptions,
region,
filter,
overrideSearchType,
}: AmazonKnowledgeBaseRetrieverArgs) {
super();
this.topK = topK;
this.filter = filter;
this.overrideSearchType = overrideSearchType;
this.bedrockAgentRuntimeClient = new BedrockAgentRuntimeClient({
region,
...clientOptions,
});
this.knowledgeBaseId = knowledgeBaseId;
}
/**
* Cleans the result text by replacing sequences of whitespace with a
* single space and removing ellipses.
* @param resText The result text to clean.
* @returns The cleaned result text.
*/
cleanResult(resText: string) {
const res = resText.replace(/\s+/g, " ").replace(/\.\.\./g, "");
return res;
}
async queryKnowledgeBase(
query: QueryBundle,
topK: number,
filter?: RetrievalFilter,
overrideSearchType?: SearchType,
): Promise<NodeWithScore[]> {
const retrieveCommand = new RetrieveCommand({
knowledgeBaseId: this.knowledgeBaseId,
retrievalQuery: {
text: extractText(query),
},
retrievalConfiguration: {
vectorSearchConfiguration: {
numberOfResults: topK,
overrideSearchType,
filter,
} as KnowledgeBaseVectorSearchConfiguration,
},
});
const retrieveResponse =
await this.bedrockAgentRuntimeClient.send(retrieveCommand);
return (
retrieveResponse.retrievalResults?.map((result) => {
let source;
switch (result.location?.type) {
case "CONFLUENCE":
source = result.location?.confluenceLocation?.url;
break;
case "S3":
source = result.location?.s3Location?.uri;
break;
case "SALESFORCE":
source = result.location?.salesforceLocation?.url;
break;
case "SHAREPOINT":
source = result.location?.sharePointLocation?.url;
break;
case "WEB":
source = result.location?.webLocation?.url;
break;
default:
source = result.location?.s3Location?.uri;
break;
}
return {
node: new Document({
text: this.cleanResult(result.content?.text || ""),
metadata: {
source,
score: result.score,
...result.metadata,
},
}),
score: result.score ?? 1.0,
};
}) ?? []
);
}
async _retrieve(query: QueryBundle): Promise<NodeWithScore[]> {
return await this.queryKnowledgeBase(
query,
this.topK,
this.filter,
this.overrideSearchType,
);
}
}
-111
View File
@@ -1,116 +1,5 @@
# @llamaindex/core
## 0.3.1
### Patch Changes
- a75af83: refactor: move some llm and embedding to single package
- Updated dependencies [ae49ff4]
- Updated dependencies [a75af83]
- @llamaindex/env@0.1.14
## 0.3.0
### Minor Changes
- 1364e8e: update metadata extractors to use PromptTemplate
- 96fc69c: add defaultQuestionExtractPrompt
## 0.2.12
### Patch Changes
- 5f67820: Fix that node parsers generate nodes with UUIDs
## 0.2.11
### Patch Changes
- ee697fb: fix: generate uuid when inserting to Qdrant
## 0.2.10
### Patch Changes
- 3489e7d: fix: num output incorrect in prompt helper
- 468bda5: fix: correct warning when chunk size smaller than 0
## 0.2.9
### Patch Changes
- b17d439: Fix #1278: resolved issue where the id\_ was not correctly passed as the id when creating a TextNode. As a result, the upsert operation to the vector database was using a generated ID instead of the provided document ID, if available.
## 0.2.8
### Patch Changes
- df441e2: fix: consoleLogger is missing from `@llamaindex/env`
- Updated dependencies [df441e2]
- @llamaindex/env@0.1.13
## 0.2.7
### Patch Changes
- 6cce3b1: feat: support `npm:postgres`
## 0.2.6
### Patch Changes
- 8b7fdba: refactor: move chat engine & retriever into core.
- `chatHistory` in BaseChatEngine now returns `ChatMessage[] | Promise<ChatMessage[]>`, instead of `BaseMemory`
- update `retrieve-end` type
## 0.2.5
### Patch Changes
- d902cc3: Fix context not being sent using ContextChatEngine
## 0.2.4
### Patch Changes
- b48bcc3: feat: add `load-transformers` event type when loading `@xenova/transformers` module
This would benefit user who want to customize the transformer env.
- Updated dependencies [b48bcc3]
- @llamaindex/env@0.1.12
## 0.2.3
### Patch Changes
- 2cd1383: refactor: align `response-synthesizers` & `chat-engine` module
- builtin event system
- correct class extends
- aligin APIs, naming with llama-index python
- move stream out of first parameter to second parameter for the better tyep checking
- remove JSONQueryEngine in `@llamaindex/experimental`, as the code quality is not satisify and we will bring it back later
## 0.2.2
### Patch Changes
- 749b43a: fix: clip embedding transform function
## 0.2.1
### Patch Changes
- ac07e3c: fix: replace instanceof check with `.type` check
- 70ccb4a: Allow arbitrary types in workflow's StartEvent and StopEvent
- ac07e3c: fix: add `console.warn` when import dual module
- Updated dependencies [ac07e3c]
- Updated dependencies [1a6137b]
- Updated dependencies [ac07e3c]
- @llamaindex/env@0.1.11
## 0.2.0
### Minor Changes
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
+71 -233
View File
@@ -1,326 +1,166 @@
{
"name": "@llamaindex/core",
"type": "module",
"version": "0.3.1",
"version": "0.2.0",
"description": "LlamaIndex Core Module",
"exports": {
"./agent": {
"require": {
"types": "./agent/dist/index.d.cts",
"default": "./agent/dist/index.cjs"
},
"import": {
"types": "./agent/dist/index.d.ts",
"default": "./agent/dist/index.js"
},
"default": {
"types": "./agent/dist/index.d.ts",
"default": "./agent/dist/index.js"
}
},
"./objects": {
"require": {
"types": "./objects/dist/index.d.cts",
"default": "./objects/dist/index.cjs"
},
"import": {
"types": "./objects/dist/index.d.ts",
"default": "./objects/dist/index.js"
},
"default": {
"types": "./objects/dist/index.d.ts",
"default": "./objects/dist/index.js"
}
},
"./node-parser": {
"require": {
"types": "./node-parser/dist/index.d.cts",
"default": "./node-parser/dist/index.cjs"
"types": "./dist/node-parser/index.d.cts",
"default": "./dist/node-parser/index.cjs"
},
"import": {
"types": "./node-parser/dist/index.d.ts",
"default": "./node-parser/dist/index.js"
"types": "./dist/node-parser/index.d.ts",
"default": "./dist/node-parser/index.js"
},
"default": {
"types": "./node-parser/dist/index.d.ts",
"default": "./node-parser/dist/index.js"
"types": "./dist/node-parser/index.d.ts",
"default": "./dist/node-parser/index.js"
}
},
"./query-engine": {
"require": {
"types": "./query-engine/dist/index.d.cts",
"default": "./query-engine/dist/index.cjs"
"types": "./dist/query-engine/index.d.cts",
"default": "./dist/query-engine/index.cjs"
},
"import": {
"types": "./query-engine/dist/index.d.ts",
"default": "./query-engine/dist/index.js"
"types": "./dist/query-engine/index.d.ts",
"default": "./dist/query-engine/index.js"
},
"default": {
"types": "./query-engine/dist/index.d.ts",
"default": "./query-engine/dist/index.js"
"types": "./dist/query-engine/index.d.ts",
"default": "./dist/query-engine/index.js"
}
},
"./llms": {
"require": {
"types": "./llms/dist/index.d.cts",
"default": "./llms/dist/index.cjs"
"types": "./dist/llms/index.d.cts",
"default": "./dist/llms/index.cjs"
},
"import": {
"types": "./llms/dist/index.d.ts",
"default": "./llms/dist/index.js"
"types": "./dist/llms/index.d.ts",
"default": "./dist/llms/index.js"
},
"default": {
"types": "./llms/dist/index.d.ts",
"default": "./llms/dist/index.js"
"types": "./dist/llms/index.d.ts",
"default": "./dist/llms/index.js"
}
},
"./decorator": {
"require": {
"types": "./decorator/dist/index.d.cts",
"default": "./decorator/dist/index.cjs"
"types": "./dist/decorator/index.d.cts",
"default": "./dist/decorator/index.cjs"
},
"import": {
"types": "./decorator/dist/index.d.ts",
"default": "./decorator/dist/index.js"
"types": "./dist/decorator/index.d.ts",
"default": "./dist/decorator/index.js"
},
"default": {
"types": "./decorator/dist/index.d.ts",
"default": "./decorator/dist/index.js"
"types": "./dist/decorator/index.d.ts",
"default": "./dist/decorator/index.js"
}
},
"./embeddings": {
"require": {
"types": "./embeddings/dist/index.d.cts",
"default": "./embeddings/dist/index.cjs"
"types": "./dist/embeddings/index.d.cts",
"default": "./dist/embeddings/index.cjs"
},
"import": {
"types": "./embeddings/dist/index.d.ts",
"default": "./embeddings/dist/index.js"
"types": "./dist/embeddings/index.d.ts",
"default": "./dist/embeddings/index.js"
},
"default": {
"types": "./embeddings/dist/index.d.ts",
"default": "./embeddings/dist/index.js"
"types": "./dist/embeddings/index.d.ts",
"default": "./dist/embeddings/index.js"
}
},
"./global": {
"require": {
"types": "./global/dist/index.d.cts",
"default": "./global/dist/index.cjs"
"types": "./dist/global/index.d.cts",
"default": "./dist/global/index.cjs"
},
"import": {
"types": "./global/dist/index.d.ts",
"default": "./global/dist/index.js"
"types": "./dist/global/index.d.ts",
"default": "./dist/global/index.js"
},
"default": {
"types": "./global/dist/index.d.ts",
"default": "./global/dist/index.js"
"types": "./dist/global/index.d.ts",
"default": "./dist/global/index.js"
}
},
"./schema": {
"require": {
"types": "./schema/dist/index.d.cts",
"default": "./schema/dist/index.cjs"
"types": "./dist/schema/index.d.cts",
"default": "./dist/schema/index.cjs"
},
"import": {
"types": "./schema/dist/index.d.ts",
"default": "./schema/dist/index.js"
"types": "./dist/schema/index.d.ts",
"default": "./dist/schema/index.js"
},
"default": {
"types": "./schema/dist/index.d.ts",
"default": "./schema/dist/index.js"
"types": "./dist/schema/index.d.ts",
"default": "./dist/schema/index.js"
}
},
"./utils": {
"require": {
"types": "./utils/dist/index.d.cts",
"default": "./utils/dist/index.cjs"
"types": "./dist/utils/index.d.cts",
"default": "./dist/utils/index.cjs"
},
"import": {
"types": "./utils/dist/index.d.ts",
"default": "./utils/dist/index.js"
"types": "./dist/utils/index.d.ts",
"default": "./dist/utils/index.js"
},
"default": {
"types": "./utils/dist/index.d.ts",
"default": "./utils/dist/index.js"
"types": "./dist/utils/index.d.ts",
"default": "./dist/utils/index.js"
}
},
"./prompts": {
"require": {
"types": "./prompts/dist/index.d.cts",
"default": "./prompts/dist/index.cjs"
"types": "./dist/prompts/index.d.cts",
"default": "./dist/prompts/index.cjs"
},
"import": {
"types": "./prompts/dist/index.d.ts",
"default": "./prompts/dist/index.js"
"types": "./dist/prompts/index.d.ts",
"default": "./dist/prompts/index.js"
},
"default": {
"types": "./prompts/dist/index.d.ts",
"default": "./prompts/dist/index.js"
"types": "./dist/prompts/index.d.ts",
"default": "./dist/prompts/index.js"
}
},
"./indices": {
"require": {
"types": "./indices/dist/index.d.cts",
"default": "./indices/dist/index.cjs"
"types": "./dist/indices/index.d.cts",
"default": "./dist/indices/index.cjs"
},
"import": {
"types": "./indices/dist/index.d.ts",
"default": "./indices/dist/index.js"
"types": "./dist/indices/index.d.ts",
"default": "./dist/indices/index.js"
},
"default": {
"types": "./indices/dist/index.d.ts",
"default": "./indices/dist/index.js"
"types": "./dist/indices/index.d.ts",
"default": "./dist/indices/index.js"
}
},
"./workflow": {
"require": {
"types": "./workflow/dist/index.d.cts",
"default": "./workflow/dist/index.cjs"
"types": "./dist/workflow/index.d.cts",
"default": "./dist/workflow/index.cjs"
},
"import": {
"types": "./workflow/dist/index.d.ts",
"default": "./workflow/dist/index.js"
"types": "./dist/workflow/index.d.ts",
"default": "./dist/workflow/index.js"
},
"default": {
"types": "./workflow/dist/index.d.ts",
"default": "./workflow/dist/index.js"
}
},
"./memory": {
"require": {
"types": "./memory/dist/index.d.cts",
"default": "./memory/dist/index.cjs"
},
"import": {
"types": "./memory/dist/index.d.ts",
"default": "./memory/dist/index.js"
},
"default": {
"types": "./memory/dist/index.d.ts",
"default": "./memory/dist/index.js"
}
},
"./storage/chat-store": {
"require": {
"types": "./storage/chat-store/dist/index.d.cts",
"default": "./storage/chat-store/dist/index.cjs"
},
"import": {
"types": "./storage/chat-store/dist/index.d.ts",
"default": "./storage/chat-store/dist/index.js"
},
"default": {
"types": "./storage/chat-store/dist/index.d.ts",
"default": "./storage/chat-store/dist/index.js"
}
},
"./response-synthesizers": {
"require": {
"types": "./response-synthesizers/dist/index.d.cts",
"default": "./response-synthesizers/dist/index.cjs"
},
"import": {
"types": "./response-synthesizers/dist/index.d.ts",
"default": "./response-synthesizers/dist/index.js"
},
"default": {
"types": "./response-synthesizers/dist/index.d.ts",
"default": "./response-synthesizers/dist/index.js"
}
},
"./chat-engine": {
"require": {
"types": "./chat-engine/dist/index.d.cts",
"default": "./chat-engine/dist/index.cjs"
},
"import": {
"types": "./chat-engine/dist/index.d.ts",
"default": "./chat-engine/dist/index.js"
},
"default": {
"types": "./chat-engine/dist/index.d.ts",
"default": "./chat-engine/dist/index.js"
}
},
"./retriever": {
"require": {
"types": "./retriever/dist/index.d.cts",
"default": "./retriever/dist/index.cjs"
},
"import": {
"types": "./retriever/dist/index.d.ts",
"default": "./retriever/dist/index.js"
},
"default": {
"types": "./retriever/dist/index.d.ts",
"default": "./retriever/dist/index.js"
}
},
"./vector-store": {
"require": {
"types": "./vector-store/dist/index.d.cts",
"default": "./vector-store/dist/index.cjs"
},
"import": {
"types": "./vector-store/dist/index.d.ts",
"default": "./vector-store/dist/index.js"
},
"default": {
"types": "./vector-store/dist/index.d.ts",
"default": "./vector-store/dist/index.js"
}
},
"./tools": {
"require": {
"types": "./tools/dist/index.d.cts",
"default": "./tools/dist/index.cjs"
},
"import": {
"types": "./tools/dist/index.d.ts",
"default": "./tools/dist/index.js"
},
"default": {
"types": "./tools/dist/index.d.ts",
"default": "./tools/dist/index.js"
}
},
"./data-structs": {
"require": {
"types": "./data-structs/dist/index.d.cts",
"default": "./data-structs/dist/index.cjs"
},
"import": {
"types": "./data-structs/dist/index.d.ts",
"default": "./data-structs/dist/index.js"
},
"default": {
"types": "./data-structs/dist/index.d.ts",
"default": "./data-structs/dist/index.js"
"types": "./dist/workflow/index.d.ts",
"default": "./dist/workflow/index.js"
}
}
},
"files": [
"./agent",
"./objects",
"./node-parser",
"./query-engine",
"./llms",
"./decorator",
"./embeddings",
"./global",
"./schema",
"./utils",
"./prompts",
"./indices",
"./workflow",
"./memory",
"./storage",
"./response-synthesizers",
"./chat-engine",
"./retriever",
"./vector-store",
"./tools",
"./data-structs"
"dist"
],
"scripts": {
"dev": "bunchee --watch",
@@ -329,12 +169,12 @@
"repository": {
"type": "git",
"directory": "packages/core",
"url": "https://github.com/run-llama/LlamaIndexTS.git"
"url": "https://github.com/himself65/LlamaIndexTS.git"
},
"devDependencies": {
"@edge-runtime/vm": "^4.0.3",
"ajv": "^8.17.1",
"bunchee": "5.5.1",
"bunchee": "5.3.2",
"happy-dom": "^15.7.4",
"natural": "^8.0.1",
"python-format-js": "^1.4.3"
@@ -342,8 +182,6 @@
"dependencies": {
"@llamaindex/env": "workspace:*",
"@types/node": "^22.5.1",
"magic-bytes.js": "^1.10.0",
"zod": "^3.23.8",
"zod-to-json-schema": "^3.23.3"
"zod": "^3.23.8"
}
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-8
View File
@@ -1,8 +0,0 @@
{
"type": "module",
"main": "./dist/index.cjs",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": "./dist/index.js",
"private": true
}
-11
View File
@@ -1,11 +0,0 @@
export { AgentRunner, AgentWorker, type AgentParamsBase } from "./base.js";
export { LLMAgent, LLMAgentWorker, type LLMAgentParams } from "./llm.js";
export type { AgentEndEvent, AgentStartEvent, TaskHandler } from "./types.js";
export {
callTool,
consumeAsyncIterable,
createReadableStream,
stepTools,
stepToolsStreaming,
validateAgentParams,
} from "./utils.js";
-36
View File
@@ -1,36 +0,0 @@
import type { ChatMessage, MessageContent } from "../llms";
import type { BaseMemory } from "../memory";
import { EngineResponse } from "../schema";
export interface BaseChatEngineParams<
AdditionalMessageOptions extends object = object,
> {
message: MessageContent;
/**
* Optional chat history if you want to customize the chat history.
*/
chatHistory?:
| ChatMessage<AdditionalMessageOptions>[]
| BaseMemory<AdditionalMessageOptions>;
}
export interface StreamingChatEngineParams<
AdditionalMessageOptions extends object = object,
> extends BaseChatEngineParams<AdditionalMessageOptions> {
stream: true;
}
export interface NonStreamingChatEngineParams<
AdditionalMessageOptions extends object = object,
> extends BaseChatEngineParams<AdditionalMessageOptions> {
stream?: false;
}
export abstract class BaseChatEngine {
abstract chat(params: NonStreamingChatEngineParams): Promise<EngineResponse>;
abstract chat(
params: StreamingChatEngineParams,
): Promise<AsyncIterable<EngineResponse>>;
abstract chatHistory: ChatMessage[] | Promise<ChatMessage[]>;
}
@@ -1,67 +0,0 @@
import { randomUUID } from "@llamaindex/env";
import type { UUID } from "../global";
import { IndexStructType } from "./struct-type";
export abstract class IndexStruct {
indexId: string;
summary: string | undefined;
constructor(
indexId: UUID = randomUUID(),
summary: string | undefined = undefined,
) {
this.indexId = indexId;
this.summary = summary;
}
toJson(): Record<string, unknown> {
return {
indexId: this.indexId,
summary: this.summary,
};
}
getSummary(): string {
if (this.summary === undefined) {
throw new Error("summary field of the index struct is not set");
}
return this.summary;
}
}
// A table of keywords mapping keywords to text chunks.
export class KeywordTable extends IndexStruct {
table: Map<string, Set<string>> = new Map();
type: IndexStructType = IndexStructType.KEYWORD_TABLE;
addNode(keywords: string[], nodeId: string): void {
keywords.forEach((keyword) => {
if (!this.table.has(keyword)) {
this.table.set(keyword, new Set());
}
this.table.get(keyword)!.add(nodeId);
});
}
deleteNode(keywords: string[], nodeId: string) {
keywords.forEach((keyword) => {
if (this.table.has(keyword)) {
this.table.get(keyword)!.delete(nodeId);
}
});
}
toJson(): Record<string, unknown> {
return {
...super.toJson(),
table: Array.from(this.table.entries()).reduce(
(acc, [keyword, nodeIds]) => {
acc[keyword] = Array.from(nodeIds);
return acc;
},
{} as Record<string, string[]>,
),
type: this.type,
};
}
}
-2
View File
@@ -1,2 +0,0 @@
export { IndexStruct, KeywordTable } from "./data-structs";
export { IndexStructType } from "./struct-type";
@@ -1,39 +0,0 @@
export const IndexStructType = {
NODE: "node",
TREE: "tree",
LIST: "list",
KEYWORD_TABLE: "keyword_table",
DICT: "dict",
SIMPLE_DICT: "simple_dict",
WEAVIATE: "weaviate",
PINECONE: "pinecone",
QDRANT: "qdrant",
LANCEDB: "lancedb",
MILVUS: "milvus",
CHROMA: "chroma",
MYSCALE: "myscale",
CLICKHOUSE: "clickhouse",
VECTOR_STORE: "vector_store",
OPENSEARCH: "opensearch",
DASHVECTOR: "dashvector",
CHATGPT_RETRIEVAL_PLUGIN: "chatgpt_retrieval_plugin",
DEEPLAKE: "deeplake",
EPSILLA: "epsilla",
MULTIMODAL_VECTOR_STORE: "multimodal",
SQL: "sql",
KG: "kg",
SIMPLE_KG: "simple_kg",
SIMPLE_LPG: "simple_lpg",
NEBULAGRAPH: "nebulagraph",
FALKORDB: "falkordb",
EMPTY: "empty",
COMPOSITE: "composite",
PANDAS: "pandas",
DOCUMENT_SUMMARY: "document_summary",
VECTARA: "vectara",
ZILLIZ_CLOUD_PIPELINE: "zilliz_cloud_pipeline",
POSTGRESML: "postgresml",
} as const;
export type IndexStructType =
(typeof IndexStructType)[keyof typeof IndexStructType];
@@ -1,48 +0,0 @@
import { AsyncLocalStorage } from "@llamaindex/env";
import { withEventCaller } from "../global";
import { isAsyncIterable, isIterable } from "../utils";
export function wrapEventCaller<This, Result, Args extends unknown[]>(
originalMethod: (this: This, ...args: Args) => Result,
context: ClassMethodDecoratorContext<object>,
) {
const name = context.name;
context.addInitializer(function () {
// @ts-expect-error
const fn = this[name].bind(this);
// @ts-expect-error
this[name] = (...args: unknown[]) => {
return withEventCaller(this, () => fn(...args));
};
});
return function (this: This, ...args: Args): Result {
const result = originalMethod.call(this, ...args);
// patch for iterators because AsyncLocalStorage doesn't work with them
if (isAsyncIterable(result)) {
const iter = result[Symbol.asyncIterator]();
const snapshot = AsyncLocalStorage.snapshot();
return (async function* asyncGeneratorWrapper() {
while (true) {
const { value, done } = await snapshot(() => iter.next());
if (done) {
break;
}
yield value;
}
})() as Result;
} else if (isIterable(result)) {
const iter = result[Symbol.iterator]();
const snapshot = AsyncLocalStorage.snapshot();
return (function* generatorWrapper() {
while (true) {
const { value, done } = snapshot(() => iter.next());
if (done) {
break;
}
yield value;
}
})() as Result;
}
return result;
};
}
+67 -3
View File
@@ -1,3 +1,67 @@
export { wrapEventCaller } from "./event-caller";
export { lazyInitHash } from "./lazy-init-hash";
export { wrapLLMEvent } from "./wrap-llm-event";
import { getEnv } from "@llamaindex/env";
import { Settings } from "../global";
import type { BaseNode } from "../schema/node";
const emitOnce = false;
export function chunkSizeCheck<
This extends { id_: string },
Args extends any[],
Return,
>(
contentGetter: (this: This, ...args: Args) => string,
_context: ClassMethodDecoratorContext<
This,
(this: This, ...args: Args) => Return
>,
) {
return function (this: This, ...args: Args) {
const content = contentGetter.call(this, ...args);
const chunkSize = Settings.chunkSize;
const enableChunkSizeCheck = getEnv("ENABLE_CHUNK_SIZE_CHECK") === "true";
if (
enableChunkSizeCheck &&
chunkSize !== undefined &&
content.length > chunkSize
) {
console.warn(
`Node (${this.id_}) is larger than chunk size: ${content.length} > ${chunkSize}`,
);
if (!emitOnce) {
console.warn(
"Will truncate the content if it is larger than chunk size",
);
console.warn("If you want to disable this behavior:");
console.warn(" 1. Set Settings.chunkSize = undefined");
console.warn(" 2. Set Settings.chunkSize to a larger value");
console.warn(
" 3. Change the way of splitting content into smaller chunks",
);
}
return content.slice(0, chunkSize);
}
return content;
};
}
export function lazyInitHash(
value: ClassAccessorDecoratorTarget<BaseNode, string>,
_context: ClassAccessorDecoratorContext,
): ClassAccessorDecoratorResult<BaseNode, string> {
return {
get() {
const oldValue = value.get.call(this);
if (oldValue === "") {
const hash = this.generateHash();
value.set.call(this, hash);
}
return value.get.call(this);
},
set(newValue: string) {
value.set.call(this, newValue);
},
init(value: string): string {
return value;
},
};
}
@@ -1,23 +0,0 @@
import type { BaseNode } from "../schema";
export function lazyInitHash(
value: ClassAccessorDecoratorTarget<BaseNode, string>,
_context: ClassAccessorDecoratorContext,
): ClassAccessorDecoratorResult<BaseNode, string> {
return {
get() {
const oldValue = value.get.call(this);
if (oldValue === "") {
const hash = this.generateHash();
value.set.call(this, hash);
}
return value.get.call(this);
},
set(newValue: string) {
value.set.call(this, newValue);
},
init(value: string): string {
return value;
},
};
}
+14 -25
View File
@@ -23,34 +23,23 @@ export abstract class BaseEmbedding extends TransformComponent {
embedBatchSize = DEFAULT_EMBED_BATCH_SIZE;
embedInfo?: EmbeddingInfo;
protected constructor(
transformFn?: (
nodes: BaseNode[],
options?: BaseEmbeddingOptions,
) => Promise<BaseNode[]>,
) {
if (transformFn) {
super(transformFn);
} else {
super(
async (
nodes: BaseNode[],
options?: BaseEmbeddingOptions,
): Promise<BaseNode[]> => {
const texts = nodes.map((node) =>
node.getContent(MetadataMode.EMBED),
);
constructor() {
super(
async (
nodes: BaseNode[],
options?: BaseEmbeddingOptions,
): Promise<BaseNode[]> => {
const texts = nodes.map((node) => node.getContent(MetadataMode.EMBED));
const embeddings = await this.getTextEmbeddingsBatch(texts, options);
const embeddings = await this.getTextEmbeddingsBatch(texts, options);
for (let i = 0; i < nodes.length; i++) {
nodes[i]!.embedding = embeddings[i];
}
for (let i = 0; i < nodes.length; i++) {
nodes[i]!.embedding = embeddings[i];
}
return nodes;
},
);
}
return nodes;
},
);
}
similarity(
-1
View File
@@ -1,5 +1,4 @@
export { BaseEmbedding, batchEmbeddings } from "./base";
export type { BaseEmbeddingOptions, EmbeddingInfo } from "./base";
export { MultiModalEmbedding } from "./muti-model";
export { truncateMaxTokens } from "./tokenizer";
export { DEFAULT_SIMILARITY_TOP_K, SimilarityType, similarity } from "./utils";
@@ -1,81 +0,0 @@
import type { MessageContentDetail } from "../llms";
import {
ImageNode,
MetadataMode,
ModalityType,
splitNodesByType,
type BaseNode,
type ImageType,
} from "../schema";
import { extractImage, extractSingleText } from "../utils";
import {
BaseEmbedding,
batchEmbeddings,
type BaseEmbeddingOptions,
} from "./base";
/*
* Base class for Multi Modal embeddings.
*/
export abstract class MultiModalEmbedding extends BaseEmbedding {
abstract getImageEmbedding(images: ImageType): Promise<number[]>;
protected constructor() {
super(
async (
nodes: BaseNode[],
options?: BaseEmbeddingOptions,
): Promise<BaseNode[]> => {
const nodeMap = splitNodesByType(nodes);
const imageNodes = nodeMap[ModalityType.IMAGE] ?? [];
const textNodes = nodeMap[ModalityType.TEXT] ?? [];
const embeddings = await batchEmbeddings(
textNodes.map((node) => node.getContent(MetadataMode.EMBED)),
this.getTextEmbeddings.bind(this),
this.embedBatchSize,
options,
);
for (let i = 0; i < textNodes.length; i++) {
textNodes[i]!.embedding = embeddings[i];
}
const imageEmbeddings = await batchEmbeddings(
imageNodes.map((n) => (n as ImageNode).image),
this.getImageEmbeddings.bind(this),
this.embedBatchSize,
options,
);
for (let i = 0; i < imageNodes.length; i++) {
imageNodes[i]!.embedding = imageEmbeddings[i];
}
return nodes;
},
);
}
/**
* Optionally override this method to retrieve multiple image embeddings in a single request
* @param images
*/
async getImageEmbeddings(images: ImageType[]): Promise<number[][]> {
return Promise.all(
images.map((imgFilePath) => this.getImageEmbedding(imgFilePath)),
);
}
async getQueryEmbedding(
query: MessageContentDetail,
): Promise<number[] | null> {
const image = extractImage(query);
if (image) {
return await this.getImageEmbedding(image);
}
const text = extractSingleText(query);
if (text) {
return await this.getTextEmbedding(text);
}
return null;
}
}
+1 -6
View File
@@ -9,9 +9,4 @@ export type {
LLMToolResultEvent,
LlamaIndexEventMaps,
} from "./settings/callback-manager";
export {
EventCaller,
getEventCaller,
withEventCaller,
} from "./settings/event-caller";
export type { JSONArray, JSONObject, JSONValue, UUID } from "./type";
export type { JSONArray, JSONObject, JSONValue } from "./type";
+1 -13
View File
@@ -1,4 +1,4 @@
import { getEnv, type Tokenizer } from "@llamaindex/env";
import type { Tokenizer } from "@llamaindex/env";
import type { LLM } from "../llms";
import {
type CallbackManager,
@@ -61,16 +61,4 @@ export const Settings = {
): Result {
return withCallbackManager(callbackManager, fn);
},
get debug() {
let debug = getEnv("DEBUG");
if (typeof window !== "undefined") {
debug ||= window.localStorage.debug;
}
return (
(Boolean(debug) && debug?.includes("llamaindex")) ||
debug === "*" ||
debug === "true"
);
},
};
@@ -1,5 +1,4 @@
import { AsyncLocalStorage, CustomEvent } from "@llamaindex/env";
import type { AgentEndEvent, AgentStartEvent } from "../../agent";
import type {
ChatMessage,
ChatResponse,
@@ -7,15 +6,9 @@ import type {
ToolCall,
ToolOutput,
} from "../../llms";
import type { QueryEndEvent, QueryStartEvent } from "../../query-engine";
import type {
SynthesizeEndEvent,
SynthesizeStartEvent,
} from "../../response-synthesizers";
import type { RetrieveEndEvent, RetrieveStartEvent } from "../../retriever";
import { TextNode } from "../../schema";
import { EventCaller, getEventCaller } from "../../utils/event-caller";
import type { UUID } from "../type";
import { EventCaller, getEventCaller } from "./event-caller";
export type LLMStartEvent = {
id: UUID;
@@ -67,14 +60,6 @@ export interface LlamaIndexEventMaps {
"chunking-end": ChunkingEndEvent;
"node-parsing-start": NodeParsingStartEvent;
"node-parsing-end": NodeParsingEndEvent;
"query-start": QueryStartEvent;
"query-end": QueryEndEvent;
"synthesize-start": SynthesizeStartEvent;
"synthesize-end": SynthesizeEndEvent;
"retrieve-start": RetrieveStartEvent;
"retrieve-end": RetrieveEndEvent;
"agent-start": AgentStartEvent;
"agent-end": AgentEndEvent;
}
export class LlamaIndexCustomEvent<T = any> extends CustomEvent<T> {
@@ -134,29 +119,16 @@ export class CallbackManager {
dispatchEvent<K extends keyof LlamaIndexEventMaps>(
event: K,
detail: LlamaIndexEventMaps[K],
sync = false,
) {
const cbs = this.#handlers.get(event);
if (!cbs) {
return;
}
if (typeof queueMicrotask === "undefined") {
console.warn(
"queueMicrotask is not available, dispatching synchronously",
);
sync = true;
}
if (sync) {
queueMicrotask(() => {
cbs.forEach((handler) =>
handler(LlamaIndexCustomEvent.fromEvent(event, { ...detail })),
);
} else {
queueMicrotask(() => {
cbs.forEach((handler) =>
handler(LlamaIndexCustomEvent.fromEvent(event, { ...detail })),
);
});
}
});
}
}
@@ -1,55 +0,0 @@
import { AsyncLocalStorage, randomUUID } from "@llamaindex/env";
const eventReasonAsyncLocalStorage = new AsyncLocalStorage<EventCaller>();
/**
* EventCaller is used to track the caller of an event.
*/
export class EventCaller {
public readonly id = randomUUID();
private constructor(
public readonly caller: unknown,
public readonly parent: EventCaller | null,
) {}
#computedCallers: unknown[] | null = null;
public get computedCallers(): unknown[] {
if (this.#computedCallers != null) {
return this.#computedCallers;
}
const callers = [this.caller];
let parent = this.parent;
while (parent != null) {
callers.push(parent.caller);
parent = parent.parent;
}
this.#computedCallers = callers;
return callers;
}
public static create(
caller: unknown,
parent: EventCaller | null,
): EventCaller {
return new EventCaller(caller, parent);
}
}
export function getEventCaller(): EventCaller | null {
return eventReasonAsyncLocalStorage.getStore() ?? null;
}
/**
* @param caller who is calling this function, pass in `this` if it's a class method
* @param fn
*/
export function withEventCaller<T>(caller: unknown, fn: () => T) {
// create a chain of event callers
const parentCaller = getEventCaller();
return eventReasonAsyncLocalStorage.run(
EventCaller.create(caller, parentCaller),
fn,
);
}
+55 -107
View File
@@ -1,23 +1,22 @@
import { type Tokenizer, tokenizers } from "@llamaindex/env";
import {
DEFAULT_CHUNK_OVERLAP_RATIO,
DEFAULT_CHUNK_SIZE,
DEFAULT_CONTEXT_WINDOW,
DEFAULT_NUM_OUTPUTS,
DEFAULT_PADDING,
Settings,
} from "../global";
import type { LLMMetadata } from "../llms";
import { TextSplitter, TokenTextSplitter, truncateText } from "../node-parser";
import { BasePromptTemplate, PromptTemplate } from "../prompts";
import { SentenceSplitter } from "../node-parser";
import type { PromptTemplate } from "../prompts";
/**
* Get the empty prompt text given a prompt.
*/
function getEmptyPromptTxt(prompt: PromptTemplate): string {
return prompt.format(
Object.fromEntries([...prompt.templateVars.keys()].map((key) => [key, ""])),
);
function getEmptyPromptTxt(prompt: PromptTemplate) {
return prompt.format({
...Object.fromEntries(
[...prompt.templateVars.keys()].map((key) => [key, ""]),
),
});
}
/**
@@ -33,24 +32,24 @@ export function getBiggestPrompt(prompts: PromptTemplate[]): PromptTemplate {
}
export type PromptHelperOptions = {
contextWindow?: number | undefined;
numOutput?: number | undefined;
chunkOverlapRatio?: number | undefined;
chunkSizeLimit?: number | undefined;
tokenizer?: Tokenizer | undefined;
separator?: string | undefined;
contextWindow?: number;
numOutput?: number;
chunkOverlapRatio?: number;
chunkSizeLimit?: number;
tokenizer?: Tokenizer;
separator?: string;
};
/**
* A collection of helper functions for working with prompts.
*/
export class PromptHelper {
contextWindow: number;
numOutput: number;
chunkOverlapRatio: number;
contextWindow = DEFAULT_CONTEXT_WINDOW;
numOutput = DEFAULT_NUM_OUTPUTS;
chunkOverlapRatio = DEFAULT_CHUNK_OVERLAP_RATIO;
chunkSizeLimit: number | undefined;
tokenizer: Tokenizer;
separator: string;
separator = " ";
constructor(options: PromptHelperOptions = {}) {
const {
@@ -70,119 +69,68 @@ export class PromptHelper {
}
/**
* Calculate the available context size based on the number of prompt tokens.
* Given a prompt, return the maximum size of the inputs to the prompt.
* @param prompt
* @returns
*/
#getAvailableContextSize(numPromptTokens: number): number {
const contextSizeTokens =
this.contextWindow - numPromptTokens - this.numOutput;
if (contextSizeTokens < 0) {
throw new Error(
`Calculated available context size ${contextSizeTokens} is not non-negative.`,
);
}
return contextSizeTokens;
private getAvailableContextSize(prompt: PromptTemplate) {
const emptyPromptText = getEmptyPromptTxt(prompt);
const promptTokens = this.tokenizer.encode(emptyPromptText);
const numPromptTokens = promptTokens.length;
return this.contextWindow - numPromptTokens - this.numOutput;
}
/**
* Calculate the available chunk size based on the prompt and other parameters.
* Find the maximum size of each chunk given a prompt.
*/
#getAvailableChunkSize<Template extends BasePromptTemplate>(
prompt: Template,
numChunks: number = 1,
padding: number = 5,
private getAvailableChunkSize(
prompt: PromptTemplate,
numChunks = 1,
padding = 5,
): number {
let numPromptTokens = 0;
const availableContextSize = this.getAvailableContextSize(prompt);
if (prompt instanceof PromptTemplate) {
numPromptTokens = this.tokenizer.encode(getEmptyPromptTxt(prompt)).length;
const result = Math.floor(availableContextSize / numChunks) - padding;
if (this.chunkSizeLimit) {
return Math.min(this.chunkSizeLimit, result);
} else {
return result;
}
const availableContextSize = this.#getAvailableContextSize(numPromptTokens);
let result = Math.floor(availableContextSize / numChunks) - padding;
if (this.chunkSizeLimit !== undefined) {
result = Math.min(this.chunkSizeLimit, result);
}
return result;
}
/**
* Creates a text splitter configured to maximally pack the available context window.
* Creates a text splitter with the correct chunk sizes and overlaps given a prompt.
*/
getTextSplitterGivenPrompt(
prompt: BasePromptTemplate,
numChunks: number = 1,
padding: number = DEFAULT_PADDING,
): TextSplitter {
const chunkSize = this.#getAvailableChunkSize(prompt, numChunks, padding);
if (chunkSize <= 0) {
throw new TypeError(`Chunk size ${chunkSize} is not positive.`);
prompt: PromptTemplate,
numChunks = 1,
padding = DEFAULT_PADDING,
) {
const chunkSize = this.getAvailableChunkSize(prompt, numChunks, padding);
if (chunkSize === 0) {
throw new Error("Got 0 as available chunk size");
}
const chunkOverlap = Math.floor(this.chunkOverlapRatio * chunkSize);
return new TokenTextSplitter({
separator: this.separator,
const chunkOverlap = this.chunkOverlapRatio * chunkSize;
return new SentenceSplitter({
chunkSize,
chunkOverlap,
separator: this.separator,
tokenizer: this.tokenizer,
});
}
/**
* Truncate text chunks to fit within the available context window.
*/
truncate(
prompt: BasePromptTemplate,
textChunks: string[],
padding: number = DEFAULT_PADDING,
): string[] {
const textSplitter = this.getTextSplitterGivenPrompt(
prompt,
textChunks.length,
padding,
);
return textChunks.map((chunk) => truncateText(chunk, textSplitter));
}
/**
* Repack text chunks to better utilize the available context window.
* Repack resplits the strings based on the optimal text splitter.
*/
repack(
prompt: BasePromptTemplate,
prompt: PromptTemplate,
textChunks: string[],
padding: number = DEFAULT_PADDING,
): string[] {
padding = DEFAULT_PADDING,
) {
const textSplitter = this.getTextSplitterGivenPrompt(prompt, 1, padding);
const combinedStr = textChunks
.map((c) => c.trim())
.filter((c) => c.length > 0)
.join("\n\n");
const combinedStr = textChunks.join("\n\n");
return textSplitter.splitText(combinedStr);
}
static fromLLMMetadata(
metadata: LLMMetadata,
options?: {
chunkOverlapRatio?: number;
chunkSizeLimit?: number;
tokenizer?: Tokenizer;
separator?: string;
},
) {
const {
chunkOverlapRatio = DEFAULT_CHUNK_OVERLAP_RATIO,
chunkSizeLimit = DEFAULT_CHUNK_SIZE,
tokenizer = Settings.tokenizer,
separator = " ",
} = options ?? {};
return new PromptHelper({
contextWindow: metadata.contextWindow,
// fixme: numOutput is not in LLMMetadata
numOutput: DEFAULT_NUM_OUTPUTS,
chunkOverlapRatio,
chunkSizeLimit,
tokenizer,
separator,
});
}
}
-83
View File
@@ -1,83 +0,0 @@
import { Settings } from "../global";
import type { ChatMessage } from "../llms";
import { type BaseChatStore, SimpleChatStore } from "../storage/chat-store";
import { extractText } from "../utils";
export const DEFAULT_TOKEN_LIMIT_RATIO = 0.75;
export const DEFAULT_CHAT_STORE_KEY = "chat_history";
/**
* A ChatMemory is used to keep the state of back and forth chat messages
*/
export abstract class BaseMemory<
AdditionalMessageOptions extends object = object,
> {
/**
* Retrieves messages from the memory, optionally including transient messages.
* Compared to getAllMessages, this method a) allows for transient messages to be included in the retrieval and b) may return a subset of the total messages by applying a token limit.
* @param transientMessages Optional array of temporary messages to be included in the retrieval.
* These messages are not stored in the memory but are considered for the current interaction.
* @returns An array of chat messages, either synchronously or as a Promise.
*/
abstract getMessages(
transientMessages?: ChatMessage<AdditionalMessageOptions>[] | undefined,
):
| ChatMessage<AdditionalMessageOptions>[]
| Promise<ChatMessage<AdditionalMessageOptions>[]>;
/**
* Retrieves all messages stored in the memory.
* @returns An array of all chat messages, either synchronously or as a Promise.
*/
abstract getAllMessages():
| ChatMessage<AdditionalMessageOptions>[]
| Promise<ChatMessage<AdditionalMessageOptions>[]>;
/**
* Adds a new message to the memory.
* @param messages The chat message to be added to the memory.
*/
abstract put(messages: ChatMessage<AdditionalMessageOptions>): void;
/**
* Clears all messages from the memory.
*/
abstract reset(): void;
protected _tokenCountForMessages(messages: ChatMessage[]): number {
if (messages.length === 0) {
return 0;
}
const tokenizer = Settings.tokenizer;
const str = messages.map((m) => extractText(m.content)).join(" ");
return tokenizer.encode(str).length;
}
}
export abstract class BaseChatStoreMemory<
AdditionalMessageOptions extends object = object,
> extends BaseMemory<AdditionalMessageOptions> {
protected constructor(
public chatStore: BaseChatStore<AdditionalMessageOptions> = new SimpleChatStore<AdditionalMessageOptions>(),
public chatStoreKey: string = DEFAULT_CHAT_STORE_KEY,
) {
super();
}
getAllMessages(): ChatMessage<AdditionalMessageOptions>[] {
return this.chatStore.getMessages(this.chatStoreKey);
}
put(messages: ChatMessage<AdditionalMessageOptions>) {
this.chatStore.addMessage(this.chatStoreKey, messages);
}
set(messages: ChatMessage<AdditionalMessageOptions>[]) {
this.chatStore.setMessages(this.chatStoreKey, messages);
}
reset() {
this.chatStore.deleteMessages(this.chatStoreKey);
}
}
@@ -1,71 +0,0 @@
import { Settings } from "../global";
import type { ChatMessage, LLM } from "../llms";
import { type BaseChatStore } from "../storage/chat-store";
import { BaseChatStoreMemory, DEFAULT_TOKEN_LIMIT_RATIO } from "./base";
type ChatMemoryBufferOptions<AdditionalMessageOptions extends object = object> =
{
tokenLimit?: number | undefined;
chatStore?: BaseChatStore<AdditionalMessageOptions> | undefined;
chatStoreKey?: string | undefined;
chatHistory?: ChatMessage<AdditionalMessageOptions>[] | undefined;
llm?: LLM<object, AdditionalMessageOptions> | undefined;
};
export class ChatMemoryBuffer<
AdditionalMessageOptions extends object = object,
> extends BaseChatStoreMemory<AdditionalMessageOptions> {
tokenLimit: number;
constructor(
options?: Partial<ChatMemoryBufferOptions<AdditionalMessageOptions>>,
) {
super(options?.chatStore, options?.chatStoreKey);
const llm = options?.llm ?? Settings.llm;
const contextWindow = llm.metadata.contextWindow;
this.tokenLimit =
options?.tokenLimit ??
Math.ceil(contextWindow * DEFAULT_TOKEN_LIMIT_RATIO);
if (options?.chatHistory) {
this.chatStore.setMessages(this.chatStoreKey, options.chatHistory);
}
}
getMessages(
transientMessages?: ChatMessage<AdditionalMessageOptions>[] | undefined,
initialTokenCount: number = 0,
) {
const messages = this.getAllMessages();
if (initialTokenCount > this.tokenLimit) {
throw new Error("Initial token count exceeds token limit");
}
// Add input messages as transient messages
const messagesWithInput = transientMessages
? [...transientMessages, ...messages]
: messages;
let messageCount = messagesWithInput.length;
let currentMessages = messagesWithInput.slice(-messageCount);
let tokenCount =
this._tokenCountForMessages(messagesWithInput) + initialTokenCount;
while (tokenCount > this.tokenLimit && messageCount > 1) {
messageCount -= 1;
if (messagesWithInput.at(-messageCount)!.role === "assistant") {
messageCount -= 1;
}
currentMessages = messagesWithInput.slice(-messageCount);
tokenCount =
this._tokenCountForMessages(currentMessages) + initialTokenCount;
}
if (tokenCount > this.tokenLimit && messageCount <= 0) {
return [];
}
return messagesWithInput.slice(-messageCount);
}
}
-3
View File
@@ -1,3 +0,0 @@
export { BaseMemory } from "./base";
export { ChatMemoryBuffer } from "./chat-memory-buffer";
export { ChatSummaryMemoryBuffer } from "./summary-memory";

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