From 5db24e4bbc74395ef4314661fb3da30bc6a744ce Mon Sep 17 00:00:00 2001 From: Zhuyi Xue <527862+zyxue@users.noreply.github.com> Date: Thu, 8 May 2025 15:09:39 -0700 Subject: [PATCH 1/4] handle data:[DONE] more robustly although https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#request-body says >stream boolean Whether to stream back partial progress. If set, tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message but what I see is `data:[DONE]` (without space), e.g. ``` curl -q --location 'http://localhost:8080/openai/deployments/gpt-4o/chat/completions?api-version=2023-07-01-preview' \ --header 'Authorization: Bearer ' \ --header 'X-Forwarded-Client-Cert: secret' \ --header 'Content-Type: application/json' \ --data '{ "stream": true, "messages": [ { "role": "user", "content": "hello." } ] }' data:{"choices":[],"created":0,"id":"","model":"","object":"","prompt_filter_results":[{"prompt_index":0,"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}}}]} data:{"choices":[{"content_filter_results":{},"delta":{"refusal":null,"role":"assistant"},"finish_reason":null,"index":0}],"created":1746741184,"id":"chatcmpl-BV3SqfEtCuk3f8fW5x7azEkELkJZ0","model":"gpt-4o-2024-05-13","object":"chat.completion.chunk","system_fingerprint":"fp_ee1d74bde0"} ... data:{"choices":[{"content_filter_results":{"hate":{"filtered":false,"severity":"safe"},"self_harm":{"filtered":false,"severity":"safe"},"sexual":{"filtered":false,"severity":"safe"},"violence":{"filtered":false,"severity":"safe"}},"delta":{"content":"?"},"finish_reason":null,"index":0}],"created":1746741184,"id":"chatcmpl-BV3SqfEtCuk3f8fW5x7azEkELkJZ0","model":"gpt-4o-2024-05-13","object":"chat.completion.chunk","system_fingerprint":"fp_ee1d74bde0"} data:{"choices":[{"content_filter_results":{},"delta":{},"finish_reason":"stop","index":0}],"created":1746741184,"id":"chatcmpl-BV3SqfEtCuk3f8fW5x7azEkELkJZ0","model":"gpt-4o-2024-05-13","object":"chat.completion.chunk","system_fingerprint":"fp_ee1d74bde0"} data:[DONE] ``` --- core/llm/stream.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/llm/stream.ts b/core/llm/stream.ts index 0a014d931..78a4b60e3 100644 --- a/core/llm/stream.ts +++ b/core/llm/stream.ts @@ -58,7 +58,7 @@ function parseDataLine(line: string): any { } function parseSseLine(line: string): { done: boolean; data: any } { - if (line.startsWith("data: [DONE]")) { + if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) { return { done: true, data: undefined }; } if (line.startsWith("data:")) { From a13df1f6135ce21daadc945d13e41a652a2c2a5d Mon Sep 17 00:00:00 2001 From: Zhuyi Xue <527862+zyxue@users.noreply.github.com> Date: Thu, 8 May 2025 15:17:21 -0700 Subject: [PATCH 2/4] Update stream.ts --- packages/fetch/src/stream.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/fetch/src/stream.ts b/packages/fetch/src/stream.ts index 7f33e377d..f8931868c 100644 --- a/packages/fetch/src/stream.ts +++ b/packages/fetch/src/stream.ts @@ -58,7 +58,7 @@ function parseDataLine(line: string): any { } function parseSseLine(line: string): { done: boolean; data: any } { - if (line.startsWith("data: [DONE]")) { + if (line.startsWith("data:[DONE]") || line.startsWith("data: [DONE]")) { return { done: true, data: undefined }; } if (line.startsWith("data:")) { From 1ea2a105edf90e3b5ef318eeab8249e0c78329be Mon Sep 17 00:00:00 2001 From: zyxue Date: Mon, 12 May 2025 08:57:51 -0700 Subject: [PATCH 3/4] added unittest for stream --- core/llm/stream.test.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 core/llm/stream.test.ts diff --git a/core/llm/stream.test.ts b/core/llm/stream.test.ts new file mode 100644 index 000000000..c81ad3fc4 --- /dev/null +++ b/core/llm/stream.test.ts @@ -0,0 +1,29 @@ +import { parseSseLine } from "./stream"; + +// Jest unit tests +describe('parseSseLine', () => { + it('should return done:true and data:undefined for line starting with "data:[DONE]"', () => { + const result = parseSseLine('data:[DONE]'); + expect(result).toEqual({ done: true, data: undefined }); + }); + + it('should return done:true and data:undefined for line starting with "data: [DONE]"', () => { + const result = parseSseLine('data: [DONE]'); + expect(result).toEqual({ done: true, data: undefined }); + }); + + it('should return done:false and parsed data for line starting with "data:"', () => { + const result = parseSseLine('data:Hello World'); + expect(result).toEqual({ done: false, data: 'Hello World' }); + }); + + it('should return done:true and data:undefined for line starting with ": ping"', () => { + const result = parseSseLine(': ping'); + expect(result).toEqual({ done: true, data: undefined }); + }); + + it('should return done:false and data:undefined for line not starting with specific prefixes', () => { + const result = parseSseLine('random line'); + expect(result).toEqual({ done: false, data: undefined }); + }); + }); \ No newline at end of file From ad37da671439e24708e24bd3eb4affe10319afa2 Mon Sep 17 00:00:00 2001 From: Zhuyi Xue <527862+zyxue@users.noreply.github.com> Date: Mon, 19 May 2025 10:03:33 -0700 Subject: [PATCH 4/4] Updated stream.test.ts --- core/llm/stream.test.ts | 91 ++++++++++++++++++++++++++++++----------- 1 file changed, 67 insertions(+), 24 deletions(-) diff --git a/core/llm/stream.test.ts b/core/llm/stream.test.ts index c81ad3fc4..c42604a3e 100644 --- a/core/llm/stream.test.ts +++ b/core/llm/stream.test.ts @@ -1,29 +1,72 @@ -import { parseSseLine } from "./stream"; +import { Readable } from "stream"; +import { streamSse } from "./stream"; -// Jest unit tests -describe('parseSseLine', () => { - it('should return done:true and data:undefined for line starting with "data:[DONE]"', () => { - const result = parseSseLine('data:[DONE]'); - expect(result).toEqual({ done: true, data: undefined }); - }); +function createMockResponse(sseLines: string[]): Response { + // Create a Readable stream that emits the SSE lines + const stream = new Readable({ + read() { + for (const line of sseLines) { + this.push(line + "\n\n"); + } + this.push(null); // End of stream + } + }) as any; - it('should return done:true and data:undefined for line starting with "data: [DONE]"', () => { - const result = parseSseLine('data: [DONE]'); - expect(result).toEqual({ done: true, data: undefined }); - }); + // Minimal Response mock + return { + status: 200, + body: stream, + text: async () => "", + } as unknown as Response; +} - it('should return done:false and parsed data for line starting with "data:"', () => { - const result = parseSseLine('data:Hello World'); - expect(result).toEqual({ done: false, data: 'Hello World' }); - }); +describe("streamSse", () => { + it("yields parsed SSE data objects that ends with `data:[DONE]`", async () => { + const sseLines = [ + 'data: {"foo": "bar"}', + 'data: {"baz": 42}', + 'data:[DONE]' + ]; + const response = createMockResponse(sseLines); - it('should return done:true and data:undefined for line starting with ": ping"', () => { - const result = parseSseLine(': ping'); - expect(result).toEqual({ done: true, data: undefined }); - }); + const results = []; + for await (const data of streamSse(response)) { + results.push(data); + } - it('should return done:false and data:undefined for line not starting with specific prefixes', () => { - const result = parseSseLine('random line'); - expect(result).toEqual({ done: false, data: undefined }); - }); - }); \ No newline at end of file + expect(results).toEqual([ + { foo: "bar" }, + { baz: 42 } + ]); + }); + + it("yields parsed SSE data objects that ends with `data: [DONE]` (with a space before [DONE]", async () => { + const sseLines = [ + 'data: {"foo": "bar"}', + 'data: {"baz": 42}', + 'data: [DONE]' + ]; + const response = createMockResponse(sseLines); + + const results = []; + for await (const data of streamSse(response)) { + results.push(data); + } + + expect(results).toEqual([ + { foo: "bar" }, + { baz: 42 } + ]); + }); + + it("throws on malformed JSON", async () => { + const sseLines = [ + 'data: {"foo": "bar"', + 'data:[DONE]' + ]; + const response = createMockResponse(sseLines); + + const iterator = streamSse(response)[Symbol.asyncIterator](); + await expect(iterator.next()).rejects.toThrow(/Malformed JSON/); + }); +});