diff --git a/src/api/helper.ts b/src/api/helper.ts index e50a0ff..76ccb6d 100644 --- a/src/api/helper.ts +++ b/src/api/helper.ts @@ -12,7 +12,12 @@ export const parseEventSource = ( .map((line) => line.replace(/^data: /, '')) .join(''); if (jsonString === '[DONE]') return jsonString; - else return JSON.parse(jsonString); + try { + const json = JSON.parse(jsonString); + return json; + } catch { + return '[ERROR]'; + } }); return result; }; diff --git a/src/components/Chat/ChatContent/ChatContent.tsx b/src/components/Chat/ChatContent/ChatContent.tsx index 03d7c37..ca27620 100644 --- a/src/components/Chat/ChatContent/ChatContent.tsx +++ b/src/components/Chat/ChatContent/ChatContent.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useState } from 'react'; import ScrollToBottom from 'react-scroll-to-bottom'; import useStore from '@store/store'; @@ -24,6 +24,7 @@ const ChatContent = () => { state.setMessages, ] ); + const [error, setError] = useState(''); const handleSubmit = async () => { const updatedMessages: MessageInterface[] = JSON.parse( @@ -33,26 +34,26 @@ const ChatContent = () => { setMessages(updatedMessages); let stream; - if (apiFree) { - stream = await getChatCompletionStreamFree(messages); - } else if (apiKey) { - stream = await getChatCompletionStreamCustom(apiKey, messages); - } + try { + if (apiFree) { + stream = await getChatCompletionStreamFree(messages); + } else if (apiKey) { + stream = await getChatCompletionStreamCustom(apiKey, messages); + } - if (stream) { - const reader = stream.getReader(); - let reading = true; - while (reading) { - const { done, value } = await reader.read(); + if (stream) { + const reader = stream.getReader(); + let reading = true; + while (reading) { + const { done, value } = await reader.read(); - try { const result = parseEventSource(new TextDecoder().decode(value)); if (result === '[DONE]' || done) { reading = false; } else { const resultString = result.reduce((output: string, curr) => { - if (curr === '[DONE]') return output; + if (typeof curr === 'string') return output; else { const content = curr.choices[0].delta.content; if (content) output += content; @@ -66,10 +67,15 @@ const ChatContent = () => { updatedMessages[updatedMessages.length - 1].content += resultString; setMessages(updatedMessages); } - } catch (e: unknown) { - console.log((e as Error).message); } } + } catch (e: unknown) { + const err = (e as Error).message; + console.log(err); + setError(err); + setTimeout(() => { + setError(''), 10000; + }); } }; @@ -95,6 +101,12 @@ const ChatContent = () => { ))} + {error !== '' && ( +
+ Invalid API key! +
+ )} +