diff --git a/examples/storageContext.ts b/examples/storageContext.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb71ceefc586b7dff3fbde32c1475d7934bae80b --- /dev/null +++ b/examples/storageContext.ts @@ -0,0 +1,37 @@ +import fs from "fs/promises"; +import { Document, VectorStoreIndex, storageContextFromDefaults } 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 + // persist the vector store automatically with the storage context + const storageContext = await storageContextFromDefaults({ persistDir: "./storage" }); + const index = await VectorStoreIndex.fromDocuments([document], storageContext); + + // Query the index + const queryEngine = index.asQueryEngine(); + const response = await queryEngine.query( + "What did the author do in college?" + ); + + // Output response + console.log(response.toString()); + + // load the index + const loadedIndex = await VectorStoreIndex.fromDocuments([], storageContext); + const laodedQueryEngine = loadedIndex.asQueryEngine(); + const loadedResponse = await laodedQueryEngine.query( + "What did the author do growing up?" + ); + console.log(loadedResponse.toString()); +} + +main().catch(console.error); diff --git a/packages/core/src/tests/StorageContext.test.ts b/packages/core/src/tests/StorageContext.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3526c4511905054e6bf47e4c499bc71ff544f2c6 --- /dev/null +++ b/packages/core/src/tests/StorageContext.test.ts @@ -0,0 +1,17 @@ +import { existsSync, rmSync } from "fs"; +import { storageContextFromDefaults, StorageContext } from "../storage/StorageContext"; +import { Document } from "../Node"; +import { VectorStoreIndex } from "../indices"; +import { ListIndex } from "../indices"; + +describe("StorageContext", () => { + test("initializes", async () => { + const storageContext = await storageContextFromDefaults({ persistDir: "/tmp/test_dir" }); + + expect(existsSync("/tmp/test_dir")).toBe(true); + expect(storageContext).toBeDefined(); + + // cleanup + rmSync("/tmp/test_dir", { recursive: true }); + }); +});