Skip to content

Commit e6dcf6a

Browse files
committed
robust stream parse
1 parent 592eb75 commit e6dcf6a

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "oneping",
3-
"version": "1.0.5",
3+
"version": "1.0.6",
44
"description": "Query LLMs and Whisper straight from the web.",
55
"type": "module",
66
"author": "Doug Hanley",

src/curl.js

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,16 @@
11
// a javascript mini-library for making chat completion requests to an LLM provider
22

3+
// general utilities
4+
5+
function robustParse(json) {
6+
try {
7+
return JSON.parse(json);
8+
} catch (e) {
9+
console.error(e);
10+
return null;
11+
}
12+
}
13+
314
//
415
// authorization
516
//
@@ -67,7 +78,8 @@ function* stream_openai(response) {
6778
if (block.length == 0) continue;
6879
const [match, data0] = /^data: (.*)$/.exec(block)
6980
if (data0 == '[DONE]') break;
70-
const data = JSON.parse(data0);
81+
const data = robustParse(data0);
82+
if (data == null) continue;
7183
const text = data.choices[0].delta.content;
7284
if (text != null) yield text;
7385
}
@@ -79,7 +91,8 @@ function* stream_anthropic(chunk) {
7991
const [line1, line2] = block.split('\n')
8092
const [match1, event] = /^event: (.*)$/.exec(line1)
8193
const [match2, data0] = /^data: (.*)$/.exec(line2)
82-
const data = JSON.parse(data0);
94+
const data = robustParse(data0);
95+
if (data == null) continue;
8396
if (event == 'content_block_start') {
8497
yield data.content_block.text;
8598
} else if (event == 'content_block_delta') {

0 commit comments

Comments
 (0)