hooks.ts 1.5 KB

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