diff --git a/src/streaming.ts b/src/streaming.ts index f69724d64..33f641888 100644 --- a/src/streaming.ts +++ b/src/streaming.ts @@ -1,6 +1,8 @@ import { ReadableStream, type Response } from './_shims/index'; import { OpenAIError } from './error'; +import { APIError } from 'openai/error'; + type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined; type ServerSentEvent = { @@ -58,13 +60,21 @@ export class Stream implements AsyncIterable { } if (sse.event === null) { + let data; + try { - yield JSON.parse(sse.data); + data = JSON.parse(sse.data); } catch (e) { console.error(`Could not parse message into JSON:`, sse.data); console.error(`From chunk:`, sse.raw); throw e; } + + if (data && data.error) { + throw new APIError(undefined, data.error, undefined, undefined); + } + + yield data; } } done = true;