-
Notifications
You must be signed in to change notification settings - Fork 863
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(streaming): correctly handle trailing new lines in byte chunks (#708
- Loading branch information
1 parent
d144789
commit 4753be2
Showing
2 changed files
with
49 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
import { LineDecoder } from 'openai/streaming'; | ||
|
||
function decodeChunks(chunks: string[], decoder?: LineDecoder): string[] { | ||
if (!decoder) { | ||
decoder = new LineDecoder(); | ||
} | ||
|
||
const lines = []; | ||
for (const chunk of chunks) { | ||
lines.push(...decoder.decode(chunk)); | ||
} | ||
|
||
return lines; | ||
} | ||
|
||
describe('line decoder', () => { | ||
test('basic', () => { | ||
// baz is not included because the line hasn't ended yet | ||
expect(decodeChunks(['foo', ' bar\nbaz'])).toEqual(['foo bar']); | ||
}); | ||
|
||
test('basic with \\r', () => { | ||
// baz is not included because the line hasn't ended yet | ||
expect(decodeChunks(['foo', ' bar\r\nbaz'])).toEqual(['foo bar']); | ||
}); | ||
|
||
test('trailing new lines', () => { | ||
expect(decodeChunks(['foo', ' bar', 'baz\n', 'thing\n'])).toEqual(['foo barbaz', 'thing']); | ||
}); | ||
|
||
test('trailing new lines with \\r', () => { | ||
expect(decodeChunks(['foo', ' bar', 'baz\r\n', 'thing\r\n'])).toEqual(['foo barbaz', 'thing']); | ||
}); | ||
|
||
test('escaped new lines', () => { | ||
expect(decodeChunks(['foo', ' bar\\nbaz\n'])).toEqual(['foo bar\\nbaz']); | ||
}); | ||
|
||
test('escaped new lines with \\r', () => { | ||
expect(decodeChunks(['foo', ' bar\\r\\nbaz\n'])).toEqual(['foo bar\\r\\nbaz']); | ||
}); | ||
}); |