feat: add chat history and session

This commit is contained in:
2024-10-01 00:46:26 +08:00
parent 441b94a061
commit 7d4e6bd299
25 changed files with 1133 additions and 221 deletions

View File

@@ -1,28 +1,180 @@
import { useShallow } from 'zustand/react/shallow';
import { useAiStore } from './store/ai-store';
import { CloseOutlined, HistoryOutlined } from '@ant-design/icons';
import { Button, Form, Input, Tooltip } from 'antd';
import { CloseOutlined, HistoryOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Dropdown, Form, Input, message, Modal, Tooltip } from 'antd';
import { useEffect } from 'react';
import { TextArea } from '../container/components/TextArea';
import clsx from 'clsx';
import { marked } from 'marked';
import { query } from '@/modules';
import { nanoid } from 'nanoid';
import { ChatMessage } from './module/ChatMessage';
import { isObjectNull } from '@/utils/is-null';
import { useNavigate } from 'react-router';
const testId = '60aca66b-4be9-4266-9568-6001032c7e13';
type FormModalProps = {
send?: any;
};
const FormModal = (props: FormModalProps) => {
const [form] = Form.useForm();
const aiStore = useAiStore(
useShallow((state) => {
return {
showEdit: state.showEdit,
setShowEdit: state.setShowEdit,
formData: state.formData,
setMessage: state.setMessage,
};
}),
);
useEffect(() => {
const open = aiStore.showEdit;
if (open) {
const isNull = isObjectNull(aiStore.formData);
if (isNull) {
form.setFieldsValue({});
} else form.setFieldsValue(aiStore.formData);
}
}, [aiStore.showEdit]);
const onFinish = async (values: any) => {
props.send({
type: 'changeSession',
data: {
id: testId,
},
});
aiStore.setMessage([]);
};
const onClose = () => {
aiStore.setShowEdit(false);
form.resetFields();
};
const isEdit = aiStore.formData.id;
return (
<Modal
title={isEdit ? 'Edit' : 'Add'}
open={aiStore.showEdit}
onClose={() => aiStore.setShowEdit(false)}
destroyOnClose
footer={false}
width={800}
onCancel={onClose}>
<Form
form={form}
onFinish={onFinish}
labelCol={{
span: 4,
}}
wrapperCol={{
span: 20,
}}>
<Form.Item name='id' hidden>
<Input />
</Form.Item>
<Form.Item name='sessionId' label='sessionId'>
<Input />
</Form.Item>
<Form.Item label=' ' colon={false}>
<Button type='primary' htmlType='submit'>
Submit
</Button>
<Button className='ml-2' htmlType='reset' onClick={onClose}>
Cancel
</Button>
</Form.Item>
</Form>
</Modal>
);
};
export const useListenQuery = () => {
const aiStore = useAiStore(
useShallow((state) => {
return {
open: state.open,
key: state.key,
onMessage: state.onMessage,
};
}),
);
// TODO: Implement useEffect
useEffect(() => {
if (!aiStore.open) {
return;
}
const open = aiStore.open;
send({
type: 'subscribe',
token: query.getToken(),
data: {
key: aiStore.key,
},
});
const close = query.qws.onMessage(onMessage, {
selector: (data) => {
const requestId = data.requestId;
return {
requestId,
...data.data,
};
},
});
return () => {
send({ type: 'unsubscribe' });
close();
};
}, [aiStore.open, query]);
const send = async (data: any) => {
query.qws.send(data, {
wrapper: (data) => ({
requestId: nanoid(16),
type: 'chat',
data: data,
}),
});
};
const onMessage = (data: any) => {
type MessageData = {
chatId: string;
chatPromptId: string;
role: string;
root: boolean;
show: boolean;
data: {
message: string;
};
};
if (data.code === 200 && data.type === 'messages') {
const messageData = data.data as MessageData;
aiStore.onMessage(messageData);
}
};
return {
send,
};
};
export const AiMoudle = () => {
const [form] = Form.useForm();
const navigate = useNavigate();
const aiStore = useAiStore(
useShallow((state) => {
return {
open: state.open,
setOpen: state.setOpen,
runAi: state.runAi,
formData: state.formData,
setFormData: state.setFormData,
messages: state.messages,
setMessages: state.setMessage,
key: state.key,
root: state.root,
setRoot: state.setRoot,
title: state.title,
setShowEdit: state.setShowEdit,
list: state.list,
getList: state.getList,
};
}),
);
useEffect(() => {
if (!aiStore.open) {
return;
@@ -37,66 +189,36 @@ export const AiMoudle = () => {
useEffect(() => {
if (!aiStore.open) {
aiStore.setMessages([]);
} else {
aiStore.getList();
}
}, [aiStore.open]);
const { send } = useListenQuery();
const onSend = () => {
const data = form.getFieldsValue();
aiStore.setFormData(data);
aiStore.runAi();
send({ type: 'messages', data: { ...data, root: true } });
};
return (
<div className={clsx('w-[600px] flex-shrink-0 bg-gray-100 border-l-2 shadow-lg flex flex-col', !aiStore?.open && 'hidden')}>
<div className='flex gap-4 bg-slate-400 p-2'>
<Button className='position ml-4 !bg-slate-400 !border-black' onClick={() => aiStore.setOpen(false)} icon={<CloseOutlined />}></Button>
<h1 className='ml-4'>Ai Moudle</h1>
<div className='ml-4'>
<Tooltip title='历史会话'>
<Button className='!bg-slate-400 !border-black' icon={<HistoryOutlined />}></Button>
</Tooltip>
</div>
</div>
<div className='flex-grow p-2 overflow-hidden h-full flex flex-col'>
<div className='flex flex-col'>
<div className='mb-3'> chat message</div>
{aiStore?.messages?.map((message, index) => {
const html = marked.parse(message?.content);
return (
<div key={index} className=' justify-between px-4 w-full'>
<div className='h3 font-bold'>{message?.role}</div>
<div
className='p-4 text-xs border shadow-sm rounded-sm scrollbar max-h-[200px] w-full overflow-scroll'
dangerouslySetInnerHTML={{ __html: html }}></div>
</div>
);
})}
</div>
const inputs = form.getFieldValue('inputs');
const isNotShow = inputs?.length === 0 || !inputs;
const RootForm = (
<div className='flex flex-col relative'>
<div className={clsx('flex flex-col', isNotShow && 'invisible')}>
<div className='mt-1 ml-2'>?</div>
<div className='mt-4'>
<Form form={form}>
<Form.Item hidden name='id'>
<Input placeholder='message' />
</Form.Item>
<Form.Item name='messages' hidden>
<Input placeholder='message' />
</Form.Item>
<Form.Item name='key' hidden>
<Input placeholder='key' />
</Form.Item>
<Form.List name={'inputs'} initialValue={[]}>
{(fields, { add, remove }) => {
return (
<>
{fields.map((field, index) => {
const key = form.getFieldValue(['inputs', index, 'key']);
console.log('key', key);
const isTitle = key === 'title';
return (
<div key={field.name + '-' + index} className=''>
<Form.Item name={[field.name, 'key']} rules={[{ required: true, message: 'Missing name' }]} hidden noStyle>
<Input placeholder='name' />
</Form.Item>
<Form.Item className='!mb-0' name={[field.name, 'value']} rules={[{ required: true, message: 'Missing value' }]}>
<TextArea className='scrollbar' style={{ minHeight: isTitle ? 40 : 300 }} placeholder={key} />
<TextArea className='scrollbar' style={{ minHeight: 180 }} placeholder={key} />
</Form.Item>
</div>
);
@@ -106,13 +228,95 @@ export const AiMoudle = () => {
}}
</Form.List>
</Form>
<div className='p-4'>
<Button className='mt-4' onClick={onSend}>
Send
<div className='px-4'>
<Button type='primary' className='mt-4' onClick={onSend}>
</Button>
</div>
</div>
</div>
{isNotShow && (
<div className='mt-2 text-gray-400 flex absolute top-3'>
<div
className='text-blue-500 cursor-pointer'
onClick={(e) => {
navigate('/chat/chat-prompt/list');
}}>
</div>
</div>
)}
</div>
);
const ChatForm = (
<ChatMessage
messages={aiStore.messages}
onSend={(value) => {
send({ type: 'messages', data: { message: value } });
}}
/>
);
const items = aiStore.list.map((item) => {
return {
key: item.id,
label: item.title || item.id,
onClick: () => {
// aiStore.setKey(item.id);
// 选中具体的
send({
type: 'changeSession',
data: {
id: item.id,
},
});
aiStore.setMessages([]);
},
};
});
return (
<div className={clsx('w-[600px] flex-shrink-0 bg-gray-100 border-l-2 shadow-lg flex flex-col', !aiStore?.open && 'hidden')}>
<div className='flex justify-between p-2 border bg-white'>
<div className='flex gap-4'>
<Button className='position ml-4 ' onClick={() => aiStore.setOpen(false)} icon={<CloseOutlined />}></Button>
<h1 className=''>{aiStore.title || 'Ai Module'}</h1>
</div>
<div className='mr-4 flex'>
{!aiStore.root && (
<Button
className='mr-2'
onClick={() => {
aiStore.setMessages([]);
aiStore.setRoot(true);
send({
type: 'changeSession',
data: {
id: null,
},
});
}}
icon={<PlusOutlined />}></Button>
)}
<Dropdown
className='mr-2'
placement='bottomRight'
menu={{
items,
}}>
<Button className='' icon={<HistoryOutlined />}></Button>
</Dropdown>
{/* <Tooltip title='历史会话'>
<Button
className=''
onClick={() => {
aiStore.setShowEdit(true);
}}
icon={<HistoryOutlined />}></Button>
</Tooltip> */}
</div>
</div>
<div className='flex-grow p-2 overflow-hidden h-full flex flex-col'>{aiStore.root ? RootForm : ChatForm}</div>
<FormModal send={send} />
</div>
);
};

View File

@@ -0,0 +1,16 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="32"
height="32"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="2" y="7" width="20" height="14" rx="2" ry="2"></rect>
<rect x="6" y="11" width="4" height="4"></rect>
<rect x="14" y="11" width="4" height="4"></rect>
<path d="M6 7V5a2 2 0 012-2h8a2 2 0 012 2v2"></path>
</svg>

After

Width:  |  Height:  |  Size: 429 B

View File

@@ -0,0 +1,14 @@
<svg
xmlns="http://www.w3.org/2000/svg"
width="64"
height="64"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="7" r="5"></circle>
<path d="M5.5 21h13a2 2 0 002-2v-1a7 7 0 00-14 0v1a2 2 0 002 2z"></path>
</svg>

After

Width:  |  Height:  |  Size: 324 B

View File

@@ -0,0 +1,79 @@
import { marked } from 'marked';
import clsx from 'clsx';
import AIAvatar from '../assets/ai-avatar.svg'; // 替换为您的 AI 头像路径
import UserAvatar from '../assets/user-avatar.svg'; // 替换为您的用户头像路径
import { TextArea } from '@/pages/container/components/TextArea';
import { Button } from 'antd';
import { SendOutlined } from '@ant-design/icons';
import { useState } from 'react';
export type MessageType = 'ai' | 'user';
export type Message = {
role: string;
content: string;
};
export const ChatMessageOne = (props: { message: Message }) => {
const { message } = props;
const htmlContent = marked.parse(message.content);
const isUser = message.role === 'user';
const containerClasses = clsx('flex mb-4 items-start', {
'justify-start flex-row': !isUser,
'flex-row-reverse': isUser,
});
const messageClasses = clsx('max-w-[76%] p-3 rounded-lg ', {
'bg-blue-500 text-white': isUser,
'bg-gray-200 text-gray-800': !isUser,
});
const avatarSrc = isUser ? UserAvatar : AIAvatar;
const avatarAlt = isUser ? 'User Avatar' : 'AI Avatar';
return (
<div className={containerClasses}>
<img src={avatarSrc} alt={avatarAlt} className='w-10 h-10 mx-2 rounded-full border border-gray-300 p-2' />
<div className={messageClasses} dangerouslySetInnerHTML={{ __html: htmlContent }} />
</div>
);
};
type ChatMessageProps = {
messages: Message[];
onSend?: (message: string) => void;
};
export const ChatMessage = (props: ChatMessageProps) => {
const { messages } = props;
const [inputValue, setInputValue] = useState('');
const onSend = () => {
if (!inputValue) return;
props.onSend?.(inputValue);
setInputValue('');
};
return (
<div className='w-full h-full'>
<div className='max-h-[80%] overflow-y-auto scrollbar bg-white p-2 mx-1 border shadow-sm pt-5 rounded-lg'>
<div className='flex flex-col'>
{messages.map((message, index) => (
<ChatMessageOne key={index} message={message} />
))}
</div>
</div>
<div className='relative'>
<TextArea
value={inputValue}
onChange={(e) => {
setInputValue(e);
}}
className='max-h-64'
style={{ minHeight: 180 }}
language='markdown'
placeholder='Message AI'
/>
<Button onClick={onSend} className='absolute bottom-4 right-4 cursor-pointer' type='primary' icon={<SendOutlined />}></Button>
</div>
</div>
);
};

View File

@@ -0,0 +1,25 @@
import { StateCreator } from 'zustand';
import { AiStore } from './ai-store';
import { query } from '@/modules';
export type AiHistoryStore = {
list: any[];
getList: () => Promise<any>;
};
export const createAiHistoryStore: StateCreator<AiStore, [], [], AiHistoryStore> = (set, get, store) => {
return {
list: [],
getList: async () => {
const { key } = get();
set({ loading: true });
const res = await query.post({
path: 'chat-session',
key: 'list-history',
data: { key },
});
if (res.success) {
set({ list: res.data });
}
console.log('res', res);
},
};
};

View File

@@ -1,6 +1,8 @@
import { query } from '@/modules';
import { message } from 'antd';
import { produce } from 'immer';
import { create } from 'zustand';
import { AiHistoryStore, createAiHistoryStore } from './ai-history';
type ResData = {
created_at: string;
done?: boolean;
@@ -14,48 +16,87 @@ type ResData = {
prompt_eval_duration?: number;
total_duration?: number;
};
type MessageData = {
chatId: string;
chatPromptId: string;
role: string;
root: boolean;
show: boolean;
data: {
message: string;
};
};
export type AiStore = {
/** 打开侧边栏 */
open: boolean;
setOpen: (open: boolean) => void;
showEdit: boolean;
setShowEdit: (showEdit: boolean) => void;
loading: boolean;
setLoading: (loading: boolean) => void;
type?: string;
/** 当前app执行的key */
key: string;
setKey: (key: string) => void;
setType?: (type: string) => void;
sendMsg: (msg: string) => void;
formData: any;
setFormData: (data: any) => void;
data: any;
setData: (data: any) => void;
runAi: () => any;
title: string;
title: string; // AI Module的标题
setTitle: (title: string) => void;
messages: { role: string; content: string }[];
setMessage: (message: { role: string; content: string }[]) => void;
};
getPrompt: (key?: string) => any;
// 设置预设数据只有是root的情况下才成立
presetData?: any;
setPresetData: (data: any) => void;
/** 是否是第一条消息 */
root: boolean;
setRoot: (root: boolean) => void;
onMessage: (data: MessageData) => void;
} & AiHistoryStore;
export const useAiStore = create<AiStore>((set, get) => {
export const useAiStore = create<AiStore>((set, get, store) => {
return {
open: false,
setOpen: (open) => set({ open }),
setOpen: (open) => set({ open, root: true }),
loading: false,
setLoading: (loading) => set({ loading }),
key: '',
setKey: (key) => set({ key }),
sendMsg: (msg) => {
console.log(msg);
setKey: (key) => {
const { getPrompt } = get();
if (key) {
getPrompt(key);
}
set({ key });
},
formData: {},
setFormData: (data) => set({ formData: data }),
data: {},
setData: (data) => {
const { key, presetData = {} } = data;
console.log('key', presetData, data);
if (!key) {
console.error('key is required');
return;
title: '',
setTitle: (title) => set({ title }),
messages: [],
setMessage: (messages) => set({ messages }),
getPrompt: async (key) => {
const state = get();
const res = await query.post({
path: 'chat-prompt',
key: 'getByKey',
data: {
key: key || state.key,
},
});
if (res.code === 200) {
const { prompt } = res.data;
const { presetData } = prompt;
console.log(res.data);
state.setPresetData(presetData);
set({ root: true });
}
const { inputs = [] } = presetData.data || {};
},
presetData: {},
setPresetData: (data) => {
set({ presetData: data });
const { inputs = [] } = data?.data || {};
const formData = {
key,
inputs: inputs.map((input) => {
return {
key: input.key,
@@ -65,40 +106,23 @@ export const useAiStore = create<AiStore>((set, get) => {
}),
messages: [],
};
console.log('formData', formData);
set({ key, data, formData });
set({ formData });
},
runAi: async () => {
const { formData, messages } = get();
const loading = message.loading('loading');
const res = await query.post({
path: 'ai',
key: 'run',
data: {
key: formData.key,
inputs: [
// {
// key: 'title',
// value: '根据描述生成代码',
// },
// {
// key: 'description',
// value: '我想获取一个card, 包含标题和内容标题是evision内容是这是一个测试',
// },
...formData.inputs,
],
},
});
loading();
if (res.code === 200) {
console.log(res.data);
message.success('Success');
set({ messages: [...messages, res.data.message] });
}
root: false,
setRoot: (root) => set({ root }),
onMessage: (data) => {
const state = get();
if (state.root) set({ root: false });
const { message } = data.data;
const role = data.role;
set(
produce((state) => {
state.messages.push({ role, content: message });
}),
);
},
title: '',
setTitle: (title) => set({ title }),
messages: [],
setMessage: (messages) => set({ messages }),
showEdit: false,
setShowEdit: (showEdit) => set({ showEdit }),
...createAiHistoryStore(set, get, store),
};
});