1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
| import { useState } from 'react'
| import { useTranslation } from 'react-i18next'
| import { useToastContext } from '@/app/components/base/toast'
| import { ssePost } from '@/service/base'
|
| export const useTextGeneration = () => {
| const { t } = useTranslation()
| const { notify } = useToastContext()
| const [isResponding, setIsResponding] = useState(false)
| const [completion, setCompletion] = useState('')
| const [messageId, setMessageId] = useState<string | null>(null)
|
| const handleSend = async (
| url: string,
| data: any,
| ) => {
| if (isResponding) {
| notify({ type: 'info', message: t('appDebug.errorMessage.waitForResponse') })
| return false
| }
|
| setIsResponding(true)
| setCompletion('')
| setMessageId('')
| let res: string[] = []
| ssePost(
| url,
| {
| body: {
| response_mode: 'streaming',
| ...data,
| },
| },
| {
| onData: (data: string, _isFirstMessage: boolean, { messageId }) => {
| res.push(data)
| setCompletion(res.join(''))
| setMessageId(messageId)
| },
| onMessageReplace: (messageReplace) => {
| res = [messageReplace.answer]
| setCompletion(res.join(''))
| },
| onCompleted() {
| setIsResponding(false)
| },
| onError() {
| setIsResponding(false)
| },
| })
| return true
| }
|
| return {
| completion,
| isResponding,
| setIsResponding,
| handleSend,
| messageId,
| }
| }
|
|