-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathGenuiChat.vue
More file actions
722 lines (648 loc) · 20.9 KB
/
Copy pathGenuiChat.vue
File metadata and controls
722 lines (648 loc) · 20.9 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
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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
<script setup lang="ts">
import '@opentiny/tiny-robot/dist/style.css';
import { TrBubbleList, TrSender, TrBubbleProvider, BubbleMarkdownContentRenderer } from '@opentiny/tiny-robot';
import { AIClient, GeneratingStatus, STATUS, type ChatMessage } from '@opentiny/tiny-robot-kit';
import { IconAi, IconUser, IconArrowDown } from '@opentiny/tiny-robot-svgs';
import type {
BubbleRoleConfig,
BubbleCommonProps,
BubbleContentItem,
UserItem,
UserTextItem,
} from '@opentiny/tiny-robot';
import { ref, watch, computed, h, inject } from 'vue';
import type { Ref, Component } from 'vue';
import { CustomModelProvider } from './CustomModelProvider';
import { scrollEnd, throttle, toSlotFunction } from './chat-utils';
import { useFileUpload } from './useFileUpload';
import AttachmentsRenderer from './renderer/AttachmentsRenderer.vue';
import TemplateDataRenderer from './renderer/TemplateDataRenderer.vue';
import ReasoningRenderer from './renderer/ReasoningRenderer.vue';
import ToolRenderer from './renderer/ToolRenderer.vue';
import { type FileMeta, MIME_TYPE_MAP } from './file-upload/file-utils';
import { cardIdSymbol } from './useChat';
import { emitter } from './event-emitter';
import type { IChatProps, ICustomActionItem, IRolesConfig } from './chat.types';
import GeneratingComponent from './GeneratingComponent.vue';
import { useChatAction } from './continue-chat-action';
import type { IMessageItem, IStreamData } from '@opentiny/genui-sdk-core';
import type { IRendererProps } from '../renderer';
import { GenuiRenderer } from '../renderer';
import ErrorText from './ErrorText.vue';
import { useResize } from './composable/use-resize';
import { useConversation } from './tiny-robot-patch/useConversation';
import { useI18n } from './i18n';
import { GENUI_CONFIG } from '../config-provider/injection-tokens';
import { IResponseHandler, defaultResponseHandlers } from './response-handler';
const props = defineProps<IChatProps>();
const genuiConfig = inject(GENUI_CONFIG);
const { t } = useI18n();
const isAllowFiles = computed(() => {
const supportImage = props.features?.supportImage;
if (supportImage && supportImage?.enabled !== false) {
return true;
}
return false;
});
const buttonGroup = computed(() => {
const fileTypes = props.features?.supportImage?.supportedFileTypes;
const accept = fileTypes?.map((type: string) => MIME_TYPE_MAP[type.toLowerCase()]).join(',');
return {
file: {
disabled: false,
accept,
},
};
});
// 定义角色图标以及样式
const defaultRoles: { user: BubbleRoleConfig; assistant: BubbleRoleConfig } = {
assistant: {
placement: 'start',
avatar: h(IconAi, { style: { fontSize: '32px' } }),
maxWidth: '100%',
customContentField: 'messages',
},
user: {
placement: 'end',
maxWidth: '90%',
avatar: h(IconUser, { style: { fontSize: '32px' } }),
customContentField: 'messages',
},
};
const wrapSlots = (slots: any) => {
if (!slots) {
return;
}
const newSlots: Record<string, any> = {};
Object.keys(slots).forEach((key) => {
newSlots[key] = (props: any) => {
const isFinished = computed(() => {
if (props.bubbleProps.role !== 'assistant') {
return true;
}
return props.index !== messageManager.value.messages.value.length - 1 || !generating.value;
});
const slotFn = toSlotFunction(slots[key]);
if (slotFn) {
return slotFn({
...props,
isFinished: isFinished.value,
messageManager: messageManager.value,
chatMessage: messageManager.value.messages.value[props.index],
});
}
return null;
};
});
return newSlots;
};
const roles = computed(() => {
const mergedRoles = { ...defaultRoles };
for (const keyAny in props.roles) {
const key = keyAny as keyof IRolesConfig;
mergedRoles[key] = {
...defaultRoles[key],
...props.roles[key],
slots: wrapSlots(props.roles[key]?.slots),
};
}
return mergedRoles;
});
const flatAllMessages = (messages: ChatMessage[]) =>
messages
.filter((item) => item.role === 'assistant')
.reduce((acc: IMessageItem[], chatItem) => {
const itemMessages = (chatItem as { messages?: IMessageItem[] }).messages;
if (Array.isArray(itemMessages)) {
return acc.concat(...itemMessages);
}
return acc;
}, []);
const getCardMessage = (cardId: string) => {
const flatMessages = flatAllMessages(messages.value);
return flatMessages.find((message: IMessageItem) => 'id' in message && message.id === cardId);
};
const saveState = (context: Record<string | symbol, any>) => {
const cardId = context[cardIdSymbol];
const cardMessage = getCardMessage(cardId);
if (cardMessage) {
(cardMessage as any).state = JSON.parse(JSON.stringify(context.state || {}));
}
saveConversations();
};
const chat = ({ llmFriendlyMessage, humanFriendlyMessage, context }: any) => {
saveState(context);
messageManager.value.addMessage({
role: 'user',
content: llmFriendlyMessage,
messages: [{ type: 'text', content: humanFriendlyMessage }],
});
messageManager.value.send();
};
const { continueChatAction, saveStateAction } = useChatAction({chat, saveState}); //TODO: Refactor
const generating = computed(() => GeneratingStatus.includes(messageManager.value.messageState.status));
const markdownRenderer = new BubbleMarkdownContentRenderer({
defaultAttrs: { class: 'markdown-content' },
mdConfig: { html: true },
});
const lastSchemaCardId = computed(() => {
const lastChatMessage = messages.value[messages.value.length - 1];
if (lastChatMessage?.role !== 'assistant') {
return null;
}
const items = lastChatMessage?.messages;
if (!Array.isArray(items) || !items?.length) {
return null;
}
return items[items.length - 1].id;
});
const customComponentsMap = computed(() => {
const map: Record<string, Component> = {};
props.customComponents?.forEach((item) => {
if (item.ref && item.component) {
map[item.component] = item.ref;
}
});
return map;
});
const customActionsMap = computed(() => {
const map: Record<string, ICustomActionItem> = {};
props.customActions?.forEach((action) => {
if (action.name) {
map[action.name] = action;
}
});
return map;
});
const messageRenderers = {
'custom-text': (props: BubbleCommonProps & { content: string }) =>
h('span', { class: 'tr-bubble__body-text' }, props.content),
'schema-card': (schemaCardProps: IRendererProps) => {
const isGenerating = lastSchemaCardId.value === schemaCardProps.id && generating.value;
return h(
'div',
{},
h(
GenuiRenderer,
{
...schemaCardProps,
requiredCompleteFieldSelectors: props.requiredCompleteFieldSelectors || [],
generating: isGenerating,
customComponents: customComponentsMap.value,
customActions: {
...customActionsMap.value,
continueChat: continueChatAction,
saveState: saveStateAction,
},
key: schemaCardProps.id,
},
{
header: toSlotFunction(props.rendererSlots?.header),
footer: toSlotFunction(props.rendererSlots?.footer),
},
),
);
},
tool: ToolRenderer,
reasoning: ReasoningRenderer,
markdown: markdownRenderer,
templateData: TemplateDataRenderer,
'loading-text': props.thinkComponent || GeneratingComponent,
'error-text': ErrorText,
};
const responseHandlers: Ref<IResponseHandler<IStreamData>[]> = ref(defaultResponseHandlers);
const customModelProvider = new CustomModelProvider({
getChatOptions: () => ({
url: props.url,
model: props.model || '',
temperature: props.temperature ?? 0.3,
chatConfig: props.chatConfig || { addToolCallContext: false, showThinkingResult: false },
customComponents: props.customComponents || [],
customSnippets: props.customSnippets || [],
customExamples: props.customExamples || [],
customActions: [...(props.customActions || []), continueChatAction, saveStateAction],
customFetch: props.customFetch,
}),
});
customModelProvider.setResponseHandlers(responseHandlers.value);
const client = new AIClient({
provider: 'custom',
providerImplementation: customModelProvider,
});
let conversation = useConversation({
client,
autoSave: false,
events: {
onReceiveData(data, messages, preventDefault) {
messages.value.push(data as any);
preventDefault();
},
onLoaded(conversations) {
if (!conversations.length) {
createConversation();
saveConversations();
}
// 如果通过 props.messages 传入了初始消息,则在会话加载完成后覆盖当前会话的消息
if (props.messages?.length) {
const currentMessages = messageManager.value.messages.value;
currentMessages.splice(0, currentMessages.length, ...(props.messages as any));
}
},
onFinish(data: any, context) {
if (data?.type === 'error') {
context.messages.value.push({
role: 'assistant',
content: '',
messages: [{ type: 'error-text', content: data.error.message }],
});
}
saveConversations();
},
},
});
const { messageManager, createConversation, updateTitle, state: conversationState, saveConversations } = conversation;
const messages = computed(() => messageManager.value.messages.value);
const inputMessage = computed({
get: () => messageManager.value.inputMessage.value,
set: (v: string) => {
messageManager.value.inputMessage.value = v;
},
});
const setInputMessage = (message: string) => {
inputMessage.value = message;
};
if (props.messages?.length) {
messages.value.splice(0, messages.value.length, ...(props.messages as any));
}
const { attachments, templateData, clearAttachments, processAttachments, handleFilesSelected, handleTemplateEdit } =
useFileUpload();
const handleTemplateDataUpdate = (value: UserItem[]) => {
// 使用 handleTemplateEdit 处理 template 编辑,保持 templateData 和 attachments 同步
const updatedTemplateData = handleTemplateEdit(templateData, inputMessage.value);
inputMessage.value = '';
templateData.value = updatedTemplateData;
};
const showMessages = computed(() => {
let showMessages = messages.value;
if (messageManager.value.messageState.status === STATUS.PROCESSING) {
return [
...showMessages,
{
role: 'assistant',
content: t('loading.thinking'),
loading: true,
},
];
}
const lastMessage = messages.value[messages.value.length - 1];
// 在流式返回过程中,为最后一条助手消息添加 loading-text 组件
if (generating.value && lastMessage?.role === 'assistant') {
const existingMessages = Array.isArray((lastMessage as any)?.messages) ? (lastMessage as any).messages : [];
// 检查是否已经存在 loading-text,避免重复添加
const hasLoadingText = existingMessages.some((msg: any) => msg.type === 'loading-text');
if (!hasLoadingText) {
return [
...showMessages.slice(0, -1),
{
...lastMessage,
messages: [
...existingMessages,
{
type: 'loading-text',
emitter: emitter,
message: lastMessage,
showThinkingResult: props.chatConfig?.showThinkingResult,
},
],
},
];
}
}
return showMessages;
});
const setConversationTitle = (messageContent: string) => {
const currentTitle = conversationState.conversations.find(
(conversation) => conversation.id === conversationState.currentId,
)?.title;
const DEFAULT_TITLE = t('conversation.newConversation');
if (currentTitle === DEFAULT_TITLE && conversationState.currentId) {
const contentStr = typeof messageContent === 'string' ? messageContent : JSON.stringify(messageContent);
updateTitle(conversationState.currentId, contentStr.substring(0, 20));
}
};
const clearInputMessage = () => {
inputMessage.value = '';
templateData.value = [];
clearAttachments();
};
const handleRemoveAttachment = (item: FileMeta | undefined) => {
if (!item) return;
attachments.value = attachments.value.filter((attachment) => item.name !== attachment.name);
templateData.value = templateData.value.filter((data) => data.type !== 'template' || data.content !== item.name);
};
const handleSendMessage = async (ipt: string) => {
const messageContent = ipt;
const userMessageContent: BubbleContentItem[] = [];
let apiContent: any[] = [];
const attachmentsValue = attachments.value.slice();
const templateDataValue = templateData.value.slice();
const userMessage: ChatMessage = {
role: 'user',
content: messageContent,
};
messages.value.push(userMessage);
if (attachmentsValue.length > 0) {
const result = await processAttachments(attachmentsValue, props.features || {});
if (!result) {
messageManager.value.send();
scrollToBottom();
return;
}
apiContent = templateDataValue.map((templateItem: UserItem) => {
if (templateItem.type === 'template') {
return result.apiContent.find((att: any) => att.filename === templateItem.content);
} else {
return {
type: 'text',
text: (templateItem as UserTextItem).content,
};
}
});
// 添加 templateData 类型的消息项,用于渲染
if (templateDataValue.length > 0) {
userMessageContent.push({
type: 'templateData',
templateData: templateDataValue,
attachments: attachmentsValue,
});
}
userMessage.content = apiContent;
userMessage.messages = userMessageContent;
}
messageManager.value.send();
clearInputMessage();
setConversationTitle(messageContent);
saveConversations();
scrollToBottom();
};
const handleNewConversation = () => {
createConversation();
saveConversations();
};
const abortRequest = () => {
messageManager.value.abortRequest();
saveConversations();
};
const messagesContainer: Ref<HTMLElement | undefined> = ref();
const { width: messagesContainerWidth } = useResize(messagesContainer);
const { scrollToBottom, scrollToBottomWithRetry, autoScrollToBottom, isLastMessageInBottom } =
scrollEnd(messagesContainer);
// 使用节流包装 scrollToBottom,延迟 400ms
const throttledScrollToBottom = throttle(autoScrollToBottom, 400);
// 最新消息滚动到底部
watch(() => messages.value, throttledScrollToBottom, { deep: true });
watch(
() => conversationState.currentId,
() => {
// 切换会话, 使用带重试机制的滚动函数,确保在 DOM 完全渲染后滚动到底部
scrollToBottomWithRetry(10, 150);
},
);
defineExpose({
setInputMessage,
handleNewConversation,
// @experimental
getProps: (): IChatProps => props,
getConversation: () => conversation,
// experimental, not stable
getResponseHandlers: () => responseHandlers.value,
// experimental, not stable
setResponseHandlers: (handlers: IResponseHandler<IStreamData>[]) => {
responseHandlers.value = handlers;
customModelProvider.setResponseHandlers(handlers);
},
getMessageRenderers: () => messageRenderers,
setMessageRenderer: (key: string, renderer: Component<IRendererProps>) => {
messageRenderers[key] = renderer;
},
generating,
// @experimental
lastSchemaCardId,
continueChatAction,
saveStateAction,
});
</script>
<template>
<div
class="tg-chat-container"
:class="{ 'dark': genuiConfig?.colorScheme === 'dark' }"
:style="!props.chatConfig?.showThinkingResult ? { '--thinking-display': 'none' } : {}"
>
<div
class="messages-container"
ref="messagesContainer"
:style="{ '--messages-container-width': messagesContainerWidth + 'px' }"
>
<tr-bubble-provider :content-renderers="messageRenderers" v-if="showMessages.length">
<tr-bubble-list :items="showMessages" :roles="roles" auto-scroll> </tr-bubble-list>
</tr-bubble-provider>
<slot v-else name="empty"></slot>
</div>
<div class="sender-container">
<!-- TODO: 抽离到组件 -->
<div
:class="['scroll-to-bottom-button', { 'is-generating': generating }]"
v-show="!isLastMessageInBottom"
@click="scrollToBottom"
>
<IconArrowDown class="icon-arrow-down" />
</div>
<tr-sender
v-model="inputMessage"
:placeholder="
GeneratingStatus.includes(messageManager.messageState.status)
? t('placeholder.thinking')
: t('placeholder.input')
"
:clearable="true"
:allow-files="isAllowFiles"
:buttonGroup="buttonGroup"
:loading="GeneratingStatus.includes(messageManager.messageState.status)"
@files-selected="(files) => handleFilesSelected(files, inputMessage)"
v-model:template-data="templateData"
@update:template-data="handleTemplateDataUpdate"
:showWordLimit="true"
:maxLength="20000"
@clear="clearInputMessage"
@submit="handleSendMessage"
@cancel="abortRequest"
>
<template #header v-if="attachments.length > 0">
<div class="attachments-container">
<AttachmentsRenderer :attachments="attachments" @remove="handleRemoveAttachment" />
</div>
</template>
</tr-sender>
<div class="footer-text">{{ t('footer.aiGenerated') }}</div>
</div>
</div>
</template>
<style scoped lang="less">
.tg-chat-container {
--ti-gen-chat-container-bg-color: #f0f0f0;
--thinking-display: initial;
--sender-bg: url('./assets/sender-light.svg') no-repeat center;
--sender-border-color: #e5e5e5;
--generating-bg-before: linear-gradient(90deg, #fff, #a2c7f4);
--generating-bg-after: #fff;
box-sizing: border-box;
height: 100%;
color: var(--tr-text-primary);
background-color: var(--ti-gen-chat-container-bg-color);
position: relative;
display: flex;
flex-direction: column;
overflow: auto;
&.dark {
--ti-gen-chat-container-bg-color: #191919;
--sender-bg: url('./assets/sender-dark.svg') no-repeat center;
--sender-border-color: #333;
--generating-bg-before: linear-gradient(90deg, #262626, #808080);
--generating-bg-after: #191919;
}
}
.is-loading-in-top {
margin-top: -48px;
}
.messages-container {
flex: 1;
overflow: auto;
word-break: break-word;
}
:deep(.tr-bubble__loading) {
margin-top: 8px;
}
:deep(.tr-bubble.placement-start) {
.tr-bubble__content {
padding: 0;
background: transparent;
border-radius: 0;
box-shadow: none;
}
}
:deep(.tr-bubble[data-role='assistant'] .tr-bubble__content-items:has([type^='schema-card'])) {
// 匹配:type非空 + 排除 schema-card/loading-text 这两个值
> [type]:not([type='']):not([type='schema-card']):not([type='loading-text']) {
display: var(--thinking-display, initial);
}
}
:deep(.tr-bubble__step-tool) {
& + .tr-bubble__step-tool {
margin-top: 16px;
}
}
:deep(.tr-bubble.placement-end) {
width: 100%;
}
:deep(.tr-bubble__content-wrapper) {
@avatar-and-gap-width: 56px;
// TODO: 后续规范变量名,在对外暴露
max-width: calc(100% - var(--ti-gen-chat-avatar-and-gap-width, @avatar-and-gap-width) * 2);
.tr-bubble__content {
max-width: 100%;
}
.tr-bubble__content-items {
overflow-x: auto;
}
}
.sender-container {
position: relative;
flex-shrink: 0;
padding: 16px 0;
background: var(--sender-bg);
.attachments-container {
padding: 0 20px;
}
}
.scroll-to-bottom-button {
position: absolute;
left: 50%;
transform: translateX(-50%);
top: -35px;
width: 40px;
height: 40px;
background-color: var(--generating-bg-after);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
border: 1px solid var(--sender-border-color);
z-index: 1000;
& > svg {
width: 20px;
height: 20px;
}
&:hover {
box-shadow:
0px 10px 20px 0px #0000001a,
0px 0px 1px 0px #00000026;
}
&.is-generating {
border: none;
background-color: transparent;
&::before {
content: '';
position: absolute;
top: -2px;
left: -2px;
right: -2px;
bottom: -2px;
width: calc(100% + 4px);
height: calc(100% + 4px);
border-radius: 50%;
background: var(--generating-bg-before);
z-index: 0;
animation: rotate-border 2s linear infinite;
}
&::after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
border-radius: 50%;
background-color: var(--generating-bg-after);
z-index: 1;
}
& > svg {
z-index: 2;
}
}
}
.footer-text {
font-size: 12px;
color: #999;
text-align: center;
margin-top: 16px;
}
:deep(.schema-render-container) {
@large-screen-min-width: 400px;
@min-width-safe-padding: 250px;
@small-screen-min-width: calc(var(--messages-container-width) - @min-width-safe-padding);
min-width: min(@small-screen-min-width, @large-screen-min-width);
}
@keyframes rotate-border {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
.tiny-sender {
width: 80%;
margin: 0 auto;
}
</style>