Flowise

Форк
0
103 строки · 3.9 Кб
1
import { Request, Response, NextFunction } from 'express'
2
import * as fs from 'fs'
3
import openaiAssistantsService from '../../services/openai-assistants'
4
import contentDisposition from 'content-disposition'
5
import { InternalFlowiseError } from '../../errors/internalFlowiseError'
6
import { StatusCodes } from 'http-status-codes'
7
import { streamStorageFile } from 'flowise-components'
8

9
// List available assistants
10
const getAllOpenaiAssistants = async (req: Request, res: Response, next: NextFunction) => {
11
    try {
12
        if (typeof req.query === 'undefined' || !req.query.credential) {
13
            throw new InternalFlowiseError(
14
                StatusCodes.PRECONDITION_FAILED,
15
                `Error: openaiAssistantsController.getAllOpenaiAssistants - credential not provided!`
16
            )
17
        }
18
        const apiResponse = await openaiAssistantsService.getAllOpenaiAssistants(req.query.credential as string)
19
        return res.json(apiResponse)
20
    } catch (error) {
21
        next(error)
22
    }
23
}
24

25
// Get assistant object
26
const getSingleOpenaiAssistant = async (req: Request, res: Response, next: NextFunction) => {
27
    try {
28
        if (typeof req.params === 'undefined' || !req.params.id) {
29
            throw new InternalFlowiseError(
30
                StatusCodes.PRECONDITION_FAILED,
31
                `Error: openaiAssistantsController.getSingleOpenaiAssistant - id not provided!`
32
            )
33
        }
34
        if (typeof req.query === 'undefined' || !req.query.credential) {
35
            throw new InternalFlowiseError(
36
                StatusCodes.PRECONDITION_FAILED,
37
                `Error: openaiAssistantsController.getSingleOpenaiAssistant - credential not provided!`
38
            )
39
        }
40
        const apiResponse = await openaiAssistantsService.getSingleOpenaiAssistant(req.query.credential as string, req.params.id)
41
        return res.json(apiResponse)
42
    } catch (error) {
43
        next(error)
44
    }
45
}
46

47
// Download file from assistant
48
const getFileFromAssistant = async (req: Request, res: Response, next: NextFunction) => {
49
    try {
50
        if (!req.body.chatflowId || !req.body.chatId || !req.body.fileName) {
51
            return res.status(500).send(`Invalid file path`)
52
        }
53
        const chatflowId = req.body.chatflowId as string
54
        const chatId = req.body.chatId as string
55
        const fileName = req.body.fileName as string
56
        res.setHeader('Content-Disposition', contentDisposition(fileName))
57
        const fileStream = await streamStorageFile(chatflowId, chatId, fileName)
58

59
        if (!fileStream) throw new InternalFlowiseError(StatusCodes.INTERNAL_SERVER_ERROR, `Error: getFileFromAssistant`)
60

61
        if (fileStream instanceof fs.ReadStream && fileStream?.pipe) {
62
            fileStream.pipe(res)
63
        } else {
64
            res.send(fileStream)
65
        }
66
    } catch (error) {
67
        next(error)
68
    }
69
}
70

71
const uploadAssistantFiles = async (req: Request, res: Response, next: NextFunction) => {
72
    try {
73
        if (typeof req.query === 'undefined' || !req.query.credential) {
74
            throw new InternalFlowiseError(
75
                StatusCodes.PRECONDITION_FAILED,
76
                `Error: openaiAssistantsVectorStoreController.uploadFilesToAssistantVectorStore - credential not provided!`
77
            )
78
        }
79
        const files = req.files ?? []
80
        const uploadFiles: { filePath: string; fileName: string }[] = []
81

82
        if (Array.isArray(files)) {
83
            for (const file of files) {
84
                uploadFiles.push({
85
                    filePath: file.path,
86
                    fileName: file.originalname
87
                })
88
            }
89
        }
90

91
        const apiResponse = await openaiAssistantsService.uploadFilesToAssistant(req.query.credential as string, uploadFiles)
92
        return res.json(apiResponse)
93
    } catch (error) {
94
        next(error)
95
    }
96
}
97

98
export default {
99
    getAllOpenaiAssistants,
100
    getSingleOpenaiAssistant,
101
    getFileFromAssistant,
102
    uploadAssistantFiles
103
}
104

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

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

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

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