error handling

This commit is contained in:
Jing Hua 2023-03-04 23:35:38 +08:00
parent 5f673691b1
commit b9a8f05176
5 changed files with 91 additions and 83 deletions

View file

@ -25,45 +25,41 @@ export const getChatCompletion = async (
apiKey: string, apiKey: string,
messages: MessageInterface[] messages: MessageInterface[]
) => { ) => {
try { const response = await fetch(endpoint, {
const response = await fetch(endpoint, { method: 'POST',
method: 'POST', headers: {
headers: { 'Content-Type': 'application/json',
'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}`,
Authorization: `Bearer ${apiKey}`, },
}, body: JSON.stringify({
body: JSON.stringify({ model: 'gpt-3.5-turbo',
model: 'gpt-3.5-turbo', messages,
messages, }),
}), });
}); if (!response.ok) throw new Error(await response.text());
const data = await response.json();
return data; const data = await response.json();
} catch (error) { return data;
console.error('Error:', error);
}
}; };
export const getChatCompletionStream = async ( export const getChatCompletionStream = async (
apiKey: string, apiKey: string,
messages: MessageInterface[] messages: MessageInterface[]
) => { ) => {
try { const response = await fetch(endpoint, {
const response = await fetch(endpoint, { method: 'POST',
method: 'POST', headers: {
headers: { 'Content-Type': 'application/json',
'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}`,
Authorization: `Bearer ${apiKey}`, },
}, body: JSON.stringify({
body: JSON.stringify({ model: 'gpt-3.5-turbo',
model: 'gpt-3.5-turbo', messages,
messages, stream: true,
stream: true, }),
}), });
}); if (!response.ok) throw new Error(await response.text());
const stream = response.body;
return stream; const stream = response.body;
} catch (error) { return stream;
console.error('Error:', error);
}
}; };

View file

@ -3,40 +3,36 @@ import { MessageInterface } from '@type/chat';
export const endpoint = 'https://chatgpt-api.shn.hk/v1/'; export const endpoint = 'https://chatgpt-api.shn.hk/v1/';
export const getChatCompletion = async (messages: MessageInterface[]) => { export const getChatCompletion = async (messages: MessageInterface[]) => {
try { const response = await fetch(endpoint, {
const response = await fetch(endpoint, { method: 'POST',
method: 'POST', headers: {
headers: { 'Content-Type': 'application/json',
'Content-Type': 'application/json', },
}, body: JSON.stringify({
body: JSON.stringify({ model: 'gpt-3.5-turbo',
model: 'gpt-3.5-turbo', messages,
messages, }),
}), });
}); if (!response.ok) throw new Error(await response.text());
const data = await response.json();
return data; const data = await response.json();
} catch (error) { return data;
console.error('Error:', error);
}
}; };
export const getChatCompletionStream = async (messages: MessageInterface[]) => { export const getChatCompletionStream = async (messages: MessageInterface[]) => {
try { const response = await fetch(endpoint, {
const response = await fetch(endpoint, { method: 'POST',
method: 'POST', headers: {
headers: { 'Content-Type': 'application/json',
'Content-Type': 'application/json', },
}, body: JSON.stringify({
body: JSON.stringify({ model: 'gpt-3.5-turbo',
model: 'gpt-3.5-turbo', messages,
messages, stream: true,
stream: true, }),
}), });
}); if (!response.ok) throw new Error(await response.text());
const stream = response.body;
return stream; const stream = response.body;
} catch (error) { return stream;
console.error('Error:', error);
}
}; };

View file

@ -39,8 +39,8 @@ const ChatContent = () => {
<Message role={inputRole} content='' messageIndex={-1} sticky /> <Message role={inputRole} content='' messageIndex={-1} sticky />
{error !== '' && ( {error !== '' && (
<div className='bg-red-600/50 p-2 rounded-sm w-3/5 mt-3 text-gray-900 dark:text-gray-300 text-sm'> <div className='bg-red-600/50 p-2 rounded-sm w-3/5 mt-3 text-gray-900 dark:text-gray-300 text-sm break-words'>
Invalid API key! {error}
</div> </div>
)} )}

View file

@ -1,4 +1,4 @@
import React, { useState } from 'react'; import React from 'react';
import useStore from '@store/store'; import useStore from '@store/store';
import { MessageInterface } from '@type/chat'; import { MessageInterface } from '@type/chat';
import { getChatCompletionStream as getChatCompletionStreamFree } from '@api/freeApi'; import { getChatCompletionStream as getChatCompletionStreamFree } from '@api/freeApi';
@ -6,16 +6,23 @@ import { getChatCompletionStream as getChatCompletionStreamCustom } from '@api/c
import { parseEventSource } from '@api/helper'; import { parseEventSource } from '@api/helper';
const useSubmit = () => { const useSubmit = () => {
const [error, setError] = useState<string>(''); const [
const [apiFree, apiKey, setMessages, setGenerating, generating] = useStore( error,
(state) => [ setError,
state.apiFree, apiFree,
state.apiKey, apiKey,
state.setMessages, setMessages,
state.setGenerating, setGenerating,
state.generating, generating,
] ] = useStore((state) => [
); state.error,
state.setError,
state.apiFree,
state.apiKey,
state.setMessages,
state.setGenerating,
state.generating,
]);
const handleSubmit = async () => { const handleSubmit = async () => {
if (generating) return; if (generating) return;
@ -71,8 +78,8 @@ const useSubmit = () => {
console.log(err); console.log(err);
setError(err); setError(err);
setTimeout(() => { setTimeout(() => {
setError(''), 10000; setError('');
}); }, 10000);
} }
setGenerating(false); setGenerating(false);
}; };

View file

@ -6,16 +6,19 @@ export interface ChatSlice {
chats?: ChatInterface[]; chats?: ChatInterface[];
currentChatIndex: number; currentChatIndex: number;
generating: boolean; generating: boolean;
error: string;
setMessages: (messages: MessageInterface[]) => void; setMessages: (messages: MessageInterface[]) => void;
setChats: (chats: ChatInterface[]) => void; setChats: (chats: ChatInterface[]) => void;
setCurrentChatIndex: (currentChatIndex: number) => void; setCurrentChatIndex: (currentChatIndex: number) => void;
setGenerating: (generating: boolean) => void; setGenerating: (generating: boolean) => void;
setError: (error: string) => void;
} }
export const createChatSlice: StoreSlice<ChatSlice> = (set, get) => ({ export const createChatSlice: StoreSlice<ChatSlice> = (set, get) => ({
messages: [], messages: [],
currentChatIndex: -1, currentChatIndex: -1,
generating: false, generating: false,
error: '',
setMessages: (messages: MessageInterface[]) => { setMessages: (messages: MessageInterface[]) => {
set((prev: ChatSlice) => ({ set((prev: ChatSlice) => ({
...prev, ...prev,
@ -40,4 +43,10 @@ export const createChatSlice: StoreSlice<ChatSlice> = (set, get) => ({
generating: generating, generating: generating,
})); }));
}, },
setError: (error: string) => {
set((prev: ChatSlice) => ({
...prev,
error: error,
}));
},
}); });