Flowise

Форк
0
158 строк · 6.3 Кб
1
import { Request, Response, NextFunction } from 'express'
2
import { chatType, IReactFlowObject } from '../../Interface'
3
import chatflowsService from '../../services/chatflows'
4
import chatMessagesService from '../../services/chat-messages'
5
import { clearSessionMemory } from '../../utils'
6
import { getRunningExpressApp } from '../../utils/getRunningExpressApp'
7
import { FindOptionsWhere } from 'typeorm'
8
import { ChatMessage } from '../../database/entities/ChatMessage'
9
import { InternalFlowiseError } from '../../errors/internalFlowiseError'
10
import { StatusCodes } from 'http-status-codes'
11

12
const createChatMessage = async (req: Request, res: Response, next: NextFunction) => {
13
    try {
14
        if (!req.body) {
15
            throw new InternalFlowiseError(
16
                StatusCodes.PRECONDITION_FAILED,
17
                'Error: chatMessagesController.createChatMessage - request body not provided!'
18
            )
19
        }
20
        const apiResponse = await chatMessagesService.createChatMessage(req.body)
21
        return res.json(apiResponse)
22
    } catch (error) {
23
        next(error)
24
    }
25
}
26

27
const getAllChatMessages = async (req: Request, res: Response, next: NextFunction) => {
28
    try {
29
        let chatTypeFilter = req.query?.chatType as chatType | undefined
30
        if (chatTypeFilter) {
31
            try {
32
                const chatTypeFilterArray = JSON.parse(chatTypeFilter)
33
                if (chatTypeFilterArray.includes(chatType.EXTERNAL) && chatTypeFilterArray.includes(chatType.INTERNAL)) {
34
                    chatTypeFilter = undefined
35
                } else if (chatTypeFilterArray.includes(chatType.EXTERNAL)) {
36
                    chatTypeFilter = chatType.EXTERNAL
37
                } else if (chatTypeFilterArray.includes(chatType.INTERNAL)) {
38
                    chatTypeFilter = chatType.INTERNAL
39
                }
40
            } catch (e) {
41
                return res.status(500).send(e)
42
            }
43
        }
44
        const sortOrder = req.query?.order as string | undefined
45
        const chatId = req.query?.chatId as string | undefined
46
        const memoryType = req.query?.memoryType as string | undefined
47
        const sessionId = req.query?.sessionId as string | undefined
48
        const messageId = req.query?.messageId as string | undefined
49
        const startDate = req.query?.startDate as string | undefined
50
        const endDate = req.query?.endDate as string | undefined
51
        const feedback = req.query?.feedback as boolean | undefined
52
        if (typeof req.params === 'undefined' || !req.params.id) {
53
            throw new InternalFlowiseError(
54
                StatusCodes.PRECONDITION_FAILED,
55
                `Error: chatMessageController.getAllChatMessages - id not provided!`
56
            )
57
        }
58
        const apiResponse = await chatMessagesService.getAllChatMessages(
59
            req.params.id,
60
            chatTypeFilter,
61
            sortOrder,
62
            chatId,
63
            memoryType,
64
            sessionId,
65
            startDate,
66
            endDate,
67
            messageId,
68
            feedback
69
        )
70
        return res.json(apiResponse)
71
    } catch (error) {
72
        next(error)
73
    }
74
}
75

76
const getAllInternalChatMessages = async (req: Request, res: Response, next: NextFunction) => {
77
    try {
78
        const sortOrder = req.query?.order as string | undefined
79
        const chatId = req.query?.chatId as string | undefined
80
        const memoryType = req.query?.memoryType as string | undefined
81
        const sessionId = req.query?.sessionId as string | undefined
82
        const messageId = req.query?.messageId as string | undefined
83
        const startDate = req.query?.startDate as string | undefined
84
        const endDate = req.query?.endDate as string | undefined
85
        const feedback = req.query?.feedback as boolean | undefined
86
        const apiResponse = await chatMessagesService.getAllInternalChatMessages(
87
            req.params.id,
88
            chatType.INTERNAL,
89
            sortOrder,
90
            chatId,
91
            memoryType,
92
            sessionId,
93
            startDate,
94
            endDate,
95
            messageId,
96
            feedback
97
        )
98
        return res.json(apiResponse)
99
    } catch (error) {
100
        next(error)
101
    }
102
}
103

104
//Delete all chatmessages from chatId
105
const removeAllChatMessages = async (req: Request, res: Response, next: NextFunction) => {
106
    try {
107
        const appServer = getRunningExpressApp()
108
        if (typeof req.params === 'undefined' || !req.params.id) {
109
            throw new InternalFlowiseError(
110
                StatusCodes.PRECONDITION_FAILED,
111
                'Error: chatMessagesController.removeAllChatMessages - id not provided!'
112
            )
113
        }
114
        const chatflowid = req.params.id
115
        const chatflow = await chatflowsService.getChatflowById(req.params.id)
116
        if (!chatflow) {
117
            return res.status(404).send(`Chatflow ${req.params.id} not found`)
118
        }
119
        const chatId = req.query?.chatId as string
120
        const memoryType = req.query?.memoryType as string | undefined
121
        const sessionId = req.query?.sessionId as string | undefined
122
        const chatType = req.query?.chatType as string | undefined
123
        const isClearFromViewMessageDialog = req.query?.isClearFromViewMessageDialog as string | undefined
124
        const flowData = chatflow.flowData
125
        const parsedFlowData: IReactFlowObject = JSON.parse(flowData)
126
        const nodes = parsedFlowData.nodes
127
        try {
128
            await clearSessionMemory(
129
                nodes,
130
                appServer.nodesPool.componentNodes,
131
                chatId,
132
                appServer.AppDataSource,
133
                sessionId,
134
                memoryType,
135
                isClearFromViewMessageDialog
136
            )
137
        } catch (e) {
138
            return res.status(500).send('Error clearing chat messages')
139
        }
140

141
        const deleteOptions: FindOptionsWhere<ChatMessage> = { chatflowid }
142
        if (chatId) deleteOptions.chatId = chatId
143
        if (memoryType) deleteOptions.memoryType = memoryType
144
        if (sessionId) deleteOptions.sessionId = sessionId
145
        if (chatType) deleteOptions.chatType = chatType
146
        const apiResponse = await chatMessagesService.removeAllChatMessages(chatId, chatflowid, deleteOptions)
147
        return res.json(apiResponse)
148
    } catch (error) {
149
        next(error)
150
    }
151
}
152

153
export default {
154
    createChatMessage,
155
    getAllChatMessages,
156
    getAllInternalChatMessages,
157
    removeAllChatMessages
158
}
159

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.