Compare commits

..

3 Commits

Author SHA1 Message Date
Alex Yang e80029a39a fix: type 2025-03-12 15:11:23 +00:00
Alex Yang d04cf437f2 chore(cloud): update openapi.json 2025-03-12 15:11:23 +00:00
Alex Yang 2b1b35b897 chore(cloud): update openapi.json 2025-03-12 15:11:23 +00:00
313 changed files with 759 additions and 13809 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"@llamaindex/cloud": patch
---
chore: bump sdk openapi.json
+5
View File
@@ -0,0 +1,5 @@
---
"@llamaindex/azure": patch
---
Add `fromConnectionString` method to azure storage libs to track the usage vCore.
-70
View File
@@ -1,75 +1,5 @@
# @llamaindex/doc
## 0.2.4
### Patch Changes
- 9c63f3f: Add support for openai responses api
- Updated dependencies [9c63f3f]
- Updated dependencies [c515a32]
- @llamaindex/openai@0.3.0
- @llamaindex/core@0.6.2
- @llamaindex/workflow@1.0.2
- llamaindex@0.9.15
- @llamaindex/cloud@4.0.2
- @llamaindex/node-parser@2.0.2
- @llamaindex/readers@3.0.2
## 0.2.3
### Patch Changes
- 648cfb5: Add support for supabase vector store
Added doc for the supbase vector store
- Updated dependencies [1b6f368]
- Updated dependencies [eaf326e]
- Updated dependencies [9d951b2]
- @llamaindex/core@0.6.1
- llamaindex@0.9.14
- @llamaindex/cloud@4.0.1
- @llamaindex/node-parser@2.0.1
- @llamaindex/openai@0.2.1
- @llamaindex/readers@3.0.1
- @llamaindex/workflow@1.0.1
## 0.2.2
### Patch Changes
- e98033e: docs: correct the number of indexes
## 0.2.1
### Patch Changes
- Updated dependencies [75d6e29]
- llamaindex@0.9.13
## 0.2.0
### Minor Changes
- f1db9b3: Adding an options parameter to vercel tool to tailor responses
### Patch Changes
- 21bebfc: Expose more content to fix the issue with unavailable documentation links, and adjust the documentation based on the latest code.
- 2b39cef: Added documentation for structured output in openai and ollama
- Updated dependencies [21bebfc]
- Updated dependencies [93bc0ff]
- Updated dependencies [91a18e7]
- Updated dependencies [bf56fc0]
- Updated dependencies [f8a86e4]
- Updated dependencies [5189b44]
- Updated dependencies [58a9446]
- @llamaindex/readers@3.0.0
- @llamaindex/core@0.6.0
- @llamaindex/openai@0.2.0
- @llamaindex/cloud@4.0.0
- @llamaindex/workflow@1.0.0
- llamaindex@0.9.12
- @llamaindex/node-parser@2.0.0
## 0.1.11
### Patch Changes
-2
View File
@@ -4,8 +4,6 @@ const withMDX = createMDX();
/** @type {import('next').NextConfig} */
const config = {
// default timeout for static generation is 60s, but we need to increase it to 10 minutes due to the large number of document pages
staticPageGenerationTimeout: 600,
reactStrictMode: true,
eslint: {
ignoreDuringBuilds: true,
+3 -4
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/doc",
"version": "0.2.4",
"version": "0.1.11",
"private": true,
"scripts": {
"postinstall": "fumadocs-mdx",
@@ -8,9 +8,8 @@
"build": "next build",
"dev": "next dev",
"start": "next start",
"postbuild": "tsx scripts/post-build.mts && tsx scripts/validate-links.mts",
"build:docs": "cross-env NODE_OPTIONS=\"--max-old-space-size=8192\" typedoc && tsx scripts/generate-docs.mts",
"validate-links": "tsx scripts/validate-links.mts"
"postbuild": "tsx scripts/post-build.mts",
"build:docs": "cross-env NODE_OPTIONS=\"--max-old-space-size=8192\" typedoc && tsx scripts/generate-docs.mts"
},
"dependencies": {
"@icons-pack/react-simple-icons": "^10.1.0",
-249
View File
@@ -1,249 +0,0 @@
import glob from "fast-glob";
import fs from "fs";
import matter from "gray-matter";
import path from "path";
const CONTENT_DIR = path.join(process.cwd(), "src/content/docs");
const BUILD_DIR = path.join(process.cwd(), ".next");
// Regular expression to find internal links
// This captures Markdown links [text](/docs/path) and href attributes href="/docs/path"
const INTERNAL_LINK_REGEX = /(?:(?:\]\(|\bhref=["'])\/docs\/([^")]+))/g;
// Regular expression to find relative links
// This captures relative links like [text](./path) or ![alt](../images/image.png)
const RELATIVE_LINK_REGEX = /(?:\]\()(?:\s*)(?:\.\.?)\//g;
interface LinkValidationResult {
file: string;
invalidLinks: Array<{ link: string; line: number }>;
}
interface RelativeLinkResult {
file: string;
relativeLinks: Array<{ line: number; lineContent: string }>;
}
/**
* Get all valid documentation routes from the content directory
*/
async function getValidRoutes(): Promise<Set<string>> {
const mdxFiles = await glob("**/*.mdx", { cwd: CONTENT_DIR });
const routes = new Set<string>();
// Add each MDX file as a valid route
for (const file of mdxFiles) {
// Remove .mdx extension and normalize to route format
let route = file.replace(/\.mdx$/, "");
// Handle index files
if (route.endsWith("/index")) {
route = route.replace(/\/index$/, "");
} else if (route === "index") {
route = "";
}
routes.add(route);
}
return routes;
}
/**
* Extract internal links from a MDX file
*/
function extractLinksFromFile(
filePath: string,
): Array<{ link: string; line: number }> {
const content = fs.readFileSync(filePath, "utf-8");
const { content: mdxContent } = matter(content);
const lines = mdxContent.split("\n");
const links: Array<{ link: string; line: number }> = [];
lines.forEach((line, lineNumber) => {
let match;
while ((match = INTERNAL_LINK_REGEX.exec(line)) !== null) {
if (match[1]) {
links.push({
link: match[1],
line: lineNumber + 1, // 1-based line numbers
});
}
}
});
return links;
}
/**
* Check if a link is an image link
*/
function isImageLink(link: string): boolean {
// Check for image extensions
const imageExtensions = [".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"];
const hasImageExtension = imageExtensions.some((ext) =>
link.toLowerCase().endsWith(ext),
);
// Check for markdown image syntax: ![alt](./path)
const isMarkdownImage = link.trim().startsWith("!");
return hasImageExtension || isMarkdownImage;
}
/**
* Extract relative links from a MDX file
*/
function findRelativeLinksInFile(
filePath: string,
): Array<{ line: number; lineContent: string }> {
const content = fs.readFileSync(filePath, "utf-8");
const { content: mdxContent } = matter(content);
const lines = mdxContent.split("\n");
const relativeLinks: Array<{ line: number; lineContent: string }> = [];
lines.forEach((line, lineNumber) => {
// Check for relative links
if (RELATIVE_LINK_REGEX.test(line)) {
// Reset the regex lastIndex to start from the beginning of the line
RELATIVE_LINK_REGEX.lastIndex = 0;
// Skip image links
if (!isImageLink(line)) {
relativeLinks.push({
line: lineNumber + 1, // 1-based line numbers
lineContent: line.trim(),
});
}
}
});
return relativeLinks;
}
/**
* Validate internal links in all MDX files
*/
/**
* Find relative links in all MDX files
*/
async function findRelativeLinks(): Promise<RelativeLinkResult[]> {
const mdxFiles = await glob("**/*.mdx", { cwd: CONTENT_DIR });
const results: RelativeLinkResult[] = [];
for (const file of mdxFiles) {
const filePath = path.join(CONTENT_DIR, file);
const relativeLinks = findRelativeLinksInFile(filePath);
if (relativeLinks.length > 0) {
results.push({
file,
relativeLinks,
});
}
}
return results;
}
async function validateLinks(): Promise<LinkValidationResult[]> {
const mdxFiles = await glob("**/*.mdx", { cwd: CONTENT_DIR });
const validRoutes = await getValidRoutes();
const results: LinkValidationResult[] = [];
for (const file of mdxFiles) {
const filePath = path.join(CONTENT_DIR, file);
const links = extractLinksFromFile(filePath);
const invalidLinks = links.filter(({ link }) => {
// Check if the link exists in valid routes
// First normalize the link (remove any query string or hash)
const baseLink = link.split("?")[0].split("#")[0];
// Remove the trailing slash if present.
// This works with links like "api/interfaces/MetadataFilter#operator" and "api/interfaces/MetadataFilter/#operator".
const normalizedLink = baseLink.endsWith("/")
? baseLink.slice(0, -1)
: baseLink;
// Remove llamaindex/ prefix if it exists as it's the root of the docs
let routePath = normalizedLink;
if (routePath.startsWith("llamaindex/")) {
routePath = routePath.substring("llamaindex/".length);
}
return !validRoutes.has(normalizedLink) && !validRoutes.has(routePath);
});
if (invalidLinks.length > 0) {
results.push({
file,
invalidLinks,
});
}
}
return results;
}
/**
* Main function to validate links and report errors
*/
async function main() {
console.log("🔍 Validating links in documentation...");
try {
// Check for invalid internal links
const validationResults: LinkValidationResult[] = await validateLinks();
// Check for relative links
const relativeLinksResults = await findRelativeLinks();
let hasErrors = false;
// Report invalid internal links
if (validationResults.length > 0) {
console.error("❌ Found invalid internal links:");
hasErrors = true;
for (const result of validationResults) {
console.error(`\nFile: ${result.file}`);
for (const { link, line } of result.invalidLinks) {
console.error(` - Line ${line}: /docs/${link}`);
}
}
}
// Report relative links
if (relativeLinksResults.length > 0) {
console.error("\n❌ Found relative links (use absolute paths instead):");
hasErrors = true;
for (const result of relativeLinksResults) {
console.error(`\nFile: ${result.file}`);
for (const { line, lineContent } of result.relativeLinks) {
console.error(` - Line ${line}: ${lineContent}`);
}
}
}
if (hasErrors) {
// Exit with error code to fail the build
process.exit(1);
} else {
console.log("✅ All links are valid!");
}
} catch (error) {
console.error("Error validating links:", error);
process.exit(1);
}
}
main().catch((error) => {
console.error("Unhandled error:", error);
process.exit(1);
});
+2 -1
View File
@@ -11,6 +11,8 @@ import {
} from "fumadocs-ui/page";
import { notFound } from "next/navigation";
const { AutoTypeTable } = createTypeTable();
export const revalidate = false;
export default async function Page(props: {
@@ -20,7 +22,6 @@ export default async function Page(props: {
const page = source.getPage(params.slug);
if (!page) notFound();
const { AutoTypeTable } = createTypeTable();
const MDX = page.data.body;
return (
@@ -14,7 +14,7 @@ Before you start, make sure you have try LlamaIndex.TS in Node.js to make sure y
<Card
title="Getting Started with LlamaIndex.TS in Node.js"
href="/docs/llamaindex/getting_started/frameworks/node"
href="/docs/llamaindex/getting_started/setup/node"
/>
Also, you need have the basic understanding of <a href='https://developers.cloudflare.com/workers/'><SiCloudflareworkers className="inline mr-2" color="#F38020" />Cloudflare Worker</a>.
@@ -15,28 +15,28 @@ import {
<>
<SiNodedotjs className="inline" color="#5FA04E" /> Node.js
</>
} href="/docs/llamaindex/getting_started/frameworks/node" />
} href="/docs/llamaindex/getting_started/setup/node" />
<Card title={
<>
<SiTypescript className="inline" color="#3178C6" /> TypeScript
</>
} href="/docs/llamaindex/getting_started/frameworks/typescript" />
} href="/docs/llamaindex/getting_started/setup/typescript" />
<Card title={
<>
<SiVite className='inline' color='#646CFF' /> Vite
</>
} href="/docs/llamaindex/getting_started/frameworks/vite" />
} href="/docs/llamaindex/getting_started/setup/vite" />
<Card
title={
<>
<SiNextdotjs className='inline' /> Next.js (React Server Component)
</>
}
href="/docs/llamaindex/getting_started/frameworks/next"
href="/docs/llamaindex/getting_started/setup/next"
/>
<Card title={
<>
<SiCloudflareworkers className='inline' color='#F38020' /> Cloudflare Workers
</>
} href="/docs/llamaindex/getting_started/frameworks/cloudflare" />
} href="/docs/llamaindex/getting_started/setup/cloudflare" />
</Cards>
@@ -7,7 +7,7 @@ Before you start, make sure you have try LlamaIndex.TS in Node.js to make sure y
<Card
title="Getting Started with LlamaIndex.TS in Node.js"
href="/docs/llamaindex/getting_started/frameworks/node"
href="/docs/llamaindex/getting_started/setup/node"
/>
## Differences between Node.js and Next.js
@@ -35,7 +35,7 @@ If you see any dependency issues, you are welcome to open an issue on the GitHub
## Edge Runtime
[Vercel Edge Runtime](https://edge-runtime.vercel.app/) is a subset of Node.js APIs. Similar to [Cloudflare Workers](/docs/llamaindex/getting_started/frameworks/cloudflare#difference-between-nodejs-and-cloudflare-worker),
[Vercel Edge Runtime](https://edge-runtime.vercel.app/) is a subset of Node.js APIs. Similar to [Cloudflare Workers](./cloudflare#difference-between-nodejs-and-cloudflare-worker),
it is a serverless platform that runs your code on the edge.
Not all features of Node.js are supported in Vercel Edge Runtime, so does LlamaIndex.TS, we are working on more compatibility with all JavaScript runtimes.
@@ -48,5 +48,5 @@ By the default, we are using `js-tiktoken` for tokenization. You can install `gp
<Card
title="Getting Started with LlamaIndex.TS in TypeScript"
href="/docs/llamaindex/getting_started/frameworks/typescript"
href="/docs/llamaindex/getting_started/setup/typescript"
/>
@@ -7,7 +7,7 @@ Before you start, make sure you have try LlamaIndex.TS in Node.js to make sure y
<Card
title="Getting Started with LlamaIndex.TS in Node.js"
href="/docs/llamaindex/getting_started/frameworks/node"
href="/docs/llamaindex/getting_started/setup/node"
/>
Also, make sure you have a basic understanding of [Vite](https://vitejs.dev/).
@@ -84,7 +84,6 @@ const queryTool = llamaindex({
model: openai("gpt-4"),
index,
description: "Search through the documents",
options: { fields: ["sourceNodes", "messages"]}
});
// Use the tool with Vercel's AI SDK
@@ -75,7 +75,7 @@ Now:
import { SimpleDirectoryReader } from "@llamaindex/readers/directory";
```
For more details about available data loaders and their usage, check the [Loading Data](/docs/llamaindex/modules/loading).
For more details about available data loaders and their usage, check the [Loading Data](/docs/llamaindex/guide/loading).
### 4. Prefer using `llamaindex` instead of `@llamaindex/core`
@@ -21,6 +21,11 @@ LlamaIndex.TS comes with a few built-in agents, but you can also create your own
- ReACT Agent
- Meta3.1 504B via Bedrock (in `@llamaIndex/community`)
## Examples
- [OpenAI Agent](/docs/llamaindex/examples/agent)
- [Gemini Agent](/docs/llamaindex/examples/agent_gemini)
## Api References
- [OpenAIAgent](/docs/api/classes/OpenAIAgent)
@@ -3,7 +3,7 @@ title: Agent Workflows
---
Agent Workflows are a powerful system that enables you to create and orchestrate one or multiple agents with tools to perform specific tasks. It's built on top of the base [`Workflow`](/docs/llamaindex/modules/workflows) system and provides a streamlined interface for agent interactions.
Agent Workflows are a powerful system that enables you to create and orchestrate one or multiple agents with tools to perform specific tasks. It's built on top of the base [`Workflow`](./workflows) system and provides a streamlined interface for agent interactions.
## Usage
@@ -6,7 +6,7 @@ import { ChatDemoRSC } from '../../../../../components/demo/chat/rsc/demo';
Using [chat-ui](https://github.com/run-llama/chat-ui), it's easy to add a chat interface to your LlamaIndexTS application using [Next.js RSC](https://nextjs.org/docs/app/building-your-application/rendering/server-components) and [Vercel AI RSC](https://sdk.vercel.ai/docs/ai-sdk-rsc/overview).
With RSC, the chat messages are not returned as JSON from the server (like when using an [API route](/docs/llamaindex/modules/chat/chat)), instead the chat message components are rendered on the server side.
With RSC, the chat messages are not returned as JSON from the server (like when using an [API route](./chat)), instead the chat message components are rendered on the server side.
This is for example useful for rendering a whole chat history on the server before sending it to the client. [Check here](https://sdk.vercel.ai/docs/getting-started/navigating-the-library#when-to-use-ai-sdk-rsc), for a discussion of when to use use RSC.
For implementing a chat interface with RSC, you need to create an AI action and then connect the chat interface to use it.
@@ -2,7 +2,7 @@
title: Index
---
An index is the basic container and organization for your data. LlamaIndex.TS supports three indexes:
An index is the basic container and organization for your data. LlamaIndex.TS supports two indexes:
- `VectorStoreIndex` - will send the top-k `Node`s to the LLM when generating a response. The default top-k is 2.
- `SummaryIndex` - will send every `Node` in the index to the LLM in order to generate a response
@@ -35,7 +35,7 @@ Currently, the following readers are mapped to specific file types:
- [TextFileReader](/docs/api/classes/TextFileReader): `.txt`
- [PDFReader](/docs/api/classes/PDFReader): `.pdf`
- [CSVReader](/docs/api/classes/CSVReader): `.csv`
- [PapaCSVReader](/docs/api/classes/PapaCSVReader): `.csv`
- [MarkdownReader](/docs/api/classes/MarkdownReader): `.md`
- [DocxReader](/docs/api/classes/DocxReader): `.docx`
- [HTMLReader](/docs/api/classes/HTMLReader): `.htm`, `.html`
@@ -6,11 +6,11 @@ Chat stores manage chat history by storing sequences of messages in a structured
## Available Chat Stores
- [SimpleChatStore](/docs/api/classes/SimpleChatStore): A simple in-memory chat store with support for [persisting](/docs/llamaindex/modules/data_stores#local-storage) data to disk.
- [SimpleChatStore](/docs/api/classes/SimpleChatStore): A simple in-memory chat store with support for [persisting](/docs/llamaindex/modules/data_stores/#local-storage) data to disk.
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
## API Reference
- [BaseChatStore](/docs/api/classes/BaseChatStore)
- [BaseChatStore](/docs/api/interfaces/BaseChatStore)
@@ -2,12 +2,12 @@
title: Document Stores
---
Document stores contain ingested document chunks, i.e. [Node](/docs/llamaindex/modules/documents_and_nodes)s.
Document stores contain ingested document chunks, i.e. [Node](/docs/llamaindex/modules/documents_and_nodes/index)s.
## Available Document Stores
- [SimpleDocumentStore](/docs/api/classes/SimpleDocumentStore): A simple in-memory document store with support for [persisting](/docs/llamaindex/modules/data_stores#local-storage) data to disk.
- [PostgresDocumentStore](/docs/api/classes/PostgresDocumentStore): A PostgreSQL document store, see [PostgreSQL Storage](/docs/llamaindex/modules/data_stores#postgresql-storage).
- [SimpleDocumentStore](/docs/api/classes/SimpleDocumentStore): A simple in-memory document store with support for [persisting](/docs/llamaindex/modules/data_stores/#local-storage) data to disk.
- [PostgresDocumentStore](/docs/api/classes/PostgresDocumentStore): A PostgreSQL document store, see [PostgreSQL Storage](/docs/llamaindex/modules/data_stores/#postgresql-storage).
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
@@ -6,8 +6,8 @@ Index stores are underlying storage components that contain metadata(i.e. inform
## Available Index Stores
- [SimpleIndexStore](/docs/api/classes/SimpleIndexStore): A simple in-memory index store with support for [persisting](/docs/llamaindex/modules/data_stores#local-storage) data to disk.
- [PostgresIndexStore](/docs/api/classes/PostgresIndexStore): A PostgreSQL index store, , see [PostgreSQL Storage](/docs/llamaindex/modules/data_stores#postgresql-storage).
- [SimpleIndexStore](/docs/api/classes/SimpleIndexStore): A simple in-memory index store with support for [persisting](/docs/llamaindex/modules/data_stores/#local-storage) data to disk.
- [PostgresIndexStore](/docs/api/classes/PostgresIndexStore): A PostgreSQL index store, , see [PostgreSQL Storage](/docs/llamaindex/modules/data_stores/#postgresql-storage).
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
@@ -2,12 +2,12 @@
title: Key-Value Stores
---
Key-Value Stores represent underlying storage components used in [Document Stores](/docs/llamaindex/modules/data_stores/doc_stores) and [Index Stores](/docs/llamaindex/modules/data_stores/index_stores)
Key-Value Stores represent underlying storage components used in [Document Stores](/docs/llamaindex/modules/data_stores/doc_stores/index) and [Index Stores](/docs/llamaindex/modules/data_stores/index_stores/index)
## Available Key-Value Stores
- [SimpleKVStore](/docs/api/classes/SimpleKVStore): A simple Key-Value store with support of [persisting](/docs/llamaindex/modules/data_stores#local-storage) data to disk.
- [PostgresKVStore](/docs/api/classes/PostgresKVStore): A PostgreSQL Key-Value store, see [PostgreSQL Storage](/docs/llamaindex/modules/data_stores#postgresql-storage).
- [SimpleKVStore](/docs/api/classes/SimpleKVStore): A simple Key-Value store with support of [persisting](/docs/llamaindex/modules/data_stores/#local-storage) data to disk.
- [PostgresKVStore](/docs/api/classes/PostgresKVStore): A PostgreSQL Key-Value store, see [PostgreSQL Storage](/docs/llamaindex/modules/data_stores/#postgresql-storage).
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
@@ -8,7 +8,7 @@ Vector stores save embedding vectors of your ingested document chunks.
Available Vector Stores are shown on the sidebar to the left. Additionally the following integrations exist without separate documentation:
- [SimpleVectorStore](/docs/api/classes/SimpleVectorStore): A simple in-memory vector store with optional [persistance](/docs/llamaindex/modules/data_stores#local-storage) to disk.
- [SimpleVectorStore](/docs/api/classes/SimpleVectorStore): A simple in-memory vector store with optional [persistance](/docs/llamaindex/modules/data_stores/#local-storage) to disk.
- [AstraDBVectorStore](/docs/api/classes/AstraDBVectorStore): A cloud-native, scalable Database-as-a-Service built on Apache Cassandra, see [datastax.com](https://www.datastax.com/products/datastax-astra)
- [ChromaVectorStore](/docs/api/classes/ChromaVectorStore): An open-source vector database, focused on ease of use and performance, see [trychroma.com](https://www.trychroma.com/)
- [MilvusVectorStore](/docs/api/classes/MilvusVectorStore): An open-source, high-performance, highly scalable vector database, see [milvus.io](https://milvus.io/)
@@ -19,3 +19,6 @@ Available Vector Stores are shown on the sidebar to the left. Additionally the f
Check the [LlamaIndexTS Github](https://github.com/run-llama/LlamaIndexTS) for the most up to date overview of integrations.
## API Reference
- [BaseVectorStore](/docs/api/classes/BaseVectorStore)
@@ -56,10 +56,10 @@ const vectorStore = new QdrantVectorStore({
```ts
const document = new Document({ text: essay, id_: path });
const storageContext = await storageContextFromDefaults({ vectorStore });
const index = await VectorStoreIndex.fromDocuments([document], {
storageContext,
});
const index = await VectorStoreIndex.fromDocuments([document], {
vectorStore,
});
```
## Query the index
@@ -91,11 +91,11 @@ async function main() {
});
const document = new Document({ text: essay, id_: path });
const storageContext = await storageContextFromDefaults({ vectorStore });
const index = await VectorStoreIndex.fromDocuments([document], {
storageContext,
vectorStore,
});
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
@@ -1,166 +0,0 @@
---
title: Supabase Vector Store
---
[supabase.com](https://supabase.com/)
To use this vector store, you need a Supabase project. You can create one at [supabase.com](https://supabase.com/).
## Installation
import { Tab, Tabs } from "fumadocs-ui/components/tabs";
<Tabs groupId="install" items={["npm", "yarn", "pnpm"]} persist>
```shell tab="npm"
npm install llamaindex @llamaindex/supabase
```
```shell tab="yarn"
yarn add llamaindex @llamaindex/supabase
```
```shell tab="pnpm"
pnpm add llamaindex @llamaindex/supabase
```
</Tabs>
## Database Setup
Before using the vector store, you need to:
1. Enable the `pgvector` extension
2. Create a table for storing vectors
3. Create a vector similarity search function
```sql
create table documents (
id uuid primary key,
content text,
metadata jsonb,
embedding vector(1536)
);
```
-- Create a function for similarity search
```sql
create function match_documents (
query_embedding vector(1536),
match_count int
) returns table (
id uuid,
content text,
metadata jsonb,
embedding vector(1536),
similarity float
)
language plpgsql
as $$
begin
return query
select
id,
content,
metadata,
embedding,
1 - (embedding <=> query_embedding) as similarity
from documents
order by embedding <=> query_embedding
limit match_count;
end;
$$;
```
## Importing the modules
```ts
import { Document, VectorStoreIndex } from "llamaindex";
import { SupabaseVectorStore } from "@llamaindex/supabase";
```
## Setup Supabase
```ts
const vectorStore = new SupabaseVectorStore({
supabaseUrl: process.env.SUPABASE_URL,
supabaseKey: process.env.SUPABASE_KEY,
table: "documents",
});
```
## Setup the index
```ts
const documents = [
new Document({
text: "Sample document text",
metadata: { source: "example" }
})
];
const storageContext = await storageContextFromDefaults({ vectorStore });
const index = await VectorStoreIndex.fromDocuments(documents, {
storageContext,
});
```
## Query the index
```ts
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What is in the document?",
});
// Output response
console.log(response.toString());
```
## Full code
```ts
import { Document, VectorStoreIndex, storageContextFromDefaults } from "llamaindex";
import { SupabaseVectorStore } from "@llamaindex/supabase";
async function main() {
// Initialize the vector store
const vectorStore = new SupabaseVectorStore({
supabaseUrl: process.env.SUPABASE_URL,
supabaseKey: process.env.SUPABASE_KEY,
table: "documents",
});
// Create sample documents
const documents = [
new Document({
text: "Vector search enables semantic similarity search",
metadata: {
source: "research_paper",
author: "Jane Smith",
},
}),
];
// Create storage context
const storageContext = await storageContextFromDefaults({ vectorStore });
// Create and store embeddings
const index = await VectorStoreIndex.fromDocuments(documents, {
storageContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What is vector search?",
});
// Output response
console.log(response.toString());
}
main().catch(console.error);
```
## API Reference
- [SupabaseVectorStore](/docs/api/classes/SupabaseVectorStore)
@@ -74,4 +74,4 @@ the response is not correct with a score of 2.5
## API Reference
- [CorrectnessEvaluator](/docs/api/classes/CorrectnessEvaluator)
- [CorrectnessEvaluator](/docs/api/classes/CorrectnessEvaluator)
@@ -8,7 +8,7 @@ Currently, the following components are Transformation objects:
- [SentenceSplitter](/docs/api/classes/SentenceSplitter)
- [MetadataExtractor](/docs/llamaindex/modules/documents_and_nodes/metadata_extraction)
- [Embeddings](/docs/llamaindex/modules/embeddings)
- [Embeddings](/docs/llamaindex/modules/embeddings/index)
## Usage Pattern
@@ -55,35 +55,6 @@ const results = await queryEngine.query({
});
```
## Using JSON Response Format
You can configure Ollama to return responses in JSON format:
```ts
import { Ollama } from "@llamaindex/llms/ollama";
import { z } from "zod";
// Simple JSON format
const llm = new Ollama({
model: "llama2",
temperature: 0,
responseFormat: { type: "json_object" }
});
// Using Zod schema for validation
const responseSchema = z.object({
summary: z.string(),
topics: z.array(z.string()),
sentiment: z.enum(["positive", "negative", "neutral"])
});
const llm = new Ollama({
model: "llama2",
temperature: 0,
responseFormat: responseSchema
});
```
## Full Example
```ts
@@ -46,289 +46,6 @@ or
Settings.llm = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY>, baseURL: "https://api.scaleway.ai/v1" });
```
## Using OpenAI Responses API
The OpenAI Responses API provides enhanced functionality for handling complex interactions, including built-in tools, annotations, and streaming responses. Here's how to use it:
### Basic Setup
```ts
import { openaiResponses } from "@llamaindex/openai";
const llm = openaiResponses({
model: "gpt-4o",
temperature: 0.1,
maxOutputTokens: 1000
});
```
### Message Content Types
The API supports different types of message content, including text and images:
```ts
const response = await llm.chat({
messages: [
{
role: "user",
content: [
{
type: "input_text",
text: "What's in this image?"
},
{
type: "input_image",
image_url: "https://example.com/image.jpg",
detail: "auto" // Optional: can be "auto", "low", or "high"
}
]
}
]
});
```
### Advanced Features
#### Built-in Tools
```ts
const llm = openaiResponses({
model: "gpt-4o",
builtInTools: [
{
type: "function",
name: "search_files",
description: "Search through available files"
}
],
strict: true // Enable strict mode for tool calls
});
```
#### Response Tracking and Storage
```ts
const llm = openaiResponses({
trackPreviousResponses: true, // Enable response tracking
store: true, // Store responses for future reference
user: "user-123", // Associate responses with a user
callMetadata: { // Add custom metadata
sessionId: "session-123",
context: "customer-support"
}
});
```
#### Streaming Responses
```ts
const response = await llm.chat({
messages: [
{
role: "user",
content: "Generate a long response"
}
],
stream: true // Enable streaming
});
for await (const chunk of response) {
console.log(chunk.delta); // Process each chunk of the response
}
```
### Configuration Options
The OpenAI Responses API supports various configuration options:
```ts
const llm = openaiResponses({
// Model and basic settings
model: "gpt-4o",
temperature: 0.1,
topP: 1,
maxOutputTokens: 1000,
// API configuration
apiKey: "your-api-key",
baseURL: "custom-endpoint",
maxRetries: 10,
timeout: 60000,
// Response handling
trackPreviousResponses: false,
store: false,
strict: false,
// Additional options
instructions: "Custom instructions for the model",
truncation: "auto", // Can be "auto", "disabled", or null
include: ["citations", "reasoning"] // Specify what to include in responses
});
```
### Response Structure
The API returns responses with rich metadata and optional annotations:
```ts
interface ResponseStructure {
message: {
content: string;
role: "assistant";
options: {
built_in_tool_calls: Array<ToolCall>;
annotations?: Array<Citation | URLCitation | FilePath>;
refusal?: string;
reasoning?: ReasoningItem;
usage?: ResponseUsage;
toolCall?: Array<PartialToolCall>;
}
}
}
```
### Best Practices
1. Use `trackPreviousResponses` when you need conversation continuity
2. Enable `strict` mode when using tools to ensure accurate function calls
3. Set appropriate `maxOutputTokens` to control response length
4. Use `annotations` to track citations and references in responses
5. Implement error handling for potential API failures and retries
## Using JSON Response Format
You can configure OpenAI to return responses in JSON format:
```ts
Settings.llm = new OpenAI({
model: "gpt-4o",
temperature: 0,
responseFormat: { type: "json_object" }
});
// You can also use a Zod schema to validate the response structure
import { z } from "zod";
const responseSchema = z.object({
summary: z.string(),
topics: z.array(z.string()),
sentiment: z.enum(["positive", "negative", "neutral"])
});
Settings.llm = new OpenAI({
model: "gpt-4o",
temperature: 0,
responseFormat: responseSchema
});
```
## Response Formats
The OpenAI LLM supports different response formats to structure the output in specific ways. There are two main approaches to formatting responses:
### 1. JSON Object Format
The simplest way to get structured JSON responses is using the `json_object` response format:
```ts
Settings.llm = new OpenAI({
model: "gpt-4o",
temperature: 0,
responseFormat: { type: "json_object" }
});
const response = await llm.chat({
messages: [
{
role: "system",
content: "You are a helpful assistant that outputs JSON."
},
{
role: "user",
content: "Summarize this meeting transcript"
}
]
});
// Response will be valid JSON
console.log(response.message.content);
```
### 2. Schema Validation with Zod
For more robust type safety and validation, you can use Zod schemas to define the expected response structure:
```ts
import { z } from "zod";
// Define the response schema
const meetingSchema = z.object({
summary: z.string(),
participants: z.array(z.string()),
actionItems: z.array(z.string()),
nextSteps: z.string()
});
// Configure the LLM with the schema
Settings.llm = new OpenAI({
model: "gpt-4o",
temperature: 0,
responseFormat: meetingSchema
});
const response = await llm.chat({
messages: [
{
role: "user",
content: "Summarize this meeting transcript"
}
]
});
// Response will be typed and validated according to the schema
const result = response.message.content;
console.log(result.summary);
console.log(result.actionItems);
```
### Response Format Options
The response format can be configured in two ways:
1. At LLM initialization:
```ts
const llm = new OpenAI({
model: "gpt-4o",
responseFormat: { type: "json_object" } // or a Zod schema
});
```
2. Per request:
```ts
const response = await llm.chat({
messages: [...],
responseFormat: { type: "json_object" } // or a Zod schema
});
```
The response format options are:
- `{ type: "json_object" }` - Returns responses as JSON objects
- `zodSchema` - A Zod schema that defines and validates the response structure
### Best Practices
1. Use JSON object format for simple structured responses
2. Use Zod schemas when you need:
- Type safety
- Response validation
- Complex nested structures
- Specific field constraints
3. Set a low temperature (e.g. 0) when using structured outputs for more reliable formatting
4. Include clear instructions in system or user messages about the expected response format
5. Handle potential parsing errors when working with JSON responses
## Load and index documents
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
@@ -5,7 +5,7 @@ description: Learn how to use Node Parsers and Text Splitters to extract data fr
import { CodeNodeParserDemo } from '../../../../../components/demo/code-node-parser.tsx';
import { Tab, Tabs } from "fumadocs-ui/components/tabs";
Node parsers are a simple abstraction that take a list of documents, and chunk them into `Node` objects, such that each node is a specific chunk of the parent document. When a document is broken into nodes, all of it's attributes are inherited to the children nodes (i.e. `metadata`, text and metadata templates, etc.). You can read more about `Node` and `Document` properties [here](/docs/llamaindex/modules/loading).
Node parsers are a simple abstraction that take a list of documents, and chunk them into `Node` objects, such that each node is a specific chunk of the parent document. When a document is broken into nodes, all of it's attributes are inherited to the children nodes (i.e. `metadata`, text and metadata templates, etc.). You can read more about `Node` and `Document` properties [here](./).
## NodeParser
@@ -28,21 +28,14 @@ Answer:`;
### 1. Customizing the default prompt on initialization
The first method is to create a new instance of a Response Synthesizer (or the module you would like to update the prompt) by using the getResponseSynthesizer function. Instead of passing the custom prompt to the deprecated responseBuilder parameter, call getResponseSynthesizer with the mode as the first argument and supply the new prompt via the options parameter.
The first method is to create a new instance of `ResponseSynthesizer` (or the module you would like to update the prompt) and pass the custom prompt to the `responseBuilder` parameter. Then, pass the instance to the `asQueryEngine` method of the index.
```ts
// Create an instance of Response Synthesizer
// Deprecated usage:
// Create an instance of response synthesizer
const responseSynthesizer = new ResponseSynthesizer({
responseBuilder: new CompactAndRefine(undefined, newTextQaPrompt),
});
// Current usage:
const responseSynthesizer = getResponseSynthesizer('compact', {
textQATemplate: newTextQaPrompt
})
// Create index
const index = await VectorStoreIndex.fromDocuments([document]);
@@ -82,5 +75,5 @@ const response = await queryEngine.query({
## API Reference
- [Response Synthesizer](/docs/llamaindex/modules/response_synthesizer)
- [ResponseSynthesizer](/docs/api/classes/ResponseSynthesizer)
- [CompactAndRefine](/docs/api/classes/CompactAndRefine)
@@ -1,5 +1,5 @@
---
title: Response Synthesizer
title: ResponseSynthesizer
---
The ResponseSynthesizer is responsible for sending the query, nodes, and prompt templates to the LLM to generate a response. There are a few key modes for generating a response:
@@ -12,17 +12,15 @@ The ResponseSynthesizer is responsible for sending the query, nodes, and prompt
multiple compact prompts. The same as `refine`, but should result in less LLM calls.
- `TreeSummarize`: Given a set of text chunks and the query, recursively construct a tree
and return the root node as the response. Good for summarization purposes.
- `MultiModal`: Combines textual inputs with additional modality-specific metadata to generate an integrated response.
It leverages a text QA template to build a prompt that incorporates various input types and produces either streaming or complete responses.
This approach is ideal for use cases where enriching the answer with multi-modal context (such as images, audio, or other data)
can enhance the output quality.
- `SimpleResponseBuilder`: Given a set of text chunks and the query, apply the query to each text
chunk while accumulating the responses into an array. Returns a concatenated string of all
responses. Good for when you need to run the same query separately against each text
chunk.
```typescript
import { NodeWithScore, TextNode, getResponseSynthesizer, responseModeSchema } from "llamaindex";
import { NodeWithScore, TextNode, ResponseSynthesizer } from "llamaindex";
// you can also use responseModeSchema.Enum.refine, responseModeSchema.Enum.tree_summarize, responseModeSchema.Enum.multi_modal
// or you can use the CompactAndRefine, Refine, TreeSummarize, or MultiModal classes directly
const responseSynthesizer = getResponseSynthesizer(responseModeSchema.Enum.compact);
const responseSynthesizer = new ResponseSynthesizer();
const nodesWithScore: NodeWithScore[] = [
{
@@ -57,9 +55,8 @@ for await (const chunk of stream) {
## API Reference
- [getResponseSynthesizer](/docs/api/functions/getResponseSynthesizer)
- [responseModeSchema](/docs/api/variables/responseModeSchema)
- [ResponseSynthesizer](/docs/api/classes/ResponseSynthesizer)
- [Refine](/docs/api/classes/Refine)
- [CompactAndRefine](/docs/api/classes/CompactAndRefine)
- [TreeSummarize](/docs/api/classes/TreeSummarize)
- [MultiModal](/docs/api/classes/MultiModal)
- [SimpleResponseBuilder](/docs/api/classes/SimpleResponseBuilder)
@@ -7,59 +7,9 @@ A tool can be called to perform custom actions, or retrieve extra information ba
A result from a tool call can be used by subsequent steps in a workflow, or to compute a final answer.
For example, a "weather tool" could fetch some live weather information from a geographical location.
## Tool Function
The `tool` function is a utility provided to define a tool that can be used by an agent. It takes a function and a configuration object as arguments. The configuration object includes the tool's name, description, and parameters.
### Parameters with Zod
The `parameters` field in the tool configuration is defined using `zod`, a TypeScript-first schema declaration and validation library. `zod` allows you to specify the expected structure and types of the input parameters, ensuring that the data passed to the tool is valid.
Example:
```ts
import { agent, tool } from "llamaindex";
import { z } from "zod";
// first arg is LLM input, second is bound arg
const queryKnowledgeBase = async ({ question }, { userToken }) => {
const response = await fetch(`https://knowledge-base.com?token=${userToken}&query=${question}`);
// ...
};
// define tool with zod validation
const kbTool = tool(queryKnowledgeBase, {
name: 'queryKnowledgeBase',
description: 'Query knowledge base',
parameters: z.object({
question: z.string({
description: 'The user question',
}),
}),
});
```
In this example, `z.object` is used to define a schema for the `parameters` where `question` is expected to be a string. This ensures that any input to the tool adheres to the specified structure, providing a layer of type safety and validation.
## Built-in tools
You can import built-in tools from the `@llamaindex/tools` package.
```ts
import { agent } from "llamaindex";
import { wiki } from "@llamaindex/tools";
const researchAgent = agent({
name: "WikiAgent",
description: "Gathering information from the internet",
systemPrompt: `You are a research agent. Your role is to gather information from the internet using the provided tools.`,
tools: [wiki()],
});
```
## Function tool
You can still use the `FunctionTool` class to define a tool.
Function tools are implemented with the `FunctionTool` class.
A `FunctionTool` is constructed from a function with signature
```ts
(input: T, additionalArg?: AdditionalToolArgument) => R
@@ -5,7 +5,7 @@ title: Basic Agent
import { DynamicCodeBlock } from 'fumadocs-ui/components/dynamic-codeblock';
import CodeSource from "!raw-loader!../../../../../../../examples/agent/openai";
We have a comprehensive, step-by-step [guide to building agents in LlamaIndex.TS](/docs/llamaindex/tutorials/agents/1_setup) that we recommend to learn what agents are and how to build them for production. But building a basic agent is simple:
We have a comprehensive, step-by-step [guide to building agents in LlamaIndex.TS](./agents/1_setup) that we recommend to learn what agents are and how to build them for production. But building a basic agent is simple:
## Set up
@@ -1,8 +1,8 @@
{
"title": "Tutorials",
"pages": [
"basic_agent",
"rag",
"basic_agent",
"agents",
"workflow",
"local_llm",
@@ -30,10 +30,10 @@ LlamaIndex.TS help you prepare the knowledge base with a suite of data connector
![](./_static/concepts/indexing.jpg)
[**Data Loaders**](/docs/llamaindex/modules/data_loaders):
[**Data Loaders**](/docs/llamaindex/modules/data_loaders/index):
A data connector (i.e. `Reader`) ingest data from different data sources and data formats into a simple `Document` representation (text and simple metadata).
[**Documents / Nodes**](/docs/llamaindex/modules/documents_and_nodes): A `Document` is a generic container around any data source - for instance, a PDF, an API output, or retrieved data from a database. A `Node` is the atomic unit of data in LlamaIndex and represents a "chunk" of a source `Document`. It's a rich representation that includes metadata and relationships (to other nodes) to enable accurate and expressive retrieval operations.
[**Documents / Nodes**](/docs/llamaindex/modules/documents_and_nodes/index): A `Document` is a generic container around any data source - for instance, a PDF, an API output, or retrieved data from a database. A `Node` is the atomic unit of data in LlamaIndex and represents a "chunk" of a source `Document`. It's a rich representation that includes metadata and relationships (to other nodes) to enable accurate and expressive retrieval operations.
[**Data Indexes**](/docs/llamaindex/modules/data_index):
Once you've ingested your data, LlamaIndex helps you index data into a format that's easy to retrieve.
@@ -6,7 +6,7 @@ import { DynamicCodeBlock } from 'fumadocs-ui/components/dynamic-codeblock';
import CodeSource from "!raw-loader!../../../../../../../../examples/vectorIndex";
import TSConfigSource from "!!raw-loader!../../../../../../../../examples/tsconfig.json";
One of the most common use-cases for LlamaIndex is Retrieval-Augmented Generation or RAG, in which your data is indexed and selectively retrieved to be given to an LLM as source material for responding to a query. You can learn more about the [concepts behind RAG](/docs/llamaindex/tutorials/rag/concepts).
One of the most common use-cases for LlamaIndex is Retrieval-Augmented Generation or RAG, in which your data is indexed and selectively retrieved to be given to an LLM as source material for responding to a query. You can learn more about the [concepts behind RAG](./rag/concepts).
## Set up the project
@@ -17,9 +17,9 @@ npm init
npm install -D typescript @types/node
```
Then, check out the [installation](/docs/llamaindex/getting_started) steps to install LlamaIndex.TS and prepare an OpenAI key.
Then, check out the [installation](../setup) steps to install LlamaIndex.TS and prepare an OpenAI key.
You can use [other LLMs](/docs/llamaindex/modules/llms) via their APIs; if you would prefer to use local models check out our [local LLM example](/docs/llamaindex/tutorials/local_llm).
You can use [other LLMs](/docs/llamaindex/modules/llms) via their APIs; if you would prefer to use local models check out our [local LLM example](./local_llm).
## Run queries
@@ -5,9 +5,9 @@ title: Structured data extraction
import { DynamicCodeBlock } from 'fumadocs-ui/components/dynamic-codeblock';
import CodeSource from "!raw-loader!../../../../../../../examples/jsonExtract";
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](/docs/llamaindex/getting_started) guide.
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](../setup) guide.
You can use [other LLMs](/docs/llamaindex/modules/llms) via their APIs; if you would prefer to use local models check out our [local LLM example](/docs/llamaindex/tutorials/local_llm).
You can use [other LLMs](/docs/llamaindex/modules/llms) via their APIs; if you would prefer to use local models check out our [local LLM example](./local_llm).
## Set up
+1 -6
View File
@@ -1,13 +1,8 @@
{
"plugin": ["typedoc-plugin-markdown", "typedoc-plugin-merge-modules"],
"entryPoints": [
"../../packages/{,**/}index.ts",
"../../packages/readers/src/*.ts",
"../../packages/cloud/src/{reader,utils}.ts"
],
"entryPoints": ["../../packages/**/src/index.ts"],
"exclude": [
"../../packages/autotool/**/src/index.ts",
"../../packages/cloud/src/client/index.ts",
"**/node_modules/**",
"**/dist/**",
"**/test/**",
@@ -1,31 +1,5 @@
# @llamaindex/cloudflare-worker-agent-test
## 0.0.149
### Patch Changes
- llamaindex@0.9.15
## 0.0.148
### Patch Changes
- Updated dependencies [9d951b2]
- llamaindex@0.9.14
## 0.0.147
### Patch Changes
- Updated dependencies [75d6e29]
- llamaindex@0.9.13
## 0.0.146
### Patch Changes
- llamaindex@0.9.12
## 0.0.145
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/cloudflare-worker-agent-test",
"version": "0.0.149",
"version": "0.0.145",
"type": "module",
"private": true,
"scripts": {
@@ -1,25 +1,5 @@
# @llamaindex/llama-parse-browser-test
## 0.0.57
### Patch Changes
- @llamaindex/cloud@4.0.2
## 0.0.56
### Patch Changes
- @llamaindex/cloud@4.0.1
## 0.0.55
### Patch Changes
- Updated dependencies [bf56fc0]
- Updated dependencies [5189b44]
- @llamaindex/cloud@4.0.0
## 0.0.54
### Patch Changes
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/llama-parse-browser-test",
"private": true,
"version": "0.0.57",
"version": "0.0.54",
"type": "module",
"scripts": {
"dev": "vite",
@@ -10,7 +10,7 @@
},
"devDependencies": {
"typescript": "^5.7.3",
"vite": "^5.4.16",
"vite": "^5.4.12",
"vite-plugin-wasm": "^3.3.0"
},
"dependencies": {
-26
View File
@@ -1,31 +1,5 @@
# @llamaindex/next-agent-test
## 0.1.149
### Patch Changes
- llamaindex@0.9.15
## 0.1.148
### Patch Changes
- Updated dependencies [9d951b2]
- llamaindex@0.9.14
## 0.1.147
### Patch Changes
- Updated dependencies [75d6e29]
- llamaindex@0.9.13
## 0.1.146
### Patch Changes
- llamaindex@0.9.12
## 0.1.145
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/next-agent-test",
"version": "0.1.149",
"version": "0.1.145",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,31 +1,5 @@
# test-edge-runtime
## 0.1.148
### Patch Changes
- llamaindex@0.9.15
## 0.1.147
### Patch Changes
- Updated dependencies [9d951b2]
- llamaindex@0.9.14
## 0.1.146
### Patch Changes
- Updated dependencies [75d6e29]
- llamaindex@0.9.13
## 0.1.145
### Patch Changes
- llamaindex@0.9.12
## 0.1.144
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/nextjs-edge-runtime-test",
"version": "0.1.148",
"version": "0.1.144",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,40 +1,5 @@
# @llamaindex/next-node-runtime
## 0.1.15
### Patch Changes
- llamaindex@0.9.15
- @llamaindex/huggingface@0.1.2
- @llamaindex/readers@3.0.2
## 0.1.14
### Patch Changes
- Updated dependencies [9d951b2]
- llamaindex@0.9.14
- @llamaindex/huggingface@0.1.1
- @llamaindex/readers@3.0.1
## 0.1.13
### Patch Changes
- Updated dependencies [75d6e29]
- llamaindex@0.9.13
## 0.1.12
### Patch Changes
- Updated dependencies [21bebfc]
- Updated dependencies [91a18e7]
- Updated dependencies [5189b44]
- @llamaindex/readers@3.0.0
- @llamaindex/huggingface@0.1.0
- llamaindex@0.9.12
## 0.1.11
### Patch Changes
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/next-node-runtime-test",
"version": "0.1.15",
"version": "0.1.11",
"private": true,
"scripts": {
"dev": "next dev",
@@ -1,31 +1,5 @@
# vite-import-llamaindex
## 0.0.15
### Patch Changes
- llamaindex@0.9.15
## 0.0.14
### Patch Changes
- Updated dependencies [9d951b2]
- llamaindex@0.9.14
## 0.0.13
### Patch Changes
- Updated dependencies [75d6e29]
- llamaindex@0.9.13
## 0.0.12
### Patch Changes
- llamaindex@0.9.12
## 0.0.11
### Patch Changes
@@ -1,7 +1,7 @@
{
"name": "vite-import-llamaindex",
"private": true,
"version": "0.0.15",
"version": "0.0.11",
"type": "module",
"scripts": {
"build": "vite build",
@@ -16,7 +16,7 @@
"@size-limit/preset-big-lib": "^11.1.6",
"size-limit": "^11.1.6",
"typescript": "^5.7.3",
"vite": "^5.4.16"
"vite": "^6.1.0"
},
"dependencies": {
"llamaindex": "workspace:*"
@@ -1,31 +1,5 @@
# @llamaindex/waku-query-engine-test
## 0.0.149
### Patch Changes
- llamaindex@0.9.15
## 0.0.148
### Patch Changes
- Updated dependencies [9d951b2]
- llamaindex@0.9.14
## 0.0.147
### Patch Changes
- Updated dependencies [75d6e29]
- llamaindex@0.9.13
## 0.0.146
### Patch Changes
- llamaindex@0.9.12
## 0.0.145
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/waku-query-engine-test",
"version": "0.0.149",
"version": "0.0.145",
"type": "module",
"private": true,
"scripts": {
-1
View File
@@ -42,7 +42,6 @@ export class OpenAI implements LLM {
contextWindow: 2048,
tokenizer: undefined,
isFunctionCallingModel: true,
structuredOutput: false,
};
}
-3
View File
@@ -50,9 +50,6 @@ export default tseslint.config(
"**/lib/*",
"**/deps/**",
"**/.next/**",
"**/.source/**", // Ignore .source directories
"!.git", // Don't ignore .git directory
"**/.*", // Ignore all dot files and directories
"**/node_modules/**",
"**/build/**",
"**/.docusaurus/**",
-1
View File
@@ -1 +0,0 @@
20
-173
View File
@@ -1,178 +1,5 @@
# examples
## 0.3.2
### Patch Changes
- 9c63f3f: Add support for openai responses api
- Updated dependencies [9c63f3f]
- Updated dependencies [c515a32]
- @llamaindex/openai@0.3.0
- @llamaindex/google@0.2.2
- @llamaindex/core@0.6.2
- @llamaindex/workflow@1.0.2
- llamaindex@0.9.15
- @llamaindex/clip@0.0.48
- @llamaindex/deepinfra@0.0.48
- @llamaindex/deepseek@0.0.8
- @llamaindex/fireworks@0.0.8
- @llamaindex/groq@0.0.63
- @llamaindex/huggingface@0.1.2
- @llamaindex/jinaai@0.0.8
- @llamaindex/perplexity@0.0.5
- @llamaindex/azure@0.1.11
- @llamaindex/elastic-search@0.1.2
- @llamaindex/milvus@0.1.11
- @llamaindex/qdrant@0.1.11
- @llamaindex/supabase@0.1.1
- @llamaindex/together@0.0.8
- @llamaindex/vllm@0.0.34
- @llamaindex/cloud@4.0.2
- @llamaindex/node-parser@2.0.2
- @llamaindex/anthropic@0.3.2
- @llamaindex/cohere@0.0.16
- @llamaindex/mistral@0.1.2
- @llamaindex/mixedbread@0.0.16
- @llamaindex/ollama@0.1.2
- @llamaindex/portkey-ai@0.0.44
- @llamaindex/replicate@0.0.44
- @llamaindex/astra@0.0.16
- @llamaindex/chroma@0.0.16
- @llamaindex/firestore@1.0.9
- @llamaindex/mongodb@0.0.16
- @llamaindex/pinecone@0.1.2
- @llamaindex/postgres@0.0.44
- @llamaindex/upstash@0.0.16
- @llamaindex/weaviate@0.0.16
- @llamaindex/vercel@0.1.2
- @llamaindex/voyage-ai@1.0.8
- @llamaindex/readers@3.0.2
- @llamaindex/tools@0.0.4
## 0.3.1
### Patch Changes
- 648cfb5: Add support for supabase vector store
Added doc for the supbase vector store
- Updated dependencies [648cfb5]
- Updated dependencies [1b6f368]
- Updated dependencies [eaf326e]
- Updated dependencies [9d951b2]
- @llamaindex/supabase@0.1.0
- @llamaindex/core@0.6.1
- llamaindex@0.9.14
- @llamaindex/tools@0.0.3
- @llamaindex/cloud@4.0.1
- @llamaindex/node-parser@2.0.1
- @llamaindex/anthropic@0.3.1
- @llamaindex/clip@0.0.47
- @llamaindex/cohere@0.0.15
- @llamaindex/deepinfra@0.0.47
- @llamaindex/google@0.2.1
- @llamaindex/huggingface@0.1.1
- @llamaindex/jinaai@0.0.7
- @llamaindex/mistral@0.1.1
- @llamaindex/mixedbread@0.0.15
- @llamaindex/ollama@0.1.1
- @llamaindex/openai@0.2.1
- @llamaindex/perplexity@0.0.4
- @llamaindex/portkey-ai@0.0.43
- @llamaindex/replicate@0.0.43
- @llamaindex/astra@0.0.15
- @llamaindex/azure@0.1.10
- @llamaindex/chroma@0.0.15
- @llamaindex/elastic-search@0.1.1
- @llamaindex/firestore@1.0.8
- @llamaindex/milvus@0.1.10
- @llamaindex/mongodb@0.0.15
- @llamaindex/pinecone@0.1.1
- @llamaindex/postgres@0.0.43
- @llamaindex/qdrant@0.1.10
- @llamaindex/upstash@0.0.15
- @llamaindex/weaviate@0.0.15
- @llamaindex/vercel@0.1.1
- @llamaindex/voyage-ai@1.0.7
- @llamaindex/readers@3.0.1
- @llamaindex/workflow@1.0.1
- @llamaindex/deepseek@0.0.7
- @llamaindex/fireworks@0.0.7
- @llamaindex/groq@0.0.62
- @llamaindex/together@0.0.7
- @llamaindex/vllm@0.0.33
## 0.3.0
### Minor Changes
- 91a18e7: Added support for structured output in the chat api of openai and ollama
Added structured output parameter in the provider
- d1c1f99: Added support for function calling in mistral provider
Update model list for mistral provider
Added example for the tool call in mistral
### Patch Changes
- 2509353: Added support for elastic search vector store
- Updated dependencies [21bebfc]
- Updated dependencies [77e24ce]
- Updated dependencies [93bc0ff]
- Updated dependencies [2509353]
- Updated dependencies [da06e45]
- Updated dependencies [2a0a899]
- Updated dependencies [050cd53]
- Updated dependencies [91a18e7]
- Updated dependencies [bf56fc0]
- Updated dependencies [f1db9b3]
- Updated dependencies [da8068e]
- Updated dependencies [c7ff323]
- Updated dependencies [f8a86e4]
- Updated dependencies [d1c1f99]
- Updated dependencies [5189b44]
- Updated dependencies [3fd4cc3]
- Updated dependencies [04f8c96]
- Updated dependencies [58a9446]
- @llamaindex/readers@3.0.0
- @llamaindex/core@0.6.0
- @llamaindex/tools@0.0.2
- @llamaindex/elastic-search@0.1.0
- @llamaindex/google@0.2.0
- @llamaindex/pinecone@0.1.0
- @llamaindex/huggingface@0.1.0
- @llamaindex/anthropic@0.3.0
- @llamaindex/mistral@0.1.0
- @llamaindex/ollama@0.1.0
- @llamaindex/openai@0.2.0
- @llamaindex/cloud@4.0.0
- @llamaindex/vercel@0.1.0
- @llamaindex/azure@0.1.9
- @llamaindex/workflow@1.0.0
- @llamaindex/mongodb@0.0.14
- llamaindex@0.9.12
- @llamaindex/node-parser@2.0.0
- @llamaindex/clip@0.0.46
- @llamaindex/cohere@0.0.14
- @llamaindex/deepinfra@0.0.46
- @llamaindex/jinaai@0.0.6
- @llamaindex/mixedbread@0.0.14
- @llamaindex/perplexity@0.0.3
- @llamaindex/portkey-ai@0.0.42
- @llamaindex/replicate@0.0.42
- @llamaindex/astra@0.0.14
- @llamaindex/chroma@0.0.14
- @llamaindex/firestore@1.0.7
- @llamaindex/milvus@0.1.9
- @llamaindex/postgres@0.0.42
- @llamaindex/qdrant@0.1.9
- @llamaindex/upstash@0.0.14
- @llamaindex/weaviate@0.0.14
- @llamaindex/voyage-ai@1.0.6
- @llamaindex/deepseek@0.0.6
- @llamaindex/fireworks@0.0.6
- @llamaindex/groq@0.0.61
- @llamaindex/together@0.0.6
- @llamaindex/vllm@0.0.32
## 0.2.10
### Patch Changes
+27 -23
View File
@@ -1,35 +1,39 @@
import { openai } from "@llamaindex/openai";
import { agent, tool } from "llamaindex";
import { OpenAI } from "@llamaindex/openai";
import { FunctionTool, agent } from "llamaindex";
import { z } from "zod";
const sumNumbers = tool({
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: z.object({
a: z.number().describe("The first number"),
b: z.number().describe("The second number"),
}),
execute: ({ a, b }: { a: number; b: number }) => `${a + b}`,
});
const sumNumbers = FunctionTool.from(
({ a, b }: { a: number; b: number }) => `${a + b}`,
{
name: "sumNumbers",
description: "Use this function to sum two numbers",
parameters: z.object({
a: z.number().describe("The first number"),
b: z.number().describe("The second number"),
}),
},
);
const divideNumbers = tool({
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: z.object({
a: z.number().describe("The dividend a to divide"),
b: z.number().describe("The divisor b to divide by"),
}),
execute: ({ a, b }: { a: number; b: number }) => `${a / b}`,
});
const divideNumbers = FunctionTool.from(
({ a, b }: { a: number; b: number }) => `${a / b}`,
{
name: "divideNumbers",
description: "Use this function to divide two numbers",
parameters: z.object({
a: z.number().describe("The dividend a to divide"),
b: z.number().describe("The divisor b to divide by"),
}),
},
);
async function main() {
const mathAgent = agent({
const workflow = agent({
tools: [sumNumbers, divideNumbers],
llm: openai({ model: "gpt-4o-mini" }),
llm: new OpenAI({ model: "gpt-4o-mini" }),
verbose: false,
});
const response = await mathAgent.run("How much is 5 + 5? then divide by 2");
const response = await workflow.run("How much is 5 + 5? then divide by 2");
console.log(response.data);
}
-51
View File
@@ -1,51 +0,0 @@
import {
AgentStream,
AgentToolCallResult,
Document,
VectorStoreIndex,
agent,
openai,
} from "llamaindex";
async function main() {
const index = await VectorStoreIndex.fromDocuments([
new Document({
text: "Cats have a specialized collarbone that allows them to always land on their feet when they fall.",
}),
new Document({
text: "Dogs have a sense of smell that is 10,000 to 100,000 times more acute than humans.",
}),
new Document({
text: "Cats are known for their agility and ability to jump high.",
}),
]);
const myAgent = agent({
llm: openai({ model: "gpt-4o" }),
tools: [
index.queryTool({
options: { similarityTopK: 2 },
includeSourceNodes: true,
}),
],
});
const context = myAgent.run("The fact about cats");
for await (const event of context) {
if (event instanceof AgentToolCallResult) {
console.log(
"Using these retrieved information to answer the question:\n",
event.data.toolOutput.result,
);
} else if (event instanceof AgentStream) {
for (const chunk of event.data.delta) {
process.stdout.write(chunk);
}
}
}
}
void main().then(() => {
console.log("Done");
});
+3 -2
View File
@@ -1,12 +1,13 @@
import { OpenAI } from "@llamaindex/openai";
import { wiki } from "@llamaindex/tools";
import { AgentStream, agent } from "llamaindex";
import { WikipediaTool } from "../wiki";
async function main() {
const llm = new OpenAI({ model: "gpt-4-turbo" });
const wikiTool = new WikipediaTool();
const workflow = agent({
tools: [wiki()],
tools: [wikiTool],
llm,
verbose: false,
});
+2 -2
View File
@@ -10,7 +10,7 @@ import {
import os from "os";
import { z } from "zod";
import { wiki } from "@llamaindex/tools";
import { WikipediaTool } from "../wiki";
const llm = openai({
model: "gpt-4o-mini",
});
@@ -46,7 +46,7 @@ async function main() {
description:
"Responsible for gathering relevant information from the internet",
systemPrompt: `You are a research agent. Your role is to gather information from the internet using the provided tools and then transfer this information to the report agent for content creation.`,
tools: [wiki()],
tools: [new WikipediaTool()],
canHandoffTo: [reportAgent],
llm,
});
+2 -2
View File
@@ -1,7 +1,7 @@
import { anthropic } from "@llamaindex/anthropic";
import { wiki } from "@llamaindex/tools";
import { agent, tool } from "llamaindex";
import { z } from "zod";
import { WikipediaTool } from "../wiki";
const workflow = agent({
tools: [
@@ -13,7 +13,7 @@ const workflow = agent({
}),
execute: ({ location }) => `The weather in ${location} is sunny`,
}),
wiki(),
new WikipediaTool(),
],
llm: anthropic({
apiKey: process.env.ANTHROPIC_API_KEY,
-25
View File
@@ -1,25 +0,0 @@
import { gemini, GEMINI_MODEL } from "@llamaindex/google";
(async () => {
if (!process.env.GOOGLE_API_KEY) {
throw new Error("Please set the GOOGLE_API_KEY environment variable.");
}
const llm = gemini({
model: GEMINI_MODEL.GEMINI_PRO_LATEST,
});
const stream = await llm.chat({
messages: [
{ content: "You want to talk in rhymes.", role: "system" },
{
content:
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
role: "user",
},
],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}
console.log("\n\ndone");
})();
+12 -39
View File
@@ -1,5 +1,4 @@
import { OpenAI } from "@llamaindex/openai";
import { z } from "zod";
// Example using OpenAI's chat API to extract JSON from a sales call transcript
// using json_mode see https://platform.openai.com/docs/guides/text-generation/json-mode for more details
@@ -7,47 +6,22 @@ import { z } from "zod";
const transcript =
"[Phone rings]\n\nJohn: Hello, this is John.\n\nSarah: Hi John, this is Sarah from XYZ Company. I'm calling to discuss our new product, the XYZ Widget, and see if it might be a good fit for your business.\n\nJohn: Hi Sarah, thanks for reaching out. I'm definitely interested in learning more about the XYZ Widget. Can you give me a quick overview of what it does?\n\nSarah: Of course! The XYZ Widget is a cutting-edge tool that helps businesses streamline their workflow and improve productivity. It's designed to automate repetitive tasks and provide real-time data analytics to help you make informed decisions.\n\nJohn: That sounds really interesting. I can see how that could benefit our team. Do you have any case studies or success stories from other companies who have used the XYZ Widget?\n\nSarah: Absolutely, we have several case studies that I can share with you. I'll send those over along with some additional information about the product. I'd also love to schedule a demo for you and your team to see the XYZ Widget in action.\n\nJohn: That would be great. I'll make sure to review the case studies and then we can set up a time for the demo. In the meantime, are there any specific action items or next steps we should take?\n\nSarah: Yes, I'll send over the information and then follow up with you to schedule the demo. In the meantime, feel free to reach out if you have any questions or need further information.\n\nJohn: Sounds good, I appreciate your help Sarah. I'm looking forward to learning more about the XYZ Widget and seeing how it can benefit our business.\n\nSarah: Thank you, John. I'll be in touch soon. Have a great day!\n\nJohn: You too, bye.";
const exampleSchema = z.object({
summary: z.string(),
products: z.array(z.string()),
rep_name: z.string(),
prospect_name: z.string(),
action_items: z.array(z.string()),
});
const example = {
summary:
"High-level summary of the call transcript. Should not exceed 3 sentences.",
products: ["product 1", "product 2"],
rep_name: "Name of the sales rep",
prospect_name: "Name of the prospect",
action_items: ["action item 1", "action item 2"],
};
async function main() {
const llm = new OpenAI({
model: "gpt-4o",
model: "gpt-4-1106-preview",
additionalChatOptions: { response_format: { type: "json_object" } },
});
//response format as zod schema
const example = {
summary:
"High-level summary of the call transcript. Should not exceed 3 sentences.",
products: ["product 1", "product 2"],
rep_name: "Name of the sales rep",
prospect_name: "Name of the prospect",
action_items: ["action item 1", "action item 2"],
};
const response = await llm.chat({
messages: [
{
role: "system",
content: `You are an expert assistant for summarizing and extracting insights from sales call transcripts.`,
},
{
role: "user",
content: `Here is the transcript: \n------\n${transcript}\n------`,
},
],
responseFormat: exampleSchema,
});
console.log(response.message.content);
//response format as json_object
const response2 = await llm.chat({
messages: [
{
role: "system",
@@ -60,10 +34,9 @@ async function main() {
content: `Here is the transcript: \n------\n${transcript}\n------`,
},
],
responseFormat: { type: "json_object" },
});
console.log(response2.message.content);
console.log(response.message.content);
}
main().catch(console.error);
-31
View File
@@ -1,31 +0,0 @@
import { mistral } from "@llamaindex/mistral";
import { wiki } from "@llamaindex/tools";
import { agent, tool } from "llamaindex";
import { z } from "zod";
const workflow = agent({
tools: [
tool({
name: "weather",
description: "Get the weather",
parameters: z.object({
location: z.string().describe("The location to get the weather for"),
}),
execute: ({ location }) => `The weather in ${location} is sunny`,
}),
wiki(),
],
llm: mistral({
apiKey: process.env.MISTRAL_API_KEY,
model: "mistral-small-latest",
}),
});
async function main() {
const result = await workflow.run(
"What is the weather in New York? What's the history of New York from Wikipedia in 3 sentences?",
);
console.log(result.data);
}
void main();
-30
View File
@@ -1,30 +0,0 @@
import { openaiResponses } from "@llamaindex/openai";
import { wiki } from "@llamaindex/tools";
import { agent, tool } from "llamaindex";
import { z } from "zod";
const workflow = agent({
tools: [
tool({
name: "weather",
description: "Get the weather",
parameters: z.object({
location: z.string().describe("The location to get the weather for"),
}),
execute: ({ location }) => `The weather in ${location} is sunny`,
}),
wiki(),
],
llm: openaiResponses({
model: "gpt-4o-mini",
}),
});
async function main() {
const result = await workflow.run(
"What is the weather in New York? What's the history of New York from Wikipedia in 3 sentences?",
);
console.log(result.data);
}
void main();
-33
View File
@@ -1,33 +0,0 @@
import { openaiResponses } from "@llamaindex/openai";
async function main() {
const llm = openaiResponses({
model: "gpt-4o",
maxOutputTokens: 1000,
apiKey: process.env.MY_OPENAI_API_KEY,
});
const response = await llm.chat({
messages: [
{
role: "user",
content: [
{
type: "text",
text: "What's in this image? Describe it in detail.",
},
{
type: "image_url",
image_url: {
url: "https://storage.googleapis.com/cloud-samples-data/vision/face/faces.jpeg",
},
},
],
},
],
});
console.log("Single Image Analysis:", response.message.content);
}
main().catch(console.error);
@@ -1,22 +0,0 @@
import { openaiResponses } from "@llamaindex/openai";
async function main() {
const llm = openaiResponses({
model: "gpt-4o-mini",
temperature: 0.1,
});
// Basic chat example
const response = await llm.chat({
messages: [
{
role: "user",
content: "What is the capital of France?",
},
],
});
console.log(response.message.content);
}
main().catch(console.error);
-26
View File
@@ -1,26 +0,0 @@
import { openaiResponses } from "@llamaindex/openai";
async function main() {
const llm = openaiResponses({
model: "gpt-4o-mini",
temperature: 0.1,
});
const stream = await llm.chat({
messages: [
{ content: "You want to talk in rhymes.", role: "system" },
{
content:
"How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
role: "user",
},
],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}
}
main().catch(console.error);
-37
View File
@@ -1,37 +0,0 @@
import { openaiResponses } from "@llamaindex/openai";
import { tool } from "llamaindex";
import { z } from "zod";
async function main() {
const weatherTool = tool({
name: "weather",
description: "Get the weather",
parameters: z.object({
location: z.string({
description: "The location to get the weather for",
}),
}),
execute: ({ location }) => {
return `The weather in ${location} is sunny`;
},
});
const llm = openaiResponses({
model: "gpt-4o-mini",
temperature: 0.1,
});
const response = await llm.chat({
messages: [
{
role: "user",
content: "What is the weather in New York?",
},
],
tools: [weatherTool],
});
console.log(response.message.options);
}
main().catch(console.error);
-23
View File
@@ -1,23 +0,0 @@
import { openaiResponses } from "@llamaindex/openai";
async function main() {
const llm = openaiResponses({
model: "gpt-4o",
temperature: 0.1,
builtInTools: [{ type: "web_search_preview" }],
});
// Streaming chat example
const response = await llm.chat({
messages: [
{
role: "user",
content: "What are the latest developments in AI?",
},
],
});
console.log(response.message.content);
}
main().catch(console.error);
+39 -42
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/examples",
"version": "0.3.2",
"version": "0.2.10",
"private": true,
"scripts": {
"lint": "eslint .",
@@ -11,47 +11,44 @@
"@azure/cosmos": "^4.1.1",
"@azure/identity": "^4.4.1",
"@azure/search-documents": "^12.1.0",
"@llamaindex/anthropic": "^0.3.2",
"@llamaindex/astra": "^0.0.16",
"@llamaindex/azure": "^0.1.11",
"@llamaindex/chroma": "^0.0.16",
"@llamaindex/clip": "^0.0.48",
"@llamaindex/cloud": "^4.0.2",
"@llamaindex/cohere": "^0.0.16",
"@llamaindex/core": "^0.6.2",
"@llamaindex/deepinfra": "^0.0.48",
"@llamaindex/anthropic": "^0.2.6",
"@llamaindex/astra": "^0.0.13",
"@llamaindex/azure": "^0.1.8",
"@llamaindex/chroma": "^0.0.13",
"@llamaindex/clip": "^0.0.45",
"@llamaindex/cloud": "^3.0.9",
"@llamaindex/cohere": "^0.0.13",
"@llamaindex/core": "^0.5.8",
"@llamaindex/deepinfra": "^0.0.45",
"@llamaindex/env": "^0.1.29",
"@llamaindex/firestore": "^1.0.9",
"@llamaindex/google": "^0.2.2",
"@llamaindex/groq": "^0.0.63",
"@llamaindex/huggingface": "^0.1.2",
"@llamaindex/milvus": "^0.1.11",
"@llamaindex/mistral": "^0.1.2",
"@llamaindex/mixedbread": "^0.0.16",
"@llamaindex/mongodb": "^0.0.16",
"@llamaindex/elastic-search": "^0.1.2",
"@llamaindex/node-parser": "^2.0.2",
"@llamaindex/ollama": "^0.1.2",
"@llamaindex/openai": "^0.3.0",
"@llamaindex/pinecone": "^0.1.2",
"@llamaindex/portkey-ai": "^0.0.44",
"@llamaindex/postgres": "^0.0.44",
"@llamaindex/qdrant": "^0.1.11",
"@llamaindex/readers": "^3.0.2",
"@llamaindex/replicate": "^0.0.44",
"@llamaindex/upstash": "^0.0.16",
"@llamaindex/vercel": "^0.1.2",
"@llamaindex/vllm": "^0.0.34",
"@llamaindex/voyage-ai": "^1.0.8",
"@llamaindex/weaviate": "^0.0.16",
"@llamaindex/workflow": "^1.0.2",
"@llamaindex/deepseek": "^0.0.8",
"@llamaindex/fireworks": "^0.0.8",
"@llamaindex/together": "^0.0.8",
"@llamaindex/jinaai": "^0.0.8",
"@llamaindex/perplexity": "^0.0.5",
"@llamaindex/supabase": "^0.1.1",
"@llamaindex/tools": "^0.0.4",
"@llamaindex/firestore": "^1.0.6",
"@llamaindex/google": "^0.1.2",
"@llamaindex/groq": "^0.0.60",
"@llamaindex/huggingface": "^0.0.45",
"@llamaindex/milvus": "^0.1.8",
"@llamaindex/mistral": "^0.0.14",
"@llamaindex/mixedbread": "^0.0.13",
"@llamaindex/mongodb": "^0.0.13",
"@llamaindex/node-parser": "^1.0.8",
"@llamaindex/ollama": "^0.0.48",
"@llamaindex/openai": "^0.1.61",
"@llamaindex/pinecone": "^0.0.13",
"@llamaindex/portkey-ai": "^0.0.41",
"@llamaindex/postgres": "^0.0.41",
"@llamaindex/qdrant": "^0.1.8",
"@llamaindex/readers": "^2.0.8",
"@llamaindex/replicate": "^0.0.41",
"@llamaindex/upstash": "^0.0.13",
"@llamaindex/vercel": "^0.0.19",
"@llamaindex/vllm": "^0.0.31",
"@llamaindex/voyage-ai": "^1.0.5",
"@llamaindex/weaviate": "^0.0.13",
"@llamaindex/workflow": "^0.0.16",
"@llamaindex/deepseek": "^0.0.5",
"@llamaindex/fireworks": "^0.0.5",
"@llamaindex/together": "^0.0.5",
"@llamaindex/jinaai": "^0.0.5",
"@llamaindex/perplexity": "^0.0.2",
"@notionhq/client": "^2.2.15",
"@pinecone-database/pinecone": "^4.0.0",
"@vercel/postgres": "^0.10.0",
@@ -60,7 +57,7 @@
"commander": "^12.1.0",
"dotenv": "^16.4.5",
"js-tiktoken": "^1.0.14",
"llamaindex": "^0.9.15",
"llamaindex": "^0.9.11",
"mongodb": "6.7.0",
"postgres": "^3.4.4",
"wikipedia": "^2.1.2",
@@ -1,73 +0,0 @@
import { ElasticSearchVectorStore } from "@llamaindex/elastic-search";
import {
gemini,
GEMINI_EMBEDDING_MODEL,
GEMINI_MODEL,
GeminiEmbedding,
} from "@llamaindex/google";
import {
Document,
Settings,
storageContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
async function main() {
Settings.embedModel = new GeminiEmbedding({
model: GEMINI_EMBEDDING_MODEL.TEXT_EMBEDDING_004,
});
Settings.llm = gemini({
model: GEMINI_MODEL.GEMINI_PRO_1_5_FLASH,
});
// Create sample documents
const documents = [
new Document({
text: "Elastic search is a powerful search engine",
metadata: {
source: "tech_docs",
author: "John Doe",
},
}),
new Document({
text: "Vector search enables semantic similarity search",
metadata: {
source: "research_paper",
author: "Jane Smith",
},
}),
new Document({
text: "Elasticsearch supports various distance metrics for vector search",
metadata: {
source: "tech_docs",
author: "Bob Wilson",
},
}),
];
// Initialize ElasticSearch Vector Store
const vectorStore = new ElasticSearchVectorStore({
indexName: "llamaindex-demo",
esCloudId: process.env.ES_CLOUD_ID,
esApiKey: process.env.ES_API_KEY,
});
// Create storage context with the vector store
const storageContext = await storageContextFromDefaults({
vectorStore,
});
// Create and store embeddings in ElasticSearch
const index = await VectorStoreIndex.fromDocuments(documents, {
storageContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
// Simple query
const response = await queryEngine.query({
query: "What is vector search?",
});
console.log("Basic Query Response:", response.toString());
}
main().catch(console.error);
@@ -1,8 +0,0 @@
{
"name": "elastic-search-vector-store",
"type": "module",
"private": true,
"scripts": {
"start": "npx tsx index.ts"
}
}
-75
View File
@@ -1,75 +0,0 @@
import {
gemini,
GEMINI_EMBEDDING_MODEL,
GEMINI_MODEL,
GeminiEmbedding,
} from "@llamaindex/google";
import { SupabaseVectorStore } from "@llamaindex/supabase";
import {
Document,
Settings,
storageContextFromDefaults,
VectorStoreIndex,
} from "llamaindex";
async function main() {
Settings.embedModel = new GeminiEmbedding({
model: GEMINI_EMBEDDING_MODEL.TEXT_EMBEDDING_004,
});
Settings.llm = gemini({
model: GEMINI_MODEL.GEMINI_PRO_1_5_FLASH,
});
// Create sample documents
const documents = [
new Document({
text: "Supbase is a powerful Database engine",
metadata: {
source: "tech_docs",
author: "John Doe",
},
}),
new Document({
text: "Vector search enables semantic similarity search",
metadata: {
source: "research_paper",
author: "Jane Smith",
},
}),
new Document({
text: "Supbase vector store supports various distance metrics for vector search",
metadata: {
source: "tech_docs",
author: "Bob Wilson",
},
}),
];
// Initialize ElasticSearch Vector Store
const vectorStore = new SupabaseVectorStore({
supabaseUrl: process.env.SUPABASE_URL,
supabaseKey: process.env.SUPABASE_KEY,
table: "document",
});
// await vectorStore.delete("fc079c38-2af4-4782-96e4-955c28608fcf");
// Create storage context with the vector store
const storageContext = await storageContextFromDefaults({
vectorStore,
});
// Create and store embeddings in ElasticSearch
const index = await VectorStoreIndex.fromDocuments(documents, {
storageContext,
});
// Query the index
const queryEngine = index.asQueryEngine();
// Simple query
const response = await queryEngine.query({
query: "What is vector search?",
});
console.log("Basic Query Response:", response.toString());
}
main().catch(console.error);
@@ -1,8 +0,0 @@
{
"name": "vector-store-supabase",
"type": "module",
"private": true,
"scripts": {
"start": "npx tsx index.ts"
}
}
+2 -2
View File
@@ -1,7 +1,7 @@
import { openai } from "@ai-sdk/openai";
import { wiki } from "@llamaindex/tools";
import { VercelLLM } from "@llamaindex/vercel";
import { LLMAgent } from "llamaindex";
import { WikipediaTool } from "../wiki";
async function main() {
// Create an instance of VercelLLM with the OpenAI model
@@ -33,7 +33,7 @@ async function main() {
console.log("\n=== Test 3: Using LLMAgent with WikipediaTool ===");
const agent = new LLMAgent({
llm: vercelLLM,
tools: [wiki()],
tools: [new WikipediaTool()],
});
const { message } = await agent.chat({
+62
View File
@@ -0,0 +1,62 @@
/** Example of a tool that uses Wikipedia */
import type { JSONSchemaType } from "ajv";
import type { BaseTool, ToolMetadata } from "llamaindex";
import { default as wiki } from "wikipedia";
type WikipediaParameter = {
query: string;
lang?: string;
};
type WikipediaToolParams = {
metadata?: ToolMetadata<JSONSchemaType<WikipediaParameter>>;
};
const DEFAULT_META_DATA: ToolMetadata<JSONSchemaType<WikipediaParameter>> = {
name: "wikipedia_search",
description: "A tool that uses a query engine to search Wikipedia.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "The query to search for",
},
lang: {
type: "string",
description: "The language to search in",
nullable: true,
},
},
required: ["query"],
},
};
export class WikipediaTool implements BaseTool<WikipediaParameter> {
private readonly DEFAULT_LANG = "en";
metadata: ToolMetadata<JSONSchemaType<WikipediaParameter>>;
constructor(params?: WikipediaToolParams) {
this.metadata = params?.metadata || DEFAULT_META_DATA;
}
async loadData(
page: string,
lang: string = this.DEFAULT_LANG,
): Promise<string> {
wiki.setLang(lang);
const pageResult = await wiki.page(page, { autoSuggest: false });
const content = await pageResult.content();
return content;
}
async call({
query,
lang = this.DEFAULT_LANG,
}: WikipediaParameter): Promise<string> {
const searchResult = await wiki.search(query);
if (searchResult.results.length === 0) return "No search results.";
return await this.loadData(searchResult.results[0].title, lang);
}
}
+1 -5
View File
@@ -35,8 +35,7 @@
"prettier-plugin-tailwindcss": "^0.6.11",
"turbo": "^2.4.4",
"typescript": "^5.7.3",
"typescript-eslint": "^8.18.0",
"vitest": "^3.1.1"
"typescript-eslint": "^8.18.0"
},
"packageManager": "pnpm@9.12.3",
"lint-staged": {
@@ -47,8 +46,5 @@
"*.{json,md,yml}": [
"prettier --write"
]
},
"dependencies": {
"p-retry": "^6.2.1"
}
}
-26
View File
@@ -1,31 +1,5 @@
# @llamaindex/autotool
## 6.0.15
### Patch Changes
- llamaindex@0.9.15
## 6.0.14
### Patch Changes
- Updated dependencies [9d951b2]
- llamaindex@0.9.14
## 6.0.13
### Patch Changes
- Updated dependencies [75d6e29]
- llamaindex@0.9.13
## 6.0.12
### Patch Changes
- llamaindex@0.9.12
## 6.0.11
### Patch Changes
@@ -1,35 +1,5 @@
# @llamaindex/autotool-01-node-example
## 0.0.96
### Patch Changes
- llamaindex@0.9.15
- @llamaindex/autotool@6.0.15
## 0.0.95
### Patch Changes
- Updated dependencies [9d951b2]
- llamaindex@0.9.14
- @llamaindex/autotool@6.0.14
## 0.0.94
### Patch Changes
- Updated dependencies [75d6e29]
- llamaindex@0.9.13
- @llamaindex/autotool@6.0.13
## 0.0.93
### Patch Changes
- llamaindex@0.9.12
- @llamaindex/autotool@6.0.12
## 0.0.92
### Patch Changes
@@ -13,5 +13,5 @@
"scripts": {
"start": "node --import tsx --import @llamaindex/autotool/node ./src/index.ts"
},
"version": "0.0.96"
"version": "0.0.92"
}
+1 -1
View File
@@ -6,7 +6,7 @@
"url": "git+https://github.com/run-llama/LlamaIndexTS.git",
"directory": "packages/autotool"
},
"version": "6.0.15",
"version": "6.0.11",
"description": "auto transpile your JS function to LLM Agent compatible",
"files": [
"dist",
-27
View File
@@ -1,32 +1,5 @@
# @llamaindex/cloud
## 4.0.2
### Patch Changes
- Updated dependencies [9c63f3f]
- @llamaindex/core@0.6.2
## 4.0.1
### Patch Changes
- Updated dependencies [1b6f368]
- Updated dependencies [eaf326e]
- @llamaindex/core@0.6.1
## 4.0.0
### Patch Changes
- bf56fc0: chore: bump sdk openapi.json
- 5189b44: fix: add retry handling logic to parser reader and fix lint issues
- Updated dependencies [21bebfc]
- Updated dependencies [93bc0ff]
- Updated dependencies [91a18e7]
- Updated dependencies [5189b44]
- @llamaindex/core@0.6.0
## 3.0.9
### Patch Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@llamaindex/cloud",
"version": "4.0.2",
"version": "3.0.9",
"type": "module",
"license": "MIT",
"scripts": {
+118 -203
View File
@@ -1,8 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { type Client, createClient, createConfig } from "@hey-api/client-fetch";
import { Document, FileReader } from "@llamaindex/core/schema";
import { fs, getEnv, path } from "@llamaindex/env";
import pRetry from "p-retry";
import {
type Body_upload_file_api_v1_parsing_upload_post,
type ParserLanguages,
@@ -17,18 +15,16 @@ import {
import { sleep } from "./utils";
export type Language = ParserLanguages;
export type ResultType = "text" | "markdown" | "json";
// Export the backoff pattern type.
export type BackoffPattern = "constant" | "linear" | "exponential";
// TODO: should move into @llamaindex/env
//todo: should move into @llamaindex/env
type WriteStream = {
write: (text: string) => void;
};
// Do not modify this variable or cause type errors
// eslint-disable-next-line no-var
// eslint-disable-next-line @typescript-eslint/no-explicit-any, no-var
var process: any;
/**
@@ -45,57 +41,48 @@ export class LlamaParseReader extends FileReader {
// The result type for the parser.
resultType: ResultType = "text";
// The interval in seconds to check if the parsing is done.
checkInterval: number = 1;
checkInterval = 1;
// The maximum timeout in seconds to wait for the parsing to finish.
maxTimeout = 2000;
// Whether to print the progress of the parsing.
verbose = true;
// The language to parse the file in.
// The language of the text to parse.
language: ParserLanguages[] = ["en"];
// New polling options:
// Controls the backoff mode: "constant", "linear", or "exponential".
backoffPattern: BackoffPattern = "linear";
// Maximum interval in seconds between polls.
maxCheckInterval: number = 5;
// Maximum number of retryable errors before giving up.
maxErrorCount: number = 4;
// The parsing instruction for the parser. Backend default is an empty string.
parsingInstruction?: string | undefined;
// Whether to ignore diagonal text (when the text rotation in degrees is not 0, 90, 180, or 270). Backend default is false.
// Wether to ignore diagonal text (when the text rotation in degrees is not 0, 90, 180 or 270, so not a horizontal or vertical text). Backend default is false.
skipDiagonalText?: boolean | undefined;
// Whether to ignore the cache and re-process the document. Documents are cached for 48 hours after job completion. Backend default is false.
// Wheter to ignore the cache and re-process the document. All documents are kept in cache for 48hours after the job was completed to avoid processing the same document twice. Backend default is false.
invalidateCache?: boolean | undefined;
// Whether the document should not be cached. Backend default is false.
// Wether the document should not be cached in the first place. Backend default is false.
doNotCache?: boolean | undefined;
// Whether to use a faster mode to extract text (skipping OCR and table/heading reconstruction). Not compatible with gpt4oMode. Backend default is false.
// Wether to use a faster mode to extract text from documents. This mode will skip OCR of images, and table/heading reconstruction. Note: Non-compatible with gpt4oMode. Backend default is false.
fastMode?: boolean | undefined;
// Whether to keep columns in the text according to document layout. May reduce reconstruction accuracy and LLM/embedings performance.
// Wether to keep column in the text according to document layout. Reduce reconstruction accuracy, and LLM's/embedings performances in most cases.
doNotUnrollColumns?: boolean | undefined;
// A templated page separator for splitting text. If not set, default is "\n---\n".
// A templated page separator to use to split the text. If the results contain `{page_number}` (e.g. JSON mode), it will be replaced by the next page number. If not set the default separator '\\n---\\n' will be used.
pageSeparator?: string | undefined;
// A templated prefix to add at the beginning of each page.
//A templated prefix to add to the beginning of each page. If the results contain `{page_number}`, it will be replaced by the page number.>
pagePrefix?: string | undefined;
// A templated suffix to add at the end of each page.
// A templated suffix to add to the end of each page. If the results contain `{page_number}`, it will be replaced by the page number.
pageSuffix?: string | undefined;
// Deprecated. Use vendorMultimodal params. Whether to use gpt-4o to extract text.
// Deprecated. Use vendorMultimodal params. Whether to use gpt-4o to extract text from documents.
gpt4oMode: boolean = false;
// Deprecated. Use vendorMultimodal params. The API key for GPT-4o. Can be set via LLAMA_CLOUD_GPT4O_API_KEY.
// Deprecated. Use vendorMultimodal params. The API key for the GPT-4o API. Optional, lowers the cost of parsing. Can be set as an env variable: LLAMA_CLOUD_GPT4O_API_KEY.
gpt4oApiKey?: string | undefined;
// The bounding box margins as a string.
// The bounding box to use to extract text from documents. Describe as a string containing the bounding box margins.
boundingBox?: string | undefined;
// The target pages (comma separated list, starting at 0).
// The target pages to extract text from documents. Describe as a comma separated list of page numbers. The first page of the document is page 0
targetPages?: string | undefined;
// Whether to ignore errors during parsing.
// Whether or not to ignore and skip errors raised during parsing.
ignoreErrors: boolean = true;
// Whether to split by page using the pageSeparator (or "\n---\n" as default).
// Whether to split by page using the pageSeparator or '\n---\n' as default.
splitByPage: boolean = true;
// Whether to use the vendor multimodal API.
useVendorMultimodalModel: boolean = false;
// The model name for the vendor multimodal API.
// The model name for the vendor multimodal API
vendorMultimodalModelName?: string | undefined;
// The API key for the multimodal API. Can be set via LLAMA_CLOUD_VENDOR_MULTIMODAL_API_KEY.
// The API key for the multimodal API. Can also be set as an env variable: LLAMA_CLOUD_VENDOR_MULTIMODAL_API_KEY
vendorMultimodalApiKey?: string | undefined;
webhookUrl?: string | undefined;
@@ -186,7 +173,7 @@ export class LlamaParseReader extends FileReader {
}
this.apiKey = apiKey;
if (this.baseUrl.endsWith("/")) {
this.baseUrl = this.baseUrl.slice(0, -1);
this.baseUrl = this.baseUrl.slice(0, -"/".length);
}
if (this.baseUrl.endsWith("/api/parsing")) {
this.baseUrl = this.baseUrl.slice(0, -"/api/parsing".length);
@@ -216,19 +203,13 @@ export class LlamaParseReader extends FileReader {
);
}
/**
* Creates a job for the LlamaParse API.
*
* @param data - The file data as a Uint8Array.
* @param filename - Optional filename for the file.
* @returns A Promise resolving to the job ID as a string.
*/
// Create a job for the LlamaParse API
async #createJob(data: Uint8Array, filename?: string): Promise<string> {
if (this.verbose) {
console.log("Started uploading the file");
}
// TODO: remove Blob usage when we drop Node.js 18 support
// todo: remove Blob usage when we drop Node.js 18 support
const file: File | Blob =
globalThis.File && filename
? new File([data], filename)
@@ -339,124 +320,87 @@ export class LlamaParseReader extends FileReader {
return response.data.id;
}
/**
* Retrieves the result of a parsing job.
*
* Uses a polling loop with retry logic. Each API call is retried
* up to maxErrorCount times if it fails with a 5XX or socket error.
* The delay between polls increases according to the specified backoffPattern ("constant", "linear", or "exponential"),
* capped by maxCheckInterval.
*
* @param jobId - The job ID.
* @param resultType - The type of result to fetch ("text", "json", or "markdown").
* @returns A Promise resolving to the job result.
*/
// Get the result of the job
private async getJobResult(
jobId: string,
resultType: "text" | "json" | "markdown",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> {
const signal = AbortSignal.timeout(this.maxTimeout * 1000);
let tries = 0;
let currentInterval = this.checkInterval;
while (true) {
await sleep(currentInterval * 1000);
await sleep(this.checkInterval * 1000);
// Wraps the API call in a retry
let result;
try {
result = await pRetry(
() =>
getJobApiV1ParsingJobJobIdGet({
// Check the job status. If unsuccessful response, checks if maximum timeout has been reached. If reached, throws an error
const result = await getJobApiV1ParsingJobJobIdGet({
client: this.#client,
throwOnError: true,
path: {
job_id: jobId,
},
query: {
project_id: this.project_id ?? null,
organization_id: this.organization_id ?? null,
},
signal,
});
const { data } = result;
const status = (data as Record<string, unknown>)["status"];
// If job has completed, return the result
if (status === "SUCCESS") {
let result;
switch (resultType) {
case "json": {
result = await getJobJsonResultApiV1ParsingJobJobIdResultJsonGet({
client: this.#client,
throwOnError: true,
path: { job_id: jobId },
path: {
job_id: jobId,
},
query: {
project_id: this.project_id ?? null,
organization_id: this.organization_id ?? null,
},
signal: AbortSignal.timeout(this.maxTimeout * 1000),
}),
{
retries: this.maxErrorCount,
onFailedAttempt: (error) => {
// Retry only on 5XX or socket errors.
const status = (error.cause as any)?.response?.status;
if (
!(
(status && status >= 500 && status < 600) ||
((error.cause as any)?.code &&
((error.cause as any).code === "ECONNRESET" ||
(error.cause as any).code === "ETIMEDOUT" ||
(error.cause as any).code === "ECONNREFUSED"))
)
) {
throw error;
}
if (this.verbose) {
console.warn(
`Attempting to get job ${jobId} result (attempt ${error.attemptNumber}) failed. Retrying...`,
);
}
},
},
);
} catch (e: any) {
throw new Error(
`Max error count reached for job ${jobId}: ${e.message}`,
);
}
const { data } = result;
const status = (data as Record<string, unknown>)["status"];
if (status === "SUCCESS") {
let resultData;
switch (resultType) {
case "json": {
resultData =
await getJobJsonResultApiV1ParsingJobJobIdResultJsonGet({
client: this.#client,
throwOnError: true,
path: { job_id: jobId },
query: {
project_id: this.project_id ?? null,
organization_id: this.organization_id ?? null,
},
signal: AbortSignal.timeout(this.maxTimeout * 1000),
});
signal,
});
break;
}
case "markdown": {
resultData =
await getJobResultApiV1ParsingJobJobIdResultMarkdownGet({
client: this.#client,
throwOnError: true,
path: { job_id: jobId },
query: {
project_id: this.project_id ?? null,
organization_id: this.organization_id ?? null,
},
signal: AbortSignal.timeout(this.maxTimeout * 1000),
});
result = await getJobResultApiV1ParsingJobJobIdResultMarkdownGet({
client: this.#client,
throwOnError: true,
path: {
job_id: jobId,
},
query: {
project_id: this.project_id ?? null,
organization_id: this.organization_id ?? null,
},
signal,
});
break;
}
case "text": {
resultData =
await getJobTextResultApiV1ParsingJobJobIdResultTextGet({
client: this.#client,
throwOnError: true,
path: { job_id: jobId },
query: {
project_id: this.project_id ?? null,
organization_id: this.organization_id ?? null,
},
signal: AbortSignal.timeout(this.maxTimeout * 1000),
});
result = await getJobTextResultApiV1ParsingJobJobIdResultTextGet({
client: this.#client,
throwOnError: true,
path: {
job_id: jobId,
},
query: {
project_id: this.project_id ?? null,
organization_id: this.organization_id ?? null,
},
signal,
});
break;
}
}
return resultData.data;
return result.data;
// If job is still pending, check if maximum timeout has been reached. If reached, throws an error
} else if (status === "PENDING") {
signal.throwIfAborted();
if (this.verbose && tries % 10 === 0) {
this.stdout?.write(".");
}
@@ -464,35 +408,23 @@ export class LlamaParseReader extends FileReader {
} else {
if (this.verbose) {
console.error(
`Received error response ${status} for job ${jobId}. Got Error Code: ${data.error_code} and Error Message: ${data.error_message}`,
`Recieved Error response ${status} for job ${jobId}. Got Error Code: ${data.error_code} and Error Message: ${data.error_message}`,
);
}
throw new Error(
`Failed to parse the file: ${jobId}, status: ${status}`,
);
}
// Adjust the polling interval based on the backoff pattern.
if (this.backoffPattern === "exponential") {
currentInterval = Math.min(currentInterval * 2, this.maxCheckInterval);
} else if (this.backoffPattern === "linear") {
currentInterval = Math.min(
currentInterval + this.checkInterval,
this.maxCheckInterval,
);
} else if (this.backoffPattern === "constant") {
currentInterval = this.checkInterval;
}
}
}
/**
* Loads data from a file and returns an array of Document objects.
* To be used with resultType "text" or "markdown".
* To be used with resultType = "text" and "markdown"
*
* @param fileContent - The content of the file as a Uint8Array.
* @param filename - Optional filename for the file.
* @returns A Promise that resolves to an array of Document objects.
* @param {Uint8Array} fileContent - The content of the file to be loaded.
* @param {string} filename - The name of the file to be loaded.
* @return {Promise<Document[]>} A Promise object that resolves to an array of Document objects.
*/
async loadDataAsContent(
fileContent: Uint8Array,
@@ -504,38 +436,42 @@ export class LlamaParseReader extends FileReader {
console.log(`Started parsing the file under job id ${jobId}`);
}
// Return results as Document objects.
// Return results as Document objects
const jobResults = await this.getJobResult(jobId, this.resultType);
const resultText = jobResults[this.resultType];
// Split the text by separator if splitByPage is true.
// Split the text by separator if splitByPage is true
if (this.splitByPage) {
return this.splitTextBySeparator(resultText);
}
return [new Document({ text: resultText })];
return [
new Document({
text: resultText,
}),
];
})
.catch((error) => {
console.warn(
`Error while parsing the file with: ${error.message ?? error.detail}`,
);
if (this.ignoreErrors) {
console.warn(
`Error while parsing the file: ${error.message ?? error.detail}`,
);
return [];
} else {
throw error;
}
});
}
/**
* Loads data from a file and returns an array of JSON objects.
* To be used with resultType "json".
* To be used with resultType = "json"
*
* @param filePathOrContent - The file path or the file content as a Uint8Array.
* @returns A Promise that resolves to an array of JSON objects.
* @param {string} filePathOrContent - The file path to the file or the content of the file as a Buffer
* @return {Promise<Record<string, any>[]>} A Promise that resolves to an array of JSON objects.
*/
async loadJson(
filePathOrContent: string | Uint8Array,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<Record<string, any>[]> {
let jobId;
const isFilePath = typeof filePathOrContent === "string";
@@ -543,7 +479,7 @@ export class LlamaParseReader extends FileReader {
const data = isFilePath
? await fs.readFile(filePathOrContent)
: filePathOrContent;
// Create a job for the file.
// Creates a job for the file
jobId = await this.#createJob(
data,
isFilePath ? path.basename(filePathOrContent) : undefined,
@@ -552,14 +488,14 @@ export class LlamaParseReader extends FileReader {
console.log(`Started parsing the file under job id ${jobId}`);
}
// Return results as an array of JSON objects.
// Return results as an array of JSON objects (same format as Python version of the reader)
const resultJson = await this.getJobResult(jobId, "json");
resultJson.job_id = jobId;
resultJson.file_path = isFilePath ? filePathOrContent : undefined;
return [resultJson];
} catch (e) {
console.error(`Error while parsing the file under job id ${jobId}`, e);
if (this.ignoreErrors) {
console.error(`Error while parsing the file under job id ${jobId}`, e);
return [];
} else {
throw e;
@@ -569,24 +505,27 @@ export class LlamaParseReader extends FileReader {
/**
* Downloads and saves images from a given JSON result to a specified download path.
* Currently only supports resultType "json".
* Currently only supports resultType = "json"
*
* @param jsonResult - The JSON result containing image information.
* @param downloadPath - The path where the downloaded images will be saved.
* @returns A Promise that resolves to an array of image objects.
* @param {Record<string, any>[]} jsonResult - The JSON result containing image information.
* @param {string} downloadPath - The path to save the downloaded images.
* @return {Promise<Record<string, any>[]>} A Promise that resolves to an array of image objects.
*/
async getImages(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
jsonResult: Record<string, any>[],
downloadPath: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<Record<string, any>[]> {
try {
// Create download directory if it doesn't exist (checks for write access).
// Create download directory if it doesn't exist (Actually check for write access, not existence, since fsPromises does not have a `existsSync` method)
try {
await fs.access(downloadPath);
} catch {
await fs.mkdir(downloadPath, { recursive: true });
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const images: Record<string, any>[] = [];
for (const result of jsonResult) {
const jobId = result.job_id;
@@ -602,7 +541,7 @@ export class LlamaParseReader extends FileReader {
imageName,
);
await this.fetchAndSaveImage(imageName, imagePath, jobId);
// Assign metadata to the image.
// Assign metadata to the image
image.path = imagePath;
image.job_id = jobId;
image.original_pdf_path = result.file_path;
@@ -622,14 +561,6 @@ export class LlamaParseReader extends FileReader {
}
}
/**
* Constructs the file path for an image.
*
* @param downloadPath - The base download directory.
* @param jobId - The job ID.
* @param imageName - The image name.
* @returns A Promise that resolves to the full image path.
*/
private async getImagePath(
downloadPath: string,
jobId: string,
@@ -638,13 +569,6 @@ export class LlamaParseReader extends FileReader {
return path.join(downloadPath, `${jobId}-${imageName}`);
}
/**
* Fetches an image from the API and saves it to the specified path.
*
* @param imageName - The name of the image.
* @param imagePath - The local path to save the image.
* @param jobId - The associated job ID.
*/
private async fetchAndSaveImage(
imageName: string,
imagePath: string,
@@ -666,21 +590,18 @@ export class LlamaParseReader extends FileReader {
throw new Error(`Failed to download image: ${response.error.detail}`);
}
const blob = (await response.data) as Blob;
// Write the image buffer to the specified imagePath.
// Write the image buffer to the specified imagePath
await fs.writeFile(imagePath, new Uint8Array(await blob.arrayBuffer()));
}
/**
* Filters out invalid values (null, undefined, empty string) for specific parameters.
*
* @param params - The parameters object.
* @param keysToCheck - The keys to check for valid values.
* @returns A new object with filtered parameters.
*/
// Filters out invalid values (null, undefined, empty string) of specific params.
private filterSpecificParams(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
params: Record<string, any>,
keysToCheck: string[],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Record<string, any> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const filteredParams: Record<string, any> = {};
for (const [key, value] of Object.entries(params)) {
if (keysToCheck.includes(key)) {
@@ -694,12 +615,6 @@ export class LlamaParseReader extends FileReader {
return filteredParams;
}
/**
* Splits text into Document objects using the page separator.
*
* @param text - The text to be split.
* @returns An array of Document objects.
*/
private splitTextBySeparator(text: string): Document[] {
const separator = this.pageSeparator ?? "\n---\n";
const textChunks = text.split(separator);
-33
View File
@@ -1,38 +1,5 @@
# @llamaindex/community
## 0.0.94
### Patch Changes
- Updated dependencies [9c63f3f]
- @llamaindex/core@0.6.2
## 0.0.93
### Patch Changes
- Updated dependencies [1b6f368]
- Updated dependencies [eaf326e]
- @llamaindex/core@0.6.1
## 0.0.92
### Patch Changes
- 1325178: fix: stringify all tool results for anthropic on bedrock
## 0.0.91
### Patch Changes
- 5189b44: fix: add retry handling logic to parser reader and fix lint issues
- 3fd4cc3: feat: use google's new gen ai library to support multimodal output
- Updated dependencies [21bebfc]
- Updated dependencies [93bc0ff]
- Updated dependencies [91a18e7]
- Updated dependencies [5189b44]
- @llamaindex/core@0.6.0
## 0.0.90
### Patch Changes
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/community",
"description": "Community package for LlamaIndexTS",
"version": "0.0.94",
"version": "0.0.90",
"type": "module",
"types": "dist/type/index.d.ts",
"main": "dist/cjs/index.js",
@@ -24,7 +24,6 @@ import {
} from "./utils";
export class AmazonProvider extends Provider<ConverseStreamOutput> {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getResultFromResponse(response: Record<string, any>): ConverseResponse {
return JSON.parse(toUtf8(response.body));
}
@@ -53,7 +52,7 @@ export class AmazonProvider extends Provider<ConverseStreamOutput> {
}
getTextFromStreamResponse(response: ResponseStream): string {
const event: ConverseStreamOutput | undefined =
let event: ConverseStreamOutput | undefined =
this.getStreamingEventResponse(response);
if (!event || !event.contentBlockDelta) return "";
const delta: ContentBlockDelta | undefined = event.contentBlockDelta.delta;
@@ -10,10 +10,12 @@ import type {
MessageContentDetail,
ToolCallLLMMessageOptions,
} from "@llamaindex/core/llms";
import { extractDataUrlComponents } from "../utils";
import {
extractDataUrlComponents,
mapMessageContentToMessageContentDetails,
} from "../utils";
import type { JSONObject } from "@llamaindex/core/global";
import { mapMessageContentToMessageContentDetails } from "../../utils";
import type { AmazonMessage, AmazonMessages } from "./types";
const ACCEPTED_IMAGE_MIME_TYPES = [
@@ -54,7 +56,7 @@ export const mapImageContent = (imageUrl: string): ImageBlock => {
mimeType as keyof typeof ACCEPTED_IMAGE_MIME_TYPE_FORMAT_MAP
],
// @ts-expect-error: there's a mistake in the "@aws-sdk/client-bedrock-runtime" compared to the actual api
// @ts-ignore: there's a mistake in the "@aws-sdk/client-bedrock-runtime" compared to the actual api
source: { bytes: data },
};
};
@@ -6,8 +6,10 @@ import type {
MessageContentDetail,
ToolCallLLMMessageOptions,
} from "@llamaindex/core/llms";
import { mapMessageContentToMessageContentDetails } from "../../utils";
import { extractDataUrlComponents } from "../utils";
import {
extractDataUrlComponents,
mapMessageContentToMessageContentDetails,
} from "../utils";
import type {
AnthropicContent,
AnthropicImageContent,
@@ -111,7 +113,7 @@ export const mapChatMessagesToAnthropicMessages = <
{
type: "tool_result",
tool_use_id: msg.options.toolResult.id,
content: JSON.stringify(msg.options.toolResult.result),
content: msg.options.toolResult.result,
},
],
},
+1 -2
View File
@@ -22,9 +22,9 @@ import {
type BedrockChatStreamResponse,
Provider,
} from "./provider";
import { mapMessageContentToMessageContentDetails } from "./utils";
import { wrapLLMEvent } from "@llamaindex/core/decorator";
import { mapMessageContentToMessageContentDetails } from "../utils";
import { AmazonProvider } from "./amazon/provider";
import { AnthropicProvider } from "./anthropic/provider";
import { MetaProvider } from "./meta/provider";
@@ -381,7 +381,6 @@ export class Bedrock extends ToolCallLLM<BedrockAdditionalChatOptions> {
maxTokens: this.maxTokens,
contextWindow: BEDROCK_FOUNDATION_LLMS[this.model] ?? 128000,
tokenizer: undefined,
structuredOutput: false,
};
}
@@ -1,3 +1,14 @@
import type {
MessageContent,
MessageContentDetail,
} from "@llamaindex/core/llms";
export const mapMessageContentToMessageContentDetails = (
content: MessageContent,
): MessageContentDetail[] => {
return Array.isArray(content) ? content : [{ type: "text", text: content }];
};
export const toUtf8 = (input: Uint8Array): string =>
new TextDecoder("utf-8").decode(input);
-10
View File
@@ -1,10 +0,0 @@
import type {
MessageContent,
MessageContentDetail,
} from "@llamaindex/core/llms";
export const mapMessageContentToMessageContentDetails = (
content: MessageContent,
): MessageContentDetail[] => {
return Array.isArray(content) ? content : [{ type: "text", text: content }];
};
-26
View File
@@ -1,31 +1,5 @@
# @llamaindex/core
## 0.6.2
### Patch Changes
- 9c63f3f: Add support for openai responses api
## 0.6.1
### Patch Changes
- 1b6f368: Support loading from URLs for all readers extending FileReader
- eaf326e: Fix passing right llm setting from SimpleChatEngine to ChatMemoryBuffer
## 0.6.0
### Minor Changes
- 91a18e7: Added support for structured output in the chat api of openai and ollama
Added structured output parameter in the provider
### Patch Changes
- 21bebfc: Expose more content to fix the issue with unavailable documentation links, and adjust the documentation based on the latest code.
- 93bc0ff: fix: include additional options for context chat engine
- 5189b44: fix: add retry handling logic to parser reader and fix lint issues
## 0.5.8
### Patch Changes

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