页面简介
Learn how to set up the Deepgram provider and check AI Gateway availability.
正文摘录
AI SDK ProvidersMenuDeepgramCopy for LLMView MarkdownAsk AI about this pageThe Deepgram provider contains language model support for the Deepgram transcription and speech generation APIs. Deepgram models are not currently available through AI Gateway, so the opening example uses @ai-sdk/deepgram directly. See Using AI Gateway below for supported alternatives. import { generateSpeech } from 'ai'; import { deepgram } from '@ai-sdk/deepgram'; import { writeFile } from 'node:fs/promises'; const { audio } = await generateSpeech({ model: deepgram.speech('aura-2'), text: 'Hello, world!', outputFormat: 'mp3', voice: 'thalia', language: 'en', }); await writeFile('speech.mp3', audio.uint8Array); Using AI Gateway The current AI Gateway model catalog does not list Deepgram models. Use @ai-sdk/deepgram for the APIs on this page. To use other speech models through Gateway, install ai and configure a Gateway API key: pnpmnpmyarnbun$ pnpm add ai Set an AI Gateway API key in your environment: export AI_GATEWAY_API_KEY=your_api_key_here Vercel deployments can also use OIDC authentication. See the Gateway documentation for supported models and APIs. Using @ai-sdk/deepgram For direct access to Deepgram, install ai and @ai-sdk/deepgram: pnpmnpmyarnbun$ pnpm add ai @ai-sdk/deepgram Set your Deepgram API credential in the DEEPGRAM_API_KEY environment variable: export DEEPGRAM_API_KEY=your_api_key_here The following sections document the direct @ai-sdk/deepgram provider, including its model factories and settings. Gateway model and feature availability can differ. Provider Instance You can import the default provider instance deepgram from @ai-sdk/deepgram: import { deepgram } from '@ai-sdk/deepgram'; If you need a customized setup, you can import createDeepgram from @ai-sdk/deepgram and create a provider instance with your settings: import { createDeepgram } from '@ai-sdk/deepgram'; const deepgram = createDeepgram({ // custom settings, e.g. fetch: customFetch, }); You can use the following optional settings to customize the Deepgram provider instance: apiKey string | PromiseLike<string> | (() => string | PromiseLike<string>) Pass a synchronous or asynchronous callback to resolve the key before each request. The callback is responsible for caching and refreshing credentials. API key that is being sent using the Authorization header. It defaults to the DEEPGRAM_API_KEY environment variable. headers Record<string,string> Custom headers to include in the requests. fetch (input: RequestInfo, init?: RequestInit) => Promise<Response> Custom fetch implementation. Defaults to the global fetch function. You can use it as a middleware to intercept requests, or to provide a custom fetch implementation for e.g. testing. webSocket WebSocketConstructor Custom WebSocket implementation for streaming transcription and streaming speech. Defaults to the global WebSocket. Use a header-capable implementation such as ws when you need to forward custom HTTP headers during the handshake. Speech Models You can create models that call the Deepgram text-to-speech API using the .speech() factory method. The first argument is the voice family ID: flux (Flux TTS), aura-2, or aura (Aura-1). The voice and language are selected with the generateSpeech voice and language options — the provider composes the upstream Deepgram model ID as <family>-<voice>-<language> (language defaults to en): import { generateSpeech } from 'ai'; import { deepgram } from '@ai-sdk/deepgram'; const result = await generateSpeech({ model: deepgram.speech('aura-2'), voice: 'thalia', language: 'en', text: 'Hello, world!', }); Full voice model IDs (e.g. deepgram.speech('aura-2-helena-en')) still pass through, but the family ID + voice/language form above is the recommended path — it matches voice selection in the other speech providers. You can also pass additional provider-specific options using the providerOptions argument: import { generateSpeech } from 'ai'; import { deepgram, type DeepgramSpeechModelOptions } from '@ai-sdk/deepgram'; const result = await generateSpeech({ model: deepgram.speech('aura-2'), voice: 'helena', text: 'Hello, world!', providerOptions: { deepgram: { encoding: 'linear16', sampleRate: 24000, } satisfies DeepgramSpeechModelOptions, }, }); The following provider options are available: encoding string Encoding type for the audio output. Supported values: 'linear16', 'mulaw', 'alaw', 'mp3', 'opus', 'flac', 'aac'. Optional. container string Container format for the output audio. Supported values: 'wav', 'ogg', 'none'. Optional. sampleRate number Sample rate for the output audio in Hz. Supported values depend on the encoding: 8000, 16000, 24000, 32000, 48000. Flux TTS also supports 44100 for linear16. Optional. bitRate number | string Bitrate of the audio in bits per second. For mp3: 32000 or 48000 (Flux TTS: 8000, 16000, 24000, 32000, 40000, or 48000). For opus: 4000 to 650000. For aac: 4000 to 192000. Optional. expressivity number Flux TTS only (beta). Delivery register from -2 (calm) to 2 (animated); defaults to 0, the voice's tuned delivery. Ignored with a warning for Aura models. Optional. callback string Not supported. Deepgram processes requests with a callback URL asynchronously and answers with a JSON acknowledgement ({ "request_id": "..." }) instead of audio, so generateSpeech rejects this option with an InvalidArgumentError. Call the Deepgram REST API directly when you need asynchronous callback delivery. callbackMethod enum Not supported. Only used together with callback, which generateSpeech rejects. Allowed values: 'POST', 'PUT'. The option is ignored with an unsupported warning. mipOptOut boolean Opts out requests from the Deepgram Model Improvement Program. Optional. tag string | array of strings Label your requests for identification during usage reporting. Optional. Speech results include Deepgram response details in providerMetadata.deepgram: modelName (the resolved upstream model), modelUuid, additionalModelUuids, charCount (the billed character count), breaksApplied, pronunciationsApplied, pronunciationWarnings (when present), and requestId. The generateSpeech speed option is passed through to Deepgram's speed parameter. Aura accepts speeds in the 0.7–1.5 range and Flux TTS 0.5–1.5 in 0.05 increments; Deepgram rejects other values with a 400 error, and speed is not supported for all languages. instructions is not supported and is ignored with a warning. Flux TTS Flux TTS is Deepgram's text-to-speech family for voice agents. Use the flux family ID with a Flux voice; the language option selects the voice's language (English and 41 other languages): import { generateSpeech } from 'ai'; import { deepgram, type DeepgramSpeechModelOptions } from '@ai-sdk/deepgram'; const english = await generateSpeech({ model: deepgram.speech('flux'), voice: 'haley', text: 'Hello, world!', providerOptions: { deepgram: { expressivity: 1 } satisfies DeepgramSpeechModelOptions, }, }); const spanish = await generateSpeech({ model: deepgram.speech('flux'), voice: 'carmen', language: 'es', text: '¡Hola, mundo!', }); Flux voices are served by Deepgram's /v2/speak endpoint and Aura voices by /v1/speak; the provider picks the endpoint from the model ID. Full Flux model IDs such as deepgram.speech('flux-haley-en') also pass through. Streaming Speech Use experimental_streamSpeech with Flux TTS to synthesize text as it arrives (for example from streamText) over Deepgram's /v2/speak WebSocket API: import { deepgram } from '@ai-sdk/deepgram'; import { experimental_streamSpeech as streamSpeech } from 'ai'; const result = streamSpeech({ model: deepgram.speech('flux'), voice: 'haley', text: textStream, // e.g. streamText(...).textStream outputFormat: { type: 'audio/pcm', rate: 24000 }, }); for await (const chunk of result.audioStream) { // raw 16-bit little-endian PCM } console.log(await result.usage); The socket emits raw audio only: audio/pcm (16-bit little-endian at 8000, 16000, 24000, 32000, 44100, or 48000 Hz; default 24000), audio/pcmu, or audio/pcma (8000 or 16000 Hz; default 8000). Text parts are forwarded as they arrive and can split anywhere; the end of the text ends the turn. speed, expressivity, mipOptOut, and tag apply, while the batch-only encoding, container, sampleRate, and bitRate options are ignored with a warning. A stream speaks a single voice. result.usage reports Deepgram's billable character count. The connection is kept alive while the text input is idle and while the last audio is synthesized after the end of the text. Aura models stream over Deepgram's /v1/speak WebSocket API, with the same call: const result = streamSpeech({ model: deepgram.speech('aura-2'), voice: 'thalia', text: textStream, outputFormat: { type: 'audio/pcm', rate: 24000 }, }); The model ID is composed from the family, voice, and language as for generateSpeech (aura-2 with voice: 'thalia' is aura-2-thalia-en), and full voice IDs such as aura-2-helena-en or the Aura-1 aura-asteria-en pass through. Other model IDs throw before connecting. The Aura socket emits audio/pcm (16-bit little-endian at 8000, 16000, 24000, 32000, or 48000 Hz; default 24000), audio/pcmu, or audio/pcma (8000 or 16000 Hz; default 8000). Text parts are sent as they arrive, and Deepgram starts speaking complete sentences before the text ends; the end of the text flushes the rest. mipOptOut and tag are sent on the connection URL; Deepgram's tagging guide covers the streaming API, and several tags are sent as repeated tag parameters. speed is sent too: Deepgram documents it for Aura-2 voices in English and Spanish, from 0.7 to 1.5 (voice controls), and validates the value itself. expressivity is a Flux option and is ignored with a warning. Deepgram warnings during the stream are reported as non-fatal error parts, and an Error message from Deepgram fails the stream. Deepgram documents these limits for the Aura socket: 2,000 characters per text payload, 2,400 characters per minute sent to the socket, 20 Flush messages per 60 seconds