@ai-sdk/google-vertex 5.0.0-canary.98 → 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.
@@ -0,0 +1,231 @@
1
+ import type { SharedV4Warning, TranscriptionModelV4 } from '@ai-sdk/provider';
2
+ import {
3
+ combineHeaders,
4
+ convertUint8ArrayToBase64,
5
+ createJsonResponseHandler,
6
+ parseProviderOptions,
7
+ postJsonToApi,
8
+ resolve,
9
+ serializeModelOptions,
10
+ WORKFLOW_DESERIALIZE,
11
+ WORKFLOW_SERIALIZE,
12
+ type FetchFunction,
13
+ type Resolvable,
14
+ } from '@ai-sdk/provider-utils';
15
+ import { z } from 'zod/v4';
16
+ import { googleVertexFailedResponseHandler } from './google-vertex-error';
17
+ import {
18
+ googleVertexTranscriptionProviderOptionsSchema,
19
+ type GoogleVertexTranscriptionModelId,
20
+ type GoogleVertexTranscriptionModelOptions,
21
+ } from './google-vertex-transcription-model-options';
22
+
23
+ interface GoogleVertexTranscriptionModelConfig {
24
+ provider: string;
25
+ /** Google Cloud project id. */
26
+ project: string;
27
+ /** Default Speech-to-Text region (overridable via provider options). */
28
+ location: string;
29
+ headers?: Resolvable<Record<string, string | undefined>>;
30
+ fetch?: FetchFunction;
31
+ _internal?: {
32
+ currentDate?: () => Date;
33
+ };
34
+ }
35
+
36
+ // Speech-to-Text Durations are strings like `"1.200s"`; parse to seconds.
37
+ function parseDurationSeconds(
38
+ value: string | null | undefined,
39
+ ): number | undefined {
40
+ if (value == null) {
41
+ return undefined;
42
+ }
43
+ const seconds = Number.parseFloat(value);
44
+ return Number.isFinite(seconds) ? seconds : undefined;
45
+ }
46
+
47
+ function convertBcp47ToIso6391(
48
+ value: string | null | undefined,
49
+ ): string | undefined {
50
+ if (value == null) {
51
+ return undefined;
52
+ }
53
+
54
+ try {
55
+ const language = new Intl.Locale(value).language;
56
+ return language.length === 2 ? language : undefined;
57
+ } catch {
58
+ return undefined;
59
+ }
60
+ }
61
+
62
+ export class GoogleVertexTranscriptionModel implements TranscriptionModelV4 {
63
+ readonly specificationVersion = 'v4';
64
+
65
+ static [WORKFLOW_SERIALIZE](model: GoogleVertexTranscriptionModel) {
66
+ return serializeModelOptions({
67
+ modelId: model.modelId,
68
+ config: model.config,
69
+ });
70
+ }
71
+
72
+ static [WORKFLOW_DESERIALIZE](options: {
73
+ modelId: GoogleVertexTranscriptionModelId;
74
+ config: GoogleVertexTranscriptionModelConfig;
75
+ }) {
76
+ return new GoogleVertexTranscriptionModel(options.modelId, options.config);
77
+ }
78
+
79
+ get provider(): string {
80
+ return this.config.provider;
81
+ }
82
+
83
+ constructor(
84
+ readonly modelId: GoogleVertexTranscriptionModelId,
85
+ private readonly config: GoogleVertexTranscriptionModelConfig,
86
+ ) {}
87
+
88
+ async doGenerate(
89
+ options: Parameters<TranscriptionModelV4['doGenerate']>[0],
90
+ ): Promise<Awaited<ReturnType<TranscriptionModelV4['doGenerate']>>> {
91
+ const currentDate = this.config._internal?.currentDate?.() ?? new Date();
92
+ const warnings: SharedV4Warning[] = [];
93
+
94
+ // Provider options may be passed under `googleVertex`, `vertex`, or `google`
95
+ // (matching the Vertex language + embedding models).
96
+ let googleOptions: GoogleVertexTranscriptionModelOptions | undefined;
97
+ for (const provider of ['googleVertex', 'vertex', 'google'] as const) {
98
+ googleOptions = await parseProviderOptions({
99
+ provider,
100
+ providerOptions: options.providerOptions,
101
+ schema: googleVertexTranscriptionProviderOptionsSchema,
102
+ });
103
+ if (googleOptions != null) {
104
+ break;
105
+ }
106
+ }
107
+
108
+ const region = googleOptions?.region ?? this.config.location;
109
+ const languageCodes = googleOptions?.languageCodes ?? ['auto'];
110
+
111
+ // The recognize API takes base64-encoded audio in the `content` field. A
112
+ // string audio input is already base64-encoded per the spec.
113
+ const content =
114
+ typeof options.audio === 'string'
115
+ ? options.audio
116
+ : convertUint8ArrayToBase64(options.audio);
117
+
118
+ const requestBody = {
119
+ config: {
120
+ model: this.modelId,
121
+ languageCodes,
122
+ // Let Speech-to-Text auto-detect the audio encoding (wav/mp3/flac/…).
123
+ autoDecodingConfig: {},
124
+ features: {
125
+ // Word timing populates `segments`.
126
+ enableWordTimeOffsets: googleOptions?.enableWordTimeOffsets ?? true,
127
+ enableAutomaticPunctuation:
128
+ googleOptions?.enableAutomaticPunctuation ?? true,
129
+ },
130
+ },
131
+ content,
132
+ };
133
+
134
+ const host =
135
+ region === 'global'
136
+ ? 'speech.googleapis.com'
137
+ : `${region}-speech.googleapis.com`;
138
+
139
+ const url =
140
+ `https://${host}/v2/projects/` +
141
+ `${this.config.project}/locations/${region}/recognizers/_:recognize`;
142
+
143
+ const {
144
+ value: response,
145
+ responseHeaders,
146
+ rawValue: rawResponse,
147
+ } = await postJsonToApi({
148
+ url,
149
+ headers: combineHeaders(
150
+ this.config.headers ? await resolve(this.config.headers) : undefined,
151
+ options.headers,
152
+ ),
153
+ body: requestBody,
154
+ failedResponseHandler: googleVertexFailedResponseHandler,
155
+ successfulResponseHandler: createJsonResponseHandler(
156
+ googleVertexTranscriptionResponseSchema,
157
+ ),
158
+ abortSignal: options.abortSignal,
159
+ fetch: this.config.fetch,
160
+ });
161
+
162
+ // Results are sequential portions of the audio; concatenate their primary
163
+ // alternatives into the full transcript and collect word-level segments.
164
+ const results = response.results ?? [];
165
+ const text = results
166
+ .map(result => result.alternatives?.[0]?.transcript ?? '')
167
+ .join(' ')
168
+ .trim();
169
+ const segments = results.flatMap(
170
+ result =>
171
+ result.alternatives?.[0]?.words?.flatMap(word => {
172
+ const startSecond = parseDurationSeconds(word.startOffset);
173
+ const endSecond = parseDurationSeconds(word.endOffset);
174
+
175
+ return word.word == null || startSecond == null || endSecond == null
176
+ ? []
177
+ : [{ text: word.word, startSecond, endSecond }];
178
+ }) ?? [],
179
+ );
180
+ const language = convertBcp47ToIso6391(results[0]?.languageCode);
181
+
182
+ return {
183
+ text,
184
+ segments,
185
+ language,
186
+ durationInSeconds: parseDurationSeconds(
187
+ response.metadata?.totalBilledDuration,
188
+ ),
189
+ warnings,
190
+ response: {
191
+ timestamp: currentDate,
192
+ modelId: this.modelId,
193
+ headers: responseHeaders,
194
+ body: rawResponse,
195
+ },
196
+ };
197
+ }
198
+ }
199
+
200
+ // Minimal schema: only the fields the implementation reads, with `.nullish()`
201
+ // so provider API changes don't break parsing.
202
+ const googleVertexTranscriptionResponseSchema = z.object({
203
+ results: z
204
+ .array(
205
+ z.object({
206
+ alternatives: z
207
+ .array(
208
+ z.object({
209
+ transcript: z.string().nullish(),
210
+ words: z
211
+ .array(
212
+ z.object({
213
+ word: z.string().nullish(),
214
+ startOffset: z.string().nullish(),
215
+ endOffset: z.string().nullish(),
216
+ }),
217
+ )
218
+ .nullish(),
219
+ }),
220
+ )
221
+ .nullish(),
222
+ languageCode: z.string().nullish(),
223
+ }),
224
+ )
225
+ .nullish(),
226
+ metadata: z
227
+ .object({
228
+ totalBilledDuration: z.string().nullish(),
229
+ })
230
+ .nullish(),
231
+ });
@@ -125,6 +125,12 @@ export class GoogleVertexVideoModel implements Experimental_VideoModelV4 {
125
125
  parameters.seed = options.seed;
126
126
  }
