forked from okahu-demos/chatbot-coffee-vercel
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.ts
More file actions
61 lines (49 loc) · 1.76 KB
/
Copy pathutils.ts
File metadata and controls
61 lines (49 loc) · 1.76 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
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { Embeddings } from "@langchain/core/embeddings";
import { PromptTemplate } from "@langchain/core/prompts";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { Document } from "@langchain/core/documents";
import coffeeData from "../../../../data/coffeeEmbedding.json";
import { VectorStoreRetriever } from "@langchain/core/vectorstores"
export const waitFor = async (ms: number): Promise<void> => {
return new Promise(resolve => {
setTimeout(resolve, ms);
});
};
interface ChatbotComponents {
retriever: VectorStoreRetriever<MemoryVectorStore>;
prompt: PromptTemplate;
model: ChatOpenAI;
}
export const createChatbotComponents = async (): Promise<ChatbotComponents> => {
const embeddings = new OpenAIEmbeddings();
const model = new ChatOpenAI({});
const prompt = PromptTemplate.fromTemplate(`Answer the question based only on the following context:
{context} .
If you don't know the answer, you can say "I don't know".
Question: {question}`);
class CoffeeEmbeddings extends Embeddings {
model = "OpenAIEmbeddings";
embedDocuments(_documents: string[]): Promise<number[][]> {
return new Promise((resolve) => {
resolve(coffeeData.map((item) => item.embedding));
});
}
async embedQuery(document: string): Promise<number[]> {
return await embeddings.embedQuery(document);
}
}
const documents = coffeeData.map((item) => {
return new Document({
pageContent: item.text,
metadata: {}
});
})
const vectorStore = await MemoryVectorStore.fromDocuments(
documents,
new CoffeeEmbeddings({}),
{}
);
const retriever = vectorStore.asRetriever();
return { retriever, prompt, model };
};