import {designComponent, getComponentCls, iKeyboardEvent, PropType, reactive, useClasses, useModel, useRefs} from "@peryl/react-compose"; import Input from "../Input"; import {EditProps, useEdit} from "../../uses/useEdit"; import {StyleProps, useStyle} from "../../uses/useStyle"; import i18n from "../i18n"; import Button from "../Button"; import './ai-chat-box.scss'; import $message from "../$message"; import {uuid} from "@peryl/utils/uuid"; import {$ai, iAiChatResponse, iAiChatStreamParameter, iAiConfiguration, iAiHistory} from "../$ai"; import $configuration from "../$configuration"; import Scroll from "../Scroll"; import {delay} from "@peryl/utils/delay"; import {toArray} from "@peryl/utils/toArray"; import {lastItem} from "@peryl/utils/lastItem"; import {createEffects} from "@peryl/utils/createEffects"; export const AiChatBox = designComponent({ props: { ...EditProps, ...StyleProps, /*ai配置信息*/ aiConfig: { type: Object as PropType }, /*填充高度*/ fitHeight: { type: Boolean }, /*已有的对话历史信息*/ histories: { type: Array as PropType }, /*系统提示词*/ systemContent: { type: String }, /*用户输入的内容*/ modelValue: { type: String }, /*手动处理大模型返回的message*/ handleMessage: { type: Function as PropType }, /*处理流式响应内容*/ handleReceive: { type: Function as PropType<(data: { fullText?: string, chunkText?: string }) => void> }, /*在发送用户内容之前触发的动作函数*/ beforeSendUserContent: { type: Function as PropType<(data: { userContent: string, messages: iAiHistory[] }) => Promise> }, /*手动处理流式调用模型服务*/ handleChatStream: { type: Function as PropType<(parameter: iAiChatStreamParameter & { userContent: string }) => Promise> }, /*输入框最小高度*/ inputMinHeight: { type: String, default: '80px' }, /*输入框最大高度*/ inputMaxHeight: { type: String, default: '225px' }, /*是否启用记忆对话/多轮对话*/ enableMemory: { type: Boolean }, /*记忆对话最大记忆轮数*/ memoryLimit: { type: Number, default: 15 }, }, /*在顶部显示的插槽内容*/ slots: ['prepend'], emits: { onUpdateModelValue: (val?: string) => true, }, setup({ props, slots, event: { emit } }) { /* * 定义双向绑定属性modelValue(非受控/自控属性);自动维护一个内部变量“_moduleValue”, * 当props.modelValue变化时将新值更新到“_modelValue”;当在组件内部执行赋值语句如“model.value = xxx”时, * 将自动调用“emit.onUpdateModelValue(xxx)”函数派发事件“onUpdateModelValue”,触发绑定值更新事件; */ const model = useModel(() => props.modelValue, emit.onUpdateModelValue); /*获取Scroll组件的实例引用,流式对话期间,调用滚动容器的滚动方法滚动到底部,显示流式相应的最新内容;*/ const { refs, onRef } = useRefs({ scroll: Scroll }); /* * 启用表单编辑组件控制功能;这样AiChatBox组件能够被父组件的只读/禁用控制, * 同时也能够通过控制AiChatBox的只读/禁用属性来控制其内部的组件的只读/禁用状态; */ useEdit(); /* * 启动组件的样式控制,功能,道理类似于“编辑控制”,可以使得AiChatBox能够被其父组件控制主题样式、 * 也能够通过控制板AiChatBox来控制其子组件的状态样式; */ const { styleComputed } = useStyle(); const aiConfig = props.aiConfig || $configuration.use('aiConfig'); const classes = useClasses(() => [ getComponentCls('ai-chat-box'), `ai-chat-box-size-${styleComputed.value.size}`, { 'ai-chat-box-fit-height': props.fitHeight } ]); const state = reactive({ /*对话历史*/ histories: props.histories || [] as iChatBoxHistory[], loading: false }); /*执行流式调用的时候需要将“abortEffects”作为参数传递给调用参数,流式调用发起的时候会监听abortEffects.clear函数执行,当执行这个函数时会自动停止流式调用;*/ const { effects: abortEffects } = createEffects(); const methods = { scrollEnd: async () => { if (!!refs.scroll) { await delay(78); refs.scroll.methods.scrollEnd(); } }, addHistory: async (...history: iChatBoxHistory[]) => { state.histories.push(...history); history = state.histories.slice(history.length * -1); await methods.scrollEnd(); return history; }, /* * 发起流式调用 */ send: async (userContent: string) => { /*发起流式调用的时候立即清空输入框内容*/ model.value = ''; /*将输入框的对话内容添加到对话历史中*/ const newUserHistory: iChatBoxHistory = { role: 'user', content: userContent, id: uuid() }; await methods.addHistory(newUserHistory); /*const { message, chatData } = await $ai.chatSystem(userContent, props.systemContent, aiConfig);*/ let messages: iAiHistory[] = props.enableMemory ? state.histories : (() => { const { role, content } = newUserHistory; return [{ role, content }]; })(); messages = messages.slice(props.memoryLimit * -1); /*发起流式调用前的处理动作*/ await props.beforeSendUserContent?.({ userContent, messages }); /*插入提示词*/ if (!!props.systemContent?.trim().length) {messages.unshift({ role: 'system', content: props.systemContent });} /*大模型回复内容消息对象*/ let chatBoxHistory: iChatBoxHistory | undefined = undefined; /*大模型回复的结果消息内容*/ let message = ''; /*流式调用参数*/ const aiChatStreamParameter: iAiChatStreamParameter & { userContent: string } = { aiConfig, messages, userContent, abortEffects, onReceiving: ({ fullText, chunkText }) => { // console.log('receiving', fullText); props.handleReceive?.({ fullText, chunkText }); if (!chatBoxHistory) { state.histories.push({ role: 'assistant', content: '', id: uuid() }); chatBoxHistory = lastItem(state.histories); } chatBoxHistory!.content = fullText; methods.scrollEnd(); }, onFinish: (fullText) => { message = fullText; }, }; if (!!props.handleChatStream) { /*手动处理流式调用*/ await props.handleChatStream(aiChatStreamParameter); } else { /*默认处理流式调用*/ await $ai.chatStream(aiChatStreamParameter); } /*大模型没有返回任何内容,抛出异常*/ if (!message.length) { throw new Error('message is empty!'); } /*可以手动处理返回的消息,自定义往对话框插入内容*/ const newHistory: void | iChatBoxHistory | iChatBoxHistory[] = await props.handleMessage?.({ message, userContent, // chatData, addHistory: methods.addHistory, histories: state.histories, scrollEnd: methods.scrollEnd, }); if (newHistory != null) { await methods.addHistory(...toArray(newHistory)); } return { message, /*chatData*/ }; }, }; const handler = { /* * 处理点击发送暂停按钮 */ onClickSend: async () => { /*当前正处于流式调用期间,执行停止流式调用逻辑*/ if (state.loading) { console.log('abort'); abortEffects.clear(); return; } /*当前未开始流式调用,准备执行流式调用*/ console.log('send'); /*先清理掉上次流式调用产生的副作用*/ abortEffects.clear(); /*新增一个副作用,使得流式调用结束之后,设置loading标识为false*/ abortEffects.push(() => state.loading = false); /*设置loading标识为true*/ state.loading = true; try { const userContent = model.value; if (!userContent?.trim().length) { $message.error(i18n.$it('ai.require').d('提问的内容不能为空')); return; } await methods.send(userContent); } finally { state.loading = false; } }, /*处理在输入框中执行回车按键*/ onEnterTextarea: (e: KeyboardEvent) => { if (e.shiftKey) {return;} handler.onClickSend(); }, }; return { refer: { refs, aiConfig, state, methods, }, render: () => (
{slots.prepend.isExist() && (
{slots.prepend()}
)} {(!!state.histories.length || props.fitHeight || slots.prepend.isExist()) && (
{(() => { const content = state.histories.map((history) => (
{!!history.render ? history.render() : history.content}
)); if (props.fitHeight) { return {content}; } else { return content; } })()}
)}
) }; }, }); /* * AiChatBox对话历史行数据类型 * 当行数据对象中存在render属性函数时,渲染内容调用这个render函数来渲染; * 当没有这个render属性函数时,渲染内容为消息文本字符串 */ export interface iChatBoxHistory extends iAiHistory { id: string, render?: () => any, } export default AiChatBox; /* * 组件属性handleMessage函数类型 */ export interface iChatBoxHandleMessage { (param: { message: string, userContent: string, chatData?: iAiChatResponse, addHistory: (...history: iChatBoxHistory[]) => void, histories: iChatBoxHistory[], scrollEnd: () => Promise, }): void | iChatBoxHistory | iChatBoxHistory[] | Promise; }