127
127
 
128
+ const generateAudio =
129
+ options.generateAudio ?? googleVertexOptions?.generateAudio;
130
+ if (generateAudio != null) {
131
+ parameters.generateAudio = generateAudio;
132
+ }
133
+
128
134
  if (googleVertexOptions != null) {
129
135
  const opts = googleVertexOptions;
130
136
 
@@ -137,9 +143,6 @@ export class GoogleVertexVideoModel implements Experimental_VideoModelV4 {
137
143
  if (opts.negativePrompt !== undefined && opts.negativePrompt !== null) {
138
144
  parameters.negativePrompt = opts.negativePrompt;
139
145
  }
140
- if (opts.generateAudio !== undefined && opts.generateAudio !== null) {
141
- parameters.generateAudio = opts.generateAudio;
142
- }
143
146
  if (
144
147
  opts.gcsOutputDirectory !== undefined &&
145
148
  opts.gcsOutputDirectory !== null
package/src/index.ts CHANGED
@@ -1,4 +1,8 @@
1
1
  export type { GoogleVertexEmbeddingModelOptions } from './google-vertex-embedding-model-options';
2
+ export type {
3
+ GoogleVertexTranscriptionModelId,
4
+ GoogleVertexTranscriptionModelOptions,
5
+ } from './google-vertex-transcription-model-options';
2
6
  export type {
3
7
  GoogleVertexImageModelOptions,
4
8
  /** @deprecated Use `GoogleVertexImageModelOptions` instead. */
@@ -10,6 +14,10 @@ export type {
10
14
  GoogleVertexVideoModelOptions as GoogleVertexVideoProviderOptions,
11
15
  } from './google-vertex-video-model-options';
12
16
  export type { GoogleVertexVideoModelId } from './google-vertex-video-settings';
17
+ export type {
18
+ GoogleVertexSpeechModelId,
19
+ GoogleVertexSpeechModelOptions,
20
+ } from './google-vertex-speech-model-options';
13
21
  export {
14
22
  createGoogleVertex,
15
23
  /** @deprecated Use `createGoogleVertex` instead. */
@@ -75,12 +75,21 @@ export function createGoogleVertexMaas(
75
75
  description: 'Google Vertex project',
76
76
  });
77
77
 
78
- // Construct base URL: https://aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/openapi
78
+ const getHost = (location: string) => {
79
+ if (location === 'global') {
80
+ return 'aiplatform.googleapis.com';
81
+ } else if (location === 'eu' || location === 'us') {
82
+ return `aiplatform.${location}.rep.googleapis.com`;
83
+ } else {
84
+ return `${location}-aiplatform.googleapis.com`;
85
+ }
86
+ };
87
+
79
88
  const constructBaseURL = () => {
80
89
  const projectId = loadProject();
81
90
  const location = loadLocation() ?? 'global';
82
91
 
83
- return `https://aiplatform.googleapis.com/v1/projects/${projectId}/locations/${location}/endpoints/openapi`;
92
+ return `https://${getHost(location)}/v1/projects/${projectId}/locations/${location}/endpoints/openapi`;
84
93
  };
85
94
 
86
95
  const loadBaseURL = () =>