Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tidy-onions-camp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'ai-connector': patch
---

Throw error when provided AI response isn't valid
24 changes: 24 additions & 0 deletions packages/core/streams/ai-stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,29 @@ export function trimStartOfStreamHelper(): (text: string) => string {
* @throws Will throw an error if the response is not OK.
*/
export function AIStream(

res: Response,
customParser: AIStreamParser,
callbacks?: AIStreamCallbacks
): ReadableStream {
// If the response is not OK, we want to throw an error to indicate that
// the AI service is not available.
// When catching this error, we can check the status code and return a handled
// error response to the client.
if (!res.ok) {
throw new Error(
`Failed to convert the response to stream. Received status code: ${res.status}.`
)
}

const stream =
res.body ||
new ReadableStream({
start(controller) {
controller.close()
}
})

response: Response,
customParser?: AIStreamParser,
callbacks?: AIStreamCallbacksAndOptions,
Expand Down Expand Up @@ -315,6 +338,7 @@ export function AIStream(

const responseBodyStream = response.body || createEmptyReadableStream();


return responseBodyStream
.pipeThrough(createEventStreamTransformer(customParser))

Expand Down
Loading