-
-
Notifications
You must be signed in to change notification settings - Fork 11.1k
/
Copy pathchat.ts
602 lines (527 loc) · 17.8 KB
/
chat.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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
import { PluginRequestPayload, createHeadersWithPluginSettings } from '@lobehub/chat-plugin-sdk';
import { produce } from 'immer';
import { merge } from 'lodash-es';
import { DEFAULT_MODEL_PROVIDER_LIST } from '@/config/modelProviders';
import { INBOX_GUIDE_SYSTEMROLE } from '@/const/guide';
import { INBOX_SESSION_ID } from '@/const/session';
import { DEFAULT_AGENT_CONFIG } from '@/const/settings';
import { TracePayload, TraceTagMap } from '@/const/trace';
import { isServerMode } from '@/const/version';
import {
AgentRuntime,
AgentRuntimeError,
ChatCompletionErrorPayload,
ModelProvider,
} from '@/libs/agent-runtime';
import { filesPrompts } from '@/prompts/files';
import { BuiltinSystemRolePrompts } from '@/prompts/systemRole';
import { useSessionStore } from '@/store/session';
import { sessionMetaSelectors } from '@/store/session/selectors';
import { useToolStore } from '@/store/tool';
import { pluginSelectors, toolSelectors } from '@/store/tool/selectors';
import { useUserStore } from '@/store/user';
import {
modelConfigSelectors,
modelProviderSelectors,
preferenceSelectors,
userProfileSelectors,
} from '@/store/user/selectors';
import { ChatErrorType } from '@/types/fetch';
import { ChatMessage, MessageToolCall } from '@/types/message';
import type { ChatStreamPayload, OpenAIChatMessage } from '@/types/openai/chat';
import { UserMessageContentPart } from '@/types/openai/chat';
import { createErrorResponse } from '@/utils/errorResponse';
import { FetchSSEOptions, fetchSSE, getMessageError } from '@/utils/fetch';
import { genToolCallingName } from '@/utils/toolCall';
import { createTraceHeader, getTraceId } from '@/utils/trace';
import { createHeaderWithAuth, getProviderAuthPayload } from './_auth';
import { API_ENDPOINTS } from './_url';
interface FetchOptions extends FetchSSEOptions {
historySummary?: string;
isWelcomeQuestion?: boolean;
signal?: AbortSignal | undefined;
trace?: TracePayload;
}
interface GetChatCompletionPayload extends Partial<Omit<ChatStreamPayload, 'messages'>> {
messages: ChatMessage[];
}
interface FetchAITaskResultParams extends FetchSSEOptions {
abortController?: AbortController;
onError?: (e: Error, rawError?: any) => void;
/**
* 加载状态变化处理函数
* @param loading - 是否处于加载状态
*/
onLoadingChange?: (loading: boolean) => void;
/**
* 请求对象
*/
params: Partial<ChatStreamPayload>;
trace?: TracePayload;
}
interface CreateAssistantMessageStream extends FetchSSEOptions {
abortController?: AbortController;
historySummary?: string;
isWelcomeQuestion?: boolean;
params: GetChatCompletionPayload;
trace?: TracePayload;
}
/**
* Initializes the AgentRuntime with the client store.
* @param provider - The provider name.
* @param payload - Init options
* @returns The initialized AgentRuntime instance
*
* **Note**: if you try to fetch directly, use `fetchOnClient` instead.
*/
export function initializeWithClientStore(provider: string, payload: any) {
// add auth payload
const providerAuthPayload = getProviderAuthPayload(provider);
const commonOptions = {
// Some provider base openai sdk, so enable it run on browser
dangerouslyAllowBrowser: true,
};
let providerOptions = {};
switch (provider) {
default:
case ModelProvider.OpenAI: {
providerOptions = {
baseURL: providerAuthPayload?.baseURL,
};
break;
}
case ModelProvider.Azure: {
providerOptions = {
apiKey: providerAuthPayload?.apiKey,
apiVersion: providerAuthPayload?.azureApiVersion,
};
break;
}
case ModelProvider.Google: {
providerOptions = {
baseURL: providerAuthPayload?.baseURL,
};
break;
}
case ModelProvider.Bedrock: {
if (providerAuthPayload?.apiKey) {
providerOptions = {
accessKeyId: providerAuthPayload?.awsAccessKeyId,
accessKeySecret: providerAuthPayload?.awsSecretAccessKey,
region: providerAuthPayload?.awsRegion,
sessionToken: providerAuthPayload?.awsSessionToken,
};
}
break;
}
case ModelProvider.Ollama: {
providerOptions = {
baseURL: providerAuthPayload?.baseURL,
};
break;
}
case ModelProvider.Perplexity: {
providerOptions = {
apikey: providerAuthPayload?.apiKey,
baseURL: providerAuthPayload?.baseURL,
};
break;
}
case ModelProvider.Anthropic: {
providerOptions = {
baseURL: providerAuthPayload?.baseURL,
};
break;
}
case ModelProvider.Groq: {
providerOptions = {
apikey: providerAuthPayload?.apiKey,
baseURL: providerAuthPayload?.baseURL,
};
break;
}
case ModelProvider.Cloudflare: {
providerOptions = {
apikey: providerAuthPayload?.apiKey,
baseURLOrAccountID: providerAuthPayload?.cloudflareBaseURLOrAccountID,
};
break;
}
}
/**
* Configuration override order:
* payload -> providerOptions -> providerAuthPayload -> commonOptions
*/
return AgentRuntime.initializeWithProviderOptions(provider, {
[provider]: {
...commonOptions,
...providerAuthPayload,
...providerOptions,
...payload,
},
});
}
class ChatService {
createAssistantMessage = async (
{ plugins: enabledPlugins, messages, ...params }: GetChatCompletionPayload,
options?: FetchOptions,
) => {
const payload = merge(
{
model: DEFAULT_AGENT_CONFIG.model,
stream: true,
...DEFAULT_AGENT_CONFIG.params,
},
params,
);
// ============ 1. preprocess messages ============ //
const oaiMessages = this.processMessages(
{
messages,
model: payload.model,
tools: enabledPlugins,
},
options,
);
// ============ 2. preprocess tools ============ //
const filterTools = toolSelectors.enabledSchema(enabledPlugins)(useToolStore.getState());
// check this model can use function call
const canUseFC = modelProviderSelectors.isModelEnabledFunctionCall(payload.model)(
useUserStore.getState(),
);
// the rule that model can use tools:
// 1. tools is not empty
// 2. model can use function call
const shouldUseTools = filterTools.length > 0 && canUseFC;
const tools = shouldUseTools ? filterTools : undefined;
return this.getChatCompletion({ ...params, messages: oaiMessages, tools }, options);
};
createAssistantMessageStream = async ({
params,
abortController,
onAbort,
onMessageHandle,
onErrorHandle,
onFinish,
trace,
isWelcomeQuestion,
historySummary,
}: CreateAssistantMessageStream) => {
await this.createAssistantMessage(params, {
historySummary,
isWelcomeQuestion,
onAbort,
onErrorHandle,
onFinish,
onMessageHandle,
signal: abortController?.signal,
trace: this.mapTrace(trace, TraceTagMap.Chat),
});
};
getChatCompletion = async (params: Partial<ChatStreamPayload>, options?: FetchOptions) => {
const { signal } = options ?? {};
const { provider = ModelProvider.OpenAI, ...res } = params;
let model = res.model || DEFAULT_AGENT_CONFIG.model;
// if the provider is Azure, get the deployment name as the request model
if (provider === ModelProvider.Azure) {
const chatModelCards = modelProviderSelectors.getModelCardsById(provider)(
useUserStore.getState(),
);
const deploymentName = chatModelCards.find((i) => i.id === model)?.deploymentName;
if (deploymentName) model = deploymentName;
}
const payload = merge(
{ model: DEFAULT_AGENT_CONFIG.model, stream: true, ...DEFAULT_AGENT_CONFIG.params },
{ ...res, model },
);
/**
* Use browser agent runtime
*/
const enableFetchOnClient = modelConfigSelectors.isProviderFetchOnClient(provider)(
useUserStore.getState(),
);
let fetcher: typeof fetch | undefined = undefined;
if (enableFetchOnClient) {
/**
* Notes:
* 1. Browser agent runtime will skip auth check if a key and endpoint provided by
* user which will cause abuse of plugins services
* 2. This feature will be disabled by default
*/
fetcher = async () => {
try {
return await this.fetchOnClient({ payload, provider, signal });
} catch (e) {
const {
errorType = ChatErrorType.BadRequest,
error: errorContent,
...res
} = e as ChatCompletionErrorPayload;
const error = errorContent || e;
// track the error at server side
console.error(`Route: [${provider}] ${errorType}:`, error);
return createErrorResponse(errorType, { error, ...res, provider });
}
};
}
const traceHeader = createTraceHeader({ ...options?.trace });
const headers = await createHeaderWithAuth({
headers: { 'Content-Type': 'application/json', ...traceHeader },
provider,
});
const providerConfig = DEFAULT_MODEL_PROVIDER_LIST.find((item) => item.id === provider);
return fetchSSE(API_ENDPOINTS.chat(provider), {
body: JSON.stringify(payload),
fetcher: fetcher,
headers,
method: 'POST',
onAbort: options?.onAbort,
onErrorHandle: options?.onErrorHandle,
onFinish: options?.onFinish,
onMessageHandle: options?.onMessageHandle,
signal,
// use smoothing when enable client fetch
// https://github.com/lobehub/lobe-chat/issues/3800
smoothing: providerConfig?.smoothing || enableFetchOnClient,
});
};
/**
* run the plugin api to get result
* @param params
* @param options
*/
runPluginApi = async (params: PluginRequestPayload, options?: FetchOptions) => {
const s = useToolStore.getState();
const settings = pluginSelectors.getPluginSettingsById(params.identifier)(s);
const manifest = pluginSelectors.getToolManifestById(params.identifier)(s);
const traceHeader = createTraceHeader(this.mapTrace(options?.trace, TraceTagMap.ToolCalling));
const headers = await createHeaderWithAuth({
headers: { ...createHeadersWithPluginSettings(settings), ...traceHeader },
});
const gatewayURL = manifest?.gateway ?? API_ENDPOINTS.gateway;
const res = await fetch(gatewayURL, {
body: JSON.stringify({ ...params, manifest }),
headers,
method: 'POST',
signal: options?.signal,
});
if (!res.ok) {
throw await getMessageError(res);
}
const text = await res.text();
return { text, traceId: getTraceId(res) };
};
fetchPresetTaskResult = async ({
params,
onMessageHandle,
onFinish,
onError,
onLoadingChange,
abortController,
trace,
}: FetchAITaskResultParams) => {
const errorHandle = (error: Error, errorContent?: any) => {
onLoadingChange?.(false);
if (abortController?.signal.aborted) {
return;
}
onError?.(error, errorContent);
console.error(error);
};
onLoadingChange?.(true);
try {
await this.getChatCompletion(params, {
onErrorHandle: (error) => {
errorHandle(new Error(error.message), error);
},
onFinish,
onMessageHandle,
signal: abortController?.signal,
trace: this.mapTrace(trace, TraceTagMap.SystemChain),
});
onLoadingChange?.(false);
} catch (e) {
errorHandle(e as Error);
}
};
private processMessages = (
{
messages,
tools,
model,
}: {
messages: ChatMessage[];
model: string;
tools?: string[];
},
options?: FetchOptions,
): OpenAIChatMessage[] => {
// handle content type for vision model
// for the models with visual ability, add image url to content
// refs: https://platform.openai.com/docs/guides/vision/quick-start
const getContent = (m: ChatMessage) => {
// only if message doesn't have images and files, then return the plain content
if ((!m.imageList || m.imageList.length === 0) && (!m.fileList || m.fileList.length === 0))
return m.content;
const imageList = m.imageList || [];
const filesContext = isServerMode ? filesPrompts({ fileList: m.fileList, imageList }) : '';
return [
{ text: (m.content + '\n\n' + filesContext).trim(), type: 'text' },
...imageList.map(
(i) => ({ image_url: { detail: 'auto', url: i.url }, type: 'image_url' }) as const,
),
] as UserMessageContentPart[];
};
let postMessages = messages.map((m): OpenAIChatMessage => {
switch (m.role) {
case 'user': {
return { content: getContent(m), role: m.role };
}
case 'assistant': {
return {
content: m.content,
role: m.role,
tool_calls: m.tools?.map(
(tool): MessageToolCall => ({
function: {
arguments: tool.arguments,
name: genToolCallingName(tool.identifier, tool.apiName, tool.type),
},
id: tool.id,
type: 'function',
}),
),
};
}
case 'tool': {
return {
content: m.content,
name: genToolCallingName(m.plugin!.identifier, m.plugin!.apiName, m.plugin?.type),
role: m.role,
tool_call_id: m.tool_call_id,
};
}
default: {
return { content: m.content, role: m.role as any };
}
}
});
postMessages = produce(postMessages, (draft) => {
// if it's a welcome question, inject InboxGuide SystemRole
const inboxGuideSystemRole =
options?.isWelcomeQuestion &&
options?.trace?.sessionId === INBOX_SESSION_ID &&
INBOX_GUIDE_SYSTEMROLE;
// Inject Tool SystemRole
const hasTools = tools && tools?.length > 0;
const hasFC =
hasTools &&
modelProviderSelectors.isModelEnabledFunctionCall(model)(useUserStore.getState());
const toolsSystemRoles =
hasFC && toolSelectors.enabledSystemRoles(tools)(useToolStore.getState());
const injectSystemRoles = BuiltinSystemRolePrompts({
historySummary: options?.historySummary,
plugins: toolsSystemRoles as string,
welcome: inboxGuideSystemRole as string,
});
if (!injectSystemRoles) return;
const systemMessage = draft.find((i) => i.role === 'system');
if (systemMessage) {
systemMessage.content = [systemMessage.content, injectSystemRoles]
.filter(Boolean)
.join('\n\n');
} else {
draft.unshift({
content: injectSystemRoles,
role: 'system',
});
}
});
return this.reorderToolMessages(postMessages);
};
private mapTrace = (trace?: TracePayload, tag?: TraceTagMap): TracePayload => {
const tags = sessionMetaSelectors.currentAgentMeta(useSessionStore.getState()).tags || [];
const enabled = preferenceSelectors.userAllowTrace(useUserStore.getState());
if (!enabled) return { ...trace, enabled: false };
return {
...trace,
enabled: true,
tags: [tag, ...(trace?.tags || []), ...tags].filter(Boolean) as string[],
userId: userProfileSelectors.userId(useUserStore.getState()),
};
};
/**
* Fetch chat completion on the client side.
*/
private fetchOnClient = async (params: {
payload: Partial<ChatStreamPayload>;
provider: string;
signal?: AbortSignal;
}) => {
const agentRuntime = await initializeWithClientStore(params.provider, params.payload);
const data = params.payload as ChatStreamPayload;
/**
* if enable login and not signed in, return unauthorized error
*/
const userStore = useUserStore.getState();
if (userStore.enableAuth() && !userStore.isSignedIn) {
throw AgentRuntimeError.createError(ChatErrorType.InvalidAccessCode);
}
return agentRuntime.chat(data, { signal: params.signal });
};
/**
* Reorder tool messages to ensure that tool messages are displayed in the correct order.
* see https://github.com/lobehub/lobe-chat/pull/3155
*/
private reorderToolMessages = (messages: OpenAIChatMessage[]): OpenAIChatMessage[] => {
// 1. 先收集所有 assistant 消息中的有效 tool_call_id
const validToolCallIds = new Set<string>();
messages.forEach((message) => {
if (message.role === 'assistant' && message.tool_calls) {
message.tool_calls.forEach((toolCall) => {
validToolCallIds.add(toolCall.id);
});
}
});
// 2. 收集所有有效的 tool 消息
const toolMessages: Record<string, OpenAIChatMessage> = {};
messages.forEach((message) => {
if (
message.role === 'tool' &&
message.tool_call_id &&
validToolCallIds.has(message.tool_call_id)
) {
toolMessages[message.tool_call_id] = message;
}
});
// 3. 重新排序消息
const reorderedMessages: OpenAIChatMessage[] = [];
messages.forEach((message) => {
// 跳过无效的 tool 消息
if (
message.role === 'tool' &&
(!message.tool_call_id || !validToolCallIds.has(message.tool_call_id))
) {
return;
}
// 检查是否已经添加过该 tool 消息
const hasPushed = reorderedMessages.some(
(m) => !!message.tool_call_id && m.tool_call_id === message.tool_call_id,
);
if (hasPushed) return;
reorderedMessages.push(message);
// 如果是 assistant 消息且有 tool_calls,添加对应的 tool 消息
if (message.role === 'assistant' && message.tool_calls) {
message.tool_calls.forEach((toolCall) => {
const correspondingToolMessage = toolMessages[toolCall.id];
if (correspondingToolMessage) {
reorderedMessages.push(correspondingToolMessage);
delete toolMessages[toolCall.id];
}
});
}
});
return reorderedMessages;
};
}
export const chatService = new ChatService();