-
-
Notifications
You must be signed in to change notification settings - Fork 50
feat(cz-git): enhance OpenAI API integration with streaming support #252
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
Open
Zhengqbbb
wants to merge
5
commits into
main
Choose a base branch
from
feat/api-stream
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
bd038a7
feat(cz-git): enhance OpenAI API integration with streaming support
Zhengqbbb 5183a6c
chore: remove npmrc
Zhengqbbb 387e4da
fix(cz-git): update DeepSeek model name and cap stream output to seen…
Zhengqbbb 9e5b3b5
chore: bump dependencies
Zhengqbbb 96cd38f
fix(cz-git): add tests and support for non-stream OpenAI chat complet…
Zhengqbbb File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file was deleted.
Oops, something went wrong.
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,40 @@ | ||
| import { Readable } from 'node:stream' | ||
| import { describe, expect, it } from 'vitest' | ||
| import { readChatCompletionStreamToSubjects } from '../src/shared/utils/stream' | ||
|
|
||
| function asStream(body: string): NodeJS.ReadableStream { | ||
| return Readable.from([body]) | ||
| } | ||
|
|
||
| describe('readChatCompletionStreamToSubjects', () => { | ||
| it('parses non-stream JSON when no SSE choice deltas appear', async () => { | ||
| const json = JSON.stringify({ | ||
| choices: [{ index: 0, message: { role: 'assistant', content: 'fix login redirect' } }], | ||
| }) | ||
| const subjects = await readChatCompletionStreamToSubjects(asStream(json), 1) | ||
| expect(subjects).toEqual(['fix login redirect']) | ||
| }) | ||
|
|
||
| it('parses SSE data lines as before', async () => { | ||
| const sse = [ | ||
| 'data: {"choices":[{"index":0,"delta":{"content":"hello"}}]}', | ||
| '', | ||
| 'data: {"choices":[{"index":0,"delta":{"content":" world"}}]}', | ||
| '', | ||
| 'data: [DONE]', | ||
| '', | ||
| ].join('\n') | ||
| const subjects = await readChatCompletionStreamToSubjects(asStream(sse), 1) | ||
| expect(subjects).toEqual(['hello world']) | ||
| }) | ||
|
|
||
| it('throws when body has neither SSE choices nor non-stream completion', async () => { | ||
| await expect(readChatCompletionStreamToSubjects(asStream('not json'), 1)).rejects.toThrow( | ||
| /no streamed choice deltas/, | ||
| ) | ||
| }) | ||
|
|
||
| it('does not return a single empty subject when stream is empty', async () => { | ||
| await expect(readChatCompletionStreamToSubjects(asStream(''), 1)).rejects.toThrow() | ||
| }) | ||
| }) |
This file contains hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,4 +1,5 @@ | ||
| export * from './editor' | ||
| export * from './util' | ||
| export * from './rule' | ||
| export * from './stream' | ||
| export * from './util' | ||
| export * from './wrap' |
This file contains hidden or 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,171 @@ | ||
| /** | ||
| * @description Parse OpenAI-compatible `chat/completions` streaming (SSE) bodies | ||
| * @author Zhengqbbb <zhengqbbb@gmail.com> | ||
| * @license MIT | ||
| */ | ||
|
|
||
| import { Buffer } from 'node:buffer' | ||
| import { Readable } from 'node:stream' | ||
| import type { ReadableStream as WebReadableStream } from 'node:stream/web' | ||
|
|
||
| /** | ||
| * Normalize `fetch` response body to a Node.js readable stream. | ||
| */ | ||
| export function bodyToNodeReadable(body: unknown): NodeJS.ReadableStream { | ||
| if (body == null) | ||
| throw new Error('Response has no body') | ||
| if (typeof (body as WebReadableStream).getReader === 'function') | ||
| return Readable.fromWeb(body as WebReadableStream) | ||
| return body as NodeJS.ReadableStream | ||
| } | ||
|
|
||
| /** | ||
| * Append only user-visible completion tokens from `delta.content`. | ||
| * Skips reasoning / `reasoning_content` (not present on `content` in typical deltas). | ||
| */ | ||
| export function appendVisibleDelta(acc: string, delta: { content?: unknown } | undefined): string { | ||
| if (!delta) | ||
| return acc | ||
| const c = delta.content | ||
| if (c == null) | ||
| return acc | ||
| if (typeof c === 'string') | ||
| return acc + c | ||
| if (Array.isArray(c)) { | ||
| let s = acc | ||
| for (const p of c) { | ||
| if (p && typeof p === 'object' && (p as { type?: string, text?: string }).type === 'text') { | ||
| const t = (p as { text?: string }).text | ||
| if (typeof t === 'string') | ||
| s += t | ||
| } | ||
| } | ||
| return s | ||
| } | ||
| return acc | ||
| } | ||
|
|
||
| interface StreamChoiceChunk { index?: number, delta?: { content?: unknown } } | ||
|
|
||
| interface NonStreamChoice { index?: number, message?: { content?: unknown } } | ||
|
|
||
| async function readableToUtf8String(stream: NodeJS.ReadableStream): Promise<string> { | ||
| const chunks: Buffer[] = [] | ||
| for await (const chunk of stream as AsyncIterable<string | Buffer>) { | ||
| if (Buffer.isBuffer(chunk)) | ||
| chunks.push(chunk) | ||
| else if (typeof chunk === 'string') | ||
| chunks.push(Buffer.from(chunk)) | ||
| else | ||
| chunks.push(Buffer.from(String(chunk))) | ||
| } | ||
| return Buffer.concat(chunks as readonly Uint8Array[]).toString('utf8') | ||
| } | ||
|
|
||
| /** | ||
| * Parse a non-streaming `chat/completions` JSON body when `stream: true` was ignored. | ||
| * @returns subjects slice, or `undefined` if the body is not a usable completion object. | ||
| */ | ||
| function trySubjectsFromNonStreamCompletionJson( | ||
| body: string, | ||
| choiceCount: number, | ||
| ): string[] | undefined { | ||
| const t = body.trim() | ||
| if (!t.startsWith('{')) | ||
| return undefined | ||
| let json: unknown | ||
| try { | ||
| json = JSON.parse(t) | ||
| } | ||
| catch { | ||
| return undefined | ||
| } | ||
| if (!json || typeof json !== 'object') | ||
| return undefined | ||
| const o = json as { choices?: NonStreamChoice[], error?: { message?: string } } | ||
| if (o.error) | ||
| throw new Error(o.error.message || 'OpenAI API error') | ||
| if (!Array.isArray(o.choices)) | ||
| return undefined | ||
|
|
||
| const buffers = Array.from({ length: choiceCount }, () => '') | ||
| let maxIndexSeen = -1 | ||
| for (const ch of o.choices) { | ||
| const idx = typeof ch.index === 'number' ? ch.index : 0 | ||
| if (idx >= 0 && idx < choiceCount) { | ||
| buffers[idx] = appendVisibleDelta('', { content: ch.message?.content }) | ||
| maxIndexSeen = Math.max(maxIndexSeen, idx) | ||
| } | ||
| } | ||
| if (maxIndexSeen < 0) | ||
| return undefined | ||
| return buffers.slice(0, maxIndexSeen + 1) | ||
| } | ||
|
|
||
| function collectSubjectsFromSseLines( | ||
| body: string, | ||
| choiceCount: number, | ||
| ): { buffers: string[], maxIndexSeen: number } { | ||
| const buffers = Array.from({ length: choiceCount }, () => '') | ||
| let maxIndexSeen = -1 | ||
| for (const line of body.split(/\r?\n/)) { | ||
| const trimmed = line.trim() | ||
| if (!trimmed.startsWith('data:')) | ||
| continue | ||
| const payload = trimmed.slice(5).trim() | ||
| if (payload === '[DONE]') | ||
| continue | ||
| try { | ||
| const json = JSON.parse(payload) as { | ||
| error?: { message?: string } | ||
| choices?: StreamChoiceChunk[] | ||
| } | ||
| if (json.error) | ||
| throw new Error(json.error.message || 'OpenAI stream error') | ||
|
|
||
| for (const ch of json.choices ?? []) { | ||
| const idx = typeof ch.index === 'number' ? ch.index : 0 | ||
| if (idx >= 0 && idx < choiceCount) { | ||
| buffers[idx] = appendVisibleDelta(buffers[idx], ch.delta) | ||
| maxIndexSeen = Math.max(maxIndexSeen, idx) | ||
| } | ||
| } | ||
| } | ||
| catch (e) { | ||
| if (e instanceof SyntaxError) | ||
| continue | ||
| throw e | ||
| } | ||
| } | ||
| return { buffers, maxIndexSeen } | ||
| } | ||
|
|
||
| /** | ||
| * Read an OpenAI-style `chat/completions` response body and return one finished string per choice. | ||
| * Primary path: SSE lines (`data: {...}`) with `choices[].delta`, bucketed by `choices[].index` | ||
| * up to `choiceCount` (requested `n`). Returned length is `maxSeenIndex + 1` (capped by `choiceCount`), | ||
| * mirroring non-stream `choices.length` when fewer parallel completions appear. | ||
| * Fallback: if no choice index ever appears (e.g. provider ignores `stream: true` and returns one JSON object), | ||
| * the full body is parsed as a non-streaming completion using `choices[].message.content`. | ||
| */ | ||
| export async function readChatCompletionStreamToSubjects( | ||
| input: NodeJS.ReadableStream, | ||
| choiceCount: number, | ||
| ): Promise<string[]> { | ||
| if (choiceCount < 1) | ||
| throw new Error('choiceCount must be at least 1') | ||
|
|
||
| const body = await readableToUtf8String(input) | ||
| const { buffers, maxIndexSeen } = collectSubjectsFromSseLines(body, choiceCount) | ||
|
|
||
| if (maxIndexSeen >= 0) | ||
| return buffers.slice(0, maxIndexSeen + 1) | ||
|
|
||
| const fromJson = trySubjectsFromNonStreamCompletionJson(body, choiceCount) | ||
| if (fromJson !== undefined) | ||
| return fromJson | ||
|
|
||
| throw new Error( | ||
| 'Chat completions response had no streamed choice deltas and is not a parseable non-streaming JSON body with choices (or choices were empty).', | ||
| ) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.