Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix: Improve OpenAIStream processing to emit usage data for chunks lacking choices (#9220)

Arvin Xu8ba662c9de38
diff --git a/packages/model-runtime/src/core/streams/openai/openai.test.ts b/packages/model-runtime/src/core/streams/openai/openai.test.ts
index e8b29fcc092..8a80b0adff0 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.test.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.test.ts
@@ -295,6 +295,40 @@ describe('OpenAIStream', () => {
]);
});
+ it('should emit usage when choices are missing but usage exists', async () => {
+ const mockOpenAIStream = new ReadableStream({
+ start(controller) {
+ controller.enqueue({
+ id: '99',
+ usage: {
+ prompt_tokens: 1,
+ completion_tokens: 2,
+ total_tokens: 3,
+ prompt_cache_miss_tokens: 1,
+ },
+ });
+
+ controller.close();
+ },
+ });
+
+ const protocolStream = OpenAIStream(mockOpenAIStream);
+
+ const decoder = new TextDecoder();
+ const chunks: string[] = [];
+
+ // @ts-ignore
+ for await (const chunk of protocolStream) {
+ chunks.push(decoder.decode(chunk, { stream: true }));
+ }
+
+ expect(chunks).toEqual([
+ 'id: 99\n',
+ 'event: usage\n',
+ `data: {"inputCacheMissTokens":1,"inputTextTokens":1,"outputTextTokens":2,"totalInputTokens":1,"totalOutputTokens":2,"totalTokens":3}\n\n`,
+ ]);
+ });
+
it('should handle error when there is not correct error', async () => {
const mockOpenAIStream = new ReadableStream({
start(controller) {
@@ -331,8 +365,8 @@ describe('OpenAIStream', () => {
'event: text',
`data: "Hello"\n`,
'id: 1',
- 'event: error',
- `data: {"body":{"message":"chat response streaming chunk parse error, please contact your API Provider to fix it.","context":{"error":{"message":"Cannot read properties of undefined (reading '0')","name":"TypeError"},"chunk":{"id":"1"}}},"type":"StreamChunkError"}\n`,
+ 'event: data',
+ `data: {"id":"1"}\n`,
].map((i) => `${i}\n`),
);
});
diff --git a/packages/model-runtime/src/core/streams/openai/openai.ts b/packages/model-runtime/src/core/streams/openai/openai.ts
index 4dbca3bf8b8..9d00ce0a2ad 100644
--- a/packages/model-runtime/src/core/streams/openai/openai.ts
+++ b/packages/model-runtime/src/core/streams/openai/openai.ts
@@ -64,8 +64,7 @@ const transformOpenAIStream = (
try {
// maybe need another structure to add support for multiple choices
- const item = chunk.choices[0];
- if (!item) {
+ if (!Array.isArray(chunk.choices) || chunk.choices.length === 0) {
if (chunk.usage) {
const usage = chunk.usage;
return { data: convertUsage(usage, provider), id: chunk.id, type: 'usage' };
@@ -74,6 +73,8 @@ const transformOpenAIStream = (
return { data: chunk, id: chunk.id, type: 'data' };
}
+ const item = chunk.choices[0];
+
if (item && typeof item.delta?.tool_calls === 'object' && item.delta.tool_calls?.length > 0) {
// tools calling
const tool_calls = item.delta.tool_calls.filter(