add react-hot-toast and surface OpenAI API errors to users (#328)
This commit is contained in:
+29
-3
@@ -7,6 +7,20 @@ import {
|
||||
} from 'eventsource-parser';
|
||||
import { OPENAI_API_HOST } from '../app/const';
|
||||
|
||||
export class OpenAIError extends Error {
|
||||
type: string;
|
||||
param: string;
|
||||
code: string;
|
||||
|
||||
constructor(message: string, type: string, param: string, code: string) {
|
||||
super(message);
|
||||
this.name = 'OpenAIError';
|
||||
this.type = type;
|
||||
this.param = param;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
export const OpenAIStream = async (
|
||||
model: OpenAIModel,
|
||||
systemPrompt: string,
|
||||
@@ -41,9 +55,21 @@ export const OpenAIStream = async (
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
if (res.status !== 200) {
|
||||
const statusText = res.statusText;
|
||||
const result = await res.body?.getReader().read();
|
||||
throw new Error(`OpenAI API returned an error: ${decoder.decode(result?.value) || statusText}`);
|
||||
const result = await res.json();
|
||||
if (result.error) {
|
||||
throw new OpenAIError(
|
||||
result.error.message,
|
||||
result.error.type,
|
||||
result.error.param,
|
||||
result.error.code,
|
||||
);
|
||||
} else {
|
||||
throw new Error(
|
||||
`OpenAI API returned an error: ${
|
||||
decoder.decode(result?.value) || result.statusText
|
||||
}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const stream = new ReadableStream({
|
||||
|
||||
Reference in New Issue
Block a user