| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255 |
- import { defineStore } from 'pinia';
- import { useUserStore } from './user';
- export const useAIChat = defineStore({
- id: 'ai-chat',
- state: (): {
- /** 会话历史 */
- sessionHistory: {
- id: string;
- user_id: string;
- agent: string;
- title: string;
- title_type: string;
- version: number;
- current_message_id: number;
- inserted_at: string;
- updated_at: string;
- }[];
- /** 消息历史 */
- messageHistory: {
- id: string; // 唯一标识(可用时间戳生成)
- type: 'user' | 'system' | 'response';
- content: string;
- /** 深度思考时的文本 */
- contentR1: string;
- timestamp: number; // 排序依据
- }[];
- /** 当前会话ID */
- currentSessionID: string;
- /** 当前会话是否有流正在传输 */
- streaming: boolean;
- /** 当前会话是否启用 deepseekR1 模型 */
- deepseekR1Enable: boolean;
- /** 当前用户ID */
- userID: string;
- } => {
- const userid = useUserStore().getUserInfo.id as string;
- return {
- sessionHistory: [],
- messageHistory: [],
- currentSessionID: '',
- streaming: false,
- deepseekR1Enable: false,
- userID: userid,
- };
- },
- getters: {
- getMessageHistory: (state) => {
- return state.messageHistory.sort((a, b) => a.timestamp - b.timestamp);
- },
- },
- actions: {
- /** 创建新会话 */
- async createSession() {
- const response = await fetch('http://182.92.126.35:6005/sessions/create', {
- method: 'post',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- user_id: this.userID,
- }),
- });
- const data = await response.json();
- this.currentSessionID = data.id;
- this.messageHistory = [];
- },
- /** 根据当前会话,创建聊天流,流里的数据将会更新到消息历史中 */
- async createStream(question: string, onUpdate?: any) {
- this.streaming = true;
- this.messageHistory.push({
- id: `user_${Date.now()}`,
- type: 'user',
- content: question,
- contentR1: '',
- timestamp: Date.now(),
- });
- try {
- // 发送 POST 请求
- const response = await fetch('http://182.92.126.35:6005/chat_stream', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- chat_session_id: this.currentSessionID,
- prompt: question,
- ref_file_ids: [],
- thinking_enabled: this.deepseekR1Enable,
- }),
- });
- // 检查响应是否成功
- if (!response.ok || !response.body) {
- throw new Error('Network response was not ok');
- }
- // 获取可读流
- const reader = response.body.getReader();
- // 创建一条新的消息对象
- const newMessage = {
- id: `response_${Date.now()}`,
- type: 'response' as any,
- content: '',
- contentR1: '',
- timestamp: Date.now(),
- };
- // 将新消息添加到消息列表
- this.messageHistory.push(newMessage);
- // 读取流式数据
- while (true) {
- const { done, value } = await reader.read();
- if (done) {
- break;
- }
- // 将流数据转换为字符串
- const chunk = new TextDecoder().decode(value);
- // 使用正则表达式匹配完整的 JSON 对象
- const jsonRegex = /{.*?}/g;
- const matches = chunk.match(jsonRegex);
- if (!matches) continue;
- matches.forEach((match) => {
- const data = JSON.parse(match);
- // 找到当前消息对象并更新 content
- const targetMessage = this.messageHistory.find((msg) => msg.id === newMessage.id);
- if (!targetMessage) return;
- if (data.type === 'text') {
- targetMessage.content += data.content; // 追加内容
- }
- if (data.type === 'thinking') {
- targetMessage.contentR1 += data.content;
- }
- if (typeof onUpdate === 'function') {
- onUpdate(value);
- }
- });
- }
- } catch (error) {
- // 请求失败时设置系统消息
- this.messageHistory.push({
- id: `system_${Date.now()}`,
- type: 'system',
- content: '系统异常,请稍后再试',
- contentR1: '',
- timestamp: Date.now(),
- });
- } finally {
- this.streaming = false;
- }
- },
- /** 创建会话的标题 */
- async createSessionTitle(title: string) {
- await fetch('http://182.92.126.35:6005/sessions/title', {
- method: 'post',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- chat_session_id: this.currentSessionID,
- prompt: title,
- }),
- });
- },
- /** 修改会话的标题 */
- async changeSessionTitle(title: string, id: string) {
- try {
- const response = await fetch('http://182.92.126.35:6005/sessions/change_title', {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- chat_session_id: id,
- new_title: title,
- }),
- });
- if (!response.ok) {
- throw new Error('Network response was not ok');
- }
- this.sessionHistory.forEach((session) => {
- if (session.id === id) {
- session.title = title;
- }
- });
- } catch (error) {
- console.error('保存失败:', error);
- }
- },
- /** 获取会话历史 */
- async getSessionHistory() {
- const response = await fetch(`http://182.92.126.35:6005/sessions`, {
- method: 'post',
- headers: {
- 'Content-Type': 'application/json',
- },
- body: JSON.stringify({
- user_id: this.userID,
- }),
- });
- const data = await response.json();
- this.sessionHistory = data.chat_sessions;
- },
- /** 获取会话历史 */
- async getSessionHistoryByID(id: string) {
- const response = await fetch(`http://182.92.126.35:6005/sessions/history_chat/?chat_session_id=${id}`, {
- method: 'get',
- headers: {
- 'Content-Type': 'application/json',
- },
- });
- const data = await response.json();
- if (data.chat_messages.length === 0) return;
- this.currentSessionID = id;
- this.messageHistory = data.chat_messages.map((item: any) => {
- if (item.role === 'user') {
- // role== user 用户提问
- return {
- id: `user_${Date.now()}`,
- type: 'user',
- content: item.content,
- contentR1: '',
- timestamp: Date.now(),
- };
- } else {
- // role== assistant 机器回答
- return {
- id: `system_${Date.now()}`,
- type: 'system',
- content: item.content,
- contentR1: item.thinking_content,
- timestamp: Date.now(),
- };
- }
- });
- },
- /** 发出问题 */
- async sendQuestion(question: string, onUpdate?: any) {
- if (this.currentSessionID === '') {
- await this.createSession();
- this.createSessionTitle(question);
- this.createStream(question, onUpdate);
- } else {
- this.createSessionTitle(question);
- this.createStream(question, onUpdate);
- }
- },
- },
- });
|