Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(stream-text): unable to parse the result due to not check data: frame for sse #5

Merged
merged 1 commit into from
Dec 3, 2024
Merged
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
36 changes: 26 additions & 10 deletions packages/stream-text/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ export interface StreamTextResponse {
usage?: StreamTextResponseUsage
}

const dataHeaderPrefix = 'data: '
const dataErrorPrefix = `{"error":`

/**
* @experimental
* WIP, currently only returns `textStream`, does not support function calling (tools).
Expand All @@ -64,20 +67,33 @@ export const streamText = async (options: StreamTextOptions): Promise<StreamText
const rawChunkStream = res.body.pipeThrough(new TransformStream({
transform: (chunk, controller) => {
for (const line of decoder.decode(chunk).split('\n').filter(line => line)) {
if (line !== 'data: [DONE]') {
const data: StreamTextResponse = JSON.parse(line.slice(6))
// Some cases:
// - Empty chunk
// - :ROUTER PROCESSING from OpenRouter
if (!line || !line.startsWith(dataHeaderPrefix)) {
continue
}

controller.enqueue(data)
if (line.startsWith(dataErrorPrefix)) {
// About controller error: https://developer.mozilla.org/en-US/docs/Web/API/TransformStreamDefaultController/error
controller.error(new Error(`Error from server: ${line}`))
continue
}

if (data.choices[0].finish_reason) {
finishReason = data.choices[0].finish_reason
}
const lineWithoutPrefix = line.slice(dataHeaderPrefix.length)
if (lineWithoutPrefix === '[DONE]') {
controller.terminate()
continue
}

const data: StreamTextResponse = JSON.parse(line.slice(6))
controller.enqueue(data)

if (data.usage)
usage = data.usage
if (data.choices[0].finish_reason) {
finishReason = data.choices[0].finish_reason
}
else {
controller.terminate()
if (data.usage) {
usage = data.usage
}
}
},
Expand Down
Loading