Files
dify/web/app/components/base/text-generation/hooks.ts
yyh dfcc0f8863 refactor(dify-ui): finish primitive migration from web/base/ui to @langgenius/dify-ui (#35349)
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
2026-04-17 08:46:11 +00:00

52 lines
1.3 KiB
TypeScript

import { toast } from '@langgenius/dify-ui/toast'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ssePost } from '@/service/base'
export const useTextGeneration = () => {
const { t } = useTranslation()
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) {
toast.info(t('errorMessage.waitForResponse', { ns: 'appDebug' }))
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,
}
}