@ai-sdk/google-vertex 5.0.0-canary.99 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/xai/edge/google-vertex-xai-provider-edge.ts","../../../src/edge/google-vertex-auth-edge.ts","../../../src/version.ts","../../../src/xai/google-vertex-xai-provider.ts"],"sourcesContent":["import { resolve, type FetchFunction } from '@ai-sdk/provider-utils';\nimport {\n generateAuthToken,\n type GoogleCredentials,\n} from '../../edge/google-vertex-auth-edge';\nimport {\n createGoogleVertexXai as createGoogleVertexXaiOriginal,\n type GoogleVertexXaiProvider,\n type GoogleVertexXaiProviderSettings as GoogleVertexXaiProviderSettingsOriginal,\n} from '../google-vertex-xai-provider';\nexport type { GoogleVertexXaiProvider };\n\nexport interface GoogleVertexXaiProviderSettings extends GoogleVertexXaiProviderSettingsOriginal {\n /**\n * Optional. The Google credentials for the Google Cloud service account. If\n * not provided, the Google Vertex provider will use environment variables to\n * load the credentials.\n */\n googleCredentials?: GoogleCredentials;\n}\n\n/**\n * Create a Google Vertex AI xAI provider instance for Edge runtimes.\n * Uses the OpenAI-compatible Chat Completions API for Grok partner models.\n * Automatically handles Google Cloud authentication.\n *\n * @see https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/grok\n */\nexport function createGoogleVertexXai(\n options: GoogleVertexXaiProviderSettings = {},\n): GoogleVertexXaiProvider {\n const customFetch: FetchFunction = async (url, init) => {\n const token = await generateAuthToken(options.googleCredentials);\n const resolvedHeaders = await resolve(options.headers);\n const authHeaders = {\n ...resolvedHeaders,\n Authorization: `Bearer ${token}`,\n };\n\n const fetchInit = {\n ...init,\n headers: {\n ...init?.headers,\n ...authHeaders,\n },\n };\n\n return (options.fetch ?? fetch)(url, fetchInit);\n };\n\n return createGoogleVertexXaiOriginal({\n ...options,\n fetch: customFetch,\n headers: undefined,\n });\n}\n\n/**\n * Default Google Vertex AI xAI provider instance for Edge runtimes.\n */\nexport const googleVertexXai = createGoogleVertexXai();\n","import {\n loadOptionalSetting,\n loadSetting,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n} from '@ai-sdk/provider-utils';\nimport { VERSION } from '../version';\n\nexport interface GoogleCredentials {\n /**\n * The client email for the Google Cloud service account. Defaults to the\n * value of the `GOOGLE_CLIENT_EMAIL` environment variable.\n */\n clientEmail: string;\n\n /**\n * The private key for the Google Cloud service account. Defaults to the\n * value of the `GOOGLE_PRIVATE_KEY` environment variable.\n */\n privateKey: string;\n\n /**\n * Optional. The private key ID for the Google Cloud service account. Defaults\n * to the value of the `GOOGLE_PRIVATE_KEY_ID` environment variable.\n */\n privateKeyId?: string;\n}\n\nconst loadCredentials = async (): Promise<GoogleCredentials> => {\n try {\n return {\n clientEmail: loadSetting({\n settingValue: undefined,\n settingName: 'clientEmail',\n environmentVariableName: 'GOOGLE_CLIENT_EMAIL',\n description: 'Google client email',\n }),\n privateKey: loadSetting({\n settingValue: undefined,\n settingName: 'privateKey',\n environmentVariableName: 'GOOGLE_PRIVATE_KEY',\n description: 'Google private key',\n }),\n privateKeyId: loadOptionalSetting({\n settingValue: undefined,\n environmentVariableName: 'GOOGLE_PRIVATE_KEY_ID',\n }),\n };\n } catch (error: any) {\n throw new Error(`Failed to load Google credentials: ${error.message}`);\n }\n};\n\n// Convert a string to base64url\nconst base64url = (str: string) => {\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n};\nconst importPrivateKey = async (pemKey: string) => {\n const pemHeader = '-----BEGIN PRIVATE KEY-----';\n const pemFooter = '-----END PRIVATE KEY-----';\n\n // Remove header, footer, and any whitespace/newlines\n const pemContents = pemKey\n .replace(pemHeader, '')\n .replace(pemFooter, '')\n .replace(/\\s/g, '');\n\n // Decode base64 to binary\n const binaryString = atob(pemContents);\n\n // Convert binary string to Uint8Array\n const binaryData = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n binaryData[i] = binaryString.charCodeAt(i);\n }\n\n return await crypto.subtle.importKey(\n 'pkcs8',\n binaryData,\n { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },\n true,\n ['sign'],\n );\n};\n\nconst buildJwt = async (credentials: GoogleCredentials) => {\n const now = Math.floor(Date.now() / 1000);\n\n // Only include kid in header if privateKeyId is provided\n const header: { alg: string; typ: string; kid?: string } = {\n alg: 'RS256',\n typ: 'JWT',\n };\n\n if (credentials.privateKeyId) {\n header.kid = credentials.privateKeyId;\n }\n\n const payload = {\n iss: credentials.clientEmail,\n scope: 'https://www.googleapis.com/auth/cloud-platform',\n aud: 'https://oauth2.googleapis.com/token',\n exp: now + 3600,\n iat: now,\n };\n\n const privateKey = await importPrivateKey(credentials.privateKey);\n\n const signingInput = `${base64url(JSON.stringify(header))}.${base64url(\n JSON.stringify(payload),\n )}`;\n const encoder = new TextEncoder();\n const data = encoder.encode(signingInput);\n\n const signature = await crypto.subtle.sign(\n 'RSASSA-PKCS1-v1_5',\n privateKey,\n data,\n );\n\n const signatureBase64 = base64url(\n String.fromCharCode(...new Uint8Array(signature)),\n );\n\n return `${base64url(JSON.stringify(header))}.${base64url(\n JSON.stringify(payload),\n )}.${signatureBase64}`;\n};\n\n/**\n * Generate an authentication token for Google Vertex AI in a manner compatible\n * with the Edge runtime.\n */\nexport async function generateAuthToken(credentials?: GoogleCredentials) {\n try {\n const creds = credentials || (await loadCredentials());\n const jwt = await buildJwt(creds);\n\n const response = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: withUserAgentSuffix(\n { 'Content-Type': 'application/x-www-form-urlencoded' },\n `ai-sdk/google-vertex/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n ),\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n assertion: jwt,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Token request failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n return data.access_token;\n } catch (error) {\n throw error;\n }\n}\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n NoSuchModelError,\n type LanguageModelV4,\n type LanguageModelV4Usage,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n createOpenAICompatible,\n type OpenAICompatibleProvider,\n} from '@ai-sdk/openai-compatible';\nimport {\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n type FetchFunction,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport type { GoogleVertexXaiModelId } from './google-vertex-xai-options';\n\nexport interface GoogleVertexXaiProvider extends ProviderV4 {\n /**\n * Creates a model for text generation.\n */\n (modelId: GoogleVertexXaiModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation.\n */\n languageModel(modelId: GoogleVertexXaiModelId): LanguageModelV4;\n\n /**\n * Creates a chat model for text generation.\n */\n chatModel(modelId: GoogleVertexXaiModelId): LanguageModelV4;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface GoogleVertexXaiProviderSettings {\n /**\n * Google Cloud project ID. Defaults to the value of the `GOOGLE_VERTEX_PROJECT` environment variable.\n */\n project?: string;\n\n /**\n * Google Cloud location/region. Defaults to the value of the `GOOGLE_VERTEX_LOCATION` environment variable.\n * Use 'global' for the global endpoint.\n */\n location?: string;\n\n /**\n * Base URL for the API calls. If not provided, will be constructed from project and location.\n */\n baseURL?: string;\n\n /**\n * Headers to use for requests. Can be:\n * - A headers object\n * - A Promise that resolves to a headers object\n * - A function that returns a headers object\n * - A function that returns a Promise of a headers object\n */\n headers?: Resolvable<Record<string, string | undefined>>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n}\n\ntype GoogleVertexXaiUsage =\n | {\n prompt_tokens?: number | null;\n completion_tokens?: number | null;\n prompt_tokens_details?: {\n cached_tokens?: number | null;\n } | null;\n completion_tokens_details?: {\n reasoning_tokens?: number | null;\n } | null;\n }\n | undefined\n | null;\n\nfunction convertGoogleVertexXaiUsage(\n usage: GoogleVertexXaiUsage,\n): LanguageModelV4Usage {\n if (usage == null) {\n return {\n inputTokens: {\n total: undefined,\n noCache: undefined,\n cacheRead: undefined,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: undefined,\n text: undefined,\n reasoning: undefined,\n },\n raw: undefined,\n };\n }\n\n const promptTokens = usage.prompt_tokens ?? 0;\n const completionTokens = usage.completion_tokens ?? 0;\n const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;\n const reasoningTokens =\n usage.completion_tokens_details?.reasoning_tokens ?? 0;\n\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: completionTokens + reasoningTokens,\n text: completionTokens,\n reasoning: reasoningTokens,\n },\n raw: usage,\n };\n}\n\nfunction transformGoogleVertexXaiRequestBody(args: Record<string, any>) {\n const { reasoning_effort: _reasoningEffort, ...rest } = args;\n return rest;\n}\n\n/**\n * Create a Google Vertex AI xAI provider instance.\n * Uses the OpenAI-compatible Chat Completions API for Grok partner models.\n *\n * @see https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/grok\n */\nexport function createGoogleVertexXai(\n options: GoogleVertexXaiProviderSettings = {},\n): GoogleVertexXaiProvider {\n const loadLocation = () =>\n loadOptionalSetting({\n settingValue: options.location,\n environmentVariableName: 'GOOGLE_VERTEX_LOCATION',\n });\n\n const loadProject = () =>\n loadSetting({\n settingValue: options.project,\n settingName: 'project',\n environmentVariableName: 'GOOGLE_VERTEX_PROJECT',\n description: 'Google Vertex project',\n });\n\n const constructBaseURL = () => {\n const projectId = loadProject();\n const location = loadLocation() ?? 'global';\n\n return `https://aiplatform.googleapis.com/v1/projects/${projectId}/locations/${location}/endpoints/openapi`;\n };\n\n const loadBaseURL = () =>\n withoutTrailingSlash(options.baseURL ?? '') || constructBaseURL();\n\n let cachedProvider:\n | OpenAICompatibleProvider<GoogleVertexXaiModelId, string, string, string>\n | undefined;\n const getProvider = () =>\n (cachedProvider ??= createOpenAICompatible({\n name: 'googleVertex.xai',\n baseURL: loadBaseURL(),\n fetch: options.fetch,\n includeUsage: true,\n supportsStructuredOutputs: true,\n supportedUrls: () => ({\n 'image/*': [/^https?:\\/\\/.*$/],\n }),\n transformRequestBody: transformGoogleVertexXaiRequestBody,\n convertUsage: convertGoogleVertexXaiUsage,\n }));\n\n const createChatModel = (modelId: GoogleVertexXaiModelId) =>\n getProvider().languageModel(modelId);\n\n const provider = function (modelId: GoogleVertexXaiModelId) {\n if (new.target) {\n throw new Error(\n 'The Google Vertex xAI model function cannot be called with the new keyword.',\n );\n }\n\n return createChatModel(modelId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createChatModel;\n provider.chatModel = (modelId: GoogleVertexXaiModelId) =>\n getProvider().chatModel(modelId);\n provider.embeddingModel = (modelId: string): never => {\n throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId: string): never => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n return provider;\n}\n"],"mappings":";AAAA,SAAS,eAAmC;;;ACA5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACHA,IAAM,UACX,OACI,oBACA;;;ADuBN,IAAM,kBAAkB,YAAwC;AAC9D,MAAI;AACF,WAAO;AAAA,MACL,aAAa,YAAY;AAAA,QACvB,cAAc;AAAA,QACd,aAAa;AAAA,QACb,yBAAyB;AAAA,QACzB,aAAa;AAAA,MACf,CAAC;AAAA,MACD,YAAY,YAAY;AAAA,QACtB,cAAc;AAAA,QACd,aAAa;AAAA,QACb,yBAAyB;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,MACL;AAAA,IACF;AAEA,aAAQ,aAAQ,UAAR,YAAiB,OAAO,KAAK,SAAS;AAAA,EAChD;AAEA,SAAO,sBAA8B;AAAA,IACnC,GAAG;AAAA,IACH,OAAO;AAAA,IACP,SAAS;AAAA,EACX,CAAC;AACH;AAKO,IAAM,kBAAkBA,uBAAsB;","names":["loadOptionalSetting","loadSetting","createGoogleVertexXai"]}
1
+ {"version":3,"sources":["../../../src/xai/edge/google-vertex-xai-provider-edge.ts","../../../src/edge/google-vertex-auth-edge.ts","../../../src/version.ts","../../../src/xai/google-vertex-xai-provider.ts"],"sourcesContent":["import { resolve, type FetchFunction } from '@ai-sdk/provider-utils';\nimport {\n generateAuthToken,\n type GoogleCredentials,\n} from '../../edge/google-vertex-auth-edge';\nimport {\n createGoogleVertexXai as createGoogleVertexXaiOriginal,\n type GoogleVertexXaiProvider,\n type GoogleVertexXaiProviderSettings as GoogleVertexXaiProviderSettingsOriginal,\n} from '../google-vertex-xai-provider';\nexport type { GoogleVertexXaiProvider };\n\nexport interface GoogleVertexXaiProviderSettings extends GoogleVertexXaiProviderSettingsOriginal {\n /**\n * Optional. The Google credentials for the Google Cloud service account. If\n * not provided, the Google Vertex provider will use environment variables to\n * load the credentials.\n */\n googleCredentials?: GoogleCredentials;\n}\n\n/**\n * Create a Google Vertex AI xAI provider instance for Edge runtimes.\n * Uses the OpenAI-compatible Chat Completions API for Grok partner models.\n * Automatically handles Google Cloud authentication.\n *\n * @see https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/grok\n */\nexport function createGoogleVertexXai(\n options: GoogleVertexXaiProviderSettings = {},\n): GoogleVertexXaiProvider {\n const customFetch: FetchFunction = async (url, init) => {\n const token = await generateAuthToken(options.googleCredentials);\n const resolvedHeaders = await resolve(options.headers);\n const authHeaders = {\n ...resolvedHeaders,\n Authorization: `Bearer ${token}`,\n };\n\n const fetchInit = {\n ...init,\n headers: {\n ...init?.headers,\n ...authHeaders,\n },\n };\n\n return (options.fetch ?? fetch)(url, fetchInit);\n };\n\n return createGoogleVertexXaiOriginal({\n ...options,\n fetch: customFetch,\n headers: undefined,\n });\n}\n\n/**\n * Default Google Vertex AI xAI provider instance for Edge runtimes.\n */\nexport const googleVertexXai = createGoogleVertexXai();\n","import {\n loadOptionalSetting,\n loadSetting,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n} from '@ai-sdk/provider-utils';\nimport { VERSION } from '../version';\n\nexport interface GoogleCredentials {\n /**\n * The client email for the Google Cloud service account. Defaults to the\n * value of the `GOOGLE_CLIENT_EMAIL` environment variable.\n */\n clientEmail: string;\n\n /**\n * The private key for the Google Cloud service account. Defaults to the\n * value of the `GOOGLE_PRIVATE_KEY` environment variable.\n */\n privateKey: string;\n\n /**\n * Optional. The private key ID for the Google Cloud service account. Defaults\n * to the value of the `GOOGLE_PRIVATE_KEY_ID` environment variable.\n */\n privateKeyId?: string;\n}\n\nconst loadCredentials = async (): Promise<GoogleCredentials> => {\n try {\n return {\n clientEmail: loadSetting({\n settingValue: undefined,\n settingName: 'clientEmail',\n environmentVariableName: 'GOOGLE_CLIENT_EMAIL',\n description: 'Google client email',\n }),\n privateKey: loadSetting({\n settingValue: undefined,\n settingName: 'privateKey',\n environmentVariableName: 'GOOGLE_PRIVATE_KEY',\n description: 'Google private key',\n }),\n privateKeyId: loadOptionalSetting({\n settingValue: undefined,\n environmentVariableName: 'GOOGLE_PRIVATE_KEY_ID',\n }),\n };\n } catch (error: any) {\n throw new Error(`Failed to load Google credentials: ${error.message}`);\n }\n};\n\n// Convert a string to base64url\nconst base64url = (str: string) => {\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n};\nconst importPrivateKey = async (pemKey: string) => {\n const pemHeader = '-----BEGIN PRIVATE KEY-----';\n const pemFooter = '-----END PRIVATE KEY-----';\n\n // Remove header, footer, and any whitespace/newlines\n const pemContents = pemKey\n .replace(pemHeader, '')\n .replace(pemFooter, '')\n .replace(/\\s/g, '');\n\n // Decode base64 to binary\n const binaryString = atob(pemContents);\n\n // Convert binary string to Uint8Array\n const binaryData = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n binaryData[i] = binaryString.charCodeAt(i);\n }\n\n return await crypto.subtle.importKey(\n 'pkcs8',\n binaryData,\n { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },\n true,\n ['sign'],\n );\n};\n\nconst buildJwt = async (credentials: GoogleCredentials) => {\n const now = Math.floor(Date.now() / 1000);\n\n // Only include kid in header if privateKeyId is provided\n const header: { alg: string; typ: string; kid?: string } = {\n alg: 'RS256',\n typ: 'JWT',\n };\n\n if (credentials.privateKeyId) {\n header.kid = credentials.privateKeyId;\n }\n\n const payload = {\n iss: credentials.clientEmail,\n scope: 'https://www.googleapis.com/auth/cloud-platform',\n aud: 'https://oauth2.googleapis.com/token',\n exp: now + 3600,\n iat: now,\n };\n\n const privateKey = await importPrivateKey(credentials.privateKey);\n\n const signingInput = `${base64url(JSON.stringify(header))}.${base64url(\n JSON.stringify(payload),\n )}`;\n const encoder = new TextEncoder();\n const data = encoder.encode(signingInput);\n\n const signature = await crypto.subtle.sign(\n 'RSASSA-PKCS1-v1_5',\n privateKey,\n data,\n );\n\n const signatureBase64 = base64url(\n String.fromCharCode(...new Uint8Array(signature)),\n );\n\n return `${base64url(JSON.stringify(header))}.${base64url(\n JSON.stringify(payload),\n )}.${signatureBase64}`;\n};\n\n/**\n * Generate an authentication token for Google Vertex AI in a manner compatible\n * with the Edge runtime.\n */\nexport async function generateAuthToken(credentials?: GoogleCredentials) {\n try {\n const creds = credentials || (await loadCredentials());\n const jwt = await buildJwt(creds);\n\n const response = await fetch('https://oauth2.googleapis.com/token', {\n method: 'POST',\n headers: withUserAgentSuffix(\n { 'Content-Type': 'application/x-www-form-urlencoded' },\n `ai-sdk/google-vertex/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n ),\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',\n assertion: jwt,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Token request failed: ${response.statusText}`);\n }\n\n const data = await response.json();\n return data.access_token;\n } catch (error) {\n throw error;\n }\n}\n","// Version string of this package injected at build time.\ndeclare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import {\n NoSuchModelError,\n type LanguageModelV4,\n type LanguageModelV4Usage,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n createOpenAICompatible,\n type OpenAICompatibleProvider,\n} from '@ai-sdk/openai-compatible';\nimport {\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n type FetchFunction,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport type { GoogleVertexXaiModelId } from './google-vertex-xai-options';\n\nexport interface GoogleVertexXaiProvider extends ProviderV4 {\n /**\n * Creates a model for text generation.\n */\n (modelId: GoogleVertexXaiModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation.\n */\n languageModel(modelId: GoogleVertexXaiModelId): LanguageModelV4;\n\n /**\n * Creates a chat model for text generation.\n */\n chatModel(modelId: GoogleVertexXaiModelId): LanguageModelV4;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface GoogleVertexXaiProviderSettings {\n /**\n * Google Cloud project ID. Defaults to the value of the `GOOGLE_VERTEX_PROJECT` environment variable.\n */\n project?: string;\n\n /**\n * Google Cloud location/region. Defaults to the value of the `GOOGLE_VERTEX_LOCATION` environment variable.\n * Use 'global' for the global endpoint.\n */\n location?: string;\n\n /**\n * Base URL for the API calls. If not provided, will be constructed from project and location.\n */\n baseURL?: string;\n\n /**\n * Headers to use for requests. Can be:\n * - A headers object\n * - A Promise that resolves to a headers object\n * - A function that returns a headers object\n * - A function that returns a Promise of a headers object\n */\n headers?: Resolvable<Record<string, string | undefined>>;\n\n /**\n * Custom fetch implementation. You can use it as a middleware to intercept requests,\n * or to provide a custom fetch implementation for e.g. testing.\n */\n fetch?: FetchFunction;\n}\n\ntype GoogleVertexXaiUsage =\n | {\n prompt_tokens?: number | null;\n completion_tokens?: number | null;\n prompt_tokens_details?: {\n cached_tokens?: number | null;\n } | null;\n completion_tokens_details?: {\n reasoning_tokens?: number | null;\n } | null;\n }\n | undefined\n | null;\n\nfunction convertGoogleVertexXaiUsage(\n usage: GoogleVertexXaiUsage,\n): LanguageModelV4Usage {\n if (usage == null) {\n return {\n inputTokens: {\n total: undefined,\n noCache: undefined,\n cacheRead: undefined,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: undefined,\n text: undefined,\n reasoning: undefined,\n },\n raw: undefined,\n };\n }\n\n const promptTokens = usage.prompt_tokens ?? 0;\n const completionTokens = usage.completion_tokens ?? 0;\n const cacheReadTokens = usage.prompt_tokens_details?.cached_tokens ?? 0;\n const reasoningTokens =\n usage.completion_tokens_details?.reasoning_tokens ?? 0;\n\n return {\n inputTokens: {\n total: promptTokens,\n noCache: promptTokens - cacheReadTokens,\n cacheRead: cacheReadTokens,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: completionTokens + reasoningTokens,\n text: completionTokens,\n reasoning: reasoningTokens,\n },\n raw: usage,\n };\n}\n\nfunction transformGoogleVertexXaiRequestBody(args: Record<string, any>) {\n const { reasoning_effort: _reasoningEffort, ...rest } = args;\n return rest;\n}\n\n/**\n * Create a Google Vertex AI xAI provider instance.\n * Uses the OpenAI-compatible Chat Completions API for Grok partner models.\n *\n * @see https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/grok\n */\nexport function createGoogleVertexXai(\n options: GoogleVertexXaiProviderSettings = {},\n): GoogleVertexXaiProvider {\n const loadLocation = () =>\n loadOptionalSetting({\n settingValue: options.location,\n environmentVariableName: 'GOOGLE_VERTEX_LOCATION',\n });\n\n const loadProject = () =>\n loadSetting({\n settingValue: options.project,\n settingName: 'project',\n environmentVariableName: 'GOOGLE_VERTEX_PROJECT',\n description: 'Google Vertex project',\n });\n\n const constructBaseURL = () => {\n const projectId = loadProject();\n const location = loadLocation() ?? 'global';\n\n return `https://aiplatform.googleapis.com/v1/projects/${projectId}/locations/${location}/endpoints/openapi`;\n };\n\n const loadBaseURL = () =>\n withoutTrailingSlash(options.baseURL ?? '') || constructBaseURL();\n\n let cachedProvider:\n | OpenAICompatibleProvider<GoogleVertexXaiModelId, string, string, string>\n | undefined;\n const getProvider = () =>\n (cachedProvider ??= createOpenAICompatible({\n name: 'googleVertex.xai',\n baseURL: loadBaseURL(),\n fetch: options.fetch,\n includeUsage: true,\n supportsStructuredOutputs: true,\n supportedUrls: () => ({\n 'image/*': [/^https?:\\/\\/.*$/],\n }),\n transformRequestBody: transformGoogleVertexXaiRequestBody,\n convertUsage: convertGoogleVertexXaiUsage,\n }));\n\n const createChatModel = (modelId: GoogleVertexXaiModelId) =>\n getProvider().languageModel(modelId);\n\n const provider = function (modelId: GoogleVertexXaiModelId) {\n if (new.target) {\n throw new Error(\n 'The Google Vertex xAI model function cannot be called with the new keyword.',\n );\n }\n\n return createChatModel(modelId);\n };\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = createChatModel;\n provider.chatModel = (modelId: GoogleVertexXaiModelId) =>\n getProvider().chatModel(modelId);\n provider.embeddingModel = (modelId: string): never => {\n throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId: string): never => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n return provider;\n}\n"],"mappings":";AAAA,SAAS,eAAmC;;;ACA5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACHA,IAAM,UACX,OACI,UACA;;;ADuBN,IAAM,kBAAkB,YAAwC;AAC9D,MAAI;AACF,WAAO;AAAA,MACL,aAAa,YAAY;AAAA,QACvB,cAAc;AAAA,QACd,aAAa;AAAA,QACb,yBAAyB;AAA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AA,IAChC;AAEA,UAAM,YAAY;AAAA,MAChB,GAAG;AAAA,MACH,SAAS;AAAA,QACP,GAAG,6BAAM;AAAA,QACT,GAAG;AAAA,MACL;AAAA,IACF;AAEA,aAAQ,aAAQ,UAAR,YAAiB,OAAO,KAAK,SAAS;AAAA,EAChD;AAEA,SAAO,sBAA8B;AAAA,IACnC,GAAG;AAAA,IACH,OAAO;AAAA,IACP,SAAS;AAAA,EACX,CAAC;AACH;AAKO,IAAM,kBAAkBA,uBAAsB;","names":["loadOptionalSetting","loadSetting","createGoogleVertexXai"]}
@@ -1300,6 +1300,118 @@ The following provider options are available:
1300
1300
  model ID as a string if needed.
