add react-hot-toast and surface OpenAI API errors to users (#328)

This commit is contained in:
Jason Banich
2023-04-01 22:05:07 -07:00
committed by GitHub
parent 23ad285a4b
commit b7b6bbaaca
6 changed files with 78 additions and 5 deletions
+29 -3
View File
@@ -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({