-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsearch.js
More file actions
69 lines (57 loc) · 1.78 KB
/
Copy pathsearch.js
File metadata and controls
69 lines (57 loc) · 1.78 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { readFile } from "node:fs/promises";
import readline from "node:readline";
import { OpenAIEmbeddings } from "@langchain/openai";
import { Document } from "@langchain/core/documents";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
const products = JSON.parse(await readFile("./products.json", "utf8"));
function createStore(products) {
const embeddings = new OpenAIEmbeddings();
return MemoryVectorStore.fromDocuments(
products.map(
(product) =>
new Document({
pageContent: `Title: ${product.name}
Description: ${product.description}
Price: ${product.price}`,
metadata: { sourceId: product.id },
})
),
embeddings
);
}
const store = await createStore(products);
async function searchProducts(query, count = 1) {
const searchResults = await store.similaritySearch(query, count);
return searchResults.map((result) =>
products.find((product) => product.id === result.metadata.sourceId)
);
}
async function searchLoop() {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
const askQuestion = (query) =>
new Promise((resolve) => rl.question(query, resolve));
while (true) {
const query = await askQuestion(
'Enter your search query (or type "exit" to quit): '
);
if (query.toLowerCase() === "exit") break;
const products = await searchProducts(query, 3);
if (products.length === 0) {
console.log("No products found for your query.");
} else {
console.log("Products found:");
products.forEach((product, index) => {
console.log(
`${index + 1}. ${product.name}: ${product.description}: ${
product.price
}`
);
});
}
}
rl.close();
}
await searchLoop();