mirror of
https://github.com/run-llama/LlamaIndexTS.git
synced 2026-07-05 12:05:56 -04:00
Compare commits
56 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 65d834615d | |||
| b8be4c09e2 | |||
| e5fb332538 | |||
| 491033d534 | |||
| 885fa316a5 | |||
| b6ed679771 | |||
| 68fc6e8b50 | |||
| ea0331ef5a | |||
| 6827e245b8 | |||
| ef25d6960c | |||
| f740f44cf2 | |||
| a5e4e6d857 | |||
| cfdd6db530 | |||
| d4eda9f396 | |||
| a433b107e0 | |||
| 59f9fb6c3f | |||
| 09d532ebcc | |||
| cfd6f3ca8c | |||
| 95add73c38 | |||
| 9ee036b160 | |||
| c2b521199c | |||
| ee9f3f373a | |||
| f205358587 | |||
| 255ae7dced | |||
| b4c6d509a0 | |||
| 34cd57b639 | |||
| 50dfd7bf60 | |||
| 0b57187909 | |||
| e78e9f4832 | |||
| 383933adb5 | |||
| dd054137bf | |||
| cf3b7571eb | |||
| ae7a2c202a | |||
| 9b00d578bc | |||
| b8173e4c4e | |||
| 67b5445fb9 | |||
| 87419ef5d1 | |||
| ad218160d8 | |||
| eeb90d7991 | |||
| 7b7329bd18 | |||
| b3acbb06f4 | |||
| 7db7562841 | |||
| 0e75b124c3 | |||
| d79a0b76f3 | |||
| c3eb4933fb | |||
| e3a956aedd | |||
| e562e479dc | |||
| 1900e019e3 | |||
| 317f140822 | |||
| cd829474d6 | |||
| b6c1500570 | |||
| d06a85bd34 | |||
| 6b9a2feac5 | |||
| bd08004afe | |||
| 36f2903eb3 | |||
| 09464e6da7 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
build: use ESM as default
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
fix: update `VectorIndexRetriever` constructor parameters' type.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"llamaindex": patch
|
||||
---
|
||||
|
||||
feat: abstract `@llamaindex/env` package
|
||||
@@ -4,6 +4,6 @@
|
||||
"ghcr.io/devcontainers/features/node:1": {},
|
||||
"ghcr.io/devcontainers-contrib/features/turborepo-npm:1": {},
|
||||
"ghcr.io/devcontainers-contrib/features/typescript:2": {},
|
||||
"ghcr.io/devcontainers-contrib/features/pnpm:2": {},
|
||||
},
|
||||
"ghcr.io/devcontainers-contrib/features/pnpm:2": {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ module.exports = {
|
||||
},
|
||||
rules: {
|
||||
"max-params": ["error", 4],
|
||||
"prefer-const": "error",
|
||||
},
|
||||
ignorePatterns: ["dist/"],
|
||||
};
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
examples/readers/data/** binary
|
||||
examples/data/** binary
|
||||
@@ -38,6 +38,12 @@ jobs:
|
||||
- name: Run Circular Dependency Check
|
||||
run: pnpm run circular-check
|
||||
working-directory: ./packages/core
|
||||
- uses: actions/upload-artifact@v3
|
||||
if: failure()
|
||||
with:
|
||||
name: typecheck-build-dist
|
||||
path: ./packages/core/dist
|
||||
if-no-files-found: error
|
||||
typecheck-examples:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -55,10 +61,13 @@ jobs:
|
||||
run: pnpm run build --filter llamaindex
|
||||
- name: Copy examples
|
||||
run: rsync -rv --exclude=node_modules ./examples ${{ runner.temp }}
|
||||
- name: Pack
|
||||
- name: Pack @llamaindex/env
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/env
|
||||
- name: Pack llamaindex
|
||||
run: pnpm pack --pack-destination ${{ runner.temp }}
|
||||
working-directory: packages/core
|
||||
- name: Install llamaindex
|
||||
- name: Install
|
||||
run: npm add ${{ runner.temp }}/*.tgz
|
||||
working-directory: ${{ runner.temp }}/examples
|
||||
- name: Run Type Check
|
||||
|
||||
Vendored
-1
@@ -5,7 +5,6 @@
|
||||
"[xml]": {
|
||||
"editor.defaultFormatter": "redhat.vscode-xml"
|
||||
},
|
||||
"jest.rootPath": "./packages/core",
|
||||
"[python]": {
|
||||
"editor.defaultFormatter": "ms-python.black-formatter"
|
||||
},
|
||||
|
||||
@@ -78,3 +78,15 @@ pnpm start
|
||||
That should start a webserver which will serve the docs on https://localhost:3000
|
||||
|
||||
Any changes you make should be reflected in the browser. If you need to regenerate the API docs and find that your TSDoc isn't getting the updates, feel free to remove apps/docs/api. It will automatically regenerate itself when you run pnpm start again.
|
||||
|
||||
## Publishing
|
||||
|
||||
To publish a new version of the library, run
|
||||
|
||||
```shell
|
||||
pnpm new-llamaindex
|
||||
pnpm new-create-llama
|
||||
pnpm release
|
||||
git push # push to the main branch
|
||||
git push --tags
|
||||
```
|
||||
|
||||
@@ -127,6 +127,7 @@ module.exports = nextConfig;
|
||||
- Anthropic Claude Instant and Claude 2
|
||||
- Llama2 Chat LLMs (70B, 13B, and 7B parameters)
|
||||
- MistralAI Chat LLMs
|
||||
- Fireworks Chat LLMs
|
||||
|
||||
## Contributing:
|
||||
|
||||
|
||||
@@ -1 +1,2 @@
|
||||
label: "Agents"
|
||||
position: 3
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
# Multi-Document Agent
|
||||
|
||||
In this guide, you learn towards setting up an agent that can effectively answer different types of questions over a larger set of documents.
|
||||
|
||||
These questions include the following
|
||||
|
||||
- QA over a specific doc
|
||||
- QA comparing different docs
|
||||
- Summaries over a specific doc
|
||||
- Comparing summaries between different docs
|
||||
|
||||
We do this with the following architecture:
|
||||
|
||||
- setup a “document agent” over each Document: each doc agent can do QA/summarization within its doc
|
||||
- setup a top-level agent over this set of document agents. Do tool retrieval and then do CoT over the set of tools to answer a question.
|
||||
|
||||
## Setup and Download Data
|
||||
|
||||
We first start by installing the necessary libraries and downloading the data.
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
```ts
|
||||
import {
|
||||
Document,
|
||||
ObjectIndex,
|
||||
OpenAI,
|
||||
OpenAIAgent,
|
||||
QueryEngineTool,
|
||||
SimpleNodeParser,
|
||||
SimpleToolNodeMapping,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
And then for the data we will run through a list of countries and download the wikipedia page for each country.
|
||||
|
||||
```ts
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const dataPath = path.join(__dirname, "tmp_data");
|
||||
|
||||
const extractWikipediaTitle = async (title: string) => {
|
||||
const fileExists = fs.existsSync(path.join(dataPath, `${title}.txt`));
|
||||
|
||||
if (fileExists) {
|
||||
console.log(`File already exists for the title: ${title}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const queryParams = new URLSearchParams({
|
||||
action: "query",
|
||||
format: "json",
|
||||
titles: title,
|
||||
prop: "extracts",
|
||||
explaintext: "true",
|
||||
});
|
||||
|
||||
const url = `https://en.wikipedia.org/w/api.php?${queryParams}`;
|
||||
|
||||
const response = await fetch(url);
|
||||
const data: any = await response.json();
|
||||
|
||||
const pages = data.query.pages;
|
||||
const page = pages[Object.keys(pages)[0]];
|
||||
const wikiText = page.extract;
|
||||
|
||||
await new Promise((resolve) => {
|
||||
fs.writeFile(path.join(dataPath, `${title}.txt`), wikiText, (err: any) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
resolve(title);
|
||||
return;
|
||||
}
|
||||
console.log(`${title} stored in file!`);
|
||||
|
||||
resolve(title);
|
||||
});
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
```ts
|
||||
export const extractWikipedia = async (titles: string[]) => {
|
||||
if (!fs.existsSync(dataPath)) {
|
||||
fs.mkdirSync(dataPath);
|
||||
}
|
||||
|
||||
for await (const title of titles) {
|
||||
await extractWikipediaTitle(title);
|
||||
}
|
||||
|
||||
console.log("Extration finished!");
|
||||
```
|
||||
|
||||
These files will be saved in the `tmp_data` folder.
|
||||
|
||||
Now we can call the function to download the data for each country.
|
||||
|
||||
```ts
|
||||
await extractWikipedia([
|
||||
"Brazil",
|
||||
"United States",
|
||||
"Canada",
|
||||
"Mexico",
|
||||
"Argentina",
|
||||
"Chile",
|
||||
"Colombia",
|
||||
"Peru",
|
||||
"Venezuela",
|
||||
"Ecuador",
|
||||
"Bolivia",
|
||||
"Paraguay",
|
||||
"Uruguay",
|
||||
"Guyana",
|
||||
"Suriname",
|
||||
"French Guiana",
|
||||
"Falkland Islands",
|
||||
]);
|
||||
```
|
||||
|
||||
## Load the data
|
||||
|
||||
Now that we have the data, we can load it into the LlamaIndex and store as a document.
|
||||
|
||||
```ts
|
||||
import { Document } from "llamaindex";
|
||||
|
||||
const countryDocs: Record<string, Document> = {};
|
||||
|
||||
for (const title of wikiTitles) {
|
||||
const path = `./agent/helpers/tmp_data/${title}.txt`;
|
||||
const text = await fs.readFile(path, "utf-8");
|
||||
const document = new Document({ text: text, id_: path });
|
||||
countryDocs[title] = document;
|
||||
}
|
||||
```
|
||||
|
||||
## Setup LLM and StorageContext
|
||||
|
||||
We will be using gpt-4 for this example and we will use the `StorageContext` to store the documents in-memory.
|
||||
|
||||
```ts
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const ctx = serviceContextFromDefaults({ llm });
|
||||
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
```
|
||||
|
||||
## Building Multi-Document Agents
|
||||
|
||||
In this section we show you how to construct the multi-document agent. We first build a document agent for each document, and then define the top-level parent agent with an object index.
|
||||
|
||||
```ts
|
||||
const documentAgents: Record<string, any> = {};
|
||||
const queryEngines: Record<string, any> = {};
|
||||
```
|
||||
|
||||
Now we iterate over each country and create a document agent for each one.
|
||||
|
||||
### Build Agent for each Document
|
||||
|
||||
In this section we define “document agents” for each document.
|
||||
|
||||
We define both a vector index (for semantic search) and summary index (for summarization) for each document. The two query engines are then converted into tools that are passed to an OpenAI function calling agent.
|
||||
|
||||
This document agent can dynamically choose to perform semantic search or summarization within a given document.
|
||||
|
||||
We create a separate document agent for each coutnry.
|
||||
|
||||
```ts
|
||||
for (const title of wikiTitles) {
|
||||
// parse the document into nodes
|
||||
const nodes = new SimpleNodeParser({
|
||||
chunkSize: 200,
|
||||
chunkOverlap: 20,
|
||||
}).getNodesFromDocuments([countryDocs[title]]);
|
||||
|
||||
// create the vector index for specific search
|
||||
const vectorIndex = await VectorStoreIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
storageContext: storageContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
// create the summary index for broader search
|
||||
const summaryIndex = await SummaryIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
const vectorQueryEngine = summaryIndex.asQueryEngine();
|
||||
const summaryQueryEngine = summaryIndex.asQueryEngine();
|
||||
|
||||
// create the query engines for each task
|
||||
const queryEngineTools = [
|
||||
new QueryEngineTool({
|
||||
queryEngine: vectorQueryEngine,
|
||||
metadata: {
|
||||
name: "vector_tool",
|
||||
description: `Useful for questions related to specific aspects of ${title} (e.g. the history, arts and culture, sports, demographics, or more).`,
|
||||
},
|
||||
}),
|
||||
new QueryEngineTool({
|
||||
queryEngine: summaryQueryEngine,
|
||||
metadata: {
|
||||
name: "summary_tool",
|
||||
description: `Useful for any requests that require a holistic summary of EVERYTHING about ${title}. For questions about more specific sections, please use the vector_tool.`,
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
// create the document agent
|
||||
const agent = new OpenAIAgent({
|
||||
tools: queryEngineTools,
|
||||
llm,
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
documentAgents[title] = agent;
|
||||
queryEngines[title] = vectorIndex.asQueryEngine();
|
||||
}
|
||||
```
|
||||
|
||||
## Build Top-Level Agent
|
||||
|
||||
Now we define the top-level agent that can answer questions over the set of document agents.
|
||||
|
||||
This agent takes in all document agents as tools. This specific agent RetrieverOpenAIAgent performs tool retrieval before tool use (unlike a default agent that tries to put all tools in the prompt).
|
||||
|
||||
Here we use a top-k retriever, but we encourage you to customize the tool retriever method!
|
||||
|
||||
Firstly, we create a tool for each document agent
|
||||
|
||||
```ts
|
||||
const allTools: QueryEngineTool[] = [];
|
||||
```
|
||||
|
||||
```ts
|
||||
for (const title of wikiTitles) {
|
||||
const wikiSummary = `
|
||||
This content contains Wikipedia articles about ${title}.
|
||||
Use this tool if you want to answer any questions about ${title}
|
||||
`;
|
||||
|
||||
const docTool = new QueryEngineTool({
|
||||
queryEngine: documentAgents[title],
|
||||
metadata: {
|
||||
name: `tool_${title}`,
|
||||
description: wikiSummary,
|
||||
},
|
||||
});
|
||||
|
||||
allTools.push(docTool);
|
||||
}
|
||||
```
|
||||
|
||||
Our top level agent will use this document agents as tools and use toolRetriever to retrieve the best tool to answer a question.
|
||||
|
||||
```ts
|
||||
// map the tools to nodes
|
||||
const toolMapping = SimpleToolNodeMapping.fromObjects(allTools);
|
||||
|
||||
// create the object index
|
||||
const objectIndex = await ObjectIndex.fromObjects(
|
||||
allTools,
|
||||
toolMapping,
|
||||
VectorStoreIndex,
|
||||
{
|
||||
serviceContext,
|
||||
storageContext,
|
||||
},
|
||||
);
|
||||
|
||||
// create the top agent
|
||||
const topAgent = new OpenAIAgent({
|
||||
toolRetriever: await objectIndex.asRetriever({}),
|
||||
llm,
|
||||
verbose: true,
|
||||
prefixMessages: [
|
||||
{
|
||||
content:
|
||||
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
|
||||
role: "system",
|
||||
},
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
## Use the Agent
|
||||
|
||||
Now we can use the agent to answer questions.
|
||||
|
||||
```ts
|
||||
const response = await topAgent.chat({
|
||||
message: "Tell me the differences between Brazil and Canada economics?",
|
||||
});
|
||||
|
||||
// print output
|
||||
console.log(response);
|
||||
```
|
||||
|
||||
You can find the full code for this example [here](https://github.com/run-llama/LlamaIndexTS/tree/main/examples/agent/multi-document-agent.ts)
|
||||
@@ -1,3 +1,7 @@
|
||||
---
|
||||
sidebar_position: 0
|
||||
---
|
||||
|
||||
# OpenAI Agent
|
||||
|
||||
OpenAI API that supports function calling, it’s never been easier to build your own agent!
|
||||
@@ -82,7 +86,7 @@ const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
Now we can create an OpenAIAgent with the function tools.
|
||||
|
||||
```ts
|
||||
const worker = new OpenAIAgent({
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
@@ -93,7 +97,7 @@ const worker = new OpenAIAgent({
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await worker.chat({
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
---
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||
# OpenAI Agent + QueryEngineTool
|
||||
|
||||
QueryEngineTool is a tool that allows you to query a vector index. In this example, we will create a vector index from a set of documents and then create a QueryEngineTool from the vector index. We will then create an OpenAIAgent with the QueryEngineTool and chat with the agent.
|
||||
|
||||
## Setup
|
||||
|
||||
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
Then you can import the necessary classes and functions.
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAIAgent,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
QueryEngineTool,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Create a vector index
|
||||
|
||||
Now we can create a vector index from a set of documents.
|
||||
|
||||
```ts
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
```
|
||||
|
||||
## Create a QueryEngineTool
|
||||
|
||||
Now we can create a QueryEngineTool from the vector index.
|
||||
|
||||
```ts
|
||||
// Create a query engine from the vector index
|
||||
const abramovQueryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
// Create a QueryEngineTool with the query engine
|
||||
const queryEngineTool = new QueryEngineTool({
|
||||
queryEngine: abramovQueryEngine,
|
||||
metadata: {
|
||||
name: "abramov_query_engine",
|
||||
description: "A query engine for the Abramov documents",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Create an OpenAIAgent
|
||||
|
||||
```ts
|
||||
// Create an OpenAIAgent with the query engine tool tools
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAIAgent,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
QueryEngineTool,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Create a query engine from the vector index
|
||||
const abramovQueryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
// Create a QueryEngineTool with the query engine
|
||||
const queryEngineTool = new QueryEngineTool({
|
||||
queryEngine: abramovQueryEngine,
|
||||
metadata: {
|
||||
name: "abramov_query_engine",
|
||||
description: "A query engine for the Abramov documents",
|
||||
},
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,203 @@
|
||||
# ReAct Agent
|
||||
|
||||
The ReAct agent is an AI agent that can reason over the next action, construct an action command, execute the action, and repeat these steps in an iterative loop until the task is complete.
|
||||
|
||||
In this notebook tutorial, we showcase how to write your ReAct agent using the `llamaindex` package.
|
||||
|
||||
## Setup
|
||||
|
||||
First, you need to install the `llamaindex` package. You can do this by running the following command in your terminal:
|
||||
|
||||
```bash
|
||||
pnpm i llamaindex
|
||||
```
|
||||
|
||||
And then you can import the `OpenAIAgent` and `FunctionTool` from the `llamaindex` package.
|
||||
|
||||
```ts
|
||||
import { FunctionTool, OpenAIAgent } from "llamaindex";
|
||||
```
|
||||
|
||||
Then we can define a function to sum two numbers and another function to divide two numbers.
|
||||
|
||||
```ts
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
```
|
||||
|
||||
## Create a function tool
|
||||
|
||||
Now we can create a function tool from the sum function and another function tool from the divide function.
|
||||
|
||||
For the parameters of the sum function, we can define a JSON schema.
|
||||
|
||||
### JSON Schema
|
||||
|
||||
```ts
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor b to divide by",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
```
|
||||
|
||||
## Create an ReAct
|
||||
|
||||
Now we can create an OpenAIAgent with the function tools.
|
||||
|
||||
```ts
|
||||
const agent = new ReActAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
```
|
||||
|
||||
## Chat with the agent
|
||||
|
||||
Now we can chat with the agent.
|
||||
|
||||
```ts
|
||||
const response = await agent.chat({
|
||||
message: "How much is 5 + 5? then divide by 2",
|
||||
});
|
||||
|
||||
console.log(String(response));
|
||||
```
|
||||
|
||||
The output will be:
|
||||
|
||||
```bash
|
||||
Thought: I need to use a tool to help me answer the question.
|
||||
Action: sumNumbers
|
||||
Action Input: {"a":5,"b":5}
|
||||
|
||||
Observation: 10
|
||||
Thought: I can answer without using any more tools.
|
||||
Answer: The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
|
||||
|
||||
The sum of 5 and 5 is 10, and when divided by 2, the result is 5.
|
||||
```
|
||||
|
||||
## Full code
|
||||
|
||||
```ts
|
||||
import { FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
// Define the parameters of the divide function as a JSON schema
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The argument a to divide",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The argument b to divide",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const sumFunctionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const divideFunctionTool = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [sumFunctionTool, divideFunctionTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "I want to sum 5 and 5 and then divide by 2",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
```
|
||||
@@ -1,17 +0,0 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Reader / Loader
|
||||
|
||||
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class. Currently, `.txt`, `.pdf`, `.csv`, `.md` and `.docx` files are supported, with more planned in the future!
|
||||
|
||||
```typescript
|
||||
import { SimpleDirectoryReader } from "llamaindex";
|
||||
|
||||
documents = new SimpleDirectoryReader().loadData("./data");
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/readers/src/simple-directory-reader";
|
||||
import CodeSource2 from "!raw-loader!../../../../examples/readers/src/custom-simple-directory-reader";
|
||||
import CodeSource3 from "!raw-loader!../../../../examples/readers/src/llamaparse";
|
||||
|
||||
# Loader
|
||||
|
||||
Before you can start indexing your documents, you need to load them into memory.
|
||||
|
||||
### SimpleDirectoryReader
|
||||
|
||||
[](https://stackblitz.com/github/run-llama/LlamaIndexTS/tree/main/examples/readers?file=src/simple-directory-reader.ts&title=Simple%20Directory%20Reader)
|
||||
|
||||
LlamaIndex.TS supports easy loading of files from folders using the `SimpleDirectoryReader` class.
|
||||
|
||||
It is a simple reader that reads all files from a directory and its subdirectories.
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
Currently, it supports reading `.csv`, `.docx`, `.html`, `.md` and `.pdf` files,
|
||||
but support for other file types is planned.
|
||||
|
||||
Also, you can provide a `defaultReader` as a fallback for files with unsupported extensions.
|
||||
Or pass new readers for `fileExtToReader` to support more file types.
|
||||
|
||||
<CodeBlock language="ts" showLineNumbers metastring="{8-12,17-21}">
|
||||
{CodeSource2}
|
||||
</CodeBlock>
|
||||
|
||||
### LlamaParse
|
||||
|
||||
LlamaParse is an API created by LlamaIndex to efficiently parse files, e.g. it's great at converting PDF tables into markdown.
|
||||
|
||||
To use it, first login and get an API key from https://cloud.llamaindex.ai. Make sure to store the key in the environment variable `LLAMA_CLOUD_API_KEY`.
|
||||
|
||||
Then, you can use the `LlamaParseReader` class to read a local PDF file and convert it into a markdown document that can be used by LlamaIndex:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource3}</CodeBlock>
|
||||
|
||||
Alternatively, you can set the [`resultType`](../api/classes/LlamaParseReader.md#resulttype) option to `text` to get the parsed document as a text string.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleDirectoryReader](../api/classes/SimpleDirectoryReader.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Embeddings"
|
||||
position: 3
|
||||
@@ -0,0 +1 @@
|
||||
label: "Available Embeddings"
|
||||
@@ -0,0 +1,25 @@
|
||||
# HuggingFace
|
||||
|
||||
To use HuggingFace embeddings, you need to import `HuggingFaceEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { HuggingFaceEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const huggingFaceEmbeds = new HuggingFaceEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
# MistralAI
|
||||
|
||||
To use MistralAI embeddings, you need to import `MistralAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { MistralAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const mistralEmbedModel = new MistralAIEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: mistralEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
# Ollama
|
||||
|
||||
To use Ollama embeddings, you need to import `Ollama` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const ollamaEmbedModel = new Ollama();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: ollamaEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,27 @@
|
||||
# OpenAI
|
||||
|
||||
To use OpenAI embeddings, you need to import `OpenAIEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { OpenAIEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const openaiEmbedModel = new OpenAIEmbedding();
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: openaiEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
# Together
|
||||
|
||||
To use together embeddings, you need to import `TogetherEmbedding` from `llamaindex`.
|
||||
|
||||
```ts
|
||||
import { TogetherEmbedding, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const togetherEmbedModel = new TogetherEmbedding({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: togetherEmbedModel,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
@@ -1,7 +1,3 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# Embedding
|
||||
|
||||
The embedding model in LlamaIndex is responsible for creating numerical representations of text. By default, LlamaIndex will use the `text-embedding-ada-002` model from OpenAI.
|
||||
@@ -16,7 +12,11 @@ const openaiEmbeds = new OpenAIEmbedding();
|
||||
const serviceContext = serviceContextFromDefaults({ embedModel: openaiEmbeds });
|
||||
```
|
||||
|
||||
## Local Embedding
|
||||
|
||||
For local embeddings, you can use the [HuggingFace](./available_embeddings/huggingface.md) embedding model.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAIEmbedding](../api/classes/OpenAIEmbedding.md)
|
||||
- [ServiceContext](../api/interfaces//ServiceContext.md)
|
||||
- [OpenAIEmbedding](../../api/classes/OpenAIEmbedding.md)
|
||||
- [ServiceContext](../../api/interfaces//ServiceContext.md)
|
||||
@@ -0,0 +1,32 @@
|
||||
import CodeBlock from "@theme/CodeBlock";
|
||||
import CodeSource from "!raw-loader!../../../../examples/cloud/chat.ts";
|
||||
|
||||
# LlamaCloud
|
||||
|
||||
LlamaCloud is a new generation of managed parsing, ingestion, and retrieval services, designed to bring production-grade context-augmentation to your LLM and RAG applications.
|
||||
|
||||
Currently, LlamaCloud supports
|
||||
|
||||
- Managed Ingestion API, handling parsing and document management
|
||||
- Managed Retrieval API, configuring optimal retrieval for your RAG system
|
||||
|
||||
## Access
|
||||
|
||||
We are opening up a private beta to a limited set of enterprise partners for the managed ingestion and retrieval API. If you’re interested in centralizing your data pipelines and spending more time working on your actual RAG use cases, come [talk to us.](https://www.llamaindex.ai/contact)
|
||||
|
||||
If you have access to LlamaCloud, you can visit [LlamaCloud](https://cloud.llamaindex.ai) to sign in and get an API key.
|
||||
|
||||
## Create a Managed Index
|
||||
|
||||
Currently, you can't create a managed index on LlamaCloud using LlamaIndexTS, but you can use an existing managed index for retrieval that was created by the Python version of LlamaIndex. See [the LlamaCloudIndex documentation](https://docs.llamaindex.ai/en/stable/module_guides/indexing/llama_cloud_index.html#usage) for more information on how to create a managed index.
|
||||
|
||||
## Use a Managed Index
|
||||
|
||||
Here's an example of how to use a managed index together with a chat engine:
|
||||
|
||||
<CodeBlock language="ts">{CodeSource}</CodeBlock>
|
||||
|
||||
## API Reference
|
||||
|
||||
- [LlamaCloudIndex](../api/classes/LlamaCloudIndex.md)
|
||||
- [LlamaCloudRetriever](../api/classes/LlamaCloudRetriever.md)
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "LLMs"
|
||||
position: 3
|
||||
@@ -0,0 +1 @@
|
||||
label: "Available LLMs"
|
||||
@@ -0,0 +1,80 @@
|
||||
# Anthropic
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Anthropic, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const anthropicLLM = new Anthropic({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Anthropic,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the Anthropic LLM
|
||||
const anthropicLLM = new Anthropic({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: anthropicLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,91 @@
|
||||
# Azure OpenAI
|
||||
|
||||
To use Azure OpenAI, you only need to set a few environment variables together with the `OpenAI` class.
|
||||
|
||||
For example:
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```
|
||||
export AZURE_OPENAI_KEY="<YOUR KEY HERE>"
|
||||
export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en-us/azure/ai-services/openai/quickstart?tabs=command-line%2Cpython&pivots=rest-api>"
|
||||
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const azureOpenaiLLM = new OpenAI({ model: "gpt-4", temperature: 0 });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: azureOpenaiLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,65 @@
|
||||
# Fireworks LLM
|
||||
|
||||
Fireworks.ai focus on production use cases for open source LLMs, offering speed and quality.
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { FireworksLLM, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const fireworksLLM = new FireworksLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: fireworksLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will load the Berkshire Hathaway 2022 annual report pdf
|
||||
|
||||
```ts
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What mistakes did Warren E. Buffett make?",
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import { VectorStoreIndex } from "llamaindex";
|
||||
import { PDFReader } from "llamaindex/readers/PDFReader";
|
||||
|
||||
async function main() {
|
||||
// Load PDF
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What mistakes did Warren E. Buffett make?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
```
|
||||
@@ -0,0 +1,100 @@
|
||||
# LLama2
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
|
||||
```
|
||||
|
||||
## Usage with Replication
|
||||
|
||||
```ts
|
||||
import {
|
||||
Ollama,
|
||||
ReplicateSession,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const replicateSession = new ReplicateSession({
|
||||
replicateKey,
|
||||
});
|
||||
|
||||
const llama2LLM = new LlamaDeuce({
|
||||
chatStrategy: DeuceChatStrategy.META,
|
||||
replicateSession,
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: llama2LLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
LlamaDeuce,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const llama2LLM = new LlamaDeuce({ chatStrategy: DeuceChatStrategy.META });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,82 @@
|
||||
# Mistral
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const mistralLLM = new MistralAI({
|
||||
model: "mistral-tiny",
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
MistralAI,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const mistralLLM = new MistralAI({ model: "mistral-tiny" });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: mistralLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,89 @@
|
||||
# Ollama
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Ollama, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: ollamaLLM,
|
||||
embedModel: ollamaLLM,
|
||||
});
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Ollama,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
import fs from "fs/promises";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const ollamaLLM = new Ollama({ model: "llama2", temperature: 0.75 });
|
||||
|
||||
const essay = await fs.readFile("./paul_graham_essay.txt", "utf-8");
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
embedModel: ollamaLLM, // prevent 'Set OpenAI Key in OPENAI_API_KEY env variable' error
|
||||
llm: ollamaLLM,
|
||||
});
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
# OpenAI
|
||||
|
||||
```ts
|
||||
import { OpenAI, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0, apiKey: <YOUR_API_KEY> });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
|
||||
```
|
||||
|
||||
You can setup the apiKey on the environment variables, like:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY="<YOUR_API_KEY>"
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
OpenAI,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: openaiLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
# Portkey LLM
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { Portkey, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const portkeyLLM = new Portkey({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
Portkey,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const portkeyLLM = new Portkey({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: portkeyLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,83 @@
|
||||
# Together LLM
|
||||
|
||||
## Usage
|
||||
|
||||
```ts
|
||||
import { TogetherLLM, serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const togetherLLM = new TogetherLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Query
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
```
|
||||
|
||||
## Full Example
|
||||
|
||||
```ts
|
||||
import {
|
||||
TogetherLLM,
|
||||
Document,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Create an instance of the LLM
|
||||
const togetherLLM = new TogetherLLM({
|
||||
apiKey: "<YOUR_API_KEY>",
|
||||
});
|
||||
|
||||
// Create a service context
|
||||
const serviceContext = serviceContextFromDefaults({ llm: togetherLLM });
|
||||
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
// Load and index documents
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// get retriever
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
// Create a query engine
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const query = "What is the meaning of life?";
|
||||
|
||||
// Query
|
||||
const response = await queryEngine.query({
|
||||
query,
|
||||
});
|
||||
|
||||
// Log the response
|
||||
console.log(response.response);
|
||||
}
|
||||
```
|
||||
@@ -2,7 +2,7 @@
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
# LLM
|
||||
# Large Language Models (LLMs)
|
||||
|
||||
The LLM is responsible for reading text and generating natural language responses to queries. By default, LlamaIndex.TS uses `gpt-3.5-turbo`.
|
||||
|
||||
@@ -28,6 +28,10 @@ export AZURE_OPENAI_ENDPOINT="<YOUR ENDPOINT, see https://learn.microsoft.com/en
|
||||
export AZURE_OPENAI_DEPLOYMENT="gpt-4" # or some other deployment name
|
||||
```
|
||||
|
||||
## Local LLM
|
||||
|
||||
For local LLMs, currently we recommend the use of [Ollama](./available_llms/ollama.md) LLM.
|
||||
|
||||
## API Reference
|
||||
|
||||
- [OpenAI](../api/classes/OpenAI.md)
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
sidebar_position: 3
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
# NodeParser
|
||||
@@ -27,6 +27,71 @@ const splitter = new SentenceSplitter({ chunkSize: 1 });
|
||||
const textSplits = splitter.splitText("Hello World");
|
||||
```
|
||||
|
||||
## MarkdownNodeParser
|
||||
|
||||
The `MarkdownNodeParser` is a more advanced `NodeParser` that can handle markdown documents. It will split the markdown into nodes and then parse the nodes into a `Document` object.
|
||||
|
||||
```typescript
|
||||
import { MarkdownNodeParser } from "llamaindex";
|
||||
|
||||
const nodeParser = new MarkdownNodeParser();
|
||||
|
||||
const nodes = nodeParser.getNodesFromDocuments([
|
||||
new Document({
|
||||
text: `# Main Header
|
||||
Main content
|
||||
|
||||
# Header 2
|
||||
Header 2 content
|
||||
|
||||
## Sub-header
|
||||
Sub-header content
|
||||
|
||||
`,
|
||||
}),
|
||||
]);
|
||||
```
|
||||
|
||||
The output metadata will be something like:
|
||||
|
||||
```bash
|
||||
[
|
||||
TextNode {
|
||||
id_: '008e41a8-b097-487c-bee8-bd88b9455844',
|
||||
metadata: { 'Header 1': 'Main Header' },
|
||||
excludedEmbedMetadataKeys: [],
|
||||
excludedLlmMetadataKeys: [],
|
||||
relationships: { PARENT: [Array] },
|
||||
hash: 'KJ5e/um/RkHaNR6bonj9ormtZY7I8i4XBPVYHXv1A5M=',
|
||||
text: 'Main Header\nMain content',
|
||||
textTemplate: '',
|
||||
metadataSeparator: '\n'
|
||||
},
|
||||
TextNode {
|
||||
id_: '0f5679b3-ba63-4aff-aedc-830c4208d0b5',
|
||||
metadata: { 'Header 1': 'Header 2' },
|
||||
excludedEmbedMetadataKeys: [],
|
||||
excludedLlmMetadataKeys: [],
|
||||
relationships: { PARENT: [Array] },
|
||||
hash: 'IP/g/dIld3DcbK+uHzDpyeZ9IdOXY4brxhOIe7wc488=',
|
||||
text: 'Header 2\nHeader 2 content',
|
||||
textTemplate: '',
|
||||
metadataSeparator: '\n'
|
||||
},
|
||||
TextNode {
|
||||
id_: 'e81e9bd0-121c-4ead-8ca7-1639d65fdf90',
|
||||
metadata: { 'Header 1': 'Header 2', 'Header 2': 'Sub-header' },
|
||||
excludedEmbedMetadataKeys: [],
|
||||
excludedLlmMetadataKeys: [],
|
||||
relationships: { PARENT: [Array] },
|
||||
hash: 'B3kYNnxaYi9ghtAgwza0ZEVKF4MozobkNUlcekDL7JQ=',
|
||||
text: 'Sub-header\nSub-header content',
|
||||
textTemplate: '',
|
||||
metadataSeparator: '\n'
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
- [SimpleNodeParser](../api/classes/SimpleNodeParser.md)
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Node Postprocessors"
|
||||
position: 3
|
||||
@@ -0,0 +1,71 @@
|
||||
# Cohere Reranker
|
||||
|
||||
The Cohere Reranker is a postprocessor that uses the Cohere API to rerank the results of a search query.
|
||||
|
||||
## Setup
|
||||
|
||||
Firstly, you will need to install the `llamaindex` package.
|
||||
|
||||
```bash
|
||||
pnpm install llamaindex
|
||||
```
|
||||
|
||||
Now, you will need to sign up for an API key at [Cohere](https://cohere.ai/). Once you have your API key you can import the necessary modules and create a new instance of the `CohereRerank` class.
|
||||
|
||||
```ts
|
||||
import {
|
||||
CohereRerank,
|
||||
Document,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
```
|
||||
|
||||
## Load and index documents
|
||||
|
||||
For this example, we will use a single document. In a real-world scenario, you would have multiple documents to index.
|
||||
|
||||
```ts
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
```
|
||||
|
||||
## Increase similarity topK to retrieve more results
|
||||
|
||||
The default value for `similarityTopK` is 2. This means that only the most similar document will be returned. To retrieve more results, you can increase the value of `similarityTopK`.
|
||||
|
||||
```ts
|
||||
const retriever = index.asRetriever();
|
||||
retriever.similarityTopK = 5;
|
||||
```
|
||||
|
||||
## Create a new instance of the CohereRerank class
|
||||
|
||||
Then you can create a new instance of the `CohereRerank` class and pass in your API key and the number of results you want to return.
|
||||
|
||||
```ts
|
||||
const nodePostprocessor = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>",
|
||||
topN: 4,
|
||||
});
|
||||
```
|
||||
|
||||
## Create a query engine with the retriever and node postprocessor
|
||||
|
||||
```ts
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
nodePostprocessors: [nodePostprocessor],
|
||||
});
|
||||
|
||||
// log the response
|
||||
const response = await queryEngine.query("Where did the author grown up?");
|
||||
```
|
||||
@@ -0,0 +1,110 @@
|
||||
# Node Postprocessors
|
||||
|
||||
## Concept
|
||||
|
||||
Node postprocessors are a set of modules that take a set of nodes, and apply some kind of transformation or filtering before returning them.
|
||||
|
||||
In LlamaIndex, node postprocessors are most commonly applied within a query engine, after the node retrieval step and before the response synthesis step.
|
||||
|
||||
LlamaIndex offers several node postprocessors for immediate use, while also providing a simple API for adding your own custom postprocessors.
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
An example of using a node postprocessors is below:
|
||||
|
||||
```ts
|
||||
import {
|
||||
Node,
|
||||
NodeWithScore,
|
||||
SimilarityPostprocessor,
|
||||
CohereRerank,
|
||||
} from "llamaindex";
|
||||
|
||||
const nodes: NodeWithScore[] = [
|
||||
{
|
||||
node: new TextNode({ text: "hello world" }),
|
||||
score: 0.8,
|
||||
},
|
||||
{
|
||||
node: new TextNode({ text: "LlamaIndex is the best" }),
|
||||
score: 0.6,
|
||||
},
|
||||
];
|
||||
|
||||
// similarity postprocessor: filter nodes below 0.75 similarity score
|
||||
const processor = new SimilarityPostprocessor({
|
||||
similarityCutoff: 0.7,
|
||||
});
|
||||
|
||||
const filteredNodes = processor.postprocessNodes(nodes);
|
||||
|
||||
// cohere rerank: rerank nodes given query using trained model
|
||||
const reranker = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>",
|
||||
topN: 2,
|
||||
});
|
||||
|
||||
const rerankedNodes = await reranker.postprocessNodes(nodes, "<user_query>");
|
||||
|
||||
console.log(filteredNodes, rerankedNodes);
|
||||
```
|
||||
|
||||
Now you can use the `filteredNodes` and `rerankedNodes` in your application.
|
||||
|
||||
## Using Node Postprocessors in LlamaIndex
|
||||
|
||||
Most commonly, node-postprocessors will be used in a query engine, where they are applied to the nodes returned from a retriever, and before the response synthesis step.
|
||||
|
||||
### Using Node Postprocessors in a Query Engine
|
||||
|
||||
```ts
|
||||
import { Node, NodeWithScore, SimilarityPostprocessor, CohereRerank } from "llamaindex";
|
||||
|
||||
const nodes: NodeWithScore[] = [
|
||||
{
|
||||
node: new TextNode({ text: "hello world" }),
|
||||
score: 0.8,
|
||||
},
|
||||
{
|
||||
node: new TextNode({ text: "LlamaIndex is the best" }),
|
||||
score: 0.6,
|
||||
}
|
||||
];
|
||||
|
||||
// cohere rerank: rerank nodes given query using trained model
|
||||
const reranker = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>,
|
||||
topN: 2,
|
||||
})
|
||||
|
||||
const document = new Document({ text: "essay", id_: "essay" });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
nodePostprocessors: [processor, reranker],
|
||||
});
|
||||
|
||||
// all node post-processors will be applied during each query
|
||||
const response = await queryEngine.query("<user_query>");
|
||||
```
|
||||
|
||||
### Using with retrieved nodes
|
||||
|
||||
```ts
|
||||
import { SimilarityPostprocessor } from "llamaindex";
|
||||
|
||||
nodes = await index.asRetriever().retrieve("test query str");
|
||||
|
||||
const processor = new SimilarityPostprocessor({
|
||||
similarityCutoff: 0.7,
|
||||
});
|
||||
|
||||
const filteredNodes = processor.postprocessNodes(nodes);
|
||||
```
|
||||
@@ -0,0 +1,2 @@
|
||||
label: "Prompts"
|
||||
position: 0
|
||||
@@ -0,0 +1,76 @@
|
||||
# Prompts
|
||||
|
||||
Prompting is the fundamental input that gives LLMs their expressive power. LlamaIndex uses prompts to build the index, do insertion, perform traversal during querying, and to synthesize the final answer.
|
||||
|
||||
Users may also provide their own prompt templates to further customize the behavior of the framework. The best method for customizing is copying the default prompt from the link above, and using that as the base for any modifications.
|
||||
|
||||
## Usage Pattern
|
||||
|
||||
Currently, there are two ways to customize prompts in LlamaIndex:
|
||||
|
||||
For both methods, you will need to create an function that overrides the default prompt.
|
||||
|
||||
```ts
|
||||
// Define a custom prompt
|
||||
const newTextQaPrompt: TextQaPrompt = ({ context, query }) => {
|
||||
return `Context information is below.
|
||||
---------------------
|
||||
${context}
|
||||
---------------------
|
||||
Given the context information and not prior knowledge, answer the query.
|
||||
Answer the query in the style of a Sherlock Holmes detective novel.
|
||||
Query: ${query}
|
||||
Answer:`;
|
||||
};
|
||||
```
|
||||
|
||||
### 1. Customizing the default prompt on initialization
|
||||
|
||||
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
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new CompactAndRefine(serviceContext, newTextQaPrompt),
|
||||
});
|
||||
|
||||
// Create index
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine({ responseSynthesizer });
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
```
|
||||
|
||||
### 2. Customizing submodules prompt
|
||||
|
||||
The second method is that most of the modules in LlamaIndex have a `getPrompts` and a `updatePrompt` method that allows you to override the default prompt. This method is useful when you want to change the prompt on the fly or in submodules on a more granular level.
|
||||
|
||||
```ts
|
||||
// Create index
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
// Get a list of prompts for the query engine
|
||||
const prompts = queryEngine.getPrompts();
|
||||
|
||||
// output: { "responseSynthesizer:textQATemplate": defaultTextQaPrompt, "responseSynthesizer:refineTemplate": defaultRefineTemplatePrompt }
|
||||
|
||||
// Now, we can override the default prompt
|
||||
queryEngine.updatePrompt({
|
||||
"responseSynthesizer:textQATemplate": newTextQaPrompt,
|
||||
});
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
```
|
||||
@@ -6,6 +6,6 @@
|
||||
"composite": true,
|
||||
"incremental": true,
|
||||
"outDir": "./lib",
|
||||
"tsBuildInfoFile": "./lib/.tsbuildinfo",
|
||||
},
|
||||
"tsBuildInfoFile": "./lib/.tsbuildinfo"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
package-lock.json
|
||||
storage
|
||||
tmp_data
|
||||
@@ -0,0 +1,55 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const dataPath = path.join(__dirname, "tmp_data");
|
||||
|
||||
const extractWikipediaTitle = async (title: string) => {
|
||||
const fileExists = fs.existsSync(path.join(dataPath, `${title}.txt`));
|
||||
|
||||
if (fileExists) {
|
||||
console.log(`Arquivo já existe para o título: ${title}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const queryParams = new URLSearchParams({
|
||||
action: "query",
|
||||
format: "json",
|
||||
titles: title,
|
||||
prop: "extracts",
|
||||
explaintext: "true",
|
||||
});
|
||||
|
||||
const url = `https://en.wikipedia.org/w/api.php?${queryParams}`;
|
||||
|
||||
const response = await fetch(url);
|
||||
const data: any = await response.json();
|
||||
|
||||
const pages = data.query.pages;
|
||||
const page = pages[Object.keys(pages)[0]];
|
||||
const wikiText = page.extract;
|
||||
|
||||
await new Promise((resolve) => {
|
||||
fs.writeFile(path.join(dataPath, `${title}.txt`), wikiText, (err: any) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
resolve(title);
|
||||
return;
|
||||
}
|
||||
console.log(`${title} stored!`);
|
||||
|
||||
resolve(title);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const extractWikipedia = async (titles: string[]) => {
|
||||
if (!fs.existsSync(dataPath)) {
|
||||
fs.mkdirSync(dataPath);
|
||||
}
|
||||
|
||||
for await (const title of titles) {
|
||||
await extractWikipediaTitle(title);
|
||||
}
|
||||
|
||||
console.log("Extration finished!");
|
||||
};
|
||||
@@ -0,0 +1,157 @@
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
import {
|
||||
Document,
|
||||
ObjectIndex,
|
||||
OpenAI,
|
||||
OpenAIAgent,
|
||||
QueryEngineTool,
|
||||
SimpleNodeParser,
|
||||
SimpleToolNodeMapping,
|
||||
SummaryIndex,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
storageContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
import { extractWikipedia } from "./helpers/extractWikipedia";
|
||||
|
||||
const wikiTitles = ["Brazil", "Canada"];
|
||||
|
||||
async function main() {
|
||||
await extractWikipedia(wikiTitles);
|
||||
|
||||
const countryDocs: Record<string, Document> = {};
|
||||
|
||||
for (const title of wikiTitles) {
|
||||
const path = `./agent/helpers/tmp_data/${title}.txt`;
|
||||
const text = await fs.readFile(path, "utf-8");
|
||||
const document = new Document({ text: text, id_: path });
|
||||
countryDocs[title] = document;
|
||||
}
|
||||
|
||||
const llm = new OpenAI({
|
||||
model: "gpt-4",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm });
|
||||
const storageContext = await storageContextFromDefaults({
|
||||
persistDir: "./storage",
|
||||
});
|
||||
|
||||
// TODO: fix any
|
||||
const documentAgents: any = {};
|
||||
const queryEngines: any = {};
|
||||
|
||||
for (const title of wikiTitles) {
|
||||
console.log(`Processing ${title}`);
|
||||
|
||||
const nodes = new SimpleNodeParser({
|
||||
chunkSize: 200,
|
||||
chunkOverlap: 20,
|
||||
}).getNodesFromDocuments([countryDocs[title]]);
|
||||
|
||||
console.log(`Creating index for ${title}`);
|
||||
|
||||
const vectorIndex = await VectorStoreIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
storageContext: storageContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
const summaryIndex = await SummaryIndex.init({
|
||||
serviceContext: serviceContext,
|
||||
nodes,
|
||||
});
|
||||
|
||||
console.log(`Creating query engines for ${title}`);
|
||||
|
||||
const vectorQueryEngine = summaryIndex.asQueryEngine();
|
||||
const summaryQueryEngine = summaryIndex.asQueryEngine();
|
||||
|
||||
const queryEngineTools = [
|
||||
new QueryEngineTool({
|
||||
queryEngine: vectorQueryEngine,
|
||||
metadata: {
|
||||
name: "vector_tool",
|
||||
description: `Useful for questions related to specific aspects of ${title} (e.g. the history, arts and culture, sports, demographics, or more).`,
|
||||
},
|
||||
}),
|
||||
new QueryEngineTool({
|
||||
queryEngine: summaryQueryEngine,
|
||||
metadata: {
|
||||
name: "summary_tool",
|
||||
description: `Useful for any requests that require a holistic summary of EVERYTHING about ${title}. For questions about more specific sections, please use the vector_tool.`,
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
console.log(`Creating agents for ${title}`);
|
||||
|
||||
const agent = new OpenAIAgent({
|
||||
tools: queryEngineTools,
|
||||
llm,
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
documentAgents[title] = agent;
|
||||
queryEngines[title] = vectorIndex.asQueryEngine();
|
||||
}
|
||||
|
||||
const allTools: QueryEngineTool[] = [];
|
||||
|
||||
console.log(`Creating tools for all countries`);
|
||||
|
||||
for (const title of wikiTitles) {
|
||||
const wikiSummary = `This content contains Wikipedia articles about ${title}. Use this tool if you want to answer any questions about ${title}`;
|
||||
|
||||
console.log(`Creating tool for ${title}`);
|
||||
|
||||
const docTool = new QueryEngineTool({
|
||||
queryEngine: documentAgents[title],
|
||||
metadata: {
|
||||
name: `tool_${title}`,
|
||||
description: wikiSummary,
|
||||
},
|
||||
});
|
||||
|
||||
allTools.push(docTool);
|
||||
}
|
||||
|
||||
console.log("creating tool mapping");
|
||||
|
||||
const toolMapping = SimpleToolNodeMapping.fromObjects(allTools);
|
||||
|
||||
const objectIndex = await ObjectIndex.fromObjects(
|
||||
allTools,
|
||||
toolMapping,
|
||||
VectorStoreIndex,
|
||||
{
|
||||
serviceContext,
|
||||
storageContext,
|
||||
},
|
||||
);
|
||||
|
||||
const topAgent = new OpenAIAgent({
|
||||
toolRetriever: await objectIndex.asRetriever({}),
|
||||
llm,
|
||||
verbose: true,
|
||||
prefixMessages: [
|
||||
{
|
||||
content:
|
||||
"You are an agent designed to answer queries about a set of given countries. Please always use the tools provided to answer a question. Do not rely on prior knowledge.",
|
||||
role: "system",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const response = await topAgent.chat({
|
||||
message: "Tell me the differences between Brazil and Canada economics?",
|
||||
});
|
||||
|
||||
console.log({
|
||||
capitalOfBrazil: response,
|
||||
});
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
OpenAIAgent,
|
||||
QueryEngineTool,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Create a query engine from the vector index
|
||||
const abramovQueryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
// Create a QueryEngineTool with the query engine
|
||||
const queryEngineTool = new QueryEngineTool({
|
||||
queryEngine: abramovQueryEngine,
|
||||
metadata: {
|
||||
name: "abramov_query_engine",
|
||||
description: "A query engine for the Abramov documents",
|
||||
},
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import {
|
||||
OpenAIAgent,
|
||||
QueryEngineTool,
|
||||
SimpleDirectoryReader,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load the documents
|
||||
const documents = await new SimpleDirectoryReader().loadData({
|
||||
directoryPath: "node_modules/llamaindex/examples/",
|
||||
});
|
||||
|
||||
// Create a vector index from the documents
|
||||
const vectorIndex = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Create a query engine from the vector index
|
||||
const abramovQueryEngine = vectorIndex.asQueryEngine();
|
||||
|
||||
// Create a QueryEngineTool with the query engine
|
||||
const queryEngineTool = new QueryEngineTool({
|
||||
queryEngine: abramovQueryEngine,
|
||||
metadata: {
|
||||
name: "abramov_query_engine",
|
||||
description: "A query engine for the Abramov documents",
|
||||
},
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new OpenAIAgent({
|
||||
tools: [queryEngineTool],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "What was his salary?",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { FunctionTool, ReActAgent } from "llamaindex";
|
||||
|
||||
// Define a function to sum two numbers
|
||||
function sumNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
// Define a function to divide two numbers
|
||||
function divideNumbers({ a, b }: { a: number; b: number }): number {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// Define the parameters of the sum function as a JSON schema
|
||||
const sumJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The first number",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The second number",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
const divideJSON = {
|
||||
type: "object",
|
||||
properties: {
|
||||
a: {
|
||||
type: "number",
|
||||
description: "The dividend",
|
||||
},
|
||||
b: {
|
||||
type: "number",
|
||||
description: "The divisor",
|
||||
},
|
||||
},
|
||||
required: ["a", "b"],
|
||||
};
|
||||
|
||||
async function main() {
|
||||
// Create a function tool from the sum function
|
||||
const functionTool = new FunctionTool(sumNumbers, {
|
||||
name: "sumNumbers",
|
||||
description: "Use this function to sum two numbers",
|
||||
parameters: sumJSON,
|
||||
});
|
||||
|
||||
// Create a function tool from the divide function
|
||||
const functionTool2 = new FunctionTool(divideNumbers, {
|
||||
name: "divideNumbers",
|
||||
description: "Use this function to divide two numbers",
|
||||
parameters: divideJSON,
|
||||
});
|
||||
|
||||
// Create an OpenAIAgent with the function tools
|
||||
const agent = new ReActAgent({
|
||||
tools: [functionTool, functionTool2],
|
||||
verbose: true,
|
||||
});
|
||||
|
||||
// Chat with the agent
|
||||
const response = await agent.chat({
|
||||
message: "Divide 16 by 2 then add 20",
|
||||
});
|
||||
|
||||
// Print the response
|
||||
console.log(String(response));
|
||||
}
|
||||
|
||||
main().then(() => {
|
||||
console.log("Done");
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import { Anthropic } from "llamaindex";
|
||||
|
||||
(async () => {
|
||||
const anthropic = new Anthropic();
|
||||
const anthropic = new Anthropic({
|
||||
apiKey: process.env.ANTHROPIC_API_KEY,
|
||||
});
|
||||
const result = await anthropic.chat({
|
||||
messages: [
|
||||
{ content: "You want to talk in rhymes.", role: "system" },
|
||||
|
||||
@@ -14,18 +14,27 @@ Here are two sample scripts which work well with the sample data in the Astra Po
|
||||
|
||||
- `ASTRA_DB_APPLICATION_TOKEN`: The generated app token for your Astra database
|
||||
- `ASTRA_DB_ENDPOINT`: The API endpoint for your Astra database
|
||||
- `ASTRA_DB_NAMESPACE`: (Optional) The namespace where your collection is stored defaults to `default_keyspace`
|
||||
- `OPENAI_API_KEY`: Your OpenAI key
|
||||
|
||||
2. `cd` Into the `examples` directory
|
||||
3. run `npm i`
|
||||
|
||||
## Load the data
|
||||
## Example load and query
|
||||
|
||||
Loads and queries a simple vectorstore with some documents about Astra DB
|
||||
|
||||
run `ts-node astradb/example`
|
||||
|
||||
## Movie Reviews Example
|
||||
|
||||
### Load the data
|
||||
|
||||
This sample loads the same dataset of movie reviews as the Astra Portal sample dataset. (Feel free to load the data in your the Astra Data Explorer to compare)
|
||||
|
||||
run `ts-node astradb/load`
|
||||
|
||||
## Use RAG to Query the data
|
||||
### Use RAG to Query the data
|
||||
|
||||
Check out your data in the Astra Data Explorer and change the sample query as you see fit.
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import {
|
||||
AstraDBVectorStore,
|
||||
Document,
|
||||
storageContextFromDefaults,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
const collectionName = "test_collection";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const docs = [
|
||||
new Document({
|
||||
text: "AstraDB is built on Apache Cassandra",
|
||||
metadata: {
|
||||
id: 123,
|
||||
foo: "bar",
|
||||
},
|
||||
}),
|
||||
new Document({
|
||||
text: "AstraDB is a NoSQL DB",
|
||||
metadata: {
|
||||
id: 456,
|
||||
foo: "baz",
|
||||
},
|
||||
}),
|
||||
new Document({
|
||||
text: "AstraDB supports vector search",
|
||||
metadata: {
|
||||
id: 789,
|
||||
foo: "qux",
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const astraVS = new AstraDBVectorStore();
|
||||
await astraVS.create(collectionName, {
|
||||
vector: { dimension: 1536, metric: "cosine" },
|
||||
});
|
||||
await astraVS.connect(collectionName);
|
||||
|
||||
const ctx = await storageContextFromDefaults({ vectorStore: astraVS });
|
||||
const index = await VectorStoreIndex.fromDocuments(docs, {
|
||||
storageContext: ctx,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "Describe AstraDB.",
|
||||
});
|
||||
|
||||
console.log(response.toString());
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -10,9 +10,9 @@ const collectionName = "movie_reviews";
|
||||
async function main() {
|
||||
try {
|
||||
const reader = new PapaCSVReader(false);
|
||||
const docs = await reader.loadData("../data/movie_reviews.csv");
|
||||
const docs = await reader.loadData("./data/movie_reviews.csv");
|
||||
|
||||
const astraVS = new AstraDBVectorStore();
|
||||
const astraVS = new AstraDBVectorStore({ contentKey: "reviewtext" });
|
||||
await astraVS.create(collectionName, {
|
||||
vector: { dimension: 1536, metric: "cosine" },
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ const collectionName = "movie_reviews";
|
||||
|
||||
async function main() {
|
||||
try {
|
||||
const astraVS = new AstraDBVectorStore();
|
||||
const astraVS = new AstraDBVectorStore({ contentKey: "reviewtext" });
|
||||
await astraVS.connect(collectionName);
|
||||
|
||||
const ctx = serviceContextFromDefaults();
|
||||
@@ -19,7 +19,7 @@ async function main() {
|
||||
const queryEngine = await index.asQueryEngine({ retriever });
|
||||
|
||||
const results = await queryEngine.query({
|
||||
query: "What is the best reviewed movie?",
|
||||
query: 'How was "La Sapienza" reviewed?',
|
||||
});
|
||||
|
||||
console.log(results.response);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
# LlamaCloud Integration
|
||||
|
||||
## Getting started
|
||||
|
||||
To start the examples call them from the `examples` folder:
|
||||
|
||||
And make sure, you're setting your `LLAMA_CLOUD_API_KEY` in your environment variable:
|
||||
|
||||
```shell
|
||||
export LLAMA_CLOUD_API_KEY=your-api-key
|
||||
```
|
||||
|
||||
For using another environment, also set the `LLAMA_CLOUD_BASE_URL` environment variable:
|
||||
|
||||
```shell
|
||||
export LLAMA_CLOUD_BASE_URL="https://api.staging.llamaindex.ai"
|
||||
```
|
||||
|
||||
## Chat Engine
|
||||
|
||||
This example is using the managed index named `test` from the project `default` to create a chat engine.
|
||||
|
||||
```shell
|
||||
pnpx ts-node cloud/chat.ts
|
||||
```
|
||||
|
||||
## Query Engine
|
||||
|
||||
This example shows how to use the managed index with a query engine.
|
||||
|
||||
```shell
|
||||
pnpx ts-node cloud/query.ts
|
||||
```
|
||||
@@ -0,0 +1,29 @@
|
||||
import { stdin as input, stdout as output } from "node:process";
|
||||
import readline from "node:readline/promises";
|
||||
|
||||
import { ContextChatEngine, LlamaCloudIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const index = new LlamaCloudIndex({
|
||||
name: "test",
|
||||
projectName: "default",
|
||||
baseUrl: process.env.LLAMA_CLOUD_BASE_URL,
|
||||
apiKey: process.env.LLAMA_CLOUD_API_KEY,
|
||||
});
|
||||
const retriever = index.asRetriever({
|
||||
similarityTopK: 5,
|
||||
});
|
||||
const chatEngine = new ContextChatEngine({ retriever });
|
||||
const rl = readline.createInterface({ input, output });
|
||||
|
||||
while (true) {
|
||||
const query = await rl.question("User: ");
|
||||
const stream = await chatEngine.chat({ message: query, stream: true });
|
||||
console.log();
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,31 @@
|
||||
import { stdin as input, stdout as output } from "node:process";
|
||||
import readline from "node:readline/promises";
|
||||
|
||||
import { LlamaCloudIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const index = new LlamaCloudIndex({
|
||||
name: "test",
|
||||
projectName: "default",
|
||||
baseUrl: process.env.LLAMA_CLOUD_BASE_URL,
|
||||
apiKey: process.env.LLAMA_CLOUD_API_KEY,
|
||||
});
|
||||
const queryEngine = index.asQueryEngine({
|
||||
denseSimilarityTopK: 5,
|
||||
});
|
||||
const rl = readline.createInterface({ input, output });
|
||||
|
||||
while (true) {
|
||||
const query = await rl.question("Query: ");
|
||||
const stream = await queryEngine.query({
|
||||
query,
|
||||
stream: true,
|
||||
});
|
||||
console.log();
|
||||
for await (const chunk of stream) {
|
||||
process.stdout.write(chunk.response);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
Binary file not shown.
@@ -0,0 +1,24 @@
|
||||
import { Document, MarkdownNodeParser } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
const markdownParser = new MarkdownNodeParser();
|
||||
|
||||
const splits = markdownParser.getNodesFromDocuments([
|
||||
new Document({
|
||||
text: `# Main Header
|
||||
Main content
|
||||
|
||||
# Header 2
|
||||
Header 2 content
|
||||
|
||||
## Sub-header
|
||||
Sub-header content
|
||||
|
||||
`,
|
||||
}),
|
||||
]);
|
||||
|
||||
console.log(splits);
|
||||
}
|
||||
|
||||
main();
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import { Ollama } from "llamaindex";
|
||||
import { Ollama } from "llamaindex/llm/ollama";
|
||||
|
||||
(async () => {
|
||||
const llm = new Ollama({ model: "llama2", temperature: 0.75 });
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
Document,
|
||||
ResponseSynthesizer,
|
||||
TreeSummarize,
|
||||
TreeSummarizePrompt,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
const treeSummarizePrompt: TreeSummarizePrompt = ({ context, query }) => {
|
||||
return `Context information from multiple sources is below.
|
||||
---------------------
|
||||
${context}
|
||||
---------------------
|
||||
Given the information from multiple sources and not prior knowledge.
|
||||
Answer the query in the style of a Shakespeare play"
|
||||
Query: ${query}
|
||||
Answer:`;
|
||||
};
|
||||
|
||||
async function main() {
|
||||
const documents = new Document({
|
||||
text: "The quick brown fox jumps over the lazy dog",
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([documents]);
|
||||
|
||||
const query = "The quick brown fox jumps over the lazy dog";
|
||||
|
||||
const ctx = serviceContextFromDefaults({});
|
||||
|
||||
const responseSynthesizer = new ResponseSynthesizer({
|
||||
responseBuilder: new TreeSummarize(ctx),
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
responseSynthesizer,
|
||||
});
|
||||
|
||||
console.log({
|
||||
promptsToUse: queryEngine.getPrompts(),
|
||||
});
|
||||
|
||||
queryEngine.updatePrompts({
|
||||
"responseSynthesizer:summaryTemplate": treeSummarizePrompt,
|
||||
});
|
||||
|
||||
await queryEngine.query({ query });
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -1,61 +1,5 @@
|
||||
## Reader Examples
|
||||
## LlamaIndex Reader Examples
|
||||
|
||||
These examples show how to use a specific reader class by loading a document and running a test query.
|
||||
|
||||
1. Make sure you are in `examples` directory
|
||||
|
||||
```bash
|
||||
cd ./examples
|
||||
```
|
||||
|
||||
2. Prepare `OPENAI_API_KEY` environment variable:
|
||||
|
||||
```bash
|
||||
export OPENAI_API_KEY=your_openai_api_key
|
||||
```
|
||||
|
||||
3. Run the following command to load documents and test query:
|
||||
|
||||
- MarkdownReader Example
|
||||
|
||||
```bash
|
||||
npx ts-node readers/load-md.ts
|
||||
```
|
||||
|
||||
- DocxReader Example
|
||||
|
||||
```bash
|
||||
npx ts-node readers/load-docx.ts
|
||||
```
|
||||
|
||||
- PdfReader Example
|
||||
|
||||
```bash
|
||||
npx ts-node readers/load-pdf.ts
|
||||
```
|
||||
|
||||
- HtmlReader Example
|
||||
|
||||
```bash
|
||||
npx ts-node readers/load-html.ts
|
||||
```
|
||||
|
||||
- CsvReader Example
|
||||
|
||||
```bash
|
||||
npx ts-node readers/load-csv.ts
|
||||
```
|
||||
|
||||
- NotionReader Example
|
||||
|
||||
```bash
|
||||
export NOTION_TOKEN=your_notion_token
|
||||
npx ts-node readers/load-notion.ts
|
||||
```
|
||||
|
||||
- AssemblyAI Example
|
||||
|
||||
```bash
|
||||
export ASSEMBLYAI_API_KEY=your_assemblyai_api_key
|
||||
npx ts-node readers/load-assemblyai.ts
|
||||
```shell
|
||||
npm run start
|
||||
```
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "llamaindex-loader-example",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node --loader ts-node/esm ./src/simple-directory-reader.ts",
|
||||
"start:csv": "node --loader ts-node/esm ./src/csv.ts",
|
||||
"start:docx": "node --loader ts-node/esm ./src/docx.ts",
|
||||
"start:html": "node --loader ts-node/esm ./src/html.ts",
|
||||
"start:markdown": "node --loader ts-node/esm ./src/markdown.ts",
|
||||
"start:pdf": "node --loader ts-node/esm ./src/pdf.ts",
|
||||
"start:llamaparse": "node --loader ts-node/esm ./src/llamaparse.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"llamaindex": "latest"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.14",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.3.3"
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { program } from "commander";
|
||||
import { TranscribeParams, VectorStoreIndex } from "llamaindex";
|
||||
import { AudioTranscriptReader } from "llamaindex/readers/AssemblyAIReader";
|
||||
import { stdin as input, stdout as output } from "node:process";
|
||||
import readline from "node:readline/promises";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
|
||||
program
|
||||
.option("-a, --audio [string]", "URL or path of the audio file to transcribe")
|
||||
@@ -35,7 +35,7 @@ program
|
||||
// Create query engine
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const rl = readline.createInterface({ input, output });
|
||||
const rl = createInterface({ input, output });
|
||||
while (true) {
|
||||
const query = await rl.question("Ask a question: ");
|
||||
|
||||
@@ -10,7 +10,7 @@ import { PapaCSVReader } from "llamaindex/readers/CSVReader";
|
||||
async function main() {
|
||||
// Load CSV
|
||||
const reader = new PapaCSVReader();
|
||||
const path = "data/titanic_train.csv";
|
||||
const path = "../data/titanic_train.csv";
|
||||
const documents = await reader.loadData(path);
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { BaseReader, Document, Metadata } from "llamaindex";
|
||||
import {
|
||||
FILE_EXT_TO_READER,
|
||||
SimpleDirectoryReader,
|
||||
TextFileReader,
|
||||
} from "llamaindex/readers/SimpleDirectoryReader";
|
||||
|
||||
class ZipReader implements BaseReader {
|
||||
loadData(...args: any[]): Promise<Document<Metadata>[]> {
|
||||
throw new Error("Implement me");
|
||||
}
|
||||
}
|
||||
|
||||
const reader = new SimpleDirectoryReader();
|
||||
const documents = await reader.loadData({
|
||||
directoryPath: "../data",
|
||||
defaultReader: new TextFileReader(),
|
||||
fileExtToReader: {
|
||||
...FILE_EXT_TO_READER,
|
||||
zip: new ZipReader(),
|
||||
},
|
||||
});
|
||||
|
||||
documents.forEach((doc) => {
|
||||
console.log(`document (${doc.id_}):`, doc.getText());
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { VectorStoreIndex } from "llamaindex";
|
||||
import { DocxReader } from "llamaindex/readers/DocxReader";
|
||||
|
||||
const FILE_PATH = "./data/stars.docx";
|
||||
const FILE_PATH = "../data/stars.docx";
|
||||
const SAMPLE_QUERY = "Information about Zodiac";
|
||||
|
||||
async function main() {
|
||||
@@ -4,7 +4,7 @@ import { HTMLReader } from "llamaindex/readers/HTMLReader";
|
||||
async function main() {
|
||||
// Load page
|
||||
const reader = new HTMLReader();
|
||||
const documents = await reader.loadData("data/18-1_Changelog.html");
|
||||
const documents = await reader.loadData("../data/llamaindex.html");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
@@ -12,7 +12,7 @@ async function main() {
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What were the notable changes in 18.1?",
|
||||
query: "What can I do with LlamaIndex?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
@@ -0,0 +1,21 @@
|
||||
import { LlamaParseReader, VectorStoreIndex } from "llamaindex";
|
||||
|
||||
async function main() {
|
||||
// Load PDF using LlamaParse
|
||||
const reader = new LlamaParseReader({ resultType: "markdown" });
|
||||
const documents = await reader.loadData("../data/TOS.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What is the license grant in the TOS?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -1,7 +1,7 @@
|
||||
import { VectorStoreIndex } from "llamaindex";
|
||||
import { MarkdownReader } from "llamaindex/readers/MarkdownReader";
|
||||
|
||||
const FILE_PATH = "./data/planets.md";
|
||||
const FILE_PATH = "../data/planets.md";
|
||||
const SAMPLE_QUERY = "List all planets";
|
||||
|
||||
async function main() {
|
||||
@@ -3,7 +3,7 @@ import { program } from "commander";
|
||||
import { VectorStoreIndex } from "llamaindex";
|
||||
import { NotionReader } from "llamaindex/readers/NotionReader";
|
||||
import { stdin as input, stdout as output } from "node:process";
|
||||
import readline from "node:readline/promises";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
|
||||
program
|
||||
.argument("[page]", "Notion page id (must be provided)")
|
||||
@@ -70,7 +70,7 @@ program
|
||||
// Create query engine
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const rl = readline.createInterface({ input, output });
|
||||
const rl = createInterface({ input, output });
|
||||
while (true) {
|
||||
const query = await rl.question("Query: ");
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { VectorStoreIndex } from "llamaindex";
|
||||
import { PDFReader } from "llamaindex/readers/PDFReader";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
async function main() {
|
||||
// Load PDF
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData(
|
||||
resolve(__dirname, "../data/brk-2022.pdf"),
|
||||
);
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents);
|
||||
@@ -0,0 +1,36 @@
|
||||
import { FireworksEmbedding, FireworksLLM, VectorStoreIndex } from "llamaindex";
|
||||
import { PDFReader } from "llamaindex/readers/PDFReader";
|
||||
|
||||
import { serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const embedModel = new FireworksEmbedding({
|
||||
model: "nomic-ai/nomic-embed-text-v1.5",
|
||||
});
|
||||
|
||||
const llm = new FireworksLLM({
|
||||
model: "accounts/fireworks/models/mixtral-8x7b-instruct",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
|
||||
|
||||
async function main() {
|
||||
// Load PDF
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What mistakes did Warren E. Buffett make?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,36 @@
|
||||
import { OpenAI, OpenAIEmbedding, VectorStoreIndex } from "llamaindex";
|
||||
import { PDFReader } from "llamaindex/readers/PDFReader";
|
||||
|
||||
import { serviceContextFromDefaults } from "llamaindex";
|
||||
|
||||
const embedModel = new OpenAIEmbedding({
|
||||
model: "nomic-ai/nomic-embed-text-v1.5",
|
||||
});
|
||||
|
||||
const llm = new OpenAI({
|
||||
model: "accounts/fireworks/models/mixtral-8x7b-instruct",
|
||||
});
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({ llm, embedModel });
|
||||
|
||||
async function main() {
|
||||
// Load PDF
|
||||
const reader = new PDFReader();
|
||||
const documents = await reader.loadData("../data/brk-2022.pdf");
|
||||
|
||||
// Split text and create embeddings. Store them in a VectorStoreIndex
|
||||
const index = await VectorStoreIndex.fromDocuments(documents, {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
const response = await queryEngine.query({
|
||||
query: "What mistakes did Warren E. Buffett make?",
|
||||
});
|
||||
|
||||
// Output response
|
||||
console.log(response.toString());
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
@@ -0,0 +1,10 @@
|
||||
import { SimpleDirectoryReader } from "llamaindex/readers/SimpleDirectoryReader";
|
||||
// or
|
||||
// import { SimpleDirectoryReader } from 'llamaindex'
|
||||
|
||||
const reader = new SimpleDirectoryReader();
|
||||
const documents = await reader.loadData("../data");
|
||||
|
||||
documents.forEach((doc) => {
|
||||
console.log(`document (${doc.id_}):`, doc.getText());
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2017",
|
||||
"module": "node16",
|
||||
"moduleResolution": "node16",
|
||||
"outDir": "./dist",
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["./src/**/*.ts"]
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import {
|
||||
CohereRerank,
|
||||
Document,
|
||||
OpenAI,
|
||||
VectorStoreIndex,
|
||||
serviceContextFromDefaults,
|
||||
} from "llamaindex";
|
||||
|
||||
import essay from "../essay";
|
||||
|
||||
async function main() {
|
||||
const document = new Document({ text: essay, id_: "essay" });
|
||||
|
||||
const serviceContext = serviceContextFromDefaults({
|
||||
llm: new OpenAI({ model: "gpt-3.5-turbo", temperature: 0.1 }),
|
||||
});
|
||||
|
||||
const index = await VectorStoreIndex.fromDocuments([document], {
|
||||
serviceContext,
|
||||
});
|
||||
|
||||
const retriever = index.asRetriever();
|
||||
|
||||
retriever.similarityTopK = 5;
|
||||
|
||||
const nodePostprocessor = new CohereRerank({
|
||||
apiKey: "<COHERE_API_KEY>",
|
||||
topN: 5,
|
||||
});
|
||||
|
||||
const queryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
nodePostprocessors: [nodePostprocessor],
|
||||
});
|
||||
|
||||
const baseQueryEngine = index.asQueryEngine({
|
||||
retriever,
|
||||
});
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do growing up?",
|
||||
});
|
||||
|
||||
// cohere response
|
||||
console.log(response.response);
|
||||
|
||||
const baseResponse = await baseQueryEngine.query({
|
||||
query: "What did the author do growing up?",
|
||||
});
|
||||
|
||||
// response without cohere
|
||||
console.log(baseResponse.response);
|
||||
}
|
||||
|
||||
main().catch(console.error);
|
||||
+17
-10
@@ -1,4 +1,9 @@
|
||||
import { Document, SubQuestionQueryEngine, VectorStoreIndex } from "llamaindex";
|
||||
import {
|
||||
Document,
|
||||
QueryEngineTool,
|
||||
SubQuestionQueryEngine,
|
||||
VectorStoreIndex,
|
||||
} from "llamaindex";
|
||||
|
||||
import essay from "./essay";
|
||||
|
||||
@@ -6,16 +11,18 @@ import essay from "./essay";
|
||||
const document = new Document({ text: essay, id_: essay });
|
||||
const index = await VectorStoreIndex.fromDocuments([document]);
|
||||
|
||||
const queryEngine = SubQuestionQueryEngine.fromDefaults({
|
||||
queryEngineTools: [
|
||||
{
|
||||
queryEngine: index.asQueryEngine(),
|
||||
metadata: {
|
||||
name: "pg_essay",
|
||||
description: "Paul Graham essay on What I Worked On",
|
||||
},
|
||||
const queryEngineTools = [
|
||||
new QueryEngineTool({
|
||||
queryEngine: index.asQueryEngine(),
|
||||
metadata: {
|
||||
name: "pg_essay",
|
||||
description: "Paul Graham essay on What I Worked On",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const queryEngine = SubQuestionQueryEngine.fromDefaults({
|
||||
queryEngineTools,
|
||||
});
|
||||
|
||||
const response = await queryEngine.query({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2016",
|
||||
"target": "es2017",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"esModuleInterop": true,
|
||||
@@ -10,13 +10,13 @@
|
||||
"outDir": "./lib",
|
||||
"tsBuildInfoFile": "./lib/.tsbuildinfo",
|
||||
"incremental": true,
|
||||
"composite": true,
|
||||
"composite": true
|
||||
},
|
||||
"ts-node": {
|
||||
"files": true,
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
},
|
||||
"module": "commonjs"
|
||||
}
|
||||
},
|
||||
"include": ["./**/*.ts"],
|
||||
"include": ["./**/*.ts"]
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ async function main() {
|
||||
|
||||
// Query the index
|
||||
const queryEngine = index.asQueryEngine();
|
||||
|
||||
const response = await queryEngine.query({
|
||||
query: "What did the author do in college?",
|
||||
});
|
||||
|
||||
+5
-9
@@ -18,20 +18,16 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.27.1",
|
||||
"@turbo/gen": "^1.11.3",
|
||||
"@types/jest": "^29.5.11",
|
||||
"eslint": "^8.56.0",
|
||||
"eslint-config-custom": "workspace:*",
|
||||
"husky": "^9.0.6",
|
||||
"jest": "^29.7.0",
|
||||
"lint-staged": "^15.2.0",
|
||||
"prettier": "^3.2.4",
|
||||
"husky": "^9.0.10",
|
||||
"lint-staged": "^15.2.2",
|
||||
"prettier": "^3.2.5",
|
||||
"prettier-plugin-organize-imports": "^3.2.4",
|
||||
"ts-jest": "^29.1.2",
|
||||
"turbo": "^1.11.3",
|
||||
"turbo": "^1.12.3",
|
||||
"typescript": "^5.3.3"
|
||||
},
|
||||
"packageManager": "pnpm@8.14.3+sha256.2d0363bb6c314daa67087ef07743eea1ba2e2d360c835e8fec6b5575e4ed9484",
|
||||
"packageManager": "pnpm@8.15.1",
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"trim": "1.0.1",
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript"
|
||||
},
|
||||
"target": "esnext"
|
||||
},
|
||||
"module": {
|
||||
"type": "commonjs"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"jsc": {
|
||||
"parser": {
|
||||
"syntax": "typescript"
|
||||
},
|
||||
"target": "esnext"
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,40 @@
|
||||
# llamaindex
|
||||
|
||||
## 0.1.12
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- a5e4e6d: Add using a managed index from LlamaCloud
|
||||
- cfdd6db: fix: update pinecone vector store
|
||||
- 59f9fb6: Add Fireworks to LlamaIndex
|
||||
- 95add73: feat: multi-document agent
|
||||
|
||||
## 0.1.11
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 255ae7d: chore: update example (perfoms better with default model)
|
||||
- cf3b757: feat: add filtering of metadata to PGVectorStore
|
||||
- ee9f3f3: chore: refactor openai agent utils
|
||||
- e78e9f4: feat(reranker): cohere reranker
|
||||
- f205358: feat: markdown node parser
|
||||
- dd05413: feat: use batching in vector store index
|
||||
- 383933a: Add reader for LlamaParse
|
||||
|
||||
## 0.1.10
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- b6c1500: feat(embedBatchSize): add batching for embeddings
|
||||
- 6cc3a36: fix: update `VectorIndexRetriever` constructor parameters' type.
|
||||
- cd82947: feat(queryEngineTool): add query engine tool to agents
|
||||
|
||||
## 0.1.9
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- 09464e6: add OpenAIAgent (thanks @EmanuelCampos)
|
||||
|
||||
## 0.1.8
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
/** @type {import('ts-jest').JestConfigWithTsJest} */
|
||||
module.exports = {
|
||||
preset: "ts-jest",
|
||||
testEnvironment: "node",
|
||||
testPathIgnorePatterns: ["/lib/", "/node_modules/", "/dist/"],
|
||||
};
|
||||
+47
-158
@@ -1,26 +1,31 @@
|
||||
{
|
||||
"name": "llamaindex",
|
||||
"private": true,
|
||||
"version": "0.1.8",
|
||||
"version": "0.1.12",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.12.4",
|
||||
"@anthropic-ai/sdk": "^0.13.0",
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@datastax/astra-db-ts": "^0.1.4",
|
||||
"@llamaindex/cloud": "^0.0.1",
|
||||
"@llamaindex/env": "workspace:*",
|
||||
"@mistralai/mistralai": "^0.0.10",
|
||||
"@notionhq/client": "^2.2.14",
|
||||
"@pinecone-database/pinecone": "^1.1.3",
|
||||
"@pinecone-database/pinecone": "^2.0.1",
|
||||
"@qdrant/js-client-rest": "^1.7.0",
|
||||
"@xenova/transformers": "^2.14.1",
|
||||
"assemblyai": "^4.2.1",
|
||||
"@xenova/transformers": "^2.15.0",
|
||||
"assemblyai": "^4.2.2",
|
||||
"chromadb": "~1.7.3",
|
||||
"cohere-ai": "^7.7.5",
|
||||
"file-type": "^18.7.0",
|
||||
"js-tiktoken": "^1.0.8",
|
||||
"js-tiktoken": "^1.0.10",
|
||||
"lodash": "^4.17.21",
|
||||
"mammoth": "^1.6.0",
|
||||
"md-utils-ts": "^2.0.0",
|
||||
"mongodb": "^6.3.0",
|
||||
"notion-md-crawler": "^0.0.2",
|
||||
"openai": "^4.26.0",
|
||||
"openai": "^4.26.1",
|
||||
"papaparse": "^5.4.1",
|
||||
"pathe": "^1.1.2",
|
||||
"pdf2json": "^3.0.5",
|
||||
@@ -29,164 +34,50 @@
|
||||
"portkey-ai": "^0.1.16",
|
||||
"rake-modified": "^1.0.8",
|
||||
"replicate": "^0.25.2",
|
||||
"string-strip-html": "^13.4.5",
|
||||
"string-strip-html": "^13.4.6",
|
||||
"wink-nlp": "^1.14.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@aws-crypto/sha256-js": "^5.2.0",
|
||||
"@types/edit-json-file": "^1.7.3",
|
||||
"@types/jest": "^29.5.11",
|
||||
"@swc/cli": "^0.3.9",
|
||||
"@swc/core": "^1.4.2",
|
||||
"@types/lodash": "^4.14.202",
|
||||
"@types/node": "^18.19.10",
|
||||
"@types/node": "^18.19.14",
|
||||
"@types/papaparse": "^5.3.14",
|
||||
"@types/pg": "^8.11.0",
|
||||
"bunchee": "^4.4.3",
|
||||
"edit-json-file": "^1.8.0",
|
||||
"concurrently": "^8.2.2",
|
||||
"glob": "^10.3.10",
|
||||
"madge": "^6.1.0",
|
||||
"typescript": "^5.3.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"types": "./dist/index.d.ts",
|
||||
"main": "./dist/index.js",
|
||||
"types": "./dist/type/index.d.ts",
|
||||
"main": "./dist/cjs/index.cjs",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.mts",
|
||||
"import": "./dist/index.mjs",
|
||||
"edge-light": "./dist/index.edge-light.mjs",
|
||||
"require": "./dist/index.js"
|
||||
"import": {
|
||||
"types": "./dist/type/index.d.ts",
|
||||
"default": "./dist/index.js"
|
||||
},
|
||||
"edge-light": {
|
||||
"types": "./dist/type/index.d.ts",
|
||||
"default": "./dist/index.edge-light.js"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/type/index.d.ts",
|
||||
"default": "./dist/cjs/index.cjs"
|
||||
}
|
||||
},
|
||||
"./env": {
|
||||
"types": "./dist/env.d.mts",
|
||||
"import": "./dist/env.mjs",
|
||||
"edge-light": "./dist/env.edge-light.mjs",
|
||||
"require": "./dist/env.js"
|
||||
},
|
||||
"./ChatEngine": {
|
||||
"types": "./dist/ChatEngine.d.mts",
|
||||
"import": "./dist/ChatEngine.mjs",
|
||||
"require": "./dist/ChatEngine.js"
|
||||
},
|
||||
"./ChatHistory": {
|
||||
"types": "./dist/ChatHistory.d.mts",
|
||||
"import": "./dist/ChatHistory.mjs",
|
||||
"require": "./dist/ChatHistory.js"
|
||||
},
|
||||
"./constants": {
|
||||
"types": "./dist/constants.d.mts",
|
||||
"import": "./dist/constants.mjs",
|
||||
"require": "./dist/constants.js"
|
||||
},
|
||||
"./GlobalsHelper": {
|
||||
"types": "./dist/GlobalsHelper.d.mts",
|
||||
"import": "./dist/GlobalsHelper.mjs",
|
||||
"require": "./dist/GlobalsHelper.js"
|
||||
},
|
||||
"./Node": {
|
||||
"types": "./dist/Node.d.mts",
|
||||
"import": "./dist/Node.mjs",
|
||||
"require": "./dist/Node.js"
|
||||
},
|
||||
"./OutputParser": {
|
||||
"types": "./dist/OutputParser.d.mts",
|
||||
"import": "./dist/OutputParser.mjs",
|
||||
"require": "./dist/OutputParser.js"
|
||||
},
|
||||
"./Prompt": {
|
||||
"types": "./dist/Prompt.d.mts",
|
||||
"import": "./dist/Prompt.mjs",
|
||||
"require": "./dist/Prompt.js"
|
||||
},
|
||||
"./PromptHelper": {
|
||||
"types": "./dist/PromptHelper.d.mts",
|
||||
"import": "./dist/PromptHelper.mjs",
|
||||
"require": "./dist/PromptHelper.js"
|
||||
},
|
||||
"./QueryEngine": {
|
||||
"types": "./dist/QueryEngine.d.mts",
|
||||
"import": "./dist/QueryEngine.mjs",
|
||||
"require": "./dist/QueryEngine.js"
|
||||
},
|
||||
"./QuestionGenerator": {
|
||||
"types": "./dist/QuestionGenerator.d.mts",
|
||||
"import": "./dist/QuestionGenerator.mjs",
|
||||
"require": "./dist/QuestionGenerator.js"
|
||||
},
|
||||
"./Response": {
|
||||
"types": "./dist/Response.d.mts",
|
||||
"import": "./dist/Response.mjs",
|
||||
"require": "./dist/Response.js"
|
||||
},
|
||||
"./Retriever": {
|
||||
"types": "./dist/Retriever.d.mts",
|
||||
"import": "./dist/Retriever.mjs",
|
||||
"require": "./dist/Retriever.js"
|
||||
},
|
||||
"./ServiceContext": {
|
||||
"types": "./dist/ServiceContext.d.mts",
|
||||
"import": "./dist/ServiceContext.mjs",
|
||||
"require": "./dist/ServiceContext.js"
|
||||
},
|
||||
"./TextSplitter": {
|
||||
"types": "./dist/TextSplitter.d.mts",
|
||||
"import": "./dist/TextSplitter.mjs",
|
||||
"require": "./dist/TextSplitter.js"
|
||||
},
|
||||
"./Tool": {
|
||||
"types": "./dist/Tool.d.mts",
|
||||
"import": "./dist/Tool.mjs",
|
||||
"require": "./dist/Tool.js"
|
||||
},
|
||||
"./readers/AssemblyAIReader": {
|
||||
"types": "./dist/readers/AssemblyAIReader.d.mts",
|
||||
"import": "./dist/readers/AssemblyAIReader.mjs",
|
||||
"require": "./dist/readers/AssemblyAIReader.js"
|
||||
},
|
||||
"./readers/CSVReader": {
|
||||
"types": "./dist/readers/CSVReader.d.mts",
|
||||
"import": "./dist/readers/CSVReader.mjs",
|
||||
"require": "./dist/readers/CSVReader.js"
|
||||
},
|
||||
"./readers/DocxReader": {
|
||||
"types": "./dist/readers/DocxReader.d.mts",
|
||||
"import": "./dist/readers/DocxReader.mjs",
|
||||
"require": "./dist/readers/DocxReader.js"
|
||||
},
|
||||
"./readers/HTMLReader": {
|
||||
"types": "./dist/readers/HTMLReader.d.mts",
|
||||
"import": "./dist/readers/HTMLReader.mjs",
|
||||
"require": "./dist/readers/HTMLReader.js"
|
||||
},
|
||||
"./readers/ImageReader": {
|
||||
"types": "./dist/readers/ImageReader.d.mts",
|
||||
"import": "./dist/readers/ImageReader.mjs",
|
||||
"require": "./dist/readers/ImageReader.js"
|
||||
},
|
||||
"./readers/MarkdownReader": {
|
||||
"types": "./dist/readers/MarkdownReader.d.mts",
|
||||
"import": "./dist/readers/MarkdownReader.mjs",
|
||||
"require": "./dist/readers/MarkdownReader.js"
|
||||
},
|
||||
"./readers/NotionReader": {
|
||||
"types": "./dist/readers/NotionReader.d.mts",
|
||||
"import": "./dist/readers/NotionReader.mjs",
|
||||
"require": "./dist/readers/NotionReader.js"
|
||||
},
|
||||
"./readers/PDFReader": {
|
||||
"types": "./dist/readers/PDFReader.d.mts",
|
||||
"import": "./dist/readers/PDFReader.mjs",
|
||||
"require": "./dist/readers/PDFReader.js"
|
||||
},
|
||||
"./readers/SimpleDirectoryReader": {
|
||||
"types": "./dist/readers/SimpleDirectoryReader.d.mts",
|
||||
"import": "./dist/readers/SimpleDirectoryReader.mjs",
|
||||
"require": "./dist/readers/SimpleDirectoryReader.js"
|
||||
},
|
||||
"./readers/SimpleMongoReader": {
|
||||
"types": "./dist/readers/SimpleMongoReader.d.mts",
|
||||
"import": "./dist/readers/SimpleMongoReader.mjs",
|
||||
"require": "./dist/readers/SimpleMongoReader.js"
|
||||
"./*": {
|
||||
"import": {
|
||||
"types": "./dist/type/*.d.ts",
|
||||
"default": "./dist/*.js"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/type/*.d.ts",
|
||||
"default": "./dist/cjs/*.cjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
@@ -199,13 +90,11 @@
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "eslint .",
|
||||
"test": "jest",
|
||||
"build": "rm -rf ./dist && NODE_OPTIONS=\"--max-old-space-size=8192\" bunchee",
|
||||
"postbuild": "pnpm run copy && pnpm run modify-package-json",
|
||||
"copy": "cp -r package.json CHANGELOG.md ../../README.md ../../LICENSE examples src dist/",
|
||||
"modify-package-json": "node ./scripts/modify-package-json.mjs",
|
||||
"prepublish": "pnpm run modify-package-json && echo \"please cd ./dist and run pnpm publish\" && exit 1",
|
||||
"dev": "NODE_OPTIONS=\"--max-old-space-size=8192\" bunchee -w",
|
||||
"circular-check": "madge -c ./src/index.ts"
|
||||
"build": "rm -rf ./dist && pnpm run build:esm && pnpm run build:cjs && pnpm run build:type",
|
||||
"build:esm": "swc src -d dist --strip-leading-paths --config-file .swcrc",
|
||||
"build:cjs": "swc src -d dist/cjs --strip-leading-paths --config-file .cjs.swcrc --out-file-extension cjs",
|
||||
"build:type": "tsc -p tsconfig.json",
|
||||
"circular-check": "madge -c ./src/index.ts",
|
||||
"dev": "concurrently \"pnpm run build:esm --watch\" \"pnpm run build:cjs --watch\" \"pnpm run build:type --watch\""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* This script is used to modify the package.json file in the dist folder
|
||||
* so that it can be published to npm.
|
||||
*/
|
||||
import editJsonFile from "edit-json-file";
|
||||
import fs from "node:fs/promises";
|
||||
|
||||
{
|
||||
await fs.copyFile("./package.json", "./dist/package.json");
|
||||
const file = editJsonFile("./dist/package.json");
|
||||
|
||||
file.unset("scripts");
|
||||
file.unset("private");
|
||||
await new Promise((resolve) => file.save(resolve));
|
||||
}
|
||||
{
|
||||
const packageJson = await fs.readFile("./dist/package.json", "utf8");
|
||||
const modifiedPackageJson = packageJson.replaceAll("./dist/", "./");
|
||||
await fs.writeFile(
|
||||
"./dist/package.json",
|
||||
JSON.stringify(JSON.parse(modifiedPackageJson), null, 2),
|
||||
"utf8",
|
||||
);
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { OpenAI } from "./llm/LLM";
|
||||
import { ChatMessage, LLM, MessageType } from "./llm/types";
|
||||
import { OpenAI } from "./llm/LLM.js";
|
||||
import { ChatMessage, LLM, MessageType } from "./llm/types.js";
|
||||
import {
|
||||
defaultSummaryPrompt,
|
||||
messagesToHistoryStr,
|
||||
SummaryPrompt,
|
||||
} from "./Prompt";
|
||||
} from "./Prompt.js";
|
||||
|
||||
/**
|
||||
* A ChatHistory is used to keep the state of back and forth chat messages
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { encodingForModel } from "js-tiktoken";
|
||||
|
||||
import { Event, EventTag, EventType } from "./callbacks/CallbackManager";
|
||||
import { randomUUID } from "./env";
|
||||
import { randomUUID } from "@llamaindex/env";
|
||||
import { Event, EventTag, EventType } from "./callbacks/CallbackManager.js";
|
||||
|
||||
export enum Tokenizers {
|
||||
CL100K_BASE = "cl100k_base",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createSHA256, path, randomUUID } from "@llamaindex/env";
|
||||
import _ from "lodash";
|
||||
import { createSHA256, path, randomUUID } from "./env";
|
||||
|
||||
export enum NodeRelationship {
|
||||
SOURCE = "SOURCE",
|
||||
@@ -353,10 +353,10 @@ export function splitNodesByType(nodes: BaseNode[]): {
|
||||
imageNodes: ImageNode[];
|
||||
textNodes: TextNode[];
|
||||
} {
|
||||
let imageNodes: ImageNode[] = [];
|
||||
let textNodes: TextNode[] = [];
|
||||
const imageNodes: ImageNode[] = [];
|
||||
const textNodes: TextNode[] = [];
|
||||
|
||||
for (let node of nodes) {
|
||||
for (const node of nodes) {
|
||||
if (node instanceof ImageNode) {
|
||||
imageNodes.push(node);
|
||||
} else if (node instanceof TextNode) {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { SubQuestion } from "./engines/query/types";
|
||||
import { BaseOutputParser, StructuredOutput } from "./types";
|
||||
import { SubQuestion } from "./engines/query/types.js";
|
||||
import { BaseOutputParser, StructuredOutput } from "./types.js";
|
||||
|
||||
/**
|
||||
* Error class for output parsing. Due to the nature of LLMs, anytime we use LLM
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { SubQuestion } from "./engines/query/types";
|
||||
import { ChatMessage } from "./llm/types";
|
||||
import { ToolMetadata } from "./types";
|
||||
import { SubQuestion } from "./engines/query/types.js";
|
||||
import { ChatMessage } from "./llm/types.js";
|
||||
import { ToolMetadata } from "./types.js";
|
||||
|
||||
/**
|
||||
* A SimplePrompt is a function that takes a dictionary of inputs and returns a string.
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { globalsHelper } from "./GlobalsHelper";
|
||||
import { SimplePrompt } from "./Prompt";
|
||||
import { SentenceSplitter } from "./TextSplitter";
|
||||
import { globalsHelper } from "./GlobalsHelper.js";
|
||||
import { SimplePrompt } from "./Prompt.js";
|
||||
import { SentenceSplitter } from "./TextSplitter.js";
|
||||
import {
|
||||
DEFAULT_CHUNK_OVERLAP_RATIO,
|
||||
DEFAULT_CONTEXT_WINDOW,
|
||||
DEFAULT_NUM_OUTPUTS,
|
||||
DEFAULT_PADDING,
|
||||
} from "./constants";
|
||||
} from "./constants.js";
|
||||
|
||||
export function getEmptyPromptTxt(prompt: SimplePrompt) {
|
||||
return prompt({});
|
||||
|
||||
@@ -1,28 +1,48 @@
|
||||
import { SubQuestionOutputParser } from "./OutputParser";
|
||||
import { SubQuestionOutputParser } from "./OutputParser.js";
|
||||
import {
|
||||
SubQuestionPrompt,
|
||||
buildToolsText,
|
||||
defaultSubQuestionPrompt,
|
||||
} from "./Prompt";
|
||||
import { BaseQuestionGenerator, SubQuestion } from "./engines/query/types";
|
||||
import { OpenAI } from "./llm/LLM";
|
||||
import { LLM } from "./llm/types";
|
||||
import { BaseOutputParser, StructuredOutput, ToolMetadata } from "./types";
|
||||
} from "./Prompt.js";
|
||||
import { BaseQuestionGenerator, SubQuestion } from "./engines/query/types.js";
|
||||
import { OpenAI } from "./llm/LLM.js";
|
||||
import { LLM } from "./llm/types.js";
|
||||
import { PromptMixin } from "./prompts/index.js";
|
||||
import { BaseOutputParser, StructuredOutput, ToolMetadata } from "./types.js";
|
||||
|
||||
/**
|
||||
* LLMQuestionGenerator uses the LLM to generate new questions for the LLM using tools and a user query.
|
||||
*/
|
||||
export class LLMQuestionGenerator implements BaseQuestionGenerator {
|
||||
export class LLMQuestionGenerator
|
||||
extends PromptMixin
|
||||
implements BaseQuestionGenerator
|
||||
{
|
||||
llm: LLM;
|
||||
prompt: SubQuestionPrompt;
|
||||
outputParser: BaseOutputParser<StructuredOutput<SubQuestion[]>>;
|
||||
|
||||
constructor(init?: Partial<LLMQuestionGenerator>) {
|
||||
super();
|
||||
|
||||
this.llm = init?.llm ?? new OpenAI();
|
||||
this.prompt = init?.prompt ?? defaultSubQuestionPrompt;
|
||||
this.outputParser = init?.outputParser ?? new SubQuestionOutputParser();
|
||||
}
|
||||
|
||||
protected _getPrompts(): { [x: string]: SubQuestionPrompt } {
|
||||
return {
|
||||
subQuestion: this.prompt,
|
||||
};
|
||||
}
|
||||
|
||||
protected _updatePrompts(promptsDict: {
|
||||
subQuestion: SubQuestionPrompt;
|
||||
}): void {
|
||||
if ("subQuestion" in promptsDict) {
|
||||
this.prompt = promptsDict.subQuestion;
|
||||
}
|
||||
}
|
||||
|
||||
async generate(tools: ToolMetadata[], query: string): Promise<SubQuestion[]> {
|
||||
const toolsStr = buildToolsText(tools);
|
||||
const queryStr = query;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { BaseNode } from "./Node";
|
||||
import { BaseNode } from "./Node.js";
|
||||
|
||||
/**
|
||||
* Response is the output of a LLM
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Event } from "./callbacks/CallbackManager";
|
||||
import { NodeWithScore } from "./Node";
|
||||
import { ServiceContext } from "./ServiceContext";
|
||||
import { Event } from "./callbacks/CallbackManager.js";
|
||||
import { NodeWithScore } from "./Node.js";
|
||||
import { ServiceContext } from "./ServiceContext.js";
|
||||
|
||||
/**
|
||||
* Retrievers retrieve the nodes that most closely match our query in similarity.
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { CallbackManager } from "./callbacks/CallbackManager";
|
||||
import { BaseEmbedding, OpenAIEmbedding } from "./embeddings";
|
||||
import { LLM, OpenAI } from "./llm";
|
||||
import { NodeParser, SimpleNodeParser } from "./nodeParsers";
|
||||
import { PromptHelper } from "./PromptHelper";
|
||||
import { PromptHelper } from "./PromptHelper.js";
|
||||
import { CallbackManager } from "./callbacks/CallbackManager.js";
|
||||
import { OpenAIEmbedding } from "./embeddings/OpenAIEmbedding.js";
|
||||
import { BaseEmbedding } from "./embeddings/types.js";
|
||||
import { LLM, OpenAI } from "./llm/index.js";
|
||||
import { SimpleNodeParser } from "./nodeParsers/SimpleNodeParser.js";
|
||||
import { NodeParser } from "./nodeParsers/types.js";
|
||||
|
||||
/**
|
||||
* The ServiceContext is a collection of components that are used in different parts of the application.
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user