-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathroute.ts
More file actions
292 lines (254 loc) · 10.1 KB
/
route.ts
File metadata and controls
292 lines (254 loc) · 10.1 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
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
import { sew } from "@/actions";
import { _getConfiguredLanguageModelsFull, _getAISDKLanguageModelAndOptions, _updateChatMessages, _isOwnerOfChat } from "@/features/chat/actions";
import { createAgentStream } from "@/features/chat/agent";
import { additionalChatRequestParamsSchema, LanguageModelInfo, SBChatMessage, SearchScope } from "@/features/chat/types";
import { getAnswerPartFromAssistantMessage, getLanguageModelKey, isContextWindowError, CONTEXT_WINDOW_USER_MESSAGE } from "@/features/chat/utils";
import { apiHandler } from "@/lib/apiHandler";
import { ErrorCode } from "@/lib/errorCodes";
import { notFound, requestBodySchemaValidationError, ServiceError, serviceErrorResponse } from "@/lib/serviceError";
import { isServiceError } from "@/lib/utils";
import { withOptionalAuthV2 } from "@/withAuthV2";
import { LanguageModelV2 as AISDKLanguageModelV2 } from "@ai-sdk/provider";
import * as Sentry from "@sentry/nextjs";
import { PrismaClient } from "@sourcebot/db";
import { createLogger, env } from "@sourcebot/shared";
import { captureEvent } from "@/lib/posthog";
import {
createUIMessageStream,
createUIMessageStreamResponse,
JSONValue,
ModelMessage,
StreamTextResult,
UIMessageStreamOnFinishCallback,
UIMessageStreamOptions,
UIMessageStreamWriter
} from "ai";
import { randomUUID } from "crypto";
import { StatusCodes } from "http-status-codes";
import { NextRequest } from "next/server";
import { z } from "zod";
const logger = createLogger('chat-api');
const chatRequestSchema = z.object({
messages: z.array(z.any()),
id: z.string(),
...additionalChatRequestParamsSchema.shape,
})
export const POST = apiHandler(async (req: NextRequest) => {
const requestBody = await req.json();
const parsed = await chatRequestSchema.safeParseAsync(requestBody);
if (!parsed.success) {
return serviceErrorResponse(requestBodySchemaValidationError(parsed.error));
}
const { messages, id, selectedSearchScopes, languageModel: _languageModel } = parsed.data;
// @note: a bit of type massaging is required here since the
// zod schema does not enum on `model` or `provider`.
// @see: chat/types.ts
const languageModel = _languageModel as LanguageModelInfo;
const response = await sew(() =>
withOptionalAuthV2(async ({ org, user, prisma }) => {
// Validate that the chat exists.
const chat = await prisma.chat.findUnique({
where: {
orgId: org.id,
id,
},
});
if (!chat) {
return notFound();
}
// Check ownership - only the owner can send messages
const isOwner = await _isOwnerOfChat(chat, user);
if (!isOwner) {
return {
statusCode: StatusCodes.FORBIDDEN,
errorCode: ErrorCode.INSUFFICIENT_PERMISSIONS,
message: 'Only the owner of a chat can send messages.',
} satisfies ServiceError;
}
// From the language model ID, attempt to find the
// corresponding config in `config.json`.
const languageModelConfig =
(await _getConfiguredLanguageModelsFull())
.find((model) => getLanguageModelKey(model) === getLanguageModelKey(languageModel));
if (!languageModelConfig) {
return {
statusCode: StatusCodes.BAD_REQUEST,
errorCode: ErrorCode.INVALID_REQUEST_BODY,
message: `Language model ${languageModel.model} is not configured.`,
} satisfies ServiceError;
}
const { model, providerOptions } = await _getAISDKLanguageModelAndOptions(languageModelConfig);
await captureEvent('wa_chat_message_sent', {
chatId: id,
messageCount: messages.length,
});
const stream = await createMessageStream({
chatId: id,
messages,
selectedSearchScopes,
model,
modelName: languageModelConfig.displayName ?? languageModelConfig.model,
modelProviderOptions: providerOptions,
orgId: org.id,
prisma,
onFinish: async ({ messages }) => {
await _updateChatMessages({ chatId: id, messages, prisma });
},
onError: (error: unknown) => {
logger.error(error);
Sentry.captureException(error);
if (error == null) {
return 'unknown error';
}
const errorMessage = (() => {
if (typeof error === 'string') return error;
if (error instanceof Error) return error.message;
return JSON.stringify(error);
})();
if (isContextWindowError(errorMessage)) {
return CONTEXT_WINDOW_USER_MESSAGE;
}
return errorMessage;
}
});
return createUIMessageStreamResponse({
stream,
});
})
)
if (isServiceError(response)) {
return serviceErrorResponse(response);
}
return response;
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mergeStreamAsync = async (stream: StreamTextResult<any, any>, writer: UIMessageStreamWriter<SBChatMessage>, options: UIMessageStreamOptions<SBChatMessage> = {}) => {
await new Promise<void>((resolve) => writer.merge(stream.toUIMessageStream({
...options,
onFinish: async () => {
resolve();
}
})));
}
interface CreateMessageStreamResponseProps {
chatId: string;
messages: SBChatMessage[];
selectedSearchScopes: SearchScope[];
model: AISDKLanguageModelV2;
modelName: string;
modelProviderOptions?: Record<string, Record<string, JSONValue>>;
orgId: number;
prisma: PrismaClient;
onFinish: UIMessageStreamOnFinishCallback<SBChatMessage>;
onError: (error: unknown) => string;
}
export const createMessageStream = async ({
chatId,
messages,
selectedSearchScopes,
model,
modelName,
modelProviderOptions,
orgId,
prisma,
onFinish,
onError,
}: CreateMessageStreamResponseProps) => {
const latestMessage = messages[messages.length - 1];
const sources = latestMessage.parts
.filter((part) => part.type === 'data-source')
.map((part) => part.data);
const traceId = randomUUID();
// Extract user messages and assistant answers.
// We will use this as the context we carry between messages.
const messageHistory =
messages.map((message): ModelMessage | undefined => {
if (message.role === 'user') {
return {
role: 'user',
content: message.parts[0].type === 'text' ? message.parts[0].text : '',
};
}
if (message.role === 'assistant') {
const answerPart = getAnswerPartFromAssistantMessage(message, false);
if (answerPart) {
return {
role: 'assistant',
content: [answerPart]
}
}
}
}).filter(message => message !== undefined);
const maxMessages = env.SOURCEBOT_CHAT_MAX_MESSAGE_HISTORY;
const trimmedMessageHistory = messageHistory.length > maxMessages
? messageHistory.slice(-maxMessages)
: messageHistory;
const stream = createUIMessageStream<SBChatMessage>({
execute: async ({ writer }) => {
writer.write({
type: 'start',
});
const startTime = new Date();
const expandedRepos = (await Promise.all(selectedSearchScopes.map(async (scope) => {
if (scope.type === 'repo') {
return [scope.value];
}
if (scope.type === 'reposet') {
const reposet = await prisma.searchContext.findFirst({
where: {
orgId,
name: scope.value
},
include: {
repos: true
}
});
if (reposet) {
return reposet.repos.map(repo => repo.name);
}
}
return [];
}))).flat()
const researchStream = await createAgentStream({
model,
providerOptions: modelProviderOptions,
inputMessages: trimmedMessageHistory,
inputSources: sources,
selectedRepos: expandedRepos,
onWriteSource: (source) => {
writer.write({
type: 'data-source',
data: source,
});
},
traceId,
chatId,
});
await mergeStreamAsync(researchStream, writer, {
sendReasoning: true,
sendStart: false,
sendFinish: false,
});
const totalUsage = await researchStream.totalUsage;
writer.write({
type: 'message-metadata',
messageMetadata: {
totalTokens: totalUsage.totalTokens,
totalInputTokens: totalUsage.inputTokens,
totalOutputTokens: totalUsage.outputTokens,
totalResponseTimeMs: new Date().getTime() - startTime.getTime(),
modelName,
selectedSearchScopes,
traceId,
}
});
writer.write({
type: 'finish',
});
},
onError,
originalMessages: messages,
onFinish,
});
return stream;
};