Compare commits

..

9 Commits

Author SHA1 Message Date
Marcus Schiesser a1ef03b1cb test: add e2e test for nextjs/node with tokenizer 2024-06-25 09:56:51 -07:00
Marcus Schiesser 20498a2bce fix: use tiktoken instead of tiktoken/lite (#967) 2024-06-25 09:51:08 -07:00
Andy Garvin 0730140e62 fix: include node relationships when converting jsonToDoc (#968) 2024-06-25 22:59:16 +07:00
Andy Garvin 810711d355 docs: change references from core package to llamaindex (#969) 2024-06-25 22:55:37 +07:00
Marcus Schiesser f3b34b457c docs: add changeset (#965) 2024-06-25 21:36:00 +07:00
Fabian Wimmer 6f4b9f3372 docs: fix broken links, add API References (#962) 2024-06-24 19:10:16 -07:00
Fabian Wimmer 01658fdb31 docs: update data loaders (#961) 2024-06-24 10:45:17 -07:00
Alex Yang 66c26d9cce fix: json import (#958) 2024-06-21 11:27:08 -07:00
Marcus Schiesser a4060a7914 docs: update anthropic examples to use claude 3.5 (#954) 2024-06-21 17:27:56 +07:00
77 changed files with 790 additions and 127 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"@llamaindex/env": patch
---
Use tiktoken instead of tiktoken/lite and disable WASM tiktoken for non-Node environments
+5
View File
@@ -0,0 +1,5 @@
---
"llamaindex": patch
---
include node relationships when converting jsonToDoc
+1
View File
@@ -91,6 +91,7 @@ jobs:
- cloudflare-worker-agent
- nextjs-agent
- nextjs-edge-runtime
- nextjs-node-runtime
# - waku-query-engine
runs-on: ubuntu-latest
name: Build LlamaIndex Example (${{ matrix.packages }})
+3 -3
View File
@@ -6,7 +6,7 @@ This is a monorepo built with Turborepo
Right now there are two packages of importance:
packages/core which is the main NPM library llamaindex
packages/llamaindex which is the main NPM library llamaindex
examples is where the demo code lives
@@ -41,7 +41,7 @@ To run them, run
pnpm run test
```
To write new test cases write them in [packages/core/src/tests](/packages/llamaindex/src/tests)
To write new test cases write them in [packages/llamaindex/tests](/packages/llamaindex/tests)
We use Jest https://jestjs.io/ to write our test cases. Jest comes with a bunch of built in assertions using the expect function: https://jestjs.io/docs/expect
@@ -56,7 +56,7 @@ You can create new demo applications in the apps folder. Just run pnpm init in t
To install packages for a specific package or demo application, run
```
pnpm add [NPM Package] --filter [package or application i.e. core or docs]
pnpm add [NPM Package] --filter [package or application i.e. llamaindex or docs]
```
To install packages for every package or application run
+1 -1
View File
@@ -32,7 +32,7 @@ LlamaIndex.TS help you prepare the knowledge base with a suite of data connector
![](../_static/concepts/indexing.jpg)
[**Data Loaders**](../modules/data_loader.md):
[**Data Loaders**](../modules/data_loaders/index.mdx):
A data connector (i.e. `Reader`) ingest data from different data sources and data formats into a simple `Document` representation (text and simple metadata).
[**Documents / Nodes**](../modules/documents_and_nodes/index.md): A `Document` is a generic container around any data source - for instance, a PDF, an API output, or retrieved data from a database. A `Node` is the atomic unit of data in LlamaIndex and represents a "chunk" of a source `Document`. It's a rich representation that includes metadata and relationships (to other nodes) to enable accurate and expressive retrieval operations.
@@ -21,7 +21,7 @@ npm install -D typescript @types/node
Then, check out the [installation](../installation) steps to install LlamaIndex.TS and prepare an OpenAI key.
You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
You can use [other LLMs](../../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
## Run queries
@@ -7,9 +7,9 @@ import CodeSource from "!raw-loader!../../../../../examples/jsonExtract";
# Structured data extraction tutorial
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](../installation) guide.
You can use [other LLMs](../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
You can use [other LLMs](../../examples/other_llms) via their APIs; if you would prefer to use local models check out our [local LLM example](../../examples/local_llm).
## Set up
+6
View File
@@ -18,3 +18,9 @@ LlamaIndex.TS comes with a few built-in agents, but you can also create your own
## Examples
- [OpenAI Agent](../../examples/agent.mdx)
## Api References
- [OpenAIAgent](../../api/classes/OpenAIAgent.md)
- [AnthropicAgent](../../api/classes/AnthropicAgent.md)
- [ReActAgent](../../api/classes/ReActAgent.md)
-68
View File
@@ -1,68 +0,0 @@
---
sidebar_position: 4
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/readers/src/simple-directory-reader";
import CodeSource2 from "!raw-loader!../../../../examples/readers/src/custom-simple-directory-reader";
import CodeSource3 from "!raw-loader!../../../../examples/readers/src/llamaparse";
import CodeSource4 from "!raw-loader!../../../../examples/readers/src/simple-directory-reader-with-llamaparse.ts";
# Loader
Before you can start indexing your documents, you need to load them into memory.
### SimpleDirectoryReader
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
It is a simple reader that reads all files from a directory and its subdirectories.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Currently, it supports reading `.txt`, `.pdf`, `.csv`, `.md`, `.docx`, `.htm`, `.html`, `.jpg`, `.jpeg`, `.png` and `.gif` files, but support for other file types is planned.
You can override the default reader for all file types, inlcuding unsupported ones, with the `overrideReader` option.
Additionally, you can override the default reader for specific file types or add support for additional file types with the `fileExtToReader` option.
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions. By default it is `TextFileReader`.
SimpleDirectoryReader supports up to 9 concurrent requests. Use the `numWorkers` option to set the number of concurrent requests. By default it runs in sequential mode, i.e. set to 1.
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
{CodeSource2}
</CodeBlock>
### LlamaParse
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key as `apiKey` parameter or in the environment variable `LLAMA_CLOUD_API_KEY`.
Then, you can use the `LlamaParseReader` class to local files and convert them into a parsed document that can be used by LlamaIndex.
See [LlamaParseReader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/core/src/readers/LlamaParseReader.ts#L6) for a list of supported file types:
<CodeBlock language="ts">{CodeSource3}</CodeBlock>
Additional options can be set with the `LlamaParseReader` constructor:
- `resultType` can be set to `markdown`, `text` or `.json`. Defaults to `text`
- `language` primarly helps with OCR recognition. Defaults to `en`. See [../readers/type.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/core/src/readers/type.ts#L20) for a list of supported languages.
- `parsingInstructions` can help with complicated document structures. See this [LlamaIndex Blog Post](https://www.llamaindex.ai/blog/launching-the-first-genai-native-document-parsing-platform) for an example.
- `skipDiagonalText` set to true to ignore diagonal text.
- `invalidateCache` set to true to ignore the LlamaCloud cache. All document are kept in cache for 48hours after the job was completed to avoid processing the same document twice. Can be useful for testing when trying to re-parse the same document with, e.g. different `parsingInstructions`.
- `gpt4oMode` set to true to use GPT-4o to extract content.
- `gpt4oApiKey` set the GPT-4o API key. Optional. Lowers the cost of parsing by using your own API key. Your OpenAI account will be charged. Can also be set in the environment variable `LLAMA_CLOUD_GPT4O_API_KEY`.
- `numWorkers` as in the python version, is set in `SimpleDirectoryReader`. Default is 1.
## LlamaParse with SimpleDirectoryReader
Below a full example of `LlamaParse` integrated in `SimpleDirectoryReader` with additional options.
<CodeBlock language="ts">{CodeSource4}</CodeBlock>
## API Reference
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
- [LlamaParseReader](../api/classes/LlamaParseReader.md)
@@ -0,0 +1,2 @@
label: "Loaders"
position: 1
@@ -0,0 +1,37 @@
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../examples/readers/src/simple-directory-reader";
import CodeSource2 from "!raw-loader!../../../../../examples/readers/src/custom-simple-directory-reader";
# Loader
Before you can start indexing your documents, you need to load them into memory.
## SimpleDirectoryReader
[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
It is a simple reader that reads all files from a directory and its subdirectories.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Currently, it supports reading `.txt`, `.pdf`, `.csv`, `.md`, `.docx`, `.htm`, `.html`, `.jpg`, `.jpeg`, `.png` and `.gif` files, but support for other file types is planned.
You can modify the reader three different ways:
- `overrideReader` overrides the reader for all file types, including unsupported ones.
- `fileExtToReader` maps a reader to a specific file type. Can override reader for existing file types or add support for new file types.
- `defaultReader` sets a fallback reader for files with unsupported extensions. By default it is `TextFileReader`.
SimpleDirectoryReader supports up to 9 concurrent requests. Use the `numWorkers` option to set the number of concurrent requests. By default it runs in sequential mode, i.e. set to 1.
### Example
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
{CodeSource2}
</CodeBlock>
## API Reference
- [SimpleDirectoryReader](../../api/classes/SimpleDirectoryReader.md)
@@ -0,0 +1 @@
label: "LlamaParse"
@@ -0,0 +1,117 @@
---
sidebar_position: 2
---
# Image Retrieval
LlamaParse `json` mode supports extracting any images found in a page object by using the `getImages` function. They are downloaded to a local folder and can then be sent to a multimodal LLM for further processing.
## Usage
We use the `getImages` method to input our array of JSON objects, download the images to a specified folder and get a list of ImageNodes.
```ts
const reader = new LlamaParseReader();
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
const imageDicts = await reader.getImages(jsonObjs, "images");
```
### Multimodal Indexing
You can create an index across both text and image nodes by requesting alternative text for the image from a multimodal LLM.
```ts
import {
Document,
ImageNode,
LlamaParseReader,
OpenAI,
VectorStoreIndex,
} from "llamaindex";
import { createMessageContent } from "llamaindex/synthesizers/utils";
const reader = new LlamaParseReader();
async function main() {
// Load PDF using LlamaParse JSON mode and return an array of json objects
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
// Access the first "pages" (=a single parsed file) object in the array
const jsonList = jsonObjs[0]["pages"];
const textDocs = getTextDocs(jsonList);
const imageTextDocs = await getImageTextDocs(jsonObjs);
const documents = [...textDocs, ...imageTextDocs];
// Split text, create embeddings and query the index
const index = await VectorStoreIndex.fromDocuments(documents);
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query:
"What does the bar graph titled 'Monthly Active Platform Consumers' show?",
});
console.log(response.toString());
}
main().catch(console.error);
```
We use two helper functions to create documents from the text and image nodes provided.
#### Text Documents
To create documents from the text nodes of the json object, we just map the needed values to a new `Document` object. In this case we assign the text as text and the page number as metadata.
```ts
function getTextDocs(jsonList: { text: string; page: number }[]): Document[] {
return jsonList.map(
(page) => new Document({ text: page.text, metadata: { page: page.page } }),
);
}
```
#### Image Documents
To create documents from the images, we need to use a multimodal LLM to generate alt text.
For this we create `ImageNodes` and add them as part of our message.
We can use the `createMessageContent` function to simplify this.
```ts
async function getImageTextDocs(
jsonObjs: Record<string, any>[],
): Promise<Document[]> {
const llm = new OpenAI({
model: "gpt-4o",
temperature: 0.2,
maxTokens: 1000,
});
const imageDicts = await reader.getImages(jsonObjs, "images");
const imageDocs = [];
for (const imageDict of imageDicts) {
const imageDoc = new ImageNode({ image: imageDict.path });
const prompt = () => `Describe the image as alt text`;
const message = await createMessageContent(prompt, [imageDoc]);
const response = await llm.complete({
prompt: message,
});
const doc = new Document({
text: response.text,
metadata: { path: imageDict.path },
});
imageDocs.push(doc);
}
return imageDocs;
}
```
The returned `imageDocs` have the alt text assigned as text and the image path as metadata.
You can see the full example file [here](https://github.com/run-llama/LlamaIndexTS/blob/main/examples/readers/src/llamaparse-json.ts).
## API Reference
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
@@ -0,0 +1,58 @@
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../../../examples/readers/src/llamaparse";
import CodeSource2 from "!raw-loader!../../../../../../examples/readers/src/simple-directory-reader-with-llamaparse.ts";
# LlamaParse
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key as `apiKey` parameter or in the environment variable `LLAMA_CLOUD_API_KEY`.
Official documentation for LlamaParse can be found [here](https://docs.cloud.llamaindex.ai/).
## Usage
You can then use the `LlamaParseReader` class to load local files and convert them into a parsed document that can be used by LlamaIndex.
See [LlamaParseReader.ts](https://github.com/run-llama/LlamaIndexTS/blob/main/packages/llamaindex/src/readers/LlamaParseReader.ts) for a list of supported file types:
<CodeBlock language="ts">{CodeSource}</CodeBlock>
### Params
All options can be set with the `LlamaParseReader` constructor.
They can be divided into two groups.
#### General params:
- `apiKey` is required. Can be set as an environment variable `LLAMA_CLOUD_API_KEY`
- `checkInterval` is the interval in seconds to check if the parsing is done. Default is `1`.
- `maxTimeout` is the maximum timout to wait for parsing to finish. Default is `2000`
- `verbose` shows progress of the parsing. Default is `true`
- `ignoreErrors` set to false to get errors while parsing. Default is `true` and returns an empty array on error.
#### Advanced params:
- `resultType` can be set to `markdown`, `text` or `json`. Defaults to `text`. More information about `json` mode on the next pages.
- `language` primarly helps with OCR recognition. Defaults to `en`. Click [here](../../../api/type-aliases/Language.md) for a list of supported languages.
- `parsingInstructions?` Optional. Can help with complicated document structures. See this [LlamaIndex Blog Post](https://www.llamaindex.ai/blog/launching-the-first-genai-native-document-parsing-platform) for an example.
- `skipDiagonalText?` Optional. Set to true to ignore diagonal text. (Text that is not rotated 0, 90, 180 or 270 degrees)
- `invalidateCache?` Optional. Set to true to ignore the LlamaCloud cache. All document are kept in cache for 48hours after the job was completed to avoid processing the same document twice. Can be useful for testing when trying to re-parse the same document with, e.g. different `parsingInstructions`.
- `doNotCache?` Optional. Set to true to not cache the document.
- `fastMode?` Optional. Set to true to use the fast mode. This mode will skip OCR of images, and table/heading reconstruction. Note: Non-compatible with `gpt4oMode`.
- `doNotUnrollColumns?` Optional. Set to true to keep the text according to document layout. Reduce reconstruction accuracy, and LLM's/embedings performances in most cases.
- `pageSeperator?` Optional. The page seperator to use. Defaults is `\\n---\\n`.
- `gpt4oMode` set to true to use GPT-4o to extract content. Default is `false`.
- `gpt4oApiKey?` Optional. Set the GPT-4o API key. Lowers the cost of parsing by using your own API key. Your OpenAI account will be charged. Can also be set in the environment variable `LLAMA_CLOUD_GPT4O_API_KEY`.
- `numWorkers` as in the python version, is set in `SimpleDirectoryReader`. Default is 1.
### LlamaParse with SimpleDirectoryReader
Below a full example of `LlamaParse` integrated in `SimpleDirectoryReader` with additional options.
<CodeBlock language="ts">{CodeSource2}</CodeBlock>
## API Reference
- [SimpleDirectoryReader](../../../api/classes/SimpleDirectoryReader.md)
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
@@ -0,0 +1,59 @@
---
sidebar_position: 1
---
# JSON Mode
In JSON mode, LlamaParse will return a data structure representing the parsed object.
## Usage
For Json mode, you need to use `loadJson`. The `resultType` is automatically set with this method. Currently it can't be used with `SimpleDirectoryReader`.
More information about indexing the results on the next page.
```ts
const reader = new LlamaParseReader();
async function main() {
// Load the file and return an array of json objects
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
// Access the first "pages" (=a single parsed file) object in the array
const jsonList = jsonObjs[0]["pages"];
// Further process the jsonList object as needed.
}
```
### Output
The result format of the response, written to `jsonObjs` in the example, follows this structure:
```json
{
"pages": [
..page objects..
],
"job_metadata": {
"credits_used": int,
"credits_max": int,
"job_credits_usage": int,
"job_pages": int,
"job_is_cache_hit": boolean
},
"job_id": string ,
"file_path": string,
}
}
```
#### Page objects
Within page objects, the following keys may be present depending on your document.
- `page`: The page number of the document.
- `text`: The text extracted from the page.
- `md`: The markdown version of the extracted text.
- `images`: Any images extracted from the page.
- `items`: An array of heading, text and table objects in the order they appear on the page.
## API Reference
- [LlamaParseReader](../../../api/classes/LlamaParseReader.md)
@@ -14,5 +14,5 @@ document = new Document({ text: "text", metadata: { key: "val" } });
## API Reference
- [Document](../api/classes/Document.md)
- [TextNode](../api/classes/TextNode.md)
- [Document](../../api/classes/Document.md)
- [TextNode](../../api/classes/TextNode.md)
@@ -43,3 +43,10 @@ async function main() {
main().then(() => console.log("done"));
```
## API Reference
- [SummaryExtractor](../../api/classes/SummaryExtractor.md)
- [QuestionsAnsweredExtractor](../../api/classes/QuestionsAnsweredExtractor.md)
- [TitleExtractor](../../api/classes/TitleExtractor.md)
- [KeywordExtractor](../../api/classes/KeywordExtractor.md)
@@ -77,3 +77,7 @@ main();
```
For questions or feedback, please contact us at [feedback@deepinfra.com](mailto:feedback@deepinfra.com)
## API Reference
- [DeepInfraEmbedding](../../../api/classes/DeepInfraEmbedding.md)
@@ -31,3 +31,7 @@ Settings.embedModel = new GeminiEmbedding({
model: GEMINI_MODEL.GEMINI_PRO_LATEST,
});
```
## API Reference
- [GeminiEmbedding](../../../api/classes/GeminiEmbedding.md)
@@ -32,3 +32,7 @@ Settings.embedModel = new HuggingFaceEmbedding({
quantized: false,
});
```
## API Reference
- [HuggingFaceEmbedding](../../../api/classes/HuggingFaceEmbedding.md)
@@ -19,3 +19,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [JinaAIEmbedding](../../../api/classes/JinaAIEmbedding.md)
@@ -22,3 +22,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [MistralAIEmbedding](../../../api/classes/MistralAIEmbedding.md)
@@ -27,3 +27,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [OllamaEmbedding](../../../api/classes/OllamaEmbedding.md)
@@ -19,3 +19,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [OpenAIEmbedding](../../../api/classes/OpenAIEmbedding.md)
@@ -21,3 +21,7 @@ const results = await queryEngine.query({
query,
});
```
## API Reference
- [TogetherEmbedding](../../../api/classes/TogetherEmbedding.md)
@@ -56,3 +56,7 @@ console.log(
```bash
the response is not correct with a score of 2.5
```
## API Reference
- [CorrectnessEvaluator](../../../api/classes/CorrectnessEvaluator.md)
@@ -76,3 +76,7 @@ console.log(`the response is ${result.passing ? "faithful" : "not faithful"}`);
```bash
the response is faithful
```
## API Reference
- [FaithfulnessEvaluator](../../../api/classes/FaithfulnessEvaluator.md)
@@ -70,3 +70,7 @@ console.log(`the response is ${result.passing ? "relevant" : "not relevant"}`);
```bash
the response is relevant
```
## API Reference
- [RelevancyEvaluator](../../../api/classes/RelevancyEvaluator.md)
@@ -97,3 +97,7 @@ async function main() {
main().catch(console.error);
```
## API Reference
- [IngestionPipeline](../../api/classes/IngestionPipeline.md)
@@ -4,9 +4,9 @@ A transformation is something that takes a list of nodes as an input, and return
Currently, the following components are Transformation objects:
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
- [SimpleNodeParser](../../api/classes/SimpleNodeParser.md)
- [MetadataExtractor](../documents_and_nodes/metadata_extraction.md)
- Embeddings
- [Embeddings](../embeddings/index.md)
## Usage Pattern
@@ -63,3 +63,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [Anthropic](../../../api/classes/Anthropic.md)
@@ -74,3 +74,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [OpenAI](../../../api/classes/OpenAI.md)
@@ -81,3 +81,7 @@ async function main() {
## Feedback
If you have any feedback, please reach out to us at [feedback@deepinfra.com](mailto:feedback@deepinfra.com)
## API Reference
- [DeepInfra](../../../api/classes/DeepInfra)
@@ -59,3 +59,7 @@ async function main() {
main().catch(console.error);
```
## API Reference
- [FireworksLLM](../../../api/classes/FireworksLLM.md)
@@ -99,3 +99,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [Gemini](../../../api/classes/Gemini.md)
@@ -50,3 +50,7 @@ const results = await queryEngine.query({
<CodeBlock language="ts" showLineNumbers>
{CodeSource}
</CodeBlock>
## API Reference
- [Groq](../../../api/classes/Groq.md)
@@ -89,3 +89,8 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [LlamaDeuce](../../../api/variables/LlamaDeuce.md)
- [DeuceChatStrategy](../../../api/variables/DeuceChatStrategy.md)
@@ -66,3 +66,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [MistralAI](../../../api/classes/MistralAI.md)
@@ -71,3 +71,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [Ollama](../../../api/classes/Ollama.md)
@@ -67,3 +67,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [OpenAI](../../../api/classes/OpenAI.md)
@@ -68,3 +68,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [Portkey](../../../api/classes/Portkey.md)
@@ -66,3 +66,7 @@ async function main() {
console.log(response.response);
}
```
## API Reference
- [TogetherLLM](../../../api/classes/TogetherLLM.md)
+1 -1
View File
@@ -32,4 +32,4 @@ For local LLMs, currently we recommend the use of [Ollama](./available_llms/olla
## API Reference
- [OpenAI](../api/classes/OpenAI.md)
- [OpenAI](../../api/classes/OpenAI.md)
+1
View File
@@ -95,3 +95,4 @@ The output metadata will be something like:
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
- [SentenceSplitter](../api/classes/SentenceSplitter.md)
- [MarkdownNodeParser](../api/classes/MarkdownNodeParser.md)
@@ -65,3 +65,7 @@ const queryEngine = index.asQueryEngine({
// log the response
const response = await queryEngine.query("Where did the author grown up?");
```
## API Reference
- [CohereRerank](../../api/classes/CohereRerank.md)
@@ -103,3 +103,7 @@ const processor = new SimilarityPostprocessor({
const filteredNodes = processor.postprocessNodes(nodes);
```
## API Reference
- [SimilarityPostprocessor](../../api/classes/SimilarityPostprocessor.md)
@@ -69,3 +69,7 @@ const queryEngine = index.asQueryEngine({
// log the response
const response = await queryEngine.query("Where did the author grown up?");
```
## API Reference
- [JinaAIReranker](../../api/classes/JinaAIReranker.md)
+6
View File
@@ -70,3 +70,9 @@ const response = await queryEngine.query({
query: "What did the author do in college?",
});
```
## API Reference
- [TextQaPrompt](../../api/type-aliases/TextQaPrompt.md)
- [ResponseSynthesizer](../../api/classes/ResponseSynthesizer.md)
- [CompactAndRefine](../../api/classes/CompactAndRefine.md)
@@ -38,4 +38,4 @@ You can learn more about Tools by taking a look at the LlamaIndex Python documen
- [RetrieverQueryEngine](../../api/classes/RetrieverQueryEngine.md)
- [SubQuestionQueryEngine](../../api/classes/SubQuestionQueryEngine.md)
- [QueryEngineTool](../../api/interfaces/QueryEngineTool.md)
- [QueryEngineTool](../../api/classes/QueryEngineTool.md)
@@ -151,3 +151,8 @@ async function main() {
main();
```
## API Reference
- [VectorStoreIndex](../../api/classes/VectorStoreIndex.md)
- [ChromaVectorStore](../../api/classes/ChromaVectorStore.md)
@@ -165,3 +165,7 @@ async function main() {
main().then(() => console.log("Done"));
```
## API Reference
- [RouterQueryEngine](../../api/classes/RouterQueryEngine.md)
+1 -1
View File
@@ -23,4 +23,4 @@ const index = await VectorStoreIndex.fromDocuments([document], {
## API Reference
- [StorageContext](../api/interfaces//StorageContext.md)
- [StorageContext](../api/interfaces/StorageContext.md)
@@ -84,3 +84,7 @@ async function main() {
main().catch(console.error);
```
## API Reference
- [QdrantVectorStore](../../api/classes/QdrantVectorStore.md)
+7 -2
View File
@@ -1,11 +1,17 @@
import { FunctionTool, Settings, WikipediaTool } from "llamaindex";
import { Anthropic, FunctionTool, Settings, WikipediaTool } from "llamaindex";
import { AnthropicAgent } from "llamaindex/agent/anthropic";
Settings.callbackManager.on("llm-tool-call", (event) => {
console.log("llm-tool-call", event.detail.payload.toolCall);
});
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-3-5-sonnet",
});
const agent = new AnthropicAgent({
llm: anthropic,
tools: [
FunctionTool.from<{ location: string }>(
(query) => {
@@ -31,7 +37,6 @@ const agent = new AnthropicAgent({
});
async function main() {
// https://docs.anthropic.com/claude/docs/tool-use#tool-use-best-practices-and-limitations
const { response } = await agent.chat({
message:
"What is the weather in New York? What's the history of New York from Wikipedia in 3 sentences?",
+1 -1
View File
@@ -3,7 +3,7 @@ import { Anthropic } from "llamaindex";
(async () => {
const anthropic = new Anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
model: "claude-instant-1.2",
model: "claude-3-5-sonnet",
});
const stream = await anthropic.chat({
messages: [
+60 -22
View File
@@ -1,30 +1,68 @@
import fs from "fs/promises";
import { LlamaParseReader } from "llamaindex";
import {
Document,
ImageNode,
LlamaParseReader,
OpenAI,
VectorStoreIndex,
} from "llamaindex";
import { createMessageContent } from "llamaindex/synthesizers/utils";
const reader = new LlamaParseReader();
async function main() {
// Load PDF using LlamaParse json mode
const reader = new LlamaParseReader({ resultType: "json" });
// Load PDF using LlamaParse JSON mode and return an array of json objects
const jsonObjs = await reader.loadJson("../data/uber_10q_march_2022.pdf");
// Write the JSON objects to a file
try {
await fs.writeFile("jsonObjs.json", JSON.stringify(jsonObjs, null, 4));
console.log("Array of JSON objects has been written to jsonObjs.json");
} catch (e) {
console.error("Error writing jsonObjs.json", e);
}
// Access the first "pages" (=a single parsed file) object in the array
const jsonList = jsonObjs[0]["pages"];
// Write the list of JSON objects as a single array to a file
try {
await fs.writeFile("jsonList.json", JSON.stringify(jsonList, null, 4));
console.log(
"List of JSON objects as single array has been written to jsonList.json",
);
} catch (e) {
console.error("Error writing jsonList.json", e);
}
const textDocs = getTextDocs(jsonList);
const imageTextDocs = await getImageTextDocs(jsonObjs);
const documents = [...textDocs, ...imageTextDocs];
// Split text, create embeddings and query the index
const index = await VectorStoreIndex.fromDocuments(documents);
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query:
"What does the bar graph titled 'Monthly Active Platform Consumers' show?",
});
console.log(response.toString());
}
main().catch(console.error);
// Extract and assign text and page number from jsonList, return an array of Document objects
function getTextDocs(jsonList: { text: string; page: number }[]): Document[] {
return jsonList.map(
(page) => new Document({ text: page.text, metadata: { page: page.page } }),
);
}
// Download all images from jsonObjs, send them to OpenAI API to get alt text, return an array of Document objects
async function getImageTextDocs(
jsonObjs: Record<string, any>[],
): Promise<Document[]> {
const llm = new OpenAI({
model: "gpt-4o",
temperature: 0.2,
maxTokens: 1000,
});
const imageDicts = await reader.getImages(jsonObjs, "images");
const imageDocs = [];
for (const imageDict of imageDicts) {
const imageDoc = new ImageNode({ image: imageDict.path });
const prompt = () => `Describe the image as alt text`;
const message = await createMessageContent(prompt, [imageDoc]);
const response = await llm.complete({
prompt: message,
});
const doc = new Document({
text: response.text,
metadata: { path: imageDict.path },
});
imageDocs.push(doc);
}
return imageDocs;
}
+1 -1
View File
@@ -13,4 +13,4 @@ export function getEnv(name: string): string | undefined {
return INTERNAL_ENV[name];
}
export { Tokenizers, tokenizers, type Tokenizer } from "./tokenizers/node.js";
export { Tokenizers, tokenizers, type Tokenizer } from "./tokenizers/js.js";
+3 -7
View File
@@ -1,18 +1,14 @@
// Note: This is using th WASM implementation of tiktoken which is 60x faster
import cl100k_base from "tiktoken/encoders/cl100k_base.json";
import { Tiktoken } from "tiktoken/lite";
import type { Tokenizer } from "./types.js";
import { Tokenizers } from "./types.js";
import { get_encoding } from "tiktoken";
class TokenizerSingleton {
private defaultTokenizer: Tokenizer;
constructor() {
const encoding = new Tiktoken(
cl100k_base.bpe_ranks,
cl100k_base.special_tokens,
cl100k_base.pat_str,
);
const encoding = get_encoding("cl100k_base");
this.defaultTokenizer = {
encode: (text: string) => {
+1 -1
View File
@@ -5,7 +5,7 @@
"outDir": "./dist/type",
"tsBuildInfoFile": "./dist/.tsbuildinfo",
"emitDeclarationOnly": true,
"module": "node16",
"module": "nodenext",
"moduleResolution": "node16",
"types": ["node"],
"resolveJsonModule": true
@@ -0,0 +1,4 @@
{
"root": false,
"extends": "next/core-web-vitals"
}
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
@@ -0,0 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};
import withLlamaIndex from "llamaindex/next";
export default withLlamaIndex(nextConfig);
@@ -0,0 +1,27 @@
{
"name": "@llamaindex/next-node-runtime",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"llamaindex": "workspace:*",
"next": "14.2.4",
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"@types/node": "^20.12.11",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"eslint": "^8.57.0",
"eslint-config-next": "14.2.3",
"postcss": "^8",
"tailwindcss": "^3.4.4",
"typescript": "^5.5.2"
}
}
@@ -0,0 +1,8 @@
/** @type {import('postcss-load-config').Config} */
const config = {
plugins: {
tailwindcss: {},
},
};
export default config;
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>

After

Width:  |  Height:  |  Size: 629 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
@@ -0,0 +1,22 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
);
}
@@ -0,0 +1,16 @@
import { tokenize } from "@/utils/tokenizer";
import { use } from "react";
export const runtime = "nodejs";
export default function Home() {
const result = use(tokenize("Hello world"));
return (
<main>
<div>
<h1>Next.js Node Runtime calling tokenizer</h1>
<div>{result}</div>
</div>
</main>
);
}
@@ -0,0 +1,14 @@
// test runtime
import { Tokenizers, tokenizers } from "@llamaindex/env";
import "llamaindex";
// @ts-expect-error
if (typeof EdgeRuntime === "string") {
throw new Error("Expected to not run in EdgeRuntime");
}
export async function tokenize(str: string): Promise<string> {
const tokenizer = tokenizers.tokenizer(Tokenizers.CL100K_BASE);
const encoded = tokenizer.encode(str);
return tokenizer.decode(encoded);
}
@@ -0,0 +1,20 @@
import type { Config } from "tailwindcss";
const config: Config = {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
],
theme: {
extend: {
backgroundImage: {
"gradient-radial": "radial-gradient(var(--tw-gradient-stops))",
"gradient-conic":
"conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))",
},
},
},
plugins: [],
};
export default config;
@@ -0,0 +1,27 @@
{
"extends": "../../../../../tsconfig.json",
"compilerOptions": {
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
@@ -44,6 +44,7 @@ export function jsonToDoc(docDict: DocJson): BaseNode {
id_: dataDict.id_,
hash: dataDict.hash,
metadata: dataDict.metadata,
relationships: dataDict.relationships,
});
} else {
throw new Error(`Unknown doc type: ${docType}`);
+51 -11
View File
@@ -690,6 +690,46 @@ importers:
specifier: ^5.5.2
version: 5.5.2
packages/llamaindex/e2e/examples/nextjs-node-runtime:
dependencies:
llamaindex:
specifier: workspace:*
version: link:../../..
next:
specifier: 14.2.4
version: 14.2.4(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
react:
specifier: 18.3.1
version: 18.3.1
react-dom:
specifier: 18.3.1
version: 18.3.1(react@18.3.1)
devDependencies:
'@types/node':
specifier: ^20.12.11
version: 20.14.2
'@types/react':
specifier: ^18.3.3
version: 18.3.3
'@types/react-dom':
specifier: ^18.3.0
version: 18.3.0
eslint:
specifier: ^8.57.0
version: 8.57.0
eslint-config-next:
specifier: 14.2.3
version: 14.2.3(eslint@8.57.0)(typescript@5.5.2)
postcss:
specifier: ^8
version: 8.4.38
tailwindcss:
specifier: ^3.4.4
version: 3.4.4(ts-node@10.9.2(@types/node@20.14.2)(typescript@5.5.2))
typescript:
specifier: ^5.5.2
version: 5.5.2
packages/llamaindex/e2e/examples/waku-query-engine:
dependencies:
llamaindex:
@@ -11557,7 +11597,7 @@ snapshots:
'@babel/core': 7.24.5
'@babel/helper-compilation-targets': 7.23.6
'@babel/helper-plugin-utils': 7.24.5
debug: 4.3.4
debug: 4.3.5
lodash.debounce: 4.0.8
resolve: 1.22.8
transitivePeerDependencies:
@@ -14845,13 +14885,13 @@ snapshots:
'@types/react-router-config@5.0.11':
dependencies:
'@types/history': 4.7.11
'@types/react': 18.3.1
'@types/react': 18.3.3
'@types/react-router': 5.1.20
'@types/react-router-dom@5.3.3':
dependencies:
'@types/history': 4.7.11
'@types/react': 18.3.1
'@types/react': 18.3.3
'@types/react-router': 5.1.20
'@types/react-router@5.1.20':
@@ -15013,7 +15053,7 @@ snapshots:
dependencies:
'@typescript-eslint/types': 5.62.0
'@typescript-eslint/visitor-keys': 5.62.0
debug: 4.3.4
debug: 4.3.5
globby: 11.1.0
is-glob: 4.0.3
semver: 7.6.2
@@ -15362,14 +15402,14 @@ snapshots:
agent-base@6.0.2:
dependencies:
debug: 4.3.4
debug: 4.3.5
transitivePeerDependencies:
- supports-color
optional: true
agent-base@7.1.1:
dependencies:
debug: 4.3.4
debug: 4.3.5
transitivePeerDependencies:
- supports-color
@@ -17136,7 +17176,7 @@ snapshots:
eslint-import-resolver-typescript@3.6.1(@typescript-eslint/parser@7.2.0(eslint@8.57.0)(typescript@5.5.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1)(eslint@8.57.0):
dependencies:
debug: 4.3.4
debug: 4.3.5
enhanced-resolve: 5.17.0
eslint: 8.57.0
eslint-module-utils: 2.8.1(@typescript-eslint/parser@7.2.0(eslint@8.57.0)(typescript@5.5.2))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.6.1(@typescript-eslint/parser@7.2.0(eslint@8.57.0)(typescript@5.5.2))(eslint-import-resolver-node@0.3.9)(eslint-plugin-import@2.29.1)(eslint@8.57.0))(eslint@8.57.0)
@@ -18305,7 +18345,7 @@ snapshots:
https-proxy-agent@5.0.1:
dependencies:
agent-base: 6.0.2
debug: 4.3.4
debug: 4.3.5
transitivePeerDependencies:
- supports-color
optional: true
@@ -18313,7 +18353,7 @@ snapshots:
https-proxy-agent@7.0.4:
dependencies:
agent-base: 7.1.1
debug: 4.3.4
debug: 4.3.5
transitivePeerDependencies:
- supports-color
@@ -19566,7 +19606,7 @@ snapshots:
micromark@4.0.0:
dependencies:
'@types/debug': 4.1.12
debug: 4.3.4
debug: 4.3.5
decode-named-character-reference: 1.0.2
devlop: 1.1.0
micromark-core-commonmark: 2.0.1
@@ -21800,7 +21840,7 @@ snapshots:
spdy-transport@3.0.0:
dependencies:
debug: 4.3.4
debug: 4.3.5
detect-node: 2.1.0
hpack.js: 2.1.6
obuf: 1.1.2
+3
View File
@@ -41,6 +41,9 @@
{
"path": "./packages/llamaindex/e2e/examples/nextjs-edge-runtime/tsconfig.json"
},
{
"path": "./packages/llamaindex/e2e/examples/nextjs-node-runtime/tsconfig.json"
},
{
"path": "./packages/llamaindex/e2e/examples/waku-query-engine/tsconfig.json"
},