-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchat_with_magnolia.ts
More file actions
53 lines (46 loc) · 1.79 KB
/
Copy pathchat_with_magnolia.ts
File metadata and controls
53 lines (46 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import { MagnoliaContentsLoader } from "./document_loaders/web/magnolia.js"; // NOTE: Requires local installation of https://github.com/joaquin-alfaro/langchainjs/tree/feature/magnolia-loader locally
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
import { OpenAIEmbeddings } from "@langchain/openai";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { VectorStore } from "@langchain/core/vectorstores";
function createVectorStore(): VectorStore {
const embeddings = new OpenAIEmbeddings({
apiKey: process.env.OPENAI_API_KEY, // In Node.js defaults to process.env.OPENAI_API_KEY
model: "text-embedding-3-small",
})
return new MemoryVectorStore(embeddings) as unknown as VectorStore
}
async function loadContentsAndQuestion() {
/**
* 1. Load contents from Magnolia
*/
const loader = new MagnoliaContentsLoader({
collection: "tours",
baseUrl: "http://localhost:8080/.rest/delivery/tours/v1",
contentProperty: "body"
});
const docs = await loader.load();
/**
* 2. Split documents in chunks before embedding
*/
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 180,
chunkOverlap: 14,
})
const chunks = await splitter.splitDocuments(docs);
/**
* 3. Embed documents and store in Vector store
*/
const vectorStore = createVectorStore()
await vectorStore.addDocuments(chunks)
/**
* 4. Search contents by similarity
*/
const question = "Find tours for cycling"
const similarDocs = await vectorStore.similaritySearch(question, 3, (doc: Document | any) => doc.metadata.collection == "tours")
similarDocs.map((doc) => {
console.log(doc)
console.log('\n')
})
}
loadContentsAndQuestion()