-
Notifications
You must be signed in to change notification settings - Fork 0
/
05.conversations.ts
238 lines (181 loc) · 6.73 KB
/
05.conversations.ts
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import "dotenv/config";
import { OpenAIEmbeddings } from "@langchain/openai";
import { RecursiveCharacterTextSplitter } from "langchain/text_splitter";
import { PDFLoader } from "langchain/document_loaders/fs/pdf";
import { MemoryVectorStore } from "langchain/vectorstores/memory";
import { RunnableSequence } from "@langchain/core/runnables";
import { Document } from "@langchain/core/documents";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { RunnableMap } from "@langchain/core/runnables";
import { ChatOpenAI } from "@langchain/openai";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { MessagesPlaceholder } from "@langchain/core/prompts";
import { HumanMessage, AIMessage } from "@langchain/core/messages";
import { RunnablePassthrough } from "@langchain/core/runnables";
import { RunnableWithMessageHistory } from "@langchain/core/runnables";
import { ChatMessageHistory } from "langchain/stores/message/in_memory";
// #1 - Load the PDF and Split Chunks
const loader = new PDFLoader("eBook.pdf");
const eBookPDF = await loader.load();
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 1536,
chunkOverlap: 128,
});
const splitDocs = await splitter.splitDocuments(eBookPDF);
// #2 - Initialize VectorStore - In-Memory version
// TODO: Enahnce this to connect to a real VectorStore
const embeddings = new OpenAIEmbeddings();
const vectorstore = new MemoryVectorStore(embeddings);
await vectorstore.addDocuments(splitDocs);
const retriever = vectorstore.asRetriever();
// #3 Document retrieval in a chain
const convertDocsToString = (documents: Document[]): string => {
return documents
.map((document) => {
return `<doc>\n${document.pageContent}\n</doc>`;
})
.join("\n");
};
const documentRetrievalChain = RunnableSequence.from([
(input) => input.question,
retriever,
convertDocsToString,
]);
const results = await documentRetrievalChain.invoke({
question: "What are the prerequisites for this course?",
});
// console.log(results);
// #4 Formatting Response using a Chat Template:
const TEMPLATE_STRING = `You are an experienced researcher,
expert at interpreting and answering questions based on provided sources.
Using the provided context, answer the user's question
to the best of your ability using only the resources provided.
Be verbose!
<context>
{context}
</context>
Now, answer this question using the above context:
{question}`;
const answerGenerationPrompt = ChatPromptTemplate.fromTemplate(TEMPLATE_STRING);
const runnableMap = RunnableMap.from({
context: documentRetrievalChain,
question: (input) => input.question,
});
// const runnableMapRespones = await runnableMap.invoke({
// question: "What are the prerequisites for learning micro-frontends?"
// })
// console.log('runnableMapRespones - ', runnableMapRespones)
// #5 Agumented Generation :
const model = new ChatOpenAI({
modelName: "gpt-3.5-turbo-1106",
});
const retrievalChain = RunnableSequence.from([
{
context: documentRetrievalChain,
question: (input) => input.question,
},
answerGenerationPrompt,
model,
new StringOutputParser(),
]);
// const answer = await retrievalChain.invoke({
// question: "What are the prerequisites for this course?"
// });
// console.log("What are the prerequisites for this course?")
// console.log('original q and a - ', answer);
// WE do not have history
// const followupAnswer = await retrievalChain.invoke({
// question: "Can you list them in bullet point form?"
// });
// console.log("Can you list them in bullet point form?");
// console.log('followupAnswer - ', followupAnswer);
// console.log("Can you list them in bullet point form?");
// const docs = await documentRetrievalChain.invoke({
// question: "Can you list them in bullet point form?"
// });
// console.log(' documentRetrievalChain - ', docs);
// #6 Adding history to make it more conversational:
const REPHRASE_QUESTION_SYSTEM_TEMPLATE =
`Given the following conversation and a follow up question,
rephrase the follow up question to be a standalone question.`;
const rephraseQuestionChainPrompt = ChatPromptTemplate.fromMessages([
["system", REPHRASE_QUESTION_SYSTEM_TEMPLATE],
new MessagesPlaceholder("history"),
[
"human",
"Rephrase the following question as a standalone question:\n{question}"
],
]);
const rephraseQuestionChain = RunnableSequence.from([
rephraseQuestionChainPrompt,
new ChatOpenAI({ temperature: 0.1, modelName: "gpt-3.5-turbo-1106" }),
new StringOutputParser(),
])
const originalQuestion = "What are the prerequisites for this course?";
const originalAnswer1 = await retrievalChain.invoke({
question: originalQuestion
});
console.log('originalAnswer - ', originalAnswer1);
const chatHistory = [
new HumanMessage(originalQuestion),
new AIMessage(originalAnswer1),
];
await rephraseQuestionChain.invoke({
question: "Can you list them in bullet point form?",
history: chatHistory,
});
const ANSWER_CHAIN_SYSTEM_TEMPLATE = `You are an experienced researcher,
expert at interpreting and answering questions based on provided sources.
Using the below provided context and chat history,
answer the user's question to the best of
your ability
using only the resources provided. Be verbose!
<context>
{context}
</context>`;
const answerGenerationChainPrompt = ChatPromptTemplate.fromMessages([
["system", ANSWER_CHAIN_SYSTEM_TEMPLATE],
new MessagesPlaceholder("history"),
[
"human",
"Now, answer this question using the previous context and chat history:\n{standalone_question}"
]
]);
// await answerGenerationChainPrompt.formatMessages({
// context: "fake retrieved content",
// standalone_question: "Why is the sky blue?",
// history: [
// new HumanMessage("How are you?"),
// new AIMessage("Fine, thank you!")
// ]
// });
const conversationalRetrievalChain = RunnableSequence.from([
RunnablePassthrough.assign({
standalone_question: rephraseQuestionChain,
}),
RunnablePassthrough.assign({
context: documentRetrievalChain,
}),
answerGenerationChainPrompt,
new ChatOpenAI({ modelName: "gpt-3.5-turbo" }),
new StringOutputParser(),
]);
const messageHistory = new ChatMessageHistory();
const finalRetrievalChain = new RunnableWithMessageHistory({
runnable: conversationalRetrievalChain,
getMessageHistory: (_sessionId) => messageHistory,
historyMessagesKey: "history",
inputMessagesKey: "question",
});
// const originalQuestion = "What are the prerequisites for this course?";
const originalAnswer = await finalRetrievalChain.invoke({
question: originalQuestion,
}, {
configurable: { sessionId: "test_1" }
});
const finalResult = await finalRetrievalChain.invoke({
question: "Can you list them in bullet point form?",
}, {
configurable: { sessionId: "test_1" }
});
console.log(finalResult);