-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
conversational_retrieval_chain.ts
341 lines (318 loc) Β· 11 KB
/
conversational_retrieval_chain.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
import type { BaseRetrieverInterface } from "@langchain/core/retrievers";
import { PromptTemplate } from "@langchain/core/prompts";
import { BaseMessage, HumanMessage, AIMessage } from "@langchain/core/messages";
import { ChainValues } from "@langchain/core/utils/types";
import { CallbackManagerForChainRun } from "@langchain/core/callbacks/manager";
import { SerializedChatVectorDBQAChain } from "./serde.js";
import { BaseChain, ChainInputs } from "./base.js";
import { LLMChain } from "./llm_chain.js";
import { QAChainParams, loadQAChain } from "./question_answering/load.js";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type LoadValues = Record<string, any>;
const question_generator_template = `Given the following conversation and a follow up question, rephrase the follow up question to be a standalone question.
Chat History:
{chat_history}
Follow Up Input: {question}
Standalone question:`;
/**
* Interface for the input parameters of the
* ConversationalRetrievalQAChain class.
*/
export interface ConversationalRetrievalQAChainInput extends ChainInputs {
retriever: BaseRetrieverInterface;
combineDocumentsChain: BaseChain;
questionGeneratorChain: LLMChain;
returnSourceDocuments?: boolean;
returnGeneratedQuestion?: boolean;
inputKey?: string;
}
/**
* @deprecated This class will be removed in 1.0.0. See below for an example implementation using
* `createRetrievalChain`.
*
* Class for conducting conversational question-answering tasks with a
* retrieval component. Extends the BaseChain class and implements the
* ConversationalRetrievalQAChainInput interface.
* @example
* ```typescript
* import { ChatAnthropic } from "@langchain/anthropic";
* import {
* ChatPromptTemplate,
* MessagesPlaceholder,
* } from "@langchain/core/prompts";
* import { BaseMessage } from "@langchain/core/messages";
* import { createStuffDocumentsChain } from "langchain/chains/combine_documents";
* import { createHistoryAwareRetriever } from "langchain/chains/history_aware_retriever";
* import { createRetrievalChain } from "langchain/chains/retrieval";
*
* const retriever = ...your retriever;
* const llm = new ChatAnthropic();
*
* // Contextualize question
* const contextualizeQSystemPrompt = `
* Given a chat history and the latest user question
* which might reference context in the chat history,
* formulate a standalone question which can be understood
* without the chat history. Do NOT answer the question, just
* reformulate it if needed and otherwise return it as is.`;
* const contextualizeQPrompt = ChatPromptTemplate.fromMessages([
* ["system", contextualizeQSystemPrompt],
* new MessagesPlaceholder("chat_history"),
* ["human", "{input}"],
* ]);
* const historyAwareRetriever = await createHistoryAwareRetriever({
* llm,
* retriever,
* rephrasePrompt: contextualizeQPrompt,
* });
*
* // Answer question
* const qaSystemPrompt = `
* You are an assistant for question-answering tasks. Use
* the following pieces of retrieved context to answer the
* question. If you don't know the answer, just say that you
* don't know. Use three sentences maximum and keep the answer
* concise.
* \n\n
* {context}`;
* const qaPrompt = ChatPromptTemplate.fromMessages([
* ["system", qaSystemPrompt],
* new MessagesPlaceholder("chat_history"),
* ["human", "{input}"],
* ]);
*
* // Below we use createStuffDocuments_chain to feed all retrieved context
* // into the LLM. Note that we can also use StuffDocumentsChain and other
* // instances of BaseCombineDocumentsChain.
* const questionAnswerChain = await createStuffDocumentsChain({
* llm,
* prompt: qaPrompt,
* });
*
* const ragChain = await createRetrievalChain({
* retriever: historyAwareRetriever,
* combineDocsChain: questionAnswerChain,
* });
*
* // Usage:
* const chat_history: BaseMessage[] = [];
* const response = await ragChain.invoke({
* chat_history,
* input: "...",
* });
* ```
*/
export class ConversationalRetrievalQAChain
extends BaseChain
implements ConversationalRetrievalQAChainInput
{
static lc_name() {
return "ConversationalRetrievalQAChain";
}
inputKey = "question";
chatHistoryKey = "chat_history";
get inputKeys() {
return [this.inputKey, this.chatHistoryKey];
}
get outputKeys() {
return this.combineDocumentsChain.outputKeys.concat(
this.returnSourceDocuments ? ["sourceDocuments"] : []
);
}
retriever: BaseRetrieverInterface;
combineDocumentsChain: BaseChain;
questionGeneratorChain: LLMChain;
returnSourceDocuments = false;
returnGeneratedQuestion = false;
constructor(fields: ConversationalRetrievalQAChainInput) {
super(fields);
this.retriever = fields.retriever;
this.combineDocumentsChain = fields.combineDocumentsChain;
this.questionGeneratorChain = fields.questionGeneratorChain;
this.inputKey = fields.inputKey ?? this.inputKey;
this.returnSourceDocuments =
fields.returnSourceDocuments ?? this.returnSourceDocuments;
this.returnGeneratedQuestion =
fields.returnGeneratedQuestion ?? this.returnGeneratedQuestion;
}
/**
* Static method to convert the chat history input into a formatted
* string.
* @param chatHistory Chat history input which can be a string, an array of BaseMessage instances, or an array of string arrays.
* @returns A formatted string representing the chat history.
*/
static getChatHistoryString(
chatHistory: string | BaseMessage[] | string[][]
) {
let historyMessages: BaseMessage[];
if (Array.isArray(chatHistory)) {
// TODO: Deprecate on a breaking release
if (
Array.isArray(chatHistory[0]) &&
typeof chatHistory[0][0] === "string"
) {
console.warn(
"Passing chat history as an array of strings is deprecated.\nPlease see https://js.langchain.com/docs/modules/chains/popular/chat_vector_db#externally-managed-memory for more information."
);
historyMessages = chatHistory.flat().map((stringMessage, i) => {
if (i % 2 === 0) {
return new HumanMessage(stringMessage);
} else {
return new AIMessage(stringMessage);
}
});
} else {
historyMessages = chatHistory as BaseMessage[];
}
return historyMessages
.map((chatMessage) => {
if (chatMessage._getType() === "human") {
return `Human: ${chatMessage.content}`;
} else if (chatMessage._getType() === "ai") {
return `Assistant: ${chatMessage.content}`;
} else {
return `${chatMessage.content}`;
}
})
.join("\n");
}
return chatHistory;
}
/** @ignore */
async _call(
values: ChainValues,
runManager?: CallbackManagerForChainRun
): Promise<ChainValues> {
if (!(this.inputKey in values)) {
throw new Error(`Question key ${this.inputKey} not found.`);
}
if (!(this.chatHistoryKey in values)) {
throw new Error(`Chat history key ${this.chatHistoryKey} not found.`);
}
const question: string = values[this.inputKey];
const chatHistory: string =
ConversationalRetrievalQAChain.getChatHistoryString(
values[this.chatHistoryKey]
);
let newQuestion = question;
if (chatHistory.length > 0) {
const result = await this.questionGeneratorChain.call(
{
question,
chat_history: chatHistory,
},
runManager?.getChild("question_generator")
);
const keys = Object.keys(result);
if (keys.length === 1) {
newQuestion = result[keys[0]];
} else {
throw new Error(
"Return from llm chain has multiple values, only single values supported."
);
}
}
const docs = await this.retriever.getRelevantDocuments(
newQuestion,
runManager?.getChild("retriever")
);
const inputs = {
question: newQuestion,
input_documents: docs,
chat_history: chatHistory,
};
let result = await this.combineDocumentsChain.call(
inputs,
runManager?.getChild("combine_documents")
);
if (this.returnSourceDocuments) {
result = {
...result,
sourceDocuments: docs,
};
}
if (this.returnGeneratedQuestion) {
result = {
...result,
generatedQuestion: newQuestion,
};
}
return result;
}
_chainType(): string {
return "conversational_retrieval_chain";
}
static async deserialize(
_data: SerializedChatVectorDBQAChain,
_values: LoadValues
): Promise<ConversationalRetrievalQAChain> {
throw new Error("Not implemented.");
}
serialize(): SerializedChatVectorDBQAChain {
throw new Error("Not implemented.");
}
/**
* Static method to create a new ConversationalRetrievalQAChain from a
* BaseLanguageModel and a BaseRetriever.
* @param llm {@link BaseLanguageModelInterface} instance used to generate a new question.
* @param retriever {@link BaseRetrieverInterface} instance used to retrieve relevant documents.
* @param options.returnSourceDocuments Whether to return source documents in the final output
* @param options.questionGeneratorChainOptions Options to initialize the standalone question generation chain used as the first internal step
* @param options.qaChainOptions {@link QAChainParams} used to initialize the QA chain used as the second internal step
* @returns A new instance of ConversationalRetrievalQAChain.
*/
static fromLLM(
llm: BaseLanguageModelInterface,
retriever: BaseRetrieverInterface,
options: {
outputKey?: string; // not used
returnSourceDocuments?: boolean;
/** @deprecated Pass in questionGeneratorChainOptions.template instead */
questionGeneratorTemplate?: string;
/** @deprecated Pass in qaChainOptions.prompt instead */
qaTemplate?: string;
questionGeneratorChainOptions?: {
llm?: BaseLanguageModelInterface;
template?: string;
};
qaChainOptions?: QAChainParams;
} & Omit<
ConversationalRetrievalQAChainInput,
"retriever" | "combineDocumentsChain" | "questionGeneratorChain"
> = {}
): ConversationalRetrievalQAChain {
const {
questionGeneratorTemplate,
qaTemplate,
qaChainOptions = {
type: "stuff",
prompt: qaTemplate
? PromptTemplate.fromTemplate(qaTemplate)
: undefined,
},
questionGeneratorChainOptions,
verbose,
...rest
} = options;
const qaChain = loadQAChain(llm, qaChainOptions);
const questionGeneratorChainPrompt = PromptTemplate.fromTemplate(
questionGeneratorChainOptions?.template ??
questionGeneratorTemplate ??
question_generator_template
);
const questionGeneratorChain = new LLMChain({
prompt: questionGeneratorChainPrompt,
llm: questionGeneratorChainOptions?.llm ?? llm,
verbose,
});
const instance = new this({
retriever,
combineDocumentsChain: qaChain,
questionGeneratorChain,
verbose,
...rest,
});
return instance;
}
}