-
-
Notifications
You must be signed in to change notification settings - Fork 228
feat(ai-groq): transcription #649
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
joksas
wants to merge
6
commits into
TanStack:main
Choose a base branch
from
joksas:feat/groq-ai-transcription
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 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| '@tanstack/ai-groq': minor | ||
| --- | ||
|
|
||
| Adds Groq as a transcription provider. Groq's API is mostly OpenAI SDK-compatible, | ||
| but its transcription endpoint additionally accepts HTTP URLs as input, so this | ||
| is implemented as a custom integration rather than going through the SDK. |
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,292 @@ | ||
| import { BaseTranscriptionAdapter } from '@tanstack/ai/adapters' | ||
| import { base64ToArrayBuffer, generateId } from '@tanstack/ai-utils' | ||
| import { getGroqApiKeyFromEnv, withGroqDefaults } from '../utils/client' | ||
| import type { | ||
| TranscriptionOptions, | ||
| TranscriptionResult, | ||
| TranscriptionSegment, | ||
| } from '@tanstack/ai' | ||
| import type { GroqTranscriptionModel } from '../model-meta' | ||
| import type { GroqTranscriptionProviderOptions } from '../audio/transcription-provider-options' | ||
| import type { GroqClientConfig } from '../utils/client' | ||
|
|
||
| /** | ||
| * Configuration for the Groq Transcription adapter. | ||
| */ | ||
| export interface GroqTranscriptionConfig extends GroqClientConfig {} | ||
|
|
||
| // Shape of Groq's verbose_json transcription response | ||
| interface GroqVerboseTranscriptionResponse { | ||
| task?: string | ||
| language?: string | ||
| duration?: number | ||
| text: string | ||
| segments?: Array<{ | ||
| id: number | ||
| seek?: number | ||
| start: number | ||
| end: number | ||
| text: string | ||
| tokens?: Array<number> | ||
| temperature?: number | ||
| avg_logprob: number | ||
| compression_ratio?: number | ||
| no_speech_prob?: number | ||
| }> | ||
| words?: Array<{ word: string; start: number; end: number }> | ||
| x_groq?: { id?: string } | ||
| } | ||
|
|
||
| // Shape of Groq's json transcription response | ||
| interface GroqJsonTranscriptionResponse { | ||
| text: string | ||
| x_groq?: { id?: string } | ||
| } | ||
|
|
||
| /** | ||
| * Groq Transcription (Speech-to-Text) Adapter | ||
| * | ||
| * Tree-shakeable adapter for Groq audio transcription. Supports | ||
| * whisper-large-v3 and whisper-large-v3-turbo. | ||
| * | ||
| * Features: | ||
| * - Audio file uploads (File, Blob, ArrayBuffer, base64/data URL) | ||
| * - Remote audio URLs passed directly via Groq's `url` field — no upload needed | ||
| * - Verbose JSON response with segment and word timestamps | ||
| * - Language detection or specification (ISO-639-1) | ||
| * - Confidence scores derived from segment avg_logprob | ||
| */ | ||
| export class GroqTranscriptionAdapter< | ||
| TModel extends GroqTranscriptionModel, | ||
| > extends BaseTranscriptionAdapter<TModel, GroqTranscriptionProviderOptions> { | ||
| readonly name = 'groq' as const | ||
|
|
||
| private readonly apiKey: string | ||
| private readonly baseURL: string | ||
|
|
||
| constructor(config: GroqTranscriptionConfig, model: TModel) { | ||
| super(model, {}) | ||
| const resolved = withGroqDefaults(config) | ||
| this.apiKey = resolved.apiKey | ||
| this.baseURL = resolved.baseURL ?? 'https://api.groq.com/openai/v1' | ||
| } | ||
|
|
||
| async transcribe( | ||
| options: TranscriptionOptions<GroqTranscriptionProviderOptions>, | ||
| ): Promise<TranscriptionResult> { | ||
| const { model, audio, language, prompt, responseFormat, modelOptions } = | ||
| options | ||
|
|
||
| // Default to verbose_json so callers get language, duration, and timestamps | ||
| // without having to opt in explicitly. Both Groq whisper models support it. | ||
| const useVerbose = !responseFormat || responseFormat === 'verbose_json' | ||
| const effectiveFormat = responseFormat ?? 'verbose_json' | ||
|
|
||
| const form = new FormData() | ||
| form.append('model', model) | ||
| form.append('response_format', effectiveFormat) | ||
| if (language !== undefined) form.append('language', language) | ||
| if (prompt !== undefined) form.append('prompt', prompt) | ||
| if (modelOptions?.temperature !== undefined) { | ||
| form.append('temperature', String(modelOptions.temperature)) | ||
| } | ||
| if (modelOptions?.timestamp_granularities !== undefined) { | ||
| for (const g of modelOptions.timestamp_granularities) { | ||
| form.append('timestamp_granularities[]', g) | ||
| } | ||
| } | ||
|
|
||
| // HTTP/HTTPS URLs are forwarded directly via Groq's `url` field, which | ||
| // avoids a round-trip upload. All other inputs (File, Blob, ArrayBuffer, | ||
| // base64, data URL) are converted to a File and sent as `file`. | ||
| if (typeof audio === 'string' && /^https?:\/\//.test(audio)) { | ||
| form.append('url', audio) | ||
| } else { | ||
| form.append('file', this.prepareAudioFile(audio)) | ||
| } | ||
|
|
||
| try { | ||
| options.logger.request( | ||
| `activity=transcription provider=${this.name} model=${model} verbose=${useVerbose}`, | ||
| { provider: this.name, model }, | ||
| ) | ||
|
|
||
| const response = await fetch(`${this.baseURL}/audio/transcriptions`, { | ||
| method: 'POST', | ||
| headers: { Authorization: `Bearer ${this.apiKey}` }, | ||
| body: form, | ||
| }) | ||
|
|
||
| if (!response.ok) { | ||
| const body = await response | ||
| .json() | ||
| .catch(() => null as Record<string, unknown> | null) | ||
| const message = | ||
| (body?.error as { message?: string } | undefined)?.message ?? | ||
| `Groq API error ${response.status}` | ||
| throw new Error(message) | ||
| } | ||
|
|
||
| if (useVerbose) { | ||
| const data = (await response.json()) as GroqVerboseTranscriptionResponse | ||
| const requestId = data.x_groq?.id ?? generateId(this.name) | ||
|
|
||
| // `TranscriptionResult` declares optional fields without `| undefined`, | ||
| // so under exactOptionalPropertyTypes we must omit absent fields rather | ||
| // than assigning `undefined`. | ||
| const segments = data.segments?.map( | ||
| (seg): TranscriptionSegment => ({ | ||
| id: seg.id, | ||
| start: seg.start, | ||
| end: seg.end, | ||
| text: seg.text, | ||
| confidence: Math.exp(seg.avg_logprob), | ||
| }), | ||
| ) | ||
| const words = data.words?.map((w) => ({ | ||
| word: w.word, | ||
| start: w.start, | ||
| end: w.end, | ||
| })) | ||
|
|
||
| return { | ||
| id: requestId, | ||
| model, | ||
| text: data.text, | ||
| ...(data.language !== undefined && { language: data.language }), | ||
| ...(data.duration !== undefined && { duration: data.duration }), | ||
| ...(segments !== undefined && { segments }), | ||
| ...(words !== undefined && { words }), | ||
| } | ||
| } else if (effectiveFormat === 'text') { | ||
| const text = await response.text() | ||
| return { | ||
| id: generateId(this.name), | ||
| model, | ||
| text, | ||
| ...(language !== undefined && { language }), | ||
| } | ||
| } else { | ||
| const data = (await response.json()) as GroqJsonTranscriptionResponse | ||
| return { | ||
| id: data.x_groq?.id ?? generateId(this.name), | ||
| model, | ||
| text: data.text, | ||
| ...(language !== undefined && { language }), | ||
| } | ||
| } | ||
| } catch (error: unknown) { | ||
| options.logger.errors(`${this.name}.transcribe fatal`, { | ||
| error, | ||
| source: `${this.name}.transcribe`, | ||
| }) | ||
| throw error | ||
| } | ||
| } | ||
|
|
||
| private prepareAudioFile(audio: string | File | Blob | ArrayBuffer): File { | ||
| if (typeof File !== 'undefined' && audio instanceof File) { | ||
| return audio | ||
| } | ||
| if (typeof Blob !== 'undefined' && audio instanceof Blob) { | ||
| this.ensureFileSupport() | ||
| return new File([audio], 'audio.mp3', { | ||
| type: audio.type || 'audio/mpeg', | ||
| }) | ||
| } | ||
| if (typeof ArrayBuffer !== 'undefined' && audio instanceof ArrayBuffer) { | ||
| this.ensureFileSupport() | ||
| return new File([audio], 'audio.mp3', { type: 'audio/mpeg' }) | ||
| } | ||
| if (typeof audio === 'string') { | ||
| this.ensureFileSupport() | ||
|
|
||
| if (audio.startsWith('data:')) { | ||
| const parts = audio.split(',') | ||
| const header = parts[0] | ||
| const base64Data = parts[1] || '' | ||
| const mimeMatch = header?.match(/data:([^;]+)/) | ||
| const mimeType = mimeMatch?.[1] || 'audio/mpeg' | ||
| const bytes = base64ToArrayBuffer(base64Data) | ||
| const extension = mimeType.split('/')[1] || 'mp3' | ||
| return new File([bytes], `audio.${extension}`, { type: mimeType }) | ||
| } | ||
|
|
||
| const bytes = base64ToArrayBuffer(audio) | ||
| return new File([bytes], 'audio.mp3', { type: 'audio/mpeg' }) | ||
| } | ||
|
|
||
| throw new Error('Invalid audio input type') | ||
| } | ||
|
|
||
| // Throws on Node < 20 where the global `File` constructor is unavailable. | ||
| private ensureFileSupport(): void { | ||
| if (typeof File === 'undefined') { | ||
| throw new Error( | ||
| '`File` is not available in this environment. ' + | ||
| 'Use Node.js 20 or newer, or pass a File object directly.', | ||
| ) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Creates a Groq transcription adapter with an explicit API key. | ||
| * Type resolution happens here at the call site. | ||
| * | ||
| * @param model - The model name (e.g., 'whisper-large-v3-turbo') | ||
| * @param apiKey - Your Groq API key | ||
| * @param config - Optional additional configuration | ||
| * @returns Configured Groq transcription adapter instance | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const adapter = createGroqTranscription('whisper-large-v3-turbo', 'gsk_...'); | ||
| * | ||
| * const result = await generateTranscription({ | ||
| * adapter, | ||
| * audio: audioFile, | ||
| * language: 'en', | ||
| * }); | ||
| * ``` | ||
| */ | ||
| export function createGroqTranscription<TModel extends GroqTranscriptionModel>( | ||
| model: TModel, | ||
| apiKey: string, | ||
| config?: Omit<GroqTranscriptionConfig, 'apiKey'>, | ||
| ): GroqTranscriptionAdapter<TModel> { | ||
| return new GroqTranscriptionAdapter({ apiKey, ...config }, model) | ||
| } | ||
|
|
||
| /** | ||
| * Creates a Groq transcription adapter using the `GROQ_API_KEY` environment | ||
| * variable. Type resolution happens here at the call site. | ||
| * | ||
| * Looks for `GROQ_API_KEY` in: | ||
| * - `process.env` (Node.js) | ||
| * - `window.env` (browser with injected env) | ||
| * | ||
| * @param model - The model name (e.g., 'whisper-large-v3-turbo') | ||
| * @param config - Optional configuration (excluding apiKey which is auto-detected) | ||
| * @returns Configured Groq transcription adapter instance | ||
| * @throws Error if GROQ_API_KEY is not found in environment | ||
| * | ||
| * @example | ||
| * ```typescript | ||
| * const adapter = groqTranscription('whisper-large-v3-turbo'); | ||
| * | ||
| * const result = await generateTranscription({ | ||
| * adapter, | ||
| * audio: 'https://example.com/audio.mp3', | ||
| * }); | ||
| * | ||
| * console.log(result.text) | ||
| * ``` | ||
| */ | ||
| export function groqTranscription<TModel extends GroqTranscriptionModel>( | ||
| model: TModel, | ||
| config?: Omit<GroqTranscriptionConfig, 'apiKey'>, | ||
| ): GroqTranscriptionAdapter<TModel> { | ||
| const apiKey = getGroqApiKeyFromEnv() | ||
| return createGroqTranscription(model, apiKey, config) | ||
| } | ||
20 changes: 20 additions & 0 deletions
20
packages/ai-groq/src/audio/transcription-provider-options.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,20 @@ | ||
| /** | ||
| * Groq-specific options for audio transcription. | ||
| * | ||
| * These fields extend the shared `TranscriptionOptions` and are forwarded | ||
| * verbatim to the Groq transcription endpoint. | ||
| */ | ||
| export interface GroqTranscriptionProviderOptions { | ||
| /** | ||
| * Sampling temperature between 0 and 1. Lower values produce more | ||
| * deterministic output. Groq recommends 0 (the default) for most use cases. | ||
| */ | ||
| temperature?: number | ||
|
|
||
| /** | ||
| * Granularity levels to include when `response_format` is `verbose_json`. | ||
| * Pass `['word']`, `['segment']`, or both to control which timestamp arrays | ||
| * appear in the result. | ||
| */ | ||
| timestamp_granularities?: Array<'word' | 'segment'> | ||
| } |
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
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.