-
Notifications
You must be signed in to change notification settings - Fork 706
feat(js/plugins/compat-oai): add translation adapter and add translation flow in testapps #4786
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
Merged
ssbushi
merged 5 commits into
genkit-ai:main
from
7hokerz:7hokerz/compat-oai-translation-adapter-openai
Feb 27, 2026
Merged
Changes from 2 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
4f8e3e6
feat: generate translation adapter and add translation flow in testapps
7hokerz abdee5e
refactor: moved translation logic to translate.ts
7hokerz b4a7064
feat: implement Whisper-specific configuration and API handlers
7hokerz 6689e38
refactor: remain translate file and add test about whisper-specific
7hokerz 097c1d6
refactor: applied prompts in test code
7hokerz 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 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,45 @@ | ||
| /** | ||
| * Copyright 2024 The Fire Company | ||
| * Copyright 2024 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| import { z } from 'genkit'; | ||
| import { ModelInfo } from 'genkit/model'; | ||
| import { compatOaiTranslationModelRef } from '../translate'; | ||
|
|
||
| /** OpenAI translation ModelRef helper, same as the OpenAI-compatible spec. */ | ||
| export function openAITranslationModelRef< | ||
| CustomOptions extends z.ZodTypeAny = z.ZodTypeAny, | ||
| >(params: { | ||
| name: string; | ||
| info?: ModelInfo; | ||
| configSchema?: CustomOptions; | ||
| config?: any; | ||
| }) { | ||
| return compatOaiTranslationModelRef({ ...params, namespace: 'openai' }); | ||
| } | ||
|
|
||
| export const SUPPORTED_TRANSLATION_MODELS = { | ||
| /** | ||
| * Whisper 1 translation model. | ||
| * | ||
| * The actual OpenAI model ID is 'whisper-1', but we use 'whisper-1-translate' | ||
| * to distinguish it from the 'whisper-1' transcription model. The model ID | ||
| * is overridden in index.ts to 'whisper-1' when calling the OpenAI API. | ||
| */ | ||
| 'whisper-1-translate': openAITranslationModelRef({ | ||
| name: 'whisper-1-translate', | ||
| }), | ||
| }; |
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,223 @@ | ||
| /** | ||
| * Copyright 2024 The Fire Company | ||
| * Copyright 2024 Google LLC | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| import type { | ||
| GenerateRequest, | ||
| GenerateResponseData, | ||
| ModelReference, | ||
| } from 'genkit'; | ||
| import { GenerationCommonConfigSchema, Message, modelRef, z } from 'genkit'; | ||
| import type { ModelAction, ModelInfo } from 'genkit/model'; | ||
| import { model } from 'genkit/plugin'; | ||
| import OpenAI from 'openai'; | ||
| import type { | ||
| TranslationCreateParams, | ||
| TranslationCreateResponse, | ||
| } from 'openai/resources/audio/index.mjs'; | ||
| import { PluginOptions } from './index.js'; | ||
| import { maybeCreateRequestScopedOpenAIClient, toModelName } from './utils.js'; | ||
|
|
||
| export type TranslationRequestBuilder = ( | ||
| req: GenerateRequest, | ||
| params: TranslationCreateParams | ||
| ) => void; | ||
|
|
||
| export const TRANSLATION_MODEL_INFO: ModelInfo = { | ||
| supports: { | ||
| media: true, | ||
| output: ['text', 'json'], | ||
| multiturn: false, | ||
| systemRole: false, | ||
| tools: false, | ||
| }, | ||
| }; | ||
|
|
||
| export const TranslationConfigSchema = GenerationCommonConfigSchema.pick({ | ||
| temperature: true, | ||
| }).extend({ | ||
| response_format: z | ||
| .enum(['json', 'text', 'srt', 'verbose_json', 'vtt']) | ||
| .optional(), | ||
| }); | ||
|
|
||
| function toTranslationRequest( | ||
| modelName: string, | ||
| request: GenerateRequest, | ||
| requestBuilder?: TranslationRequestBuilder | ||
| ): TranslationCreateParams { | ||
| const message = new Message(request.messages[0]); | ||
| const media = message.media; | ||
| if (!media?.url) { | ||
| throw new Error('No media found in the request'); | ||
| } | ||
| const mediaBuffer = Buffer.from( | ||
| media.url.slice(media.url.indexOf(',') + 1), | ||
| 'base64' | ||
| ); | ||
| const mediaFile = new File([mediaBuffer], 'input', { | ||
| type: | ||
| media.contentType ?? | ||
| media.url.slice('data:'.length, media.url.indexOf(';')), | ||
| }); | ||
| const { | ||
| temperature, | ||
| version: modelVersion, | ||
| maxOutputTokens, | ||
| stopSequences, | ||
| topK, | ||
| topP, | ||
| ...restOfConfig | ||
| } = request.config ?? {}; | ||
|
|
||
| let options: TranslationCreateParams = { | ||
| model: modelVersion ?? modelName, | ||
| file: mediaFile, | ||
| prompt: message.text, | ||
| temperature, | ||
| }; | ||
| if (requestBuilder) { | ||
| requestBuilder(request, options); | ||
| } else { | ||
| options = { | ||
| ...options, | ||
| ...restOfConfig, // passthrough rest of the config | ||
| }; | ||
| } | ||
| const outputFormat = request.output?.format as 'json' | 'text' | 'media'; | ||
| const customFormat = request.config?.response_format; | ||
| if (outputFormat && customFormat) { | ||
| if ( | ||
| outputFormat === 'json' && | ||
| customFormat !== 'json' && | ||
| customFormat !== 'verbose_json' | ||
| ) { | ||
| throw new Error( | ||
| `Custom response format ${customFormat} is not compatible with output format ${outputFormat}` | ||
| ); | ||
7hokerz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
| if (outputFormat === 'media') { | ||
| throw new Error(`Output format ${outputFormat} is not supported.`); | ||
7hokerz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| options.response_format = customFormat || outputFormat || 'text'; | ||
| for (const k in options) { | ||
| if (options[k] === undefined) { | ||
| delete options[k]; | ||
| } | ||
| } | ||
| return options; | ||
| } | ||
|
|
||
| function translationToGenerateResponse( | ||
| result: TranslationCreateResponse | string | ||
| ): GenerateResponseData { | ||
| return { | ||
| message: { | ||
| role: 'model', | ||
| content: [ | ||
| { | ||
| text: typeof result === 'string' ? result : result.text, | ||
| }, | ||
| ], | ||
| }, | ||
| finishReason: 'stop', | ||
| raw: result, | ||
| }; | ||
| } | ||
|
|
||
| /** | ||
| * Method to define a new Genkit Model that is compatible with Open AI | ||
| * Translation API. | ||
| * | ||
| * These models are to be used to translate audio to text. | ||
| * | ||
| * @param params An object containing parameters for defining the OpenAI | ||
| * translation model. | ||
| * @param params.ai The Genkit AI instance. | ||
| * @param params.name The name of the model. | ||
| * @param params.client The OpenAI client instance. | ||
| * @param params.modelRef Optional reference to the model's configuration and | ||
| * custom options. | ||
| * | ||
7hokerz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| * @returns the created {@link ModelAction} | ||
| */ | ||
| export function defineCompatOpenAITranslationModel< | ||
| CustomOptions extends z.ZodTypeAny = z.ZodTypeAny, | ||
| >(params: { | ||
| name: string; | ||
| client: OpenAI; | ||
| pluginOptions?: PluginOptions; | ||
| modelRef?: ModelReference<CustomOptions>; | ||
| requestBuilder?: TranslationRequestBuilder; | ||
| }) { | ||
| const { | ||
| name, | ||
| client: defaultClient, | ||
| pluginOptions, | ||
| modelRef, | ||
| requestBuilder, | ||
| } = params; | ||
| const modelName = toModelName(name, pluginOptions?.name); | ||
| const actionName = `${pluginOptions?.name ?? 'compat-oai'}/${modelName}`; | ||
|
|
||
| return model( | ||
| { | ||
| name: actionName, | ||
| ...modelRef?.info, | ||
| configSchema: modelRef?.configSchema, | ||
| }, | ||
| async (request, { abortSignal }) => { | ||
| const params = toTranslationRequest(modelName, request, requestBuilder); | ||
| const client = maybeCreateRequestScopedOpenAIClient( | ||
| pluginOptions, | ||
| request, | ||
| defaultClient | ||
| ); | ||
| const result = await client.audio.translations.create(params, { | ||
| signal: abortSignal, | ||
| }); | ||
| return translationToGenerateResponse(result); | ||
| } | ||
| ); | ||
| } | ||
|
|
||
| /** Translation ModelRef helper, with reasonable defaults for | ||
| * OpenAI-compatible providers */ | ||
| export function compatOaiTranslationModelRef< | ||
| CustomOptions extends z.ZodTypeAny = z.ZodTypeAny, | ||
| >(params: { | ||
| name: string; | ||
| info?: ModelInfo; | ||
| configSchema?: CustomOptions; | ||
| config?: any; | ||
| namespace?: string; | ||
| }) { | ||
| const { | ||
| name, | ||
| info = TRANSLATION_MODEL_INFO, | ||
| configSchema, | ||
| config = undefined, | ||
| namespace, | ||
| } = params; | ||
| return modelRef({ | ||
| name, | ||
| configSchema: configSchema || (TranslationConfigSchema as any), | ||
| info, | ||
| config, | ||
| namespace, | ||
| }); | ||
| } | ||
Binary file not shown.
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.