-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
fix(stage-ui): proxy openai-compatible requests in electron #2011
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
jim139129
wants to merge
7
commits into
moeru-ai:main
Choose a base branch
from
jim139129:jim139129/fix/openai-compatible-electron-fetch
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 1 commit
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
cfd0ac6
fix(stage-ui): proxy openai-compatible requests in electron
jim139129 b7b9a2c
Merge branch 'main' into jim139129/fix/openai-compatible-electron-fetch
nekomeowww bcb4331
[autofix.ci] apply automated fixes
autofix-ci[bot] 8b475ab
fix(stage-ui): scope openai-compatible fetch bridge
jim139129 3259b7b
Merge branch 'moeru-ai:main' into jim139129/fix/openai-compatible-ele…
jim139129 82f6e4f
fix(stage-tamagotchi): validate openai bridge payload
jim139129 c0f8485
fix(stage-tamagotchi): register openai bridge before load
jim139129 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
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
55 changes: 55 additions & 0 deletions
55
apps/stage-tamagotchi/src/main/services/airi/openai-compatible-fetch.ts
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,55 @@ | ||
| import type { createContext as createMainEventaContext } from '@moeru/eventa/adapters/electron/main' | ||
|
|
||
| import { defineStreamInvokeHandler } from '@moeru/eventa' | ||
| import { openAICompatibleFetch } from '@proj-airi/stage-shared' | ||
|
|
||
| export function setupOpenAICompatibleFetchBridge(params: { | ||
| context: ReturnType<typeof createMainEventaContext>['context'] | ||
| }) { | ||
| defineStreamInvokeHandler(params.context, openAICompatibleFetch, async function* (payload, options) { | ||
| const url = new URL(payload.url) | ||
| if (url.protocol !== 'http:' && url.protocol !== 'https:') { | ||
| throw new Error('OpenAI-compatible fetch only supports http and https URLs.') | ||
| } | ||
|
jim139129 marked this conversation as resolved.
Outdated
|
||
|
|
||
| const response = await fetch(url, { | ||
| method: payload.method, | ||
| headers: payload.headers, | ||
| body: payload.body, | ||
| signal: options?.abortController?.signal, | ||
| }) | ||
|
|
||
| yield { | ||
| type: 'head' as const, | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| headers: Object.fromEntries(response.headers.entries()), | ||
| } | ||
|
|
||
| if (!response.body) | ||
| return | ||
|
|
||
| const reader = response.body.getReader() | ||
| let completed = false | ||
| try { | ||
| while (true) { | ||
| const { done, value } = await reader.read() | ||
| if (done) { | ||
| completed = true | ||
| return | ||
| } | ||
|
|
||
| yield { type: 'chunk' as const, chunk: value } | ||
| } | ||
| } | ||
| finally { | ||
| if (!completed) { | ||
| try { | ||
| await reader.cancel() | ||
| } | ||
| catch {} | ||
| } | ||
| reader.releaseLock() | ||
| } | ||
| }) | ||
| } | ||
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,24 @@ | ||
| import { defineInvokeEventa } from '@moeru/eventa' | ||
|
|
||
| export interface OpenAICompatibleFetchRequest { | ||
| url: string | ||
| method?: string | ||
| headers?: Record<string, string> | ||
| body?: string | ||
| } | ||
|
|
||
| export interface OpenAICompatibleFetchResponse { | ||
| type: 'head' | ||
| status: number | ||
| statusText: string | ||
| headers: Record<string, string> | ||
| } | ||
|
|
||
| export interface OpenAICompatibleFetchChunk { | ||
| type: 'chunk' | ||
| chunk: Uint8Array | ||
| } | ||
|
|
||
| export type OpenAICompatibleFetchStreamEvent = OpenAICompatibleFetchResponse | OpenAICompatibleFetchChunk | ||
|
|
||
| export const openAICompatibleFetch = defineInvokeEventa<OpenAICompatibleFetchStreamEvent, OpenAICompatibleFetchRequest>('eventa:invoke:electron:openai-compatible:fetch') |
126 changes: 126 additions & 0 deletions
126
packages/stage-ui/src/libs/providers/openaiCompatibleFetch.ts
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,126 @@ | ||
| import type { Fetch } from '@xsai/shared' | ||
|
|
||
| import { defineStreamInvoke } from '@moeru/eventa' | ||
| import { createContext } from '@moeru/eventa/adapters/electron/renderer' | ||
| import { openAICompatibleFetch } from '@proj-airi/stage-shared' | ||
|
|
||
| type IpcRendererLike = Parameters<typeof createContext>[0] | ||
|
|
||
| let sharedFetch: Fetch | undefined | ||
|
|
||
| function resolveElectronIpcRenderer(): IpcRendererLike | undefined { | ||
| if (typeof window === 'undefined') | ||
| return undefined | ||
|
|
||
| return (window as { electron?: { ipcRenderer?: IpcRendererLike } }).electron?.ipcRenderer | ||
| } | ||
|
|
||
| async function readRequestBody(init: RequestInit): Promise<string | undefined> { | ||
| if (typeof init.body === 'string') | ||
| return init.body | ||
| if (init.body == null) | ||
| return undefined | ||
|
|
||
| return await new Response(init.body).text() | ||
| } | ||
|
|
||
| function headersToRecord(headers: HeadersInit | undefined): Record<string, string> | undefined { | ||
| if (!headers) | ||
| return undefined | ||
|
|
||
| const result: Record<string, string> = {} | ||
| new Headers(headers).forEach((value, key) => { | ||
| result[key] = value | ||
| }) | ||
| return result | ||
| } | ||
|
|
||
| function shouldUseElectronFetchFallback(error: unknown) { | ||
| if (typeof DOMException !== 'undefined' && error instanceof DOMException && error.name === 'AbortError') | ||
| return false | ||
|
|
||
| return error instanceof TypeError | ||
| } | ||
|
|
||
| function normalizeRequestMethod(init: RequestInit): string { | ||
| return (init.method ?? 'GET').toUpperCase() | ||
| } | ||
|
|
||
| function canReplayRequest(method: string): boolean { | ||
| return method === 'GET' || method === 'HEAD' || method === 'OPTIONS' || method === 'TRACE' | ||
| } | ||
|
|
||
| function createElectronFetch(ipcRenderer: IpcRendererLike): Fetch { | ||
| const { context } = createContext(ipcRenderer) | ||
| const invokeFetch = defineStreamInvoke(context, openAICompatibleFetch) | ||
|
|
||
| return async (input, init) => { | ||
| const requestUrl = input.toString() | ||
| const requestMethod = normalizeRequestMethod(init) | ||
|
|
||
| const fetchThroughElectron = async () => { | ||
| const responseEvents = invokeFetch({ | ||
| url: requestUrl, | ||
| method: init.method, | ||
| headers: headersToRecord(init.headers), | ||
| body: await readRequestBody(init), | ||
| }, init.signal ? { signal: init.signal } : undefined) | ||
| const reader = responseEvents.getReader() | ||
| const head = await reader.read() | ||
|
|
||
| if (head.done || head.value.type !== 'head') { | ||
| await reader.cancel() | ||
| throw new Error('OpenAI-compatible fetch bridge closed before response headers.') | ||
| } | ||
|
|
||
| const body = new ReadableStream<Uint8Array>({ | ||
| async pull(controller) { | ||
| const next = await reader.read() | ||
| if (next.done) { | ||
| controller.close() | ||
| return | ||
| } | ||
|
|
||
| if (next.value.type !== 'chunk') { | ||
| controller.error(new Error('OpenAI-compatible fetch bridge received an unexpected response event.')) | ||
| await reader.cancel() | ||
| return | ||
| } | ||
|
|
||
| controller.enqueue(next.value.chunk) | ||
| }, | ||
| async cancel(reason) { | ||
| await reader.cancel(reason) | ||
| }, | ||
| }) | ||
|
|
||
| return new Response(body, { | ||
| status: head.value.status, | ||
| statusText: head.value.statusText, | ||
| headers: head.value.headers, | ||
| }) | ||
| } | ||
|
|
||
| if (!canReplayRequest(requestMethod)) | ||
| return await fetchThroughElectron() | ||
|
jim139129 marked this conversation as resolved.
|
||
|
|
||
| try { | ||
| return await globalThis.fetch(input, init) | ||
| } | ||
| catch (error) { | ||
| if (!shouldUseElectronFetchFallback(error)) | ||
| throw error | ||
|
|
||
| return await fetchThroughElectron() | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export function resolveOpenAICompatibleFetch(): Fetch | undefined { | ||
| const ipcRenderer = resolveElectronIpcRenderer() | ||
| if (!ipcRenderer) | ||
| return undefined | ||
|
|
||
| sharedFetch ??= createElectronFetch(ipcRenderer) | ||
| return sharedFetch | ||
| } | ||
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
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.