forked from langchain-ai/chat-langchainjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.ts
269 lines (242 loc) · 8.79 KB
/
route.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
import { NextRequest, NextResponse } from "next/server";
import type { Document } from "@langchain/core/documents";
import {
Runnable,
RunnableSequence,
RunnableMap,
RunnableBranch,
RunnableLambda,
} from "@langchain/core/runnables";
import { HumanMessage, AIMessage, BaseMessage } from "@langchain/core/messages";
import { BaseChatModel } from "@langchain/core/language_models/chat_models";
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { ChatFireworks } from "@langchain/community/chat_models/fireworks";
import { StringOutputParser } from "@langchain/core/output_parsers";
import {
PromptTemplate,
ChatPromptTemplate,
MessagesPlaceholder,
} from "@langchain/core/prompts";
import weaviate, { ApiKey } from "weaviate-ts-client";
import { WeaviateStore } from "@langchain/weaviate";
export const runtime = "edge";
const RESPONSE_TEMPLATE = `You are an expert programmer and problem-solver, tasked to answer any question about Langchain.
Using the provided context, answer the user's question to the best of your ability using the resources provided.
Generate a comprehensive and informative answer (but no more than 80 words) for a given question based solely on the provided search results (URL and content).
You must only use information from the provided search results.
Use an unbiased and journalistic tone.
Combine search results together into a coherent answer.
Do not repeat text.
Cite search results using [\${{number}}] notation.
Only cite the most relevant results that answer the question accurately.
Place these citations at the end of the sentence or paragraph that reference them - do not put them all at the end.
If different results refer to different entities within the same name, write separate answers for each entity.
If there is nothing in the context relevant to the question at hand, just say "Hmm, I'm not sure." Don't try to make up an answer.
You should use bullet points in your answer for readability
Put citations where they apply rather than putting them all at the end.
Anything between the following \`context\` html blocks is retrieved from a knowledge bank, not part of the conversation with the user.
<context>
{context}
<context/>
REMEMBER: If there is no relevant information within the context, just say "Hmm, I'm not sure." Don't try to make up an answer.
Anything between the preceding 'context' html blocks is retrieved from a knowledge bank, not part of the conversation with the user.`;
const REPHRASE_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:`;
type RetrievalChainInput = {
chat_history: string;
question: string;
};
const getRetriever = async () => {
if (
!process.env.WEAVIATE_INDEX_NAME ||
!process.env.WEAVIATE_API_KEY ||
!process.env.WEAVIATE_URL
) {
throw new Error(
"WEAVIATE_INDEX_NAME, WEAVIATE_API_KEY and WEAVIATE_URL environment variables must be set",
);
}
const client = weaviate.client({
scheme: "https",
host: process.env.WEAVIATE_URL,
apiKey: new ApiKey(process.env.WEAVIATE_API_KEY),
});
const vectorstore = await WeaviateStore.fromExistingIndex(
new OpenAIEmbeddings({}),
{
client,
indexName: process.env.WEAVIATE_INDEX_NAME,
textKey: "text",
metadataKeys: ["source", "title"],
},
);
return vectorstore.asRetriever({ k: 6 });
};
const createRetrieverChain = (llm: BaseChatModel, retriever: Runnable) => {
// Small speed/accuracy optimization: no need to rephrase the first question
// since there shouldn't be any meta-references to prior chat history
const CONDENSE_QUESTION_PROMPT =
PromptTemplate.fromTemplate(REPHRASE_TEMPLATE);
const condenseQuestionChain = RunnableSequence.from([
CONDENSE_QUESTION_PROMPT,
llm,
new StringOutputParser(),
]).withConfig({
runName: "CondenseQuestion",
});
const hasHistoryCheckFn = RunnableLambda.from(
(input: RetrievalChainInput) => input.chat_history.length > 0,
).withConfig({ runName: "HasChatHistoryCheck" });
const conversationChain = condenseQuestionChain.pipe(retriever).withConfig({
runName: "RetrievalChainWithHistory",
});
const basicRetrievalChain = RunnableLambda.from(
(input: RetrievalChainInput) => input.question,
)
.withConfig({
runName: "Itemgetter:question",
})
.pipe(retriever)
.withConfig({ runName: "RetrievalChainWithNoHistory" });
return RunnableBranch.from([
[hasHistoryCheckFn, conversationChain],
basicRetrievalChain,
]).withConfig({
runName: "FindDocs",
});
};
const formatDocs = (docs: Document[]) => {
return docs
.map((doc, i) => `<doc id='${i}'>${doc.pageContent}</doc>`)
.join("\n");
};
const formatChatHistoryAsString = (history: BaseMessage[]) => {
return history
.map((message) => `${message._getType()}: ${message.content}`)
.join("\n");
};
const serializeHistory = (input: any) => {
const chatHistory = input.chat_history || [];
const convertedChatHistory = [];
for (const message of chatHistory) {
if (message.human !== undefined) {
convertedChatHistory.push(new HumanMessage({ content: message.human }));
}
if (message["ai"] !== undefined) {
convertedChatHistory.push(new AIMessage({ content: message.ai }));
}
}
return convertedChatHistory;
};
const createChain = (llm: BaseChatModel, retriever: Runnable) => {
const retrieverChain = createRetrieverChain(llm, retriever);
const context = RunnableMap.from({
context: RunnableSequence.from([
({ question, chat_history }) => ({
question,
chat_history: formatChatHistoryAsString(chat_history),
}),
retrieverChain,
RunnableLambda.from(formatDocs).withConfig({
runName: "FormatDocumentChunks",
}),
]),
question: RunnableLambda.from(
(input: RetrievalChainInput) => input.question,
).withConfig({
runName: "Itemgetter:question",
}),
chat_history: RunnableLambda.from(
(input: RetrievalChainInput) => input.chat_history,
).withConfig({
runName: "Itemgetter:chat_history",
}),
}).withConfig({ tags: ["RetrieveDocs"] });
const prompt = ChatPromptTemplate.fromMessages([
["system", RESPONSE_TEMPLATE],
new MessagesPlaceholder("chat_history"),
["human", "{question}"],
]);
const responseSynthesizerChain = RunnableSequence.from([
prompt,
llm,
new StringOutputParser(),
]).withConfig({
tags: ["GenerateResponse"],
});
return RunnableSequence.from([
{
question: RunnableLambda.from(
(input: RetrievalChainInput) => input.question,
).withConfig({
runName: "Itemgetter:question",
}),
chat_history: RunnableLambda.from(serializeHistory).withConfig({
runName: "SerializeHistory",
}),
},
context,
responseSynthesizerChain,
]);
};
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const input = body.input;
const config = body.config;
let llm;
if (config.configurable.llm === "openai_gpt_3_5_turbo") {
llm = new ChatOpenAI({
modelName: "gpt-3.5-turbo-1106",
temperature: 0,
});
} else if (config.configurable.llm === "fireworks_mixtral") {
llm = new ChatFireworks({
modelName: "accounts/fireworks/models/mixtral-8x7b-instruct",
temperature: 0,
});
} else {
throw new Error(
"Invalid LLM option passed. Must be 'openai' or 'mixtral'. Received: " +
config.llm,
);
}
const retriever = await getRetriever();
const answerChain = createChain(llm, retriever);
/**
* Narrows streamed log output down to final output and the FindDocs tagged chain to
* selectively stream back sources.
*
* You can use .stream() to create a ReadableStream with just the final output which
* you can pass directly to the Response as well:
* https://js.langchain.com/docs/expression_language/interface#stream
*/
const stream = answerChain.streamLog(input, config, {
includeNames: body.includeNames,
});
// Only return a selection of output to the frontend
const textEncoder = new TextEncoder();
const clientStream = new ReadableStream({
async start(controller) {
for await (const chunk of stream) {
controller.enqueue(
textEncoder.encode(
"event: data\ndata: " + JSON.stringify(chunk) + "\n\n",
),
);
}
controller.enqueue(textEncoder.encode("event: end\n\n"));
controller.close();
},
});
return new Response(clientStream, {
headers: { "Content-Type": "text/event-stream" },
});
} catch (e: any) {
console.error(e);
return NextResponse.json({ error: e.message }, { status: 500 });
}
}