|
| 1 | +const { createParser } = require('eventsource-parser'); |
| 2 | + |
| 3 | +module.exports = async function fetchSSE(url, options, fetch) { |
| 4 | + const { onmessage, onError, ...fetchOptions } = options; |
| 5 | + const res = await fetch(url, fetchOptions); |
| 6 | + if (!res.ok) { |
| 7 | + let reason; |
| 8 | + |
| 9 | + try { |
| 10 | + reason = await res.text(); |
| 11 | + } catch (err) { |
| 12 | + reason = res.statusText; |
| 13 | + } |
| 14 | + |
| 15 | + const msg = `ChatGPT error ${res.status}: ${reason}`; |
| 16 | + const error = new Error(msg, { cause: res }); |
| 17 | + error.statusCode = res.status; |
| 18 | + error.statusText = res.statusText; |
| 19 | + throw error; |
| 20 | + } |
| 21 | + |
| 22 | + const parser = createParser((event) => { |
| 23 | + if (event.type === 'event') { |
| 24 | + onmessage(event.data); |
| 25 | + } |
| 26 | + }); |
| 27 | + |
| 28 | + // handle special response errors |
| 29 | + const feed = (chunk) => { |
| 30 | + let response = null; |
| 31 | + |
| 32 | + try { |
| 33 | + response = JSON.parse(chunk); |
| 34 | + } catch { |
| 35 | + // ignore |
| 36 | + } |
| 37 | + |
| 38 | + if (response?.detail?.type === 'invalid_request_error') { |
| 39 | + const msg = `ChatGPT error ${response.detail.message}: ${response.detail.code} (${response.detail.type})`; |
| 40 | + const error = new Error(msg, { cause: response }); |
| 41 | + error.statusCode = response.detail.code; |
| 42 | + error.statusText = response.detail.message; |
| 43 | + |
| 44 | + if (onError) { |
| 45 | + onError(error); |
| 46 | + } else { |
| 47 | + console.error(error); |
| 48 | + } |
| 49 | + |
| 50 | + // don't feed to the event parser |
| 51 | + return; |
| 52 | + } |
| 53 | + |
| 54 | + parser.feed(chunk); |
| 55 | + }; |
| 56 | + |
| 57 | + if (!res.body.getReader) { |
| 58 | + // Vercel polyfills `fetch` with `node-fetch`, which doesn't conform to |
| 59 | + // web standards, so this is a workaround... |
| 60 | + const body = res.body; |
| 61 | + |
| 62 | + if (!body.on || !body.read) { |
| 63 | + throw new Error('unsupported "fetch" implementation'); |
| 64 | + } |
| 65 | + |
| 66 | + body.on('readable', () => { |
| 67 | + let chunk; |
| 68 | + while (null !== (chunk = body.read())) { |
| 69 | + feed(chunk.toString()); |
| 70 | + } |
| 71 | + }); |
| 72 | + } else { |
| 73 | + for await (const chunk of streamAsyncIterable(res.body)) { |
| 74 | + const str = new TextDecoder().decode(chunk); |
| 75 | + feed(str); |
| 76 | + } |
| 77 | + } |
| 78 | +}; |
0 commit comments