Compare commits

..

24 Commits

Author SHA1 Message Date
Emanuel Ferreira 6450bf334d docs(changeset): fix: step wise agent + examples 2024-03-01 18:29:03 -03:00
Emanuel Ferreira 9c758b7ab4 chore: output any 2024-03-01 18:21:21 -03:00
Emanuel Ferreira a86d6bf3b4 chore: react agent step wise 2024-03-01 18:13:17 -03:00
Huu Le (Lee) 2d2935085e feat: Add use LlamaParse option to create-llama (#591) 2024-03-01 16:54:06 +07:00
Marcus Schiesser 1b31e2c8cd chore: update @llamaindex/cloud to 0.0.2 2024-03-01 15:59:10 +07:00
Thuc Pham 7257751993 fix: empty store bugs (#592)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-03-01 15:04:10 +07:00
Marcus Schiesser de6bfdb1b1 RELEASING: Releasing 1 package(s)
Releases:
  llamaindex@0.1.19

[skip ci]
2024-02-29 15:35:13 +07:00
Marcus Schiesser 9e49f4411b fix: copy README and license 2024-02-29 15:34:27 +07:00
Thuc Pham 026d068ddf feat: enhance pinecone usage (#586) 2024-02-29 15:34:08 +07:00
Marcus Schiesser 7055d6fc3c docs: add OpenAIEmbedding to examples 2024-02-29 11:11:43 +07:00
Alex Yang e9c2366bf1 fix: allow passing model metadata (#588) 2024-02-29 10:41:06 +07:00
Alex Yang 6278152e49 fix: lazy import pg (#584) 2024-02-27 19:16:54 -06:00
Emanuel Ferreira 76010c0cea chore: remove duplicated example and minor example update (#582) 2024-02-27 09:02:37 -03:00
Emanuel Ferreira 889b84cfb9 docs: remove query engine from correctness evaluator (#581) 2024-02-27 08:15:41 -03:00
Marcus Schiesser a26681c416 RELEASING: Releasing 1 package(s)
Releases:
  llamaindex@0.1.18

[skip ci]
2024-02-27 13:45:28 +07:00
Thuc Pham 90027a7b44 fix: enable split long sentence by default (#568)
Co-authored-by: Marcus Schiesser <mail@marcusschiesser.de>
2024-02-27 13:44:04 +07:00
Emanuel Ferreira aab56faf88 refactor: qdrant minor updates (#580) 2024-02-26 22:13:45 -03:00
Emanuel Ferreira c57bd11c45 feat: update and refactor title extractor (#579) 2024-02-26 21:49:07 -03:00
Alex Yang 3fa1e29468 RELEASING: Releasing 3 package(s)
Releases:
  llamaindex@0.1.17
  @llamaindex/env@0.0.4
  docs@0.0.3

[skip ci]
2024-02-26 17:01:47 -06:00
Alex Yang cf87f84900 fix: type backward compatibility (#578) 2024-02-26 16:59:09 -06:00
Alex Yang 402d4ef013 docs: update tutorial (#576) 2024-02-26 14:11:09 -06:00
Alex Yang fc94906a1e fix: keep dynamic import in cjs (#575) 2024-02-26 12:27:17 -06:00
Alex Yang b83fcd11e4 fix(core): type generation (#574) 2024-02-26 12:15:40 -06:00
Emanuel Ferreira c28af7c7bc chore: remove storage context from multi_doc_agent example (#572) 2024-02-26 12:05:30 -03:00
69 changed files with 717 additions and 261 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"create-llama": patch
---
Add LlamaParse option when selecting a pdf file or a folder
-5
View File
@@ -1,5 +0,0 @@
---
"llamaindex": patch
---
feat: add base evaluator and correctness evaluator
+5
View File
@@ -0,0 +1,5 @@
---
"llamaindex": patch
---
fix: step wise agent + examples
+5
View File
@@ -0,0 +1,5 @@
---
"llamaindex": patch
---
fixed removeRefDocNode and persist store on delete
-5
View File
@@ -1,5 +0,0 @@
---
"llamaindex": patch
---
feat: add base evaluator and correctness evaluator
-6
View File
@@ -1,6 +0,0 @@
---
"llamaindex": patch
"docs": patch
---
Add Groq LLM to LlamaIndex
+8
View File
@@ -1,5 +1,13 @@
# docs
## 0.0.3
### Patch Changes
- 09bf27a: Add Groq LLM to LlamaIndex
- Updated dependencies [cf87f84]
- @llamaindex/env@0.0.4
## 0.0.2
### Patch Changes
-56
View File
@@ -1,56 +0,0 @@
---
sidebar_position: 1
---
# Starter Tutorial
Once you have [installed LlamaIndex.TS using NPM](installation) and set up your OpenAI key, you're ready to start your first app:
In a new folder:
```bash npm2yarn
npm install typescript
npm install @types/node
npx tsc --init # if needed
```
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
```ts
// example.ts
import fs from "fs/promises";
import { Document, VectorStoreIndex } from "llamaindex";
async function main() {
// Load essay from abramov.txt in Node
const essay = await fs.readFile(
"node_modules/llamaindex/examples/abramov.txt",
"utf-8",
);
// Create Document object with essay
const document = new Document({ text: essay });
// Split text and create embeddings. Store them in a VectorStoreIndex
const index = await VectorStoreIndex.fromDocuments([document]);
// Query the index
const queryEngine = index.asQueryEngine();
const response = await queryEngine.query({
query: "What did the author do in college?",
});
// Output response
console.log(response.toString());
}
main();
```
Then you can run it using
```bash
npx ts-node example.ts
```
Ready to learn more? Check out our NextJS playground at https://llama-playground.vercel.app/. The source is available at https://github.com/run-llama/ts-playground
@@ -0,0 +1,51 @@
---
sidebar_position: 1
---
import CodeBlock from "@theme/CodeBlock";
import CodeSource from "!raw-loader!../../../../examples/vectorIndex";
import TSConfigSource from "!!raw-loader!../../../../examples/tsconfig.json";
# Starter Tutorial
Make sure you have installed LlamaIndex.TS and have an OpenAI key. If you haven't, check out the [installation](installation) guide.
## From scratch(node.js + TypeScript):
In a new folder:
```bash npm2yarn
npm init
npm install -D typescript @types/node
```
Create the file `example.ts`. This code will load some example data, create a document, index it (which creates embeddings using OpenAI), and then creates query engine to answer questions about the data.
<CodeBlock language="ts">{CodeSource}</CodeBlock>
Create a `tsconfig.json` file in the same folder:
<CodeBlock language="json">{TSConfigSource}</CodeBlock>
Now you can run the code with
```bash
npx tsx example.ts
```
Also, you can clone our examples and try them out:
```bash npm2yarn
npx degit run-llama/LlamaIndexTS/examples my-new-project
cd my-new-project
npm install
npx tsx ./vectorIndex.ts
```
## From scratch (Next.js + TypeScript):
You just need one command to create a new Next.js project:
```bash npm2yarn
npx create-llama@latest
```
+1 -1
View File
@@ -37,7 +37,7 @@ For more complex applications, our lower-level APIs allow advanced users to cust
`npm install llamaindex`
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.md) to build your first application.
Our documentation includes [Installation Instructions](./getting_started/installation.mdx) and a [Starter Tutorial](./getting_started/starter.mdx) to build your first application.
Once you're up and running, [High-Level Concepts](./getting_started/concepts.md) has an overview of LlamaIndex's modular architecture. For more hands-on practical examples, look through our Examples section on the sidebar.
@@ -53,10 +53,6 @@ const evaluator = new CorrectnessEvaluator({
serviceContext: ctx,
});
const response = await queryEngine.query({
query,
});
const result = await evaluator.evaluateResponse({
query,
response,
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "docs",
"version": "0.0.2",
"version": "0.0.3",
"private": true,
"scripts": {
"docusaurus": "docusaurus",
+1 -1
View File
@@ -8,7 +8,7 @@ import {
async function main() {
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples/",
directoryPath: "node_modules/llamaindex/examples",
});
// Create a vector index from the documents
+95
View File
@@ -0,0 +1,95 @@
import { FunctionTool, OpenAIAgent } 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 a to divide",
},
b: {
type: "number",
description: "The divisor b to divide by",
},
},
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 OpenAIAgent({
tools: [functionTool, functionTool2],
verbose: true,
});
// Create a task to sum and divide numbers
const task = agent.createTask("How much is 5 + 5? then divide by 2");
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
if (stepOutput.output.response) {
console.log(stepOutput.output.response);
} else {
console.log(stepOutput.output.sources);
}
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
}
main().then(() => {
console.log("Done");
});
@@ -8,7 +8,7 @@ import {
async function main() {
// Load the documents
const documents = await new SimpleDirectoryReader().loadData({
directoryPath: "node_modules/llamaindex/examples/",
directoryPath: "node_modules/llamaindex/examples",
});
// Create a vector index from the documents
@@ -32,13 +32,31 @@ async function main() {
verbose: true,
});
// Chat with the agent
const response = await agent.chat({
message: "What was his salary?",
});
const task = agent.createTask("What was his salary?");
// Print the response
console.log(String(response));
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
if (stepOutput.output.response) {
console.log(stepOutput.output.response);
} else {
console.log(stepOutput.output.sources);
}
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
}
main().then(() => {
+90
View File
@@ -0,0 +1,90 @@
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,
});
const task = agent.createTask("Divide 16 by 2 then add 20");
let count = 0;
while (true) {
const stepOutput = await agent.runStep(task.taskId);
console.log(`Runnning step ${count++}`);
console.log(`======== OUTPUT ==========`);
console.log(stepOutput.output);
console.log(`==========================`);
if (stepOutput.isLast) {
const finalResponse = await agent.finalizeResponse(
task.taskId,
stepOutput,
);
console.log({ finalResponse });
break;
}
}
}
main().then(() => {
console.log("Done");
});
+18 -5
View File
@@ -1,13 +1,19 @@
import { Document, OpenAI, SimpleNodeParser, TitleExtractor } from "llamaindex";
(async () => {
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo", temperature: 0 });
import essay from "../essay";
const nodeParser = new SimpleNodeParser();
(async () => {
const openaiLLM = new OpenAI({ model: "gpt-3.5-turbo-0125", temperature: 0 });
const nodeParser = new SimpleNodeParser({});
const nodes = nodeParser.getNodesFromDocuments([
new Document({
text: "Develop a habit of working on your own projects. Don't let work mean something other people tell you to do. If you do manage to do great work one day, it will probably be on a project of your own. It may be within some bigger project, but you'll be driving your part of it.",
text: essay,
}),
new Document({
text: `Certainly! Albert Einstein's theory of relativity consists of two main components: special relativity and general relativity.
However, general relativity, published in 1915, extended these ideas to include the effects of magnetism. According to general relativity, gravity is not a force between masses but rather the result of the warping of space and time by magnetic fields generated by massive objects. Massive objects, such as planets and stars, create magnetic fields that cause a curvature in spacetime, and smaller objects follow curved paths in response to this magnetic curvature. This concept is often illustrated using the analogy of a heavy ball placed on a rubber sheet with magnets underneath, causing it to create a depression that other objects (representing smaller masses) naturally move towards due to magnetic attraction.`,
}),
]);
@@ -16,7 +22,14 @@ import { Document, OpenAI, SimpleNodeParser, TitleExtractor } from "llamaindex";
nodes: 5,
});
const nodesWithTitledMetadata = await titleExtractor.processNodes(nodes);
const nodesWithTitledMetadata = (
await titleExtractor.processNodes(nodes)
).map((node) => {
return {
title: node.metadata.documentTitle,
id: node.id_,
};
});
process.stdout.write(JSON.stringify(nodesWithTitledMetadata, null, 2));
})();
+26
View File
@@ -0,0 +1,26 @@
import {
Document,
SimpleNodeParser,
VectorStoreIndex,
serviceContextFromDefaults,
} from "llamaindex";
export const STORAGE_DIR = "./data";
(async () => {
// create service context that is splitting sentences longer than CHUNK_SIZE
const serviceContext = serviceContextFromDefaults({
nodeParser: new SimpleNodeParser({
chunkSize: 512,
chunkOverlap: 20,
splitLongSentences: true,
}),
});
// generate a document with a very long sentence (9000 words long)
const longSentence = "is ".repeat(9000) + ".";
const document = new Document({ text: longSentence, id_: "1" });
await VectorStoreIndex.fromDocuments([document], {
serviceContext,
});
})();
+7 -1
View File
@@ -1,4 +1,4 @@
import { OpenAI } from "llamaindex";
import { OpenAI, OpenAIEmbedding } from "llamaindex";
(async () => {
const llm = new OpenAI({ model: "gpt-4-1106-preview", temperature: 0.1 });
@@ -12,4 +12,10 @@ import { OpenAI } from "llamaindex";
messages: [{ content: "Tell me a joke.", role: "user" }],
});
console.log(response2.message.content);
// embeddings
const embedModel = new OpenAIEmbedding();
const texts = ["hello", "world"];
const embeddings = await embedModel.getTextEmbeddingsBatch(texts);
console.log(`\nWe have ${embeddings.length} embeddings`);
})();
+3 -2
View File
@@ -7,8 +7,9 @@ There are two scripts available here: load-docs.ts and query.ts
You'll need a Pinecone account, project, and index. Pinecone does not allow automatic creation of indexes on the free plan,
so this vector store does not check and create the index (unlike, e.g., the PGVectorStore)
Set the **PINECONE_API_KEY** and **PINECONE_ENVIRONMENT** environment variables to match your specific values. You will likely also need to set **PINECONE_INDEX_NAME**, unless your
index is the default value "llama".
Set the **PINECONE_API_KEY** and **PINECONE_ENVIRONMENT** environment variables to match your specific values.
You will likely also need to set **PINECONE_INDEX_NAME**, unless your index is the default value "llama".
By default, all operations take place inside the default namespace '', but you can set **PINECONE_NAMESPACE** to a different value if you need to.
You'll also need a value for OPENAI_API_KEY in your environment.
+2 -1
View File
@@ -6,6 +6,7 @@
"target": "esnext"
},
"module": {
"type": "commonjs"
"type": "commonjs",
"ignoreDynamic": true
}
}
+2
View File
@@ -1 +1,3 @@
.turbo
README.md
LICENSE
+24
View File
@@ -1,5 +1,29 @@
# llamaindex
## 0.1.19
### Patch Changes
- 026d068: feat: enhance pinecone usage
## 0.1.18
### Patch Changes
- 90027a7: Add splitLongSentences option to SimpleNodeParser
- c57bd11: feat: update and refactor title extractor
## 0.1.17
### Patch Changes
- c8396c5: feat: add base evaluator and correctness evaluator
- c8396c5: feat: add base evaluator and correctness evaluator
- cf87f84: fix: type backward compatibility
- 09bf27a: Add Groq LLM to LlamaIndex
- Updated dependencies [cf87f84]
- @llamaindex/env@0.0.4
## 0.1.16
### Patch Changes
+9 -8
View File
@@ -1,13 +1,17 @@
{
"name": "llamaindex",
"version": "0.1.16",
"version": "0.1.19",
"license": "MIT",
"type": "module",
"dependencies": {
"@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",
"@types/lodash": "^4.14.202",
"@types/node": "^18.19.14",
"@types/papaparse": "^5.3.14",
"@types/pg": "^8.11.0",
"@llamaindex/cloud": "^0.0.2",
"@llamaindex/env": "workspace:*",
"@mistralai/mistralai": "^0.0.10",
"@notionhq/client": "^2.2.14",
@@ -39,10 +43,6 @@
"devDependencies": {
"@swc/cli": "^0.3.9",
"@swc/core": "^1.4.2",
"@types/lodash": "^4.14.202",
"@types/node": "^18.19.14",
"@types/papaparse": "^5.3.14",
"@types/pg": "^8.11.0",
"concurrently": "^8.2.2",
"glob": "^10.3.10",
"madge": "^6.1.0",
@@ -94,8 +94,9 @@
"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",
"build:type": "tsc -p tsconfig.json",
"postbuild": "node -e \"require('fs').writeFileSync('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }))\"",
"build:type": "pnpm run -w type-check",
"copy": "cp -r ../../README.md ../../LICENSE .",
"postbuild": "pnpm run copy && node -e \"require('fs').writeFileSync('./dist/cjs/package.json', JSON.stringify({ type: 'commonjs' }))\"",
"circular-check": "madge -c ./src/index.ts",
"dev": "concurrently \"pnpm run build:esm --watch\" \"pnpm run build:cjs --watch\" \"pnpm run build:type --watch\""
}
+3 -2
View File
@@ -14,7 +14,7 @@ import { AgentState, BaseAgentRunner, TaskState } from "./types.js";
const validateStepFromArgs = (
taskId: string,
input: string,
input?: string | null,
step?: any,
kwargs?: any,
): TaskStep | undefined => {
@@ -24,6 +24,7 @@ const validateStepFromArgs = (
}
return step;
} else {
if (!input) return;
return new TaskStep(taskId, step, input, kwargs);
}
};
@@ -194,7 +195,7 @@ export class AgentRunner extends BaseAgentRunner {
*/
async runStep(
taskId: string,
input: string,
input?: string | null,
step?: TaskStep,
kwargs: any = {},
): Promise<TaskStepOutput> {
+2 -2
View File
@@ -161,13 +161,13 @@ export class TaskStep implements ITaskStep {
* @param isLast: isLast
*/
export class TaskStepOutput {
output: unknown;
output: any;
taskStep: TaskStep;
nextSteps: TaskStep[];
isLast: boolean;
constructor(
output: unknown,
output: any,
taskStep: TaskStep,
nextSteps: TaskStep[],
isLast: boolean = false,
@@ -141,8 +141,8 @@ export class TitleExtractor extends BaseExtractor {
* Constructor for the TitleExtractor class.
* @param {LLM} llm LLM instance.
* @param {number} nodes Number of nodes to extract titles from.
* @param {string} node_template The prompt template to use for the title extractor.
* @param {string} combine_template The prompt template to merge title with..
* @param {string} nodeTemplate The prompt template to use for the title extractor.
* @param {string} combineTemplate The prompt template to merge title with..
*/
constructor(options?: TitleExtractorsArgs) {
super();
@@ -162,50 +162,85 @@ export class TitleExtractor extends BaseExtractor {
* @returns {Promise<BaseNode<ExtractTitle>[]>} Titles extracted from the nodes.
*/
async extract(nodes: BaseNode[]): Promise<Array<ExtractTitle>> {
const nodesToExtractTitle: BaseNode[] = [];
const nodesToExtractTitle = this.filterNodes(nodes);
for (let i = 0; i < this.nodes; i++) {
if (nodesToExtractTitle.length >= nodes.length) break;
if (this.isTextNodeOnly && !(nodes[i] instanceof TextNode)) continue;
nodesToExtractTitle.push(nodes[i]);
if (!nodesToExtractTitle.length) {
return [];
}
if (nodesToExtractTitle.length === 0) return [];
const nodesByDocument = this.separateNodesByDocument(nodesToExtractTitle);
const titlesByDocument = await this.extractTitles(nodesByDocument);
const titlesCandidates: string[] = [];
let title: string = "";
return nodesToExtractTitle.map((node) => {
return {
documentTitle: titlesByDocument[node.sourceNode?.nodeId ?? ""],
};
});
}
for (let i = 0; i < nodesToExtractTitle.length; i++) {
const completion = await this.llm.complete({
prompt: defaultTitleExtractorPromptTemplate({
contextStr: nodesToExtractTitle[i].getContent(MetadataMode.ALL),
}),
});
private filterNodes(nodes: BaseNode[]): BaseNode[] {
return nodes.filter((node) => {
if (this.isTextNodeOnly && !(node instanceof TextNode)) {
return false;
}
return true;
});
}
titlesCandidates.push(completion.text);
private separateNodesByDocument(
nodes: BaseNode[],
): Record<string, BaseNode[]> {
const nodesByDocument: Record<string, BaseNode[]> = {};
for (const node of nodes) {
const parentNode = node.sourceNode?.nodeId;
if (!parentNode) {
continue;
}
if (!nodesByDocument[parentNode]) {
nodesByDocument[parentNode] = [];
}
nodesByDocument[parentNode].push(node);
}
if (nodesToExtractTitle.length > 1) {
const combinedTitles = titlesCandidates.join(",");
return nodesByDocument;
}
private async extractTitles(
nodesByDocument: Record<string, BaseNode[]>,
): Promise<Record<string, string>> {
const titlesByDocument: Record<string, string> = {};
for (const [key, nodes] of Object.entries(nodesByDocument)) {
const titleCandidates = await this.getTitlesCandidates(nodes);
const combinedTitles = titleCandidates.join(", ");
const completion = await this.llm.complete({
prompt: defaultTitleCombinePromptTemplate({
contextStr: combinedTitles,
}),
});
title = completion.text;
titlesByDocument[key] = completion.text;
}
if (nodesToExtractTitle.length === 1) {
title = titlesCandidates[0];
}
return titlesByDocument;
}
return nodes.map((_) => ({
documentTitle: title.trim().replace(STRIP_REGEX, ""),
}));
private async getTitlesCandidates(nodes: BaseNode[]): Promise<string[]> {
const titleJobs = nodes.map(async (node) => {
const completion = await this.llm.complete({
prompt: defaultTitleExtractorPromptTemplate({
contextStr: node.getContent(MetadataMode.ALL),
}),
});
return completion.text;
});
return await Promise.all(titleJobs);
}
}
@@ -352,9 +387,9 @@ export class SummaryExtractor extends BaseExtractor {
*/
promptTemplate: string;
private _selfSummary: boolean;
private _prevSummary: boolean;
private _nextSummary: boolean;
private selfSummary: boolean;
private prevSummary: boolean;
private nextSummary: boolean;
constructor(options?: SummaryExtractArgs) {
const summaries = options?.summaries ?? ["self"];
@@ -372,9 +407,9 @@ export class SummaryExtractor extends BaseExtractor {
this.promptTemplate =
options?.promptTemplate ?? defaultSummaryExtractorPromptTemplate();
this._selfSummary = summaries?.includes("self") ?? false;
this._prevSummary = summaries?.includes("prev") ?? false;
this._nextSummary = summaries?.includes("next") ?? false;
this.selfSummary = summaries?.includes("self") ?? false;
this.prevSummary = summaries?.includes("prev") ?? false;
this.nextSummary = summaries?.includes("next") ?? false;
}
/**
@@ -416,13 +451,13 @@ export class SummaryExtractor extends BaseExtractor {
const metadataList: any[] = nodes.map(() => ({}));
for (let i = 0; i < nodes.length; i++) {
if (i > 0 && this._prevSummary && nodeSummaries[i - 1]) {
if (i > 0 && this.prevSummary && nodeSummaries[i - 1]) {
metadataList[i]["prevSectionSummary"] = nodeSummaries[i - 1];
}
if (i < nodes.length - 1 && this._nextSummary && nodeSummaries[i + 1]) {
if (i < nodes.length - 1 && this.nextSummary && nodeSummaries[i + 1]) {
metadataList[i]["nextSectionSummary"] = nodeSummaries[i + 1];
}
if (this._selfSummary && nodeSummaries[i]) {
if (this.selfSummary && nodeSummaries[i]) {
metadataList[i]["sectionSummary"] = nodeSummaries[i];
}
}
+6 -19
View File
@@ -21,33 +21,25 @@ export const defaultKeywordExtractorPromptTemplate = ({
contextStr = "",
keywords = 5,
}: DefaultKeywordExtractorPromptTemplate) => `${contextStr}
Give ${keywords} unique keywords for this document.
Format as comma separated. Keywords:
`;
Format as comma separated.
Keywords: `;
export const defaultTitleExtractorPromptTemplate = (
{ contextStr = "" }: DefaultPromptTemplate = {
contextStr: "",
},
) => `${contextStr}
Give a title that summarizes all of the unique entities, titles or themes found in the context.
Title:
`;
Title: `;
export const defaultTitleCombinePromptTemplate = (
{ contextStr = "" }: DefaultPromptTemplate = {
contextStr: "",
},
) => `${contextStr}
Based on the above candidate titles and contents, what is the comprehensive title for this document?
Title:
`;
Title: `;
export const defaultQuestionAnswerPromptTemplate = (
{ contextStr = "", numQuestions = 5 }: DefaultQuestionAnswerPromptTemplate = {
@@ -55,9 +47,7 @@ export const defaultQuestionAnswerPromptTemplate = (
numQuestions: 5,
},
) => `${contextStr}
Given the contextual informations, generate ${numQuestions} questions this context can provides specific answers to which are unlikely to be found elsewhere.Higher-level summaries of surrounding context may be provideds as well.
Given the contextual informations, generate ${numQuestions} questions this context can provides specific answers to which are unlikely to be found else where. Higher-level summaries of surrounding context may be provideds as well.
Try using these summaries to generate better questions that this context can answer.
`;
@@ -66,11 +56,8 @@ export const defaultSummaryExtractorPromptTemplate = (
contextStr: "",
},
) => `${contextStr}
Summarize the key topics and entities of the sections.
Summary:
`;
Summary: `;
export const defaultNodeTextTemplate = ({
metadataStr = "",
@@ -24,6 +24,7 @@ import { ClipEmbedding } from "../../embeddings/index.js";
import { RetrieverQueryEngine } from "../../engines/query/RetrieverQueryEngine.js";
import { runTransformations } from "../../ingestion/index.js";
import type { BaseNodePostprocessor } from "../../postprocessors/types.js";
import { storageContextFromDefaults } from "../../storage/StorageContext.js";
import type {
BaseIndexStore,
MetadataFilters,
@@ -32,10 +33,7 @@ import type {
VectorStoreQuery,
VectorStoreQueryResult,
} from "../../storage/index.js";
import {
VectorStoreQueryMode,
storageContextFromDefaults,
} from "../../storage/index.js";
import { VectorStoreQueryMode } from "../../storage/vectorStore/types.js";
import type { BaseSynthesizer } from "../../synthesizers/types.js";
import type { BaseQueryEngine } from "../../types.js";
import type { BaseIndexInit } from "../BaseIndex.js";
+1 -1
View File
@@ -260,7 +260,7 @@ export class OpenAI extends BaseLLM {
stream: false,
});
const content = response.choices[0].message?.content ?? "";
const content = response.choices[0].message?.content ?? null;
const kwargsOutput: Record<string, any> = {};
+5
View File
@@ -37,14 +37,18 @@ export class Ollama extends BaseEmbedding implements LLM {
additionalChatOptions?: Record<string, unknown>;
callbackManager?: CallbackManager;
protected modelMetadata: Partial<LLMMetadata>;
constructor(
init: Partial<Ollama> & {
// model is required
model: string;
modelMetadata?: Partial<LLMMetadata>;
},
) {
super();
this.model = init.model;
this.modelMetadata = init.modelMetadata ?? {};
Object.assign(this, init);
}
@@ -56,6 +60,7 @@ export class Ollama extends BaseEmbedding implements LLM {
maxTokens: undefined,
contextWindow: this.contextWindow,
tokenizer: undefined,
...this.modelMetadata,
};
}
@@ -27,12 +27,14 @@ export class SimpleNodeParser implements NodeParser {
includePrevNextRel?: boolean;
chunkSize?: number;
chunkOverlap?: number;
splitLongSentences?: boolean;
}) {
this.textSplitter =
init?.textSplitter ??
new SentenceSplitter({
chunkSize: init?.chunkSize ?? DEFAULT_CHUNK_SIZE,
chunkOverlap: init?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP,
splitLongSentences: init?.splitLongSentences ?? false,
});
this.includeMetadata = init?.includeMetadata ?? true;
this.includePrevNextRel = init?.includePrevNextRel ?? true;
+1 -1
View File
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import type { ParseConfig } from "papaparse";
import Papa from "papaparse";
import { Document } from "../Node.js";
+1 -1
View File
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import mammoth from "mammoth";
import { Document } from "../Node.js";
import type { FileReader } from "./type.js";
+1 -1
View File
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import { Document } from "../Node.js";
import type { FileReader } from "./type.js";
+1 -1
View File
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import type { Document } from "../Node.js";
import { ImageDocument } from "../Node.js";
import type { FileReader } from "./type.js";
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import { Document } from "../Node.js";
import type { FileReader } from "./type.js";
+1 -1
View File
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import { Document } from "../Node.js";
import type { FileReader } from "./type.js";
+1 -1
View File
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { createSHA256, defaultFS } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import { Document } from "../Node.js";
import type { BaseReader } from "./type.js";
@@ -1,5 +1,5 @@
import type { CompleteFileSystem } from "@llamaindex/env";
import { defaultFS, path } from "@llamaindex/env";
import type { CompleteFileSystem } from "@llamaindex/env/type";
import { Document } from "../Node.js";
import { walk } from "../storage/FileSystem.js";
import { PapaCSVReader } from "./CSVReader.js";
+1 -1
View File
@@ -1,4 +1,4 @@
import type { CompleteFileSystem } from "@llamaindex/env/type";
import type { CompleteFileSystem } from "@llamaindex/env";
import type { Document } from "../Node.js";
/**
+1 -4
View File
@@ -1,7 +1,4 @@
import type {
GenericFileSystem,
WalkableFileSystem,
} from "@llamaindex/env/type";
import type { GenericFileSystem, WalkableFileSystem } from "@llamaindex/env";
// FS utility functions
/**
+1 -1
View File
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS, path } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import {
DEFAULT_IMAGE_VECTOR_NAMESPACE,
DEFAULT_NAMESPACE,
@@ -1,4 +1,4 @@
import _, * as lodash from "lodash";
import _ from "lodash";
import type { BaseNode } from "../../Node.js";
import { ObjectType } from "../../Node.js";
import { DEFAULT_NAMESPACE } from "../constants.js";
@@ -123,10 +123,10 @@ export class KVDocumentStore extends BaseDocumentStore {
const refDocInfo = await this.kvstore.get(refDocId, this.refDocCollection);
if (!_.isNil(refDocInfo)) {
lodash.pull(refDocInfo.docIds, docId);
!_.pull(refDocInfo.nodeIds, docId);
if (refDocInfo.docIds.length > 0) {
this.kvstore.put(refDocId, refDocInfo.toDict(), this.refDocCollection);
if (refDocInfo.nodeIds.length > 0) {
this.kvstore.put(refDocId, refDocInfo, this.refDocCollection);
}
this.kvstore.delete(refDocId, this.metadataCollection);
}
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS, path } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import _ from "lodash";
import {
DEFAULT_DOC_STORE_PERSIST_FILENAME,
+1 -1
View File
@@ -1,4 +1,4 @@
import type { GenericFileSystem } from "@llamaindex/env/type";
import type { GenericFileSystem } from "@llamaindex/env";
import { BaseNode } from "../../Node.js";
import {
DEFAULT_DOC_STORE_PERSIST_FILENAME,
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS, path } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import {
DEFAULT_INDEX_STORE_PERSIST_FILENAME,
DEFAULT_PERSIST_DIR,
@@ -1,4 +1,4 @@
import type { GenericFileSystem } from "@llamaindex/env/type";
import type { GenericFileSystem } from "@llamaindex/env";
import type { IndexStruct } from "../../indices/IndexStruct.js";
import {
DEFAULT_INDEX_STORE_PERSIST_FILENAME,
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS, path } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import _ from "lodash";
import { exists } from "../FileSystem.js";
import { DEFAULT_COLLECTION } from "../constants.js";
@@ -54,6 +54,9 @@ export class SimpleKVStore extends BaseKVStore {
): Promise<boolean> {
if (key in this.data[collection]) {
delete this.data[collection][key];
if (this.persistPath) {
await this.persist(this.persistPath, this.fs);
}
return true;
}
return false;
+1 -1
View File
@@ -1,4 +1,4 @@
import type { GenericFileSystem } from "@llamaindex/env/type";
import type { GenericFileSystem } from "@llamaindex/env";
const defaultCollection = "data";
type StoredValue = Record<string, any> | null;
@@ -1,5 +1,4 @@
import pg from "pg";
import pgvector from "pgvector/pg";
import type pg from "pg";
import type {
VectorStore,
@@ -7,7 +6,7 @@ import type {
VectorStoreQueryResult,
} from "./types.js";
import type { GenericFileSystem } from "@llamaindex/env/type";
import type { GenericFileSystem } from "@llamaindex/env";
import type { BaseNode, Metadata } from "../../Node.js";
import { Document, MetadataMode } from "../../Node.js";
@@ -83,16 +82,18 @@ export class PGVectorStore implements VectorStore {
private async getDb(): Promise<pg.Client> {
if (!this.db) {
try {
const { Client } = await import("pg");
const { registerType } = await import("pgvector/pg");
// Create DB connection
// Read connection params from env - see comment block above
const db = new pg.Client({
const db = new Client({
connectionString: this.connectionString,
});
await db.connect();
// Check vector extension
db.query("CREATE EXTENSION IF NOT EXISTS vector");
await pgvector.registerType(db);
await registerType(db);
// Check schema, table(s), index(es)
await this.checkSchema(db);
@@ -6,19 +6,21 @@ import type {
VectorStoreQueryResult,
} from "./types.js";
import type { GenericFileSystem } from "@llamaindex/env/type";
import type { GenericFileSystem } from "@llamaindex/env";
import type {
FetchResponse,
Index,
ScoredPineconeRecord,
} from "@pinecone-database/pinecone";
import { Pinecone } from "@pinecone-database/pinecone";
import { type Pinecone } from "@pinecone-database/pinecone";
import type { BaseNode, Metadata } from "../../Node.js";
import { metadataDictToNode, nodeToMetadata } from "./utils.js";
type PineconeParams = {
indexName?: string;
chunkSize?: number;
namespace?: string;
textKey?: string;
};
/**
@@ -37,18 +39,23 @@ export class PineconeVectorStore implements VectorStore {
*/
db?: Pinecone;
indexName: string;
namespace: string;
chunkSize: number;
textKey: string;
constructor(params?: PineconeParams) {
this.indexName =
params?.indexName ?? process.env.PINECONE_INDEX_NAME ?? "llama";
this.namespace = params?.namespace ?? process.env.PINECONE_NAMESPACE ?? "";
this.chunkSize =
params?.chunkSize ??
Number.parseInt(process.env.PINECONE_CHUNK_SIZE ?? "100");
this.textKey = params?.textKey ?? "text";
}
private async getDb(): Promise<Pinecone> {
if (!this.db) {
const { Pinecone } = await import("@pinecone-database/pinecone");
this.db = await new Pinecone();
}
@@ -148,24 +155,23 @@ export class PineconeVectorStore implements VectorStore {
};
const idx = await this.index();
const results = await idx.query(options);
const results = await idx.namespace(this.namespace).query(options);
const idList = results.matches.map((row) => row.id);
const records: FetchResponse<any> = await idx.fetch(idList);
const records: FetchResponse<any> = await idx
.namespace(this.namespace)
.fetch(idList);
const rows = Object.values(records.records);
const nodes = rows.map((row) => {
const metadata = this.metaWithoutText(row.metadata);
const text = this.textFromResultRow(row);
const node = metadataDictToNode(metadata, {
const node = metadataDictToNode(row.metadata, {
fallback: {
id: row.id,
text,
metadata,
text: this.textFromResultRow(row),
metadata: this.metaWithoutText(row.metadata),
embedding: row.values,
},
});
node.setContent(text);
return node;
});
@@ -199,12 +205,12 @@ export class PineconeVectorStore implements VectorStore {
}
textFromResultRow(row: ScoredPineconeRecord<Metadata>): string {
return row.metadata?.text ?? "";
return row.metadata?.[this.textKey] ?? "";
}
metaWithoutText(meta: Metadata): any {
return Object.keys(meta)
.filter((key) => key != "text")
.filter((key) => key != this.textKey)
.reduce((acc: any, key: string) => {
acc[key] = meta[key];
return acc;
@@ -36,12 +36,11 @@ type QuerySearchResult = {
export class QdrantVectorStore implements VectorStore {
storesText: boolean = true;
db: QdrantClient;
collectionName: string;
batchSize: number;
collectionName: string;
private _collectionInitialized: boolean = false;
private db: QdrantClient;
private collectionInitialized: boolean = false;
/**
* Creates a new QdrantVectorStore.
@@ -59,7 +58,7 @@ export class QdrantVectorStore implements VectorStore {
batchSize,
}: QdrantParams) {
if (!client && !url) {
if (!url || !collectionName) {
if (!url) {
throw new Error("QdrantVectorStore requires url and collectionName");
}
}
@@ -122,7 +121,7 @@ export class QdrantVectorStore implements VectorStore {
if (!exists) {
await this.createCollection(this.collectionName, vectorSize);
}
this._collectionInitialized = true;
this.collectionInitialized = true;
}
/**
@@ -179,7 +178,7 @@ export class QdrantVectorStore implements VectorStore {
* @returns List of node IDs
*/
async add(embeddingResults: BaseNode[]): Promise<string[]> {
if (embeddingResults.length > 0 && !this._collectionInitialized) {
if (embeddingResults.length > 0 && !this.collectionInitialized) {
await this.initializeCollection(
embeddingResults[0].getEmbedding().length,
);
@@ -1,5 +1,5 @@
import type { GenericFileSystem } from "@llamaindex/env";
import { defaultFS, path } from "@llamaindex/env";
import type { GenericFileSystem } from "@llamaindex/env/type";
import _ from "lodash";
import type { BaseNode } from "../../Node.js";
import {
@@ -82,6 +82,9 @@ export class SimpleVectorStore implements VectorStore {
delete this.data.embeddingDict[textId];
delete this.data.textIdToRefDocId[textId];
}
if (this.persistPath) {
await this.persist(this.persistPath, this.fs);
}
return Promise.resolve();
}
+2
View File
@@ -32,6 +32,7 @@ export async function createApp({
eslint,
frontend,
openAiKey,
llamaCloudKey,
model,
communityProjectPath,
llamapack,
@@ -77,6 +78,7 @@ export async function createApp({
isOnline,
eslint,
openAiKey,
llamaCloudKey,
model,
communityProjectPath,
llamapack,
+6
View File
@@ -26,6 +26,7 @@ const createEnvLocalFile = async (
root: string,
opts?: {
openAiKey?: string;
llamaCloudKey?: string;
vectorDb?: TemplateVectorDB;
model?: string;
framework?: TemplateFramework;
@@ -46,6 +47,10 @@ const createEnvLocalFile = async (
content += `OPENAI_API_KEY=${opts?.openAiKey}\n`;
}
if (opts?.llamaCloudKey) {
content += `LLAMA_CLOUD_API_KEY=${opts?.llamaCloudKey}\n`;
}
switch (opts?.vectorDb) {
case "mongo": {
content += `# For generating a connection URI, see https://www.mongodb.com/docs/guides/atlas/connection-string\n`;
@@ -205,6 +210,7 @@ export const installTemplate = async (
// Copy the environment file to the target directory.
await createEnvLocalFile(props.root, {
openAiKey: props.openAiKey,
llamaCloudKey: props.llamaCloudKey,
vectorDb: props.vectorDb,
model: props.model,
framework: props.framework,
+9 -5
View File
@@ -8,6 +8,7 @@ import { templatesDir } from "./dir";
import { isPoetryAvailable, tryPoetryInstall } from "./poetry";
import { Tool } from "./tools";
import {
FileSourceConfig,
InstallTemplateArgs,
TemplateDataSource,
TemplateVectorDB,
@@ -244,13 +245,16 @@ export const installPythonTemplate = async ({
const dataSourceType = dataSource?.type;
if (dataSourceType !== undefined && dataSourceType !== "none") {
const loaderPath =
dataSourceType === "folder"
? path.join(compPath, "loaders", "python", "file")
: path.join(compPath, "loaders", "python", dataSourceType);
let loaderFolder: string;
if (dataSourceType === "file" || dataSourceType === "folder") {
const dataSourceConfig = dataSource?.config as FileSourceConfig;
loaderFolder = dataSourceConfig.useLlamaParse ? "llama_parse" : "file";
} else {
loaderFolder = dataSourceType;
}
await copy("**", enginePath, {
parents: true,
cwd: loaderPath,
cwd: path.join(compPath, "loaders", "python", loaderFolder),
});
}
}
+2
View File
@@ -15,6 +15,7 @@ export type TemplateDataSourceType = "none" | "file" | "folder" | "web";
// Config for both file and folder
export type FileSourceConfig = {
path?: string;
useLlamaParse?: boolean;
};
export type WebSourceConfig = {
baseUrl?: string;
@@ -35,6 +36,7 @@ export interface InstallTemplateArgs {
eslint: boolean;
customApiPath?: string;
openAiKey?: string;
llamaCloudKey?: string;
forBackend?: string;
model: string;
communityProjectPath?: string;
+16
View File
@@ -154,6 +154,18 @@ const program = new Commander.Command(packageJson.name)
`
Specify the tools you want to use by providing a comma-separated list. For example, 'wikipedia.WikipediaToolSpec,google.GoogleSearchToolSpec'. Use 'none' to not using any tools.
`,
)
.option(
"--llama-parse",
`
Enable LlamaParse.
`,
)
.option(
"--llama-cloud-key <key>",
`
Provide a LlamaCloud API key.
`,
)
.allowUnknownOption()
@@ -171,6 +183,9 @@ if (process.argv.includes("--tools")) {
program.tools = getTools(program.tools.split(","));
}
}
if (process.argv.includes("--no-llama-parse")) {
program.llamaParse = false;
}
const packageManager = !!program.useNpm
? "npm"
@@ -264,6 +279,7 @@ async function run(): Promise<void> {
eslint: program.eslint,
frontend: program.frontend,
openAiKey: program.openAiKey,
llamaCloudKey: program.llamaCloudKey,
model: program.model,
communityProjectPath: program.communityProjectPath,
llamapack: program.llamapack,
+65 -2
View File
@@ -5,7 +5,11 @@ import path from "path";
import { blue, green, red } from "picocolors";
import prompts from "prompts";
import { InstallAppArgs } from "./create-app";
import { TemplateDataSourceType, TemplateFramework } from "./helpers";
import {
FileSourceConfig,
TemplateDataSourceType,
TemplateFramework,
} from "./helpers";
import { COMMUNITY_OWNER, COMMUNITY_REPO } from "./helpers/constant";
import { templatesDir } from "./helpers/dir";
import { getAvailableLlamapackOptions } from "./helpers/llama-pack";
@@ -15,7 +19,7 @@ import { supportedTools, toolsRequireConfig } from "./helpers/tools";
export type QuestionArgs = Omit<
InstallAppArgs,
"appPath" | "packageManager"
> & { files?: string };
> & { files?: string; llamaParse?: boolean };
const supportedContextFileTypes = [
".pdf",
".doc",
@@ -63,6 +67,7 @@ const defaults: QuestionArgs = {
eslint: true,
frontend: false,
openAiKey: "",
llamaCloudKey: "",
model: "gpt-3.5-turbo",
communityProjectPath: "",
llamapack: "",
@@ -521,6 +526,64 @@ export const askQuestions = async (
}
}
if (
program.dataSource?.type === "file" ||
(program.dataSource?.type === "folder" && program.framework === "fastapi")
) {
if (ciInfo.isCI) {
program.llamaCloudKey = getPrefOrDefault("llamaCloudKey");
} else {
const dataSourceConfig = program.dataSource.config as FileSourceConfig;
dataSourceConfig.useLlamaParse = program.llamaParse;
// Is pdf file selected as data source or is it a folder data source
const askingLlamaParse =
dataSourceConfig.useLlamaParse === undefined &&
(program.dataSource.type === "folder"
? true
: dataSourceConfig.path &&
path.extname(dataSourceConfig.path) === ".pdf");
// Ask if user wants to use LlamaParse
if (askingLlamaParse) {
const { useLlamaParse } = await prompts(
{
type: "toggle",
name: "useLlamaParse",
message:
"Would you like to use LlamaParse (improved parser for RAG - requires API key)?",
initial: true,
active: "yes",
inactive: "no",
},
handlers,
);
dataSourceConfig.useLlamaParse = useLlamaParse;
program.dataSource.config = dataSourceConfig;
}
// Ask for LlamaCloud API key
if (
dataSourceConfig.useLlamaParse &&
program.llamaCloudKey === undefined
) {
const { llamaCloudKey } = await prompts(
{
type: "text",
name: "llamaCloudKey",
message: "Please provide your LlamaIndex Cloud API key:",
validate: (value) =>
value
? true
: "LlamaIndex Cloud API key is required. You can get it from: https://cloud.llamaindex.ai/api-key",
},
handlers,
);
program.llamaCloudKey = llamaCloudKey;
}
}
}
if (program.dataSource?.type === "web" && program.framework === "fastapi") {
let { baseUrl } = await prompts(
{
@@ -1,6 +1,6 @@
from llama_index.core.readers import SimpleDirectoryReader
DATA_DIR = "data" # directory to cache the generated index
DATA_DIR = "data" # directory containing the documents
def get_documents():
@@ -0,0 +1,14 @@
from llama_parse import LlamaParse
from llama_index.core import SimpleDirectoryReader
DATA_DIR = "data" # directory containing the documents
def get_documents():
parser = LlamaParse(
result_type="markdown",
verbose=True,
)
reader = SimpleDirectoryReader(DATA_DIR, file_extractor={".pdf": parser})
return reader.load_data()
+2 -1
View File
@@ -6,6 +6,7 @@
"target": "esnext"
},
"module": {
"type": "commonjs"
"type": "commonjs",
"ignoreDynamic": true
}
}
+6
View File
@@ -1,5 +1,11 @@
# @llamaindex/env
## 0.0.4
### Patch Changes
- cf87f84: fix: type backward compatibility
## 0.0.3
### Patch Changes
+7 -3
View File
@@ -1,7 +1,7 @@
{
"name": "@llamaindex/env",
"description": "environment wrapper",
"version": "0.0.3",
"version": "0.0.4",
"type": "module",
"types": "dist/type/index.d.ts",
"main": "dist/cjs/index.js",
@@ -56,12 +56,16 @@
"@aws-crypto/sha256-js": "^5.2.0",
"@swc/cli": "^0.3.9",
"@swc/core": "^1.4.2",
"@types/lodash": "^4.14.202",
"@types/node": "^20.11.20",
"pathe": "^1.1.2",
"concurrently": "^8.2.2"
},
"dependencies": {
"@types/lodash": "^4.14.202",
"@types/node": "^20.11.20",
"lodash": "^4.17.21"
},
"peerDependencies": {
"@aws-crypto/sha256-js": "^5.2.0",
"pathe": "^1.1.2"
}
}
+1
View File
@@ -38,3 +38,4 @@ export function createSHA256(): SHA256 {
export function randomUUID(): string {
return crypto.randomUUID();
}
export * from "./type.js";
+1
View File
@@ -34,4 +34,5 @@ export const defaultFS: CompleteFileSystem = {
stat: fs.stat,
};
export * from "./type.js";
export { EOL, ok, path, randomUUID };
+1
View File
@@ -36,6 +36,7 @@ module.exports = {
"PINECONE_INDEX_NAME",
"PINECONE_CHUNK_SIZE",
"PINECONE_INDEX_NAME",
"PINECONE_NAMESPACE",
"AZURE_OPENAI_API_KEY",
"AZURE_OPENAI_API_INSTANCE_NAME",
+55 -32
View File
@@ -169,8 +169,8 @@ importers:
specifier: ^0.1.4
version: 0.1.4
'@llamaindex/cloud':
specifier: ^0.0.1
version: 0.0.1
specifier: ^0.0.2
version: 0.0.2
'@llamaindex/env':
specifier: workspace:*
version: link:../env
@@ -186,6 +186,18 @@ importers:
'@qdrant/js-client-rest':
specifier: ^1.7.0
version: 1.7.0(typescript@5.3.3)
'@types/lodash':
specifier: ^4.14.202
version: 4.14.202
'@types/node':
specifier: ^18.19.14
version: 18.19.14
'@types/papaparse':
specifier: ^5.3.14
version: 5.3.14
'@types/pg':
specifier: ^8.11.0
version: 8.11.0
'@xenova/transformers':
specifier: ^2.15.0
version: 2.15.0
@@ -259,18 +271,6 @@ importers:
'@swc/core':
specifier: ^1.4.2
version: 1.4.2
'@types/lodash':
specifier: ^4.14.202
version: 4.14.202
'@types/node':
specifier: ^18.19.14
version: 18.19.14
'@types/papaparse':
specifier: ^5.3.14
version: 5.3.14
'@types/pg':
specifier: ^8.11.0
version: 8.11.0
concurrently:
specifier: ^8.2.2
version: 8.2.2
@@ -376,6 +376,12 @@ importers:
packages/env:
dependencies:
'@types/lodash':
specifier: ^4.14.202
version: 4.14.202
'@types/node':
specifier: ^20.11.20
version: 20.11.20
lodash:
specifier: ^4.17.21
version: 4.17.21
@@ -389,12 +395,6 @@ importers:
'@swc/core':
specifier: ^1.4.2
version: 1.4.2
'@types/lodash':
specifier: ^4.14.202
version: 4.14.202
'@types/node':
specifier: ^20.11.20
version: 20.11.20
concurrently:
specifier: ^8.2.2
version: 8.2.2
@@ -3258,8 +3258,19 @@ packages:
/@leichtgewicht/ip-codec@2.0.4:
resolution: {integrity: sha512-Hcv+nVC0kZnQ3tD9GVu5xSMR4VVYOteQIr/hwFPVEvPdlXqgGEuRjiheChHgdM+JyqdgNcmzZOX/tnl0JOiI7A==}
/@llamaindex/cloud@0.0.1:
resolution: {integrity: sha512-7FrLAbY459B4rcG4NaqANatDT5zKvZxIRyrY+nnTSXqu9ZMzkm1Co8IIRYx2/9feps/OLOhXsv7VKGGUr7scNQ==}
/@llamaindex/cloud@0.0.2:
resolution: {integrity: sha512-UF5RVyb3g1V25lPAkg3VvS8iGuKv0bSI10H8dS3LwUHzl8foPEqqpbNbSOoJt2VEQ1A7w1///5dyN8y+FDtkKA==}
requiresBuild: true
peerDependencies:
node-fetch: ^3.3.2
peerDependenciesMeta:
node-fetch:
optional: true
dependencies:
'@types/qs': 6.9.12
form-data: 4.0.0
js-base64: 3.7.7
qs: 6.11.2
dev: false
/@manypkg/find-root@1.1.0:
@@ -4254,6 +4265,7 @@ packages:
/@types/lodash@4.14.202:
resolution: {integrity: sha512-OvlIYQK9tNneDlS0VN54LLd5uiPCBOp7gS5Z0f1mjoJYBrtStzgmJBxONW3U6OZqdtNzZPmn9BS/7WI7BFFcFQ==}
dev: false
/@types/long@4.0.2:
resolution: {integrity: sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==}
@@ -4310,6 +4322,7 @@ packages:
resolution: {integrity: sha512-EnQ4Us2rmOS64nHDWr0XqAD8DsO6f3XR6lf9UIIrZQpUzPVdN/oPuEzfDWNHSyXLvoGgjuEm/sPwFGSSs35Wtg==}
dependencies:
undici-types: 5.26.5
dev: false
/@types/node@20.11.14:
resolution: {integrity: sha512-w3yWCcwULefjP9DmDDsgUskrMoOy5Z8MiwKHr1FvqGPtx7CvJzQvxD7eKpxNtklQxLruxSXWddyeRtyud0RcXQ==}
@@ -4326,7 +4339,7 @@ packages:
resolution: {integrity: sha512-7/rR21OS+fq8IyHTgtLkDK949uzsa6n8BkziAKtPVpugIkO6D+/ooXMvzXxDnZrmtXVfjb1bKQafYpb8s89LOg==}
dependencies:
undici-types: 5.26.5
dev: true
dev: false
/@types/node@20.11.7:
resolution: {integrity: sha512-GPmeN1C3XAyV5uybAf4cMLWT9fDWcmQhZVtMFu7OR32WjrqGG+Wnk2V1d0bmtUyE/Zy1QJ9BxyiTih9z8Oks8A==}
@@ -4342,7 +4355,7 @@ packages:
resolution: {integrity: sha512-LxJ4iEFcpqc6METwp9f6BV6VVc43m6MfH0VqFosHvrUgfXiFe6ww7R3itkOQ+TCK6Y+Iv/+RnnvtRZnkc5Kc9g==}
dependencies:
'@types/node': 20.11.17
dev: true
dev: false
/@types/parse-json@4.0.2:
resolution: {integrity: sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw==}
@@ -4353,7 +4366,7 @@ packages:
'@types/node': 20.11.17
pg-protocol: 1.6.0
pg-types: 4.0.1
dev: true
dev: false
/@types/prismjs@1.26.3:
resolution: {integrity: sha512-A0D0aTXvjlqJ5ZILMz3rNfDBOx9hHxLZYv2by47Sm/pqW35zzjusrZTryatjN/Rf8Us2gZrJD+KeHbUSTux1Cw==}
@@ -4371,6 +4384,10 @@ packages:
/@types/qs@6.9.11:
resolution: {integrity: sha512-oGk0gmhnEJK4Yyk+oI7EfXsLayXatCWPHary1MtcmbAifkobT9cM9yutG/hZKIseOU0MqbIwQ/u2nn/Gb+ltuQ==}
/@types/qs@6.9.12:
resolution: {integrity: sha512-bZcOkJ6uWrL0Qb2NAWKa7TBU+mJHPzhx9jjLL1KHF+XpzEcR7EXHvjbHlGtR/IsP1vyPrehuS6XqkmaePy//mg==}
dev: false
/@types/range-parser@1.2.7:
resolution: {integrity: sha512-hKormJbkJqzQGhziax5PItDUTMAM9uE2XXQmM37dyd4hVM+5aVl7oVxMVUiVQn2oCQFN/LKCZdvSM0pFRqbSmQ==}
@@ -9393,6 +9410,10 @@ packages:
resolution: {integrity: sha512-NnRs6dsyqUXejqk/yv2aiXlAvOs56sLkX6nUdeaNezI5LFFLlsZjOThmwnrcwh5ZZRwZlCMnVAY3CvhIhoVEKQ==}
dev: false
/js-base64@3.7.7:
resolution: {integrity: sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw==}
dev: false
/js-tiktoken@1.0.10:
resolution: {integrity: sha512-ZoSxbGjvGyMT13x6ACo9ebhDha/0FHdKA+OsQcMOWcm1Zs7r90Rhk5lhERLzji+3rA7EKpXCgwXcM5fF3DMpdA==}
dependencies:
@@ -11491,11 +11512,12 @@ packages:
/pg-int8@1.0.1:
resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==}
engines: {node: '>=4.0.0'}
dev: false
/pg-numeric@1.0.2:
resolution: {integrity: sha512-BM/Thnrw5jm2kKLE5uJkXqqExRUY/toLHda65XgFTBTFYZyopbKjBe29Ii3RbkvlsMoFwD+tHeGaCjjv0gHlyw==}
engines: {node: '>=4'}
dev: true
dev: false
/pg-pool@3.6.1(pg@8.11.3):
resolution: {integrity: sha512-jizsIzhkIitxCGfPRzJn1ZdcosIt3pz9Sh3V01fm1vZnbnCMgmGl5wvGGdNN2EL9Rmb0EcFoCkixH4Pu+sP9Og==}
@@ -11507,6 +11529,7 @@ packages:
/pg-protocol@1.6.0:
resolution: {integrity: sha512-M+PDm637OY5WM307051+bsDia5Xej6d9IR4GwJse1qA1DIhiKlksvrneZOYQq42OM+spubpcNYEo2FcKQrDk+Q==}
dev: false
/pg-types@2.2.0:
resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==}
@@ -11530,7 +11553,7 @@ packages:
postgres-date: 2.0.1
postgres-interval: 3.0.0
postgres-range: 1.1.3
dev: true
dev: false
/pg@8.11.3:
resolution: {integrity: sha512-+9iuvG8QfaaUrrph+kpF24cXkH1YOOUeArRNYIxq1viYHZagBxrTno7cecY1Fa44tJeZvaoG+Djpkc3JwehN5g==}
@@ -12067,7 +12090,7 @@ packages:
/postgres-array@3.0.2:
resolution: {integrity: sha512-6faShkdFugNQCLwucjPcY5ARoW1SlbnrZjmGl0IrrqewpvxvhSLHimCVzqeuULCbG0fQv7Dtk1yDbG3xv7Veog==}
engines: {node: '>=12'}
dev: true
dev: false
/postgres-bytea@1.0.0:
resolution: {integrity: sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w==}
@@ -12079,7 +12102,7 @@ packages:
engines: {node: '>= 6'}
dependencies:
obuf: 1.1.2
dev: true
dev: false
/postgres-date@1.0.7:
resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==}
@@ -12089,7 +12112,7 @@ packages:
/postgres-date@2.0.1:
resolution: {integrity: sha512-YtMKdsDt5Ojv1wQRvUhnyDJNSr2dGIC96mQVKz7xufp07nfuFONzdaowrMHjlAzY6GDLd4f+LUHHAAM1h4MdUw==}
engines: {node: '>=12'}
dev: true
dev: false
/postgres-interval@1.2.0:
resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==}
@@ -12101,11 +12124,11 @@ packages:
/postgres-interval@3.0.0:
resolution: {integrity: sha512-BSNDnbyZCXSxgA+1f5UU2GmwhoI0aU5yMxRGO8CdFEcY2BQF9xm/7MqKnYoM1nJDk8nONNWDk9WeSmePFhQdlw==}
engines: {node: '>=12'}
dev: true
dev: false
/postgres-range@1.1.3:
resolution: {integrity: sha512-VdlZoocy5lCP0c/t66xAfclglEapXPCIVhqqJRncYpvbCgImF0w67aPKfbqUMr72tO2k5q0TdTZwCLjPTI6C9g==}
dev: true
dev: false
/prebuild-install@7.1.1:
resolution: {integrity: sha512-jAXscXWMcCK8GgCoHOfIr0ODh5ai8mj63L2nWrjuAgXE6tDyYGnx4/8o/rCgU+B4JSyZBKbeZqzhtwtC3ovxjw==}