1301
1301
  </Note>
1302
1302
 
1303
+ ### Speech Models
1304
+
1305
+ You can create [Gemini text-to-speech](https://docs.cloud.google.com/text-to-speech/docs/gemini-tts)
1306
+ models that call the Vertex AI API using the `.speech()` factory method. For more on speech
1307
+ generation with the AI SDK see [generateSpeech()](/docs/reference/ai-sdk-core/generate-speech).
1308
+
1309
+ ```ts
1310
+ import { googleVertex } from '@ai-sdk/google-vertex';
1311
+ import { generateSpeech } from 'ai';
1312
+
1313
+ const result = await generateSpeech({
1314
+ model: googleVertex.speech('gemini-2.5-flash-tts'),
1315
+ text: 'Hello, world!',
1316
+ voice: 'Kore', // Gemini voice name
1317
+ });
1318
+ ```
1319
+
1320
+ The `voice` argument accepts one of Gemini's [30 prebuilt voices](https://ai.google.dev/gemini-api/docs/speech-generation#voices)
1321
+ (e.g. `Kore`, `Puck`, `Zephyr`); it defaults to `Kore`. Multi-speaker dialogue is available via
1322
+ `providerOptions.googleVertex.multiSpeakerVoiceConfig`.
1323
+
1324
+ By default the audio is returned as a playable WAV (Gemini returns raw PCM, which the provider
1325
+ wraps). Set `outputFormat: 'pcm'` for the raw signed 16-bit little-endian mono bytes; the sample
1326
+ rate is reported in `result.providerMetadata.google.sampleRate`.
1327
+
1328
+ #### Speech Model Capabilities
1329
+
1330
+ | Model | Multi-speaker | Style via instructions |
1331
+ | ----------------------------------- | ------------------- | ---------------------- |
1332
+ | `gemini-2.5-flash-tts` | <Check size={18} /> | <Check size={18} /> |
1333
+ | `gemini-2.5-pro-tts` | <Check size={18} /> | <Check size={18} /> |
1334
+ | `gemini-2.5-flash-lite-preview-tts` | <Check size={18} /> | <Check size={18} /> |
1335
+ | `gemini-3.1-flash-tts-preview` | <Check size={18} /> | <Check size={18} /> |
1336
+
1337
+ ### Transcription Models
1338
+
1339
+ You can transcribe audio with Google Cloud Speech-to-Text models using the
1340
+ `.transcription()` factory method together with
1341
+ [`transcribe()`](/docs/reference/ai-sdk-core/transcribe).
1342
+
1343
+ ```ts
1344
+ import { googleVertex } from '@ai-sdk/google-vertex';
1345
+ import { transcribe } from 'ai';
1346
+ import { readFile } from 'fs/promises';
1347
+
1348
+ const result = await transcribe({
1349
+ model: googleVertex.transcription('chirp_2'),
1350
+ audio: await readFile('audio.wav'),
1351
+ });
1352
+ ```
1353
+
1354
+ The provider supports [Chirp](https://docs.cloud.google.com/speech-to-text/docs/models/chirp-3)
1355
+ models `chirp_2` and `chirp_3`, plus `telephony` for phone-call audio.
1356
+ Speech-to-Text uses standard Google Cloud credentials (OAuth, Application Default
1357
+ Credentials, or a service account) and calls the Cloud Speech-to-Text API.
1358
+ Express Mode API keys are not supported for transcription models. Set
1359
+ `GOOGLE_VERTEX_LOCATION` (or `providerOptions.googleVertex.region`) to a
1360
+ Speech-to-Text region. For Chirp, `chirp_2` is available in `us-central1`,
1361
+ `europe-west4`, and `asia-southeast1`; `chirp_3` in the `us` and `eu`
1362
+ multi-regions. Chirp is not available in the `global` Speech-to-Text location,
1363
+ and these regions differ from Vertex AI regions. `telephony` availability
1364
+ depends on the selected Speech-to-Text region and language.
1365
+
1366
+ The synchronous API transcribes audio up to one minute or 10 MB, whichever is
1367
+ reached first. The spoken language is auto-detected by default; pass
1368
+ `languageCodes` to restrict it. For `telephony`, pass a supported language code
1369
+ such as `['en-US']`.
1370
+
1371
+ ```ts
1372
+ const result = await transcribe({
1373
+ model: googleVertex.transcription('chirp_3'),
1374
+ audio: await readFile('audio.wav'),
1375
+ providerOptions: {
1376
+ googleVertex: {
1377
+ region: 'us',
1378
+ languageCodes: ['en-US'],
1379
+ },
1380
+ },
1381
+ });
1382
+ ```
1383
+
1384
+ The following provider options are available:
1385
+
1386
+ - **languageCodes** _string[]_
1387
+
1388
+ BCP-47 language codes to recognize, or `['auto']` to detect the spoken
1389
+ language. Defaults to `['auto']`. Multiple explicit language codes require a
1390
+ multi-region Speech-to-Text endpoint such as `us` or `eu`.
1391
+
1392
+ - **enableAutomaticPunctuation** _boolean_
1393
+
1394
+ Whether to add punctuation to the transcript. Defaults to `true`.
1395
+
1396
+ - **enableWordTimeOffsets** _boolean_
1397
+
1398
+ Whether to include word-level timestamps in `result.segments`. Defaults to
1399
+ `true`. Google notes that enabling word-level timestamps can reduce
1400
+ transcription quality and speed.
1401
+
1402
+ - **region** _string_
1403
+
1404
+ The Speech-to-Text region for the request. Defaults to the provider
1405
+ `location`.
1406
+
1407
+ #### Transcription Model Capabilities
1408
+
1409
+ | Model | Word timestamps | Language detection |
1410
+ | ----------- | --------------------------------------------------------- | ------------------------------------------------------------------------------ |
1411
+ | `chirp_2` | Available with a potential quality and speed tradeoff | Auto detection with `['auto']` |
1412
+ | `chirp_3` | Available with a potential transcription quality tradeoff | Auto detection with `['auto']` |
1413
+ | `telephony` | Available | Explicit supported language codes, with alternative language detection support |
1414
+
1303
1415
  ## Google Vertex Anthropic Provider Usage
1304
1416
 
1305
1417
  The Google Vertex Anthropic provider for the [AI SDK](/docs) offers support for Anthropic's Claude models through the Google Vertex AI APIs. This section provides details on how to set up and use the Google Vertex Anthropic provider.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-sdk/google-vertex",
3
- "version": "5.0.0-canary.99",
3
+ "version": "5.0.0",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "sideEffects": false,
@@ -72,18 +72,18 @@
72
72
  },
73
73
  "dependencies": {
74
74
  "google-auth-library": "^10.6.2",
75
- "@ai-sdk/anthropic": "4.0.0-canary.61",
76
- "@ai-sdk/google": "4.0.0-canary.76",
77
- "@ai-sdk/openai-compatible": "3.0.0-canary.52",
78
- "@ai-sdk/provider": "4.0.0-canary.17",
79
- "@ai-sdk/provider-utils": "5.0.0-canary.44"
75
+ "@ai-sdk/anthropic": "4.0.0",
76
+ "@ai-sdk/google": "4.0.0",
77
+ "@ai-sdk/openai-compatible": "3.0.0",
78
+ "@ai-sdk/provider": "4.0.0",
79
+ "@ai-sdk/provider-utils": "5.0.0"
80
80
  },
81
81
  "devDependencies": {
82
82
  "@types/node": "22.19.19",
83
83
  "tsup": "^8.5.1",
84
84
  "typescript": "5.8.3",
85
85
  "zod": "3.25.76",
86
- "@ai-sdk/test-server": "2.0.0-canary.6",
86
+ "@ai-sdk/test-server": "2.0.0",
87
87
  "@vercel/ai-tsconfig": "0.0.0"
88
88
  },
89
89
  "peerDependencies": {
@@ -1,5 +1,6 @@
1
1
  // https://cloud.google.com/vertex-ai/generative-ai/docs/partner-models/claude
2
2
  export type GoogleVertexAnthropicModelId =
3
+ | 'claude-fable-5'
3
4
  | 'claude-opus-4-8'
4
5
  | 'claude-opus-4-7'
5
6
  | 'claude-opus-4-6'
@@ -23,7 +23,6 @@ import type { GoogleVertexConfig } from './google-vertex-config';
23
23
  export class GoogleVertexEmbeddingModel implements EmbeddingModelV4 {
24
24
  readonly specificationVersion = 'v4';
25
25
  readonly modelId: GoogleVertexEmbeddingModelId;
26
- readonly maxEmbeddingsPerCall = 2048;
27
26
  readonly supportsParallelCalls = true;
28
27
 
29
28
  private readonly config: GoogleVertexConfig;
@@ -46,6 +45,12 @@ export class GoogleVertexEmbeddingModel implements EmbeddingModelV4 {
46
45
  return this.config.provider;
47
46
  }
48
47
 
48
+ // gemini-embedding-2 models only support :embedContent (one value per call),
49
+ // not the :predict batch endpoint. https://github.com/vercel/ai/issues/15853
50
+ get maxEmbeddingsPerCall(): number {
51
+ return usesEmbedContentEndpoint(this.modelId) ? 1 : 2048;
52
+ }
53
+
49
54
  constructor(
50
55
  modelId: GoogleVertexEmbeddingModelId,
51
56
  config: GoogleVertexConfig,
@@ -100,6 +105,42 @@ export class GoogleVertexEmbeddingModel implements EmbeddingModelV4 {
100
105
  headers,
101
106
  );
102
107
 
108
+ if (usesEmbedContentEndpoint(this.modelId)) {
109
+ const {
110
+ responseHeaders,
111
+ value: response,
112
+ rawValue,
113
+ } = await postJsonToApi({
114
+ url: `${this.config.baseURL}/models/${this.modelId}:embedContent`,
115
+ headers: mergedHeaders,
116
+ body: {
117
+ content: { parts: [{ text: values[0] }] },
118
+ embedContentConfig: {
119
+ outputDimensionality: googleOptions.outputDimensionality,
120
+ taskType: googleOptions.taskType,
121
+ title: googleOptions.title,
122
+ autoTruncate: googleOptions.autoTruncate,
123
+ },
124
+ },
125
+ failedResponseHandler: googleVertexFailedResponseHandler,
126
+ successfulResponseHandler: createJsonResponseHandler(
127
+ googleVertexEmbedContentResponseSchema,
128
+ ),
129
+ abortSignal,
130
+ fetch: this.config.fetch,
131
+ });
132
+
133
+ return {
134
+ warnings: [],
135
+ embeddings: [response.embedding.values],
136
+ usage:
137
+ response.usageMetadata?.promptTokenCount == null
138
+ ? undefined
139
+ : { tokens: response.usageMetadata.promptTokenCount },
140
+ response: { headers: responseHeaders, body: rawValue },
141
+ };
142
+ }
143
+
103
144
  const url = `${this.config.baseURL}/models/${this.modelId}:predict`;
104
145
  const {
105
146
  responseHeaders,
@@ -158,3 +199,20 @@ const googleVertexTextEmbeddingResponseSchema = z.object({
158
199
  }),
159
200
  ),
160
201
  });
202
+
203
+ const googleVertexEmbedContentResponseSchema = z.object({
204
+ embedding: z.object({
205
+ values: z.array(z.number()),
206
+ }),
207
+ usageMetadata: z
208
+ .object({
209
+ promptTokenCount: z.number().nullish(),
210
+ })
211
+ .nullish(),
212
+ });
213
+
214
+ function usesEmbedContentEndpoint(modelId: GoogleVertexEmbeddingModelId) {
215
+ return (
216
+ modelId === 'gemini-embedding-2' || modelId === 'gemini-embedding-2-preview'
217
+ );
218
+ }
@@ -1,9 +1,14 @@
1
- import { GoogleLanguageModel } from '@ai-sdk/google/internal';
1
+ import {
2
+ GoogleLanguageModel,
3
+ GoogleSpeechModel,
4
+ } from '@ai-sdk/google/internal';
2
5
  import type {
3
6
  Experimental_VideoModelV4,
4
7
  ImageModelV4,
5
8
  LanguageModelV4,
6
9
  ProviderV4,
10
+ SpeechModelV4,
11
+ TranscriptionModelV4,
7
12
  } from '@ai-sdk/provider';
8
13
  import {
9
14
  generateId,
@@ -24,8 +29,11 @@ import { GoogleVertexImageModel } from './google-vertex-image-model';
24
29
  import type { GoogleVertexImageModelId } from './google-vertex-image-settings';
25
30
  import type { GoogleVertexModelId } from './google-vertex-options';
26
31
  import { googleVertexTools } from './google-vertex-tools';
32
+ import { GoogleVertexTranscriptionModel } from './google-vertex-transcription-model';
33
+ import type { GoogleVertexTranscriptionModelId } from './google-vertex-transcription-model-options';
27
34
  import { GoogleVertexVideoModel } from './google-vertex-video-model';
28
35
  import type { GoogleVertexVideoModelId } from './google-vertex-video-settings';
36
+ import type { GoogleVertexSpeechModelId } from './google-vertex-speech-model-options';
29
37
 
30
38
  const EXPRESS_MODE_BASE_URL =
31
39
  'https://aiplatform.googleapis.com/v1/publishers/google';
@@ -83,6 +91,30 @@ export interface GoogleVertexProvider extends ProviderV4 {
83
91
  * Creates a model for video generation.
84
92
  */
85
93
  videoModel(modelId: GoogleVertexVideoModelId): Experimental_VideoModelV4;
94
+
95
+ /**
96
+ * Creates a model for speech generation (text-to-speech).
97
+ */
98
+ speech(modelId: GoogleVertexSpeechModelId): SpeechModelV4;
99
+
100
+ /**
101
+ * Creates a model for speech generation (text-to-speech).
102
+ */
103
+ speechModel(modelId: GoogleVertexSpeechModelId): SpeechModelV4;
104
+
105
+ /**
106
+ * Creates a model for transcription (speech-to-text).
107
+ */
108
+ transcription(
109
+ modelId: GoogleVertexTranscriptionModelId,
110
+ ): TranscriptionModelV4;
111
+
112
+ /**
113
+ * Creates a model for transcription (speech-to-text).
114
+ */
115
+ transcriptionModel(
116
+ modelId: GoogleVertexTranscriptionModelId,
117
+ ): TranscriptionModelV4;
86
118
  }
87
119
 
88
120
  export interface GoogleVertexProviderSettings {
@@ -162,13 +194,19 @@ export function createGoogleVertex(
162
194
  const region = loadGoogleVertexLocation();
163
195
  const project = loadGoogleVertexProject();
164
196
 
165
- // For global region, use aiplatform.googleapis.com directly
166
- // For other regions, use region-aiplatform.googleapis.com
167
- const baseHost = `${region === 'global' ? '' : region + '-'}aiplatform.googleapis.com`;
197
+ const getHost = () => {
198
+ if (region === 'global') {
199
+ return 'aiplatform.googleapis.com';
200
+ } else if (region === 'eu' || region === 'us') {
201
+ return `aiplatform.${region}.rep.googleapis.com`;
202
+ } else {
203
+ return `${region}-aiplatform.googleapis.com`;
204
+ }
205
+ };
168
206
 
169
207
  return (
170
208
  withoutTrailingSlash(options.baseURL) ??
171
- `https://${baseHost}/v1beta1/projects/${project}/locations/${region}/publishers/google`
209
+ `https://${getHost()}/v1beta1/projects/${project}/locations/${region}/publishers/google`
172
210
  );
173
211
  };
174
212
 
@@ -221,6 +259,30 @@ export function createGoogleVertex(
221
259
  generateId: options.generateId ?? generateId,
222
260
  });
223
261
 
262
+ const createSpeechModel = (modelId: GoogleVertexSpeechModelId) =>
263
+ new GoogleSpeechModel(modelId, createConfig('speech'));
264
+
265
+ // Cloud Speech-to-Text reuses the Vertex auth headers from createConfig, but
266
+ // targets the Speech-to-Text API.
267
+ const createTranscriptionModel = (
268
+ modelId: GoogleVertexTranscriptionModelId,
269
+ ) => {
270
+ if (apiKey) {
271
+ throw new Error(
272
+ 'Google Vertex transcription models do not support Express Mode API keys. Use standard Google Cloud credentials instead.',
273
+ );
274
+ }
275
+
276
+ const config = createConfig('transcription');
277
+ return new GoogleVertexTranscriptionModel(modelId, {
278
+ provider: config.provider,
279
+ headers: config.headers,
280
+ fetch: config.fetch,
281
+ project: loadGoogleVertexProject(),
282
+ location: loadGoogleVertexLocation(),
283
+ });
284
+ };
285
+
224
286
  const provider = function (modelId: GoogleVertexModelId) {
225
287
  if (new.target) {
226
288
  throw new Error(
@@ -239,6 +301,10 @@ export function createGoogleVertex(
239
301
  provider.imageModel = createImageModel;
240
302
  provider.video = createVideoModel;
241
303
  provider.videoModel = createVideoModel;
304
+ provider.speech = createSpeechModel;
305
+ provider.speechModel = createSpeechModel;
306
+ provider.transcription = createTranscriptionModel;
307
+ provider.transcriptionModel = createTranscriptionModel;
242
308
  provider.tools = googleVertexTools;
243
309
 
244
310
  return provider;
@@ -0,0 +1,11 @@
1
+ import type { GoogleSpeechModelOptions } from '@ai-sdk/google';
2
+
3
+ // https://docs.cloud.google.com/text-to-speech/docs/gemini-tts
4
+ export type GoogleVertexSpeechModelId =
5
+ | 'gemini-2.5-flash-tts'
6
+ | 'gemini-2.5-pro-tts'
7
+ | 'gemini-2.5-flash-lite-preview-tts'
8
+ | 'gemini-3.1-flash-tts-preview'
9
+ | (string & {});
10
+
11
+ export type GoogleVertexSpeechModelOptions = GoogleSpeechModelOptions;
@@ -0,0 +1,46 @@
1
+ import { z } from 'zod/v4';
2
+
3
+ // Google Cloud Speech-to-Text transcription models (Speech-to-Text v2).
4
+ // https://docs.cloud.google.com/speech-to-text/docs/transcription-model
5
+ export type GoogleVertexTranscriptionModelId =
6
+ | 'chirp_2'
7
+ | 'chirp_3'
8
+ | 'telephony'
9
+ | (string & {});
10
+
11
+ export const googleVertexTranscriptionProviderOptionsSchema = z.object({
12
+ /**
13
+ * BCP-47 language codes to recognize (e.g. `['en-US']`), or `['auto']` to let
14
+ * Chirp auto-detect the spoken language. Defaults to `['auto']`. For
15
+ * `telephony`, pass a supported explicit language code.
16
+ */
17
+ languageCodes: z.array(z.string()).optional(),
18
+
19
+ /**
20
+ * Whether to add punctuation to the transcript. Defaults to `true`.
21
+ */
22
+ enableAutomaticPunctuation: z.boolean().optional(),
23
+
24
+ /**
25
+ * Whether to include word-level timestamps. Defaults to `true` so the
26
+ * transcription result can include segments.
27
+ *
28
+ * Enabling word-level timestamps can reduce transcription quality and speed
29
+ * for Chirp models.
30
+ */
31
+ enableWordTimeOffsets: z.boolean().optional(),
32
+
33
+ /**
34
+ * The Cloud Speech-to-Text region for the request (e.g. `'us'`, `'eu'`,
35
+ * `'us-central1'`). Defaults to the provider `location`.
36
+ *
37
+ * Note: Speech-to-Text regions differ from Vertex AI regions. Chirp is only
38
+ * available in specific Speech-to-Text regions and is not available in the
39
+ * `global` location.
40
+ */
41
+ region: z.string().optional(),
42
+ });
43
+
44
+ export type GoogleVertexTranscriptionModelOptions = z.infer<
45
+ typeof googleVertexTranscriptionProviderOptionsSchema
46
+ >;