@ai-sdk/google-vertex 5.0.0-beta.23 → 5.0.0-beta.25

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @ai-sdk/google-vertex
2
2
 
3
+ ## 5.0.0-beta.25
4
+
5
+ ### Patch Changes
6
+
7
+ - a34b997: feat (provider/google-vertex): add support for maas models
8
+
9
+ ## 5.0.0-beta.24
10
+
11
+ ### Patch Changes
12
+
13
+ - Updated dependencies [9715ec7]
14
+ - @ai-sdk/google@4.0.0-beta.18
15
+
3
16
  ## 5.0.0-beta.23
4
17
 
5
18
  ### Patch Changes
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  The **[Google Vertex provider](https://ai-sdk.dev/providers/ai-sdk-providers/google-vertex)** for the [AI SDK](https://ai-sdk.dev/docs) contains language model support for the [Google Vertex AI](https://cloud.google.com/vertex-ai) APIs.
4
4
 
5
- This library includes a Google Vertex Anthropic provider. This provider closely follows the core Google Vertex library's usage patterns. See more in the [Google Vertex Anthropic Provider](#google-vertex-anthropic-provider) section below.
5
+ This library includes a Google Vertex Anthropic provider and a Google Vertex MaaS provider. These providers closely follow the core Google Vertex library's usage patterns. See more in the [Google Vertex Anthropic Provider](#google-vertex-anthropic-provider) and [Google Vertex MaaS Provider](#google-vertex-maas-provider) sections below.
6
6
 
7
7
  ## Setup
8
8
 
@@ -224,6 +224,68 @@ const { text } = await generateText({
224
224
  });
225
225
  ```
226
226
 
227
+ ## Google Vertex MaaS Provider
228
+
229
+ The Google Vertex MaaS (Model as a Service) provider offers access to partner and open models hosted on Vertex AI through an OpenAI-compatible Chat Completions API. It is available for both Node.js and Edge runtimes.
230
+
231
+ ### Node.js Runtime
232
+
233
+ ```ts
234
+ import { vertexMaas } from '@ai-sdk/google-vertex/maas';
235
+ import { generateText } from 'ai';
236
+
237
+ const { text } = await generateText({
238
+ model: vertexMaas('deepseek-ai/deepseek-v3.2-maas'),
239
+ prompt: 'Write a vegetarian lasagna recipe.',
240
+ });
241
+ ```
242
+
243
+ ### Edge Runtime
244
+
245
+ ```ts
246
+ import { vertexMaas } from '@ai-sdk/google-vertex/maas/edge';
247
+ import { generateText } from 'ai';
248
+
249
+ const { text } = await generateText({
250
+ model: vertexMaas('deepseek-ai/deepseek-v3.2-maas'),
251
+ prompt: 'Write a vegetarian lasagna recipe.',
252
+ });
253
+ ```
254
+
255
+ ### Google Vertex MaaS Provider Custom Configuration
256
+
257
+ ```ts
258
+ import { createVertexMaas } from '@ai-sdk/google-vertex/maas';
259
+ import { generateText } from 'ai';
260
+
261
+ const customProvider = createVertexMaas({
262
+ project: 'your-project-id',
263
+ location: 'us-east5',
264
+ });
265
+
266
+ const { text } = await generateText({
267
+ model: customProvider('deepseek-ai/deepseek-v3.2-maas'),
268
+ prompt: 'Write a vegetarian lasagna recipe.',
269
+ });
270
+ ```
271
+
272
+ And for the Edge runtime:
273
+
274
+ ```ts
275
+ import { createVertexMaas } from '@ai-sdk/google-vertex/maas/edge';
276
+ import { generateText } from 'ai';
277
+
278
+ const customProvider = createVertexMaas({
279
+ project: 'your-project-id',
280
+ location: 'us-east5',
281
+ });
282
+
283
+ const { text } = await generateText({
284
+ model: customProvider('deepseek-ai/deepseek-v3.2-maas'),
285
+ prompt: 'Write a vegetarian lasagna recipe.',
286
+ });
287
+ ```
288
+
227
289
  ## Documentation
228
290
 
229
291
  Please check out the **[Google Vertex provider](https://ai-sdk.dev/providers/ai-sdk-providers/google-vertex)** for more information.
@@ -32,7 +32,7 @@ var import_provider_utils3 = require("@ai-sdk/provider-utils");
32
32
  var import_provider_utils = require("@ai-sdk/provider-utils");
33
33
 
34
34
  // src/version.ts
35
- var VERSION = true ? "5.0.0-beta.23" : "0.0.0-test";
35
+ var VERSION = true ? "5.0.0-beta.25" : "0.0.0-test";
36
36
 
37
37
  // src/edge/google-vertex-auth-edge.ts
38
38
  var loadCredentials = async () => {
@@ -10,7 +10,7 @@ import {
10
10
  } from "@ai-sdk/provider-utils";
11
11
 
12
12
  // src/version.ts
13
- var VERSION = true ? "5.0.0-beta.23" : "0.0.0-test";
13
+ var VERSION = true ? "5.0.0-beta.25" : "0.0.0-test";
14
14
 
15
15
  // src/edge/google-vertex-auth-edge.ts
16
16
  var loadCredentials = async () => {
@@ -33,7 +33,7 @@ var import_internal3 = require("@ai-sdk/google/internal");
33
33
  var import_provider_utils5 = require("@ai-sdk/provider-utils");
34
34
 
35
35
  // src/version.ts
36
- var VERSION = true ? "5.0.0-beta.23" : "0.0.0-test";
36
+ var VERSION = true ? "5.0.0-beta.25" : "0.0.0-test";
37
37
 
38
38
  // src/google-vertex-embedding-model.ts
39
39
  var import_provider = require("@ai-sdk/provider");
@@ -14,7 +14,7 @@ import {
14
14
  } from "@ai-sdk/provider-utils";
15
15
 
16
16
  // src/version.ts
17
- var VERSION = true ? "5.0.0-beta.23" : "0.0.0-test";
17
+ var VERSION = true ? "5.0.0-beta.25" : "0.0.0-test";
18
18
 
19
19
  // src/google-vertex-embedding-model.ts
20
20
  import {
package/dist/index.js CHANGED
@@ -55,7 +55,7 @@ var import_internal3 = require("@ai-sdk/google/internal");
55
55
  var import_provider_utils5 = require("@ai-sdk/provider-utils");
56
56
 
57
57
  // src/version.ts
58
- var VERSION = true ? "5.0.0-beta.23" : "0.0.0-test";
58
+ var VERSION = true ? "5.0.0-beta.25" : "0.0.0-test";
59
59
 
60
60
  // src/google-vertex-embedding-model.ts
61
61
  var import_provider = require("@ai-sdk/provider");
package/dist/index.mjs CHANGED
@@ -35,7 +35,7 @@ import {
35
35
  } from "@ai-sdk/provider-utils";
36
36
 
37
37
  // src/version.ts
38
- var VERSION = true ? "5.0.0-beta.23" : "0.0.0-test";
38
+ var VERSION = true ? "5.0.0-beta.25" : "0.0.0-test";
39
39
 
40
40
  // src/google-vertex-embedding-model.ts
41
41
  import {
@@ -0,0 +1,76 @@
1
+ import { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';
2
+ import { Resolvable, FetchFunction } from '@ai-sdk/provider-utils';
3
+
4
+ interface GoogleCredentials {
5
+ /**
6
+ * The client email for the Google Cloud service account. Defaults to the
7
+ * value of the `GOOGLE_CLIENT_EMAIL` environment variable.
8
+ */
9
+ clientEmail: string;
10
+ /**
11
+ * The private key for the Google Cloud service account. Defaults to the
12
+ * value of the `GOOGLE_PRIVATE_KEY` environment variable.
13
+ */
14
+ privateKey: string;
15
+ /**
16
+ * Optional. The private key ID for the Google Cloud service account. Defaults
17
+ * to the value of the `GOOGLE_PRIVATE_KEY_ID` environment variable.
18
+ */
19
+ privateKeyId?: string;
20
+ }
21
+
22
+ type GoogleVertexMaasModelId = 'deepseek-ai/deepseek-r1-0528-maas' | 'deepseek-ai/deepseek-v3.1-maas' | 'deepseek-ai/deepseek-v3.2-maas' | 'openai/gpt-oss-120b-maas' | 'openai/gpt-oss-20b-maas' | 'meta/llama-4-maverick-17b-128e-instruct-maas' | 'meta/llama-4-scout-17b-16e-instruct-maas' | 'minimax/minimax-m2-maas' | 'qwen/qwen3-coder-480b-a35b-instruct-maas' | 'qwen/qwen3-next-80b-a3b-instruct-maas' | 'qwen/qwen3-next-80b-a3b-thinking-maas' | 'moonshotai/kimi-k2-thinking-maas' | (string & {});
23
+
24
+ interface GoogleVertexMaasProvider extends OpenAICompatibleProvider<GoogleVertexMaasModelId, string, string, string> {
25
+ }
26
+ interface GoogleVertexMaasProviderSettings$1 {
27
+ /**
28
+ * Google Cloud project ID. Defaults to the value of the `GOOGLE_VERTEX_PROJECT` environment variable.
29
+ */
30
+ project?: string;
31
+ /**
32
+ * Google Cloud location/region. Defaults to the value of the `GOOGLE_VERTEX_LOCATION` environment variable.
33
+ * Use 'global' for the global endpoint.
34
+ */
35
+ location?: string;
36
+ /**
37
+ * Base URL for the API calls. If not provided, will be constructed from project and location.
38
+ */
39
+ baseURL?: string;
40
+ /**
41
+ * Headers to use for requests. Can be:
42
+ * - A headers object
43
+ * - A Promise that resolves to a headers object
44
+ * - A function that returns a headers object
45
+ * - A function that returns a Promise of a headers object
46
+ */
47
+ headers?: Resolvable<Record<string, string | undefined>>;
48
+ /**
49
+ * Custom fetch implementation. You can use it as a middleware to intercept requests,
50
+ * or to provide a custom fetch implementation for e.g. testing.
51
+ */
52
+ fetch?: FetchFunction;
53
+ }
54
+
55
+ interface GoogleVertexMaasProviderSettings extends GoogleVertexMaasProviderSettings$1 {
56
+ /**
57
+ * Optional. The Google credentials for the Google Cloud service account. If
58
+ * not provided, the Google Vertex provider will use environment variables to
59
+ * load the credentials.
60
+ */
61
+ googleCredentials?: GoogleCredentials;
62
+ }
63
+ /**
64
+ * Create a Google Vertex AI MaaS (Model as a Service) provider instance for Edge runtimes.
65
+ * Uses the OpenAI-compatible Chat Completions API for partner and open models.
66
+ * Automatically handles Google Cloud authentication.
67
+ *
68
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/maas/use-open-models
69
+ */
70
+ declare function createVertexMaas(options?: GoogleVertexMaasProviderSettings): GoogleVertexMaasProvider;
71
+ /**
72
+ * Default Google Vertex AI MaaS provider instance for Edge runtimes.
73
+ */
74
+ declare const vertexMaas: GoogleVertexMaasProvider;
75
+
76
+ export { type GoogleVertexMaasModelId, type GoogleVertexMaasProvider, type GoogleVertexMaasProviderSettings, createVertexMaas, vertexMaas };
@@ -0,0 +1,76 @@
1
+ import { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';
2
+ import { Resolvable, FetchFunction } from '@ai-sdk/provider-utils';
3
+
4
+ interface GoogleCredentials {
5
+ /**
6
+ * The client email for the Google Cloud service account. Defaults to the
7
+ * value of the `GOOGLE_CLIENT_EMAIL` environment variable.
8
+ */
9
+ clientEmail: string;
10
+ /**
11
+ * The private key for the Google Cloud service account. Defaults to the
12
+ * value of the `GOOGLE_PRIVATE_KEY` environment variable.
13
+ */
14
+ privateKey: string;
15
+ /**
16
+ * Optional. The private key ID for the Google Cloud service account. Defaults
17
+ * to the value of the `GOOGLE_PRIVATE_KEY_ID` environment variable.
18
+ */
19
+ privateKeyId?: string;
20
+ }
21
+
22
+ type GoogleVertexMaasModelId = 'deepseek-ai/deepseek-r1-0528-maas' | 'deepseek-ai/deepseek-v3.1-maas' | 'deepseek-ai/deepseek-v3.2-maas' | 'openai/gpt-oss-120b-maas' | 'openai/gpt-oss-20b-maas' | 'meta/llama-4-maverick-17b-128e-instruct-maas' | 'meta/llama-4-scout-17b-16e-instruct-maas' | 'minimax/minimax-m2-maas' | 'qwen/qwen3-coder-480b-a35b-instruct-maas' | 'qwen/qwen3-next-80b-a3b-instruct-maas' | 'qwen/qwen3-next-80b-a3b-thinking-maas' | 'moonshotai/kimi-k2-thinking-maas' | (string & {});
23
+
24
+ interface GoogleVertexMaasProvider extends OpenAICompatibleProvider<GoogleVertexMaasModelId, string, string, string> {
25
+ }
26
+ interface GoogleVertexMaasProviderSettings$1 {
27
+ /**
28
+ * Google Cloud project ID. Defaults to the value of the `GOOGLE_VERTEX_PROJECT` environment variable.
29
+ */
30
+ project?: string;
31
+ /**
32
+ * Google Cloud location/region. Defaults to the value of the `GOOGLE_VERTEX_LOCATION` environment variable.
33
+ * Use 'global' for the global endpoint.
34
+ */
35
+ location?: string;
36
+ /**
37
+ * Base URL for the API calls. If not provided, will be constructed from project and location.
38
+ */
39
+ baseURL?: string;
40
+ /**
41
+ * Headers to use for requests. Can be:
42
+ * - A headers object
43
+ * - A Promise that resolves to a headers object
44
+ * - A function that returns a headers object
45
+ * - A function that returns a Promise of a headers object
46
+ */
47
+ headers?: Resolvable<Record<string, string | undefined>>;
48
+ /**
49
+ * Custom fetch implementation. You can use it as a middleware to intercept requests,
50
+ * or to provide a custom fetch implementation for e.g. testing.
51
+ */
52
+ fetch?: FetchFunction;
53
+ }
54
+
55
+ interface GoogleVertexMaasProviderSettings extends GoogleVertexMaasProviderSettings$1 {
56
+ /**
57
+ * Optional. The Google credentials for the Google Cloud service account. If
58
+ * not provided, the Google Vertex provider will use environment variables to
59
+ * load the credentials.
60
+ */
61
+ googleCredentials?: GoogleCredentials;
62
+ }
63
+ /**
64
+ * Create a Google Vertex AI MaaS (Model as a Service) provider instance for Edge runtimes.
65
+ * Uses the OpenAI-compatible Chat Completions API for partner and open models.
66
+ * Automatically handles Google Cloud authentication.
67
+ *
68
+ * @see https://cloud.google.com/vertex-ai/generative-ai/docs/maas/use-open-models
69
+ */
70
+ declare function createVertexMaas(options?: GoogleVertexMaasProviderSettings): GoogleVertexMaasProvider;
71
+ /**
72
+ * Default Google Vertex AI MaaS provider instance for Edge runtimes.
73
+ */
74
+ declare const vertexMaas: GoogleVertexMaasProvider;
75
+
76
+ export { type GoogleVertexMaasModelId, type GoogleVertexMaasProvider, type GoogleVertexMaasProviderSettings, createVertexMaas, vertexMaas };
@@ -0,0 +1,215 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/maas/edge/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ createVertexMaas: () => createVertexMaas2,
24
+ vertexMaas: () => vertexMaas
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/maas/edge/google-vertex-maas-provider-edge.ts
29
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
30
+
31
+ // src/edge/google-vertex-auth-edge.ts
32
+ var import_provider_utils = require("@ai-sdk/provider-utils");
33
+
34
+ // src/version.ts
35
+ var VERSION = true ? "5.0.0-beta.25" : "0.0.0-test";
36
+
37
+ // src/edge/google-vertex-auth-edge.ts
38
+ var loadCredentials = async () => {
39
+ try {
40
+ return {
41
+ clientEmail: (0, import_provider_utils.loadSetting)({
42
+ settingValue: void 0,
43
+ settingName: "clientEmail",
44
+ environmentVariableName: "GOOGLE_CLIENT_EMAIL",
45
+ description: "Google client email"
46
+ }),
47
+ privateKey: (0, import_provider_utils.loadSetting)({
48
+ settingValue: void 0,
49
+ settingName: "privateKey",
50
+ environmentVariableName: "GOOGLE_PRIVATE_KEY",
51
+ description: "Google private key"
52
+ }),
53
+ privateKeyId: (0, import_provider_utils.loadOptionalSetting)({
54
+ settingValue: void 0,
55
+ environmentVariableName: "GOOGLE_PRIVATE_KEY_ID"
56
+ })
57
+ };
58
+ } catch (error) {
59
+ throw new Error(`Failed to load Google credentials: ${error.message}`);
60
+ }
61
+ };
62
+ var base64url = (str) => {
63
+ return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
64
+ };
65
+ var importPrivateKey = async (pemKey) => {
66
+ const pemHeader = "-----BEGIN PRIVATE KEY-----";
67
+ const pemFooter = "-----END PRIVATE KEY-----";
68
+ const pemContents = pemKey.replace(pemHeader, "").replace(pemFooter, "").replace(/\s/g, "");
69
+ const binaryString = atob(pemContents);
70
+ const binaryData = new Uint8Array(binaryString.length);
71
+ for (let i = 0; i < binaryString.length; i++) {
72
+ binaryData[i] = binaryString.charCodeAt(i);
73
+ }
74
+ return await crypto.subtle.importKey(
75
+ "pkcs8",
76
+ binaryData,
77
+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
78
+ true,
79
+ ["sign"]
80
+ );
81
+ };
82
+ var buildJwt = async (credentials) => {
83
+ const now = Math.floor(Date.now() / 1e3);
84
+ const header = {
85
+ alg: "RS256",
86
+ typ: "JWT"
87
+ };
88
+ if (credentials.privateKeyId) {
89
+ header.kid = credentials.privateKeyId;
90
+ }
91
+ const payload = {
92
+ iss: credentials.clientEmail,
93
+ scope: "https://www.googleapis.com/auth/cloud-platform",
94
+ aud: "https://oauth2.googleapis.com/token",
95
+ exp: now + 3600,
96
+ iat: now
97
+ };
98
+ const privateKey = await importPrivateKey(credentials.privateKey);
99
+ const signingInput = `${base64url(JSON.stringify(header))}.${base64url(
100
+ JSON.stringify(payload)
101
+ )}`;
102
+ const encoder = new TextEncoder();
103
+ const data = encoder.encode(signingInput);
104
+ const signature = await crypto.subtle.sign(
105
+ "RSASSA-PKCS1-v1_5",
106
+ privateKey,
107
+ data
108
+ );
109
+ const signatureBase64 = base64url(
110
+ String.fromCharCode(...new Uint8Array(signature))
111
+ );
112
+ return `${base64url(JSON.stringify(header))}.${base64url(
113
+ JSON.stringify(payload)
114
+ )}.${signatureBase64}`;
115
+ };
116
+ async function generateAuthToken(credentials) {
117
+ try {
118
+ const creds = credentials || await loadCredentials();
119
+ const jwt = await buildJwt(creds);
120
+ const response = await fetch("https://oauth2.googleapis.com/token", {
121
+ method: "POST",
122
+ headers: (0, import_provider_utils.withUserAgentSuffix)(
123
+ { "Content-Type": "application/x-www-form-urlencoded" },
124
+ `ai-sdk/google-vertex/${VERSION}`,
125
+ (0, import_provider_utils.getRuntimeEnvironmentUserAgent)()
126
+ ),
127
+ body: new URLSearchParams({
128
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
129
+ assertion: jwt
130
+ })
131
+ });
132
+ if (!response.ok) {
133
+ throw new Error(`Token request failed: ${response.statusText}`);
134
+ }
135
+ const data = await response.json();
136
+ return data.access_token;
137
+ } catch (error) {
138
+ throw error;
139
+ }
140
+ }
141
+
142
+ // src/maas/google-vertex-maas-provider.ts
143
+ var import_openai_compatible = require("@ai-sdk/openai-compatible");
144
+ var import_provider_utils2 = require("@ai-sdk/provider-utils");
145
+ function createVertexMaas(options = {}) {
146
+ const loadLocation = () => (0, import_provider_utils2.loadOptionalSetting)({
147
+ settingValue: options.location,
148
+ environmentVariableName: "GOOGLE_VERTEX_LOCATION"
149
+ });
150
+ const loadProject = () => (0, import_provider_utils2.loadSetting)({
151
+ settingValue: options.project,
152
+ settingName: "project",
153
+ environmentVariableName: "GOOGLE_VERTEX_PROJECT",
154
+ description: "Google Vertex project"
155
+ });
156
+ const constructBaseURL = () => {
157
+ var _a;
158
+ const projectId = loadProject();
159
+ const location = (_a = loadLocation()) != null ? _a : "global";
160
+ return `https://aiplatform.googleapis.com/v1/projects/${projectId}/locations/${location}/endpoints/openapi`;
161
+ };
162
+ const loadBaseURL = () => {
163
+ var _a;
164
+ return (0, import_provider_utils2.withoutTrailingSlash)((_a = options.baseURL) != null ? _a : "") || constructBaseURL();
165
+ };
166
+ let cachedProvider;
167
+ const getProvider = () => cachedProvider != null ? cachedProvider : cachedProvider = (0, import_openai_compatible.createOpenAICompatible)({
168
+ name: "vertex.maas",
169
+ baseURL: loadBaseURL(),
170
+ fetch: options.fetch
171
+ });
172
+ const provider = (modelId) => getProvider()(modelId);
173
+ provider.specificationVersion = "v4";
174
+ provider.languageModel = (modelId) => getProvider().languageModel(modelId);
175
+ provider.chatModel = (modelId) => getProvider().chatModel(modelId);
176
+ provider.completionModel = (modelId) => getProvider().completionModel(modelId);
177
+ provider.embeddingModel = (modelId) => getProvider().embeddingModel(modelId);
178
+ provider.textEmbeddingModel = (modelId) => getProvider().textEmbeddingModel(modelId);
179
+ provider.imageModel = (modelId) => getProvider().imageModel(modelId);
180
+ return provider;
181
+ }
182
+
183
+ // src/maas/edge/google-vertex-maas-provider-edge.ts
184
+ function createVertexMaas2(options = {}) {
185
+ const customFetch = async (url, init) => {
186
+ var _a;
187
+ const token = await generateAuthToken(options.googleCredentials);
188
+ const resolvedHeaders = await (0, import_provider_utils3.resolve)(options.headers);
189
+ const authHeaders = {
190
+ ...resolvedHeaders,
191
+ Authorization: `Bearer ${token}`
192
+ };
193
+ const fetchInit = {
194
+ ...init,
195
+ headers: {
196
+ ...init == null ? void 0 : init.headers,
197
+ ...authHeaders
198
+ }
199
+ };
200
+ return ((_a = options.fetch) != null ? _a : fetch)(url, fetchInit);
201
+ };
202
+ return createVertexMaas({
203
+ ...options,
204
+ fetch: customFetch,
205
+ headers: void 0
206
+ // Don't pass headers, we handle them in fetch
207
+ });
208
+ }
209
+ var vertexMaas = createVertexMaas2();
210
+ // Annotate the CommonJS export names for ESM import in node:
211
+ 0 && (module.exports = {
212
+ createVertexMaas,
213
+ vertexMaas
214
+ });
215
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/maas/edge/index.ts","../../../src/maas/edge/google-vertex-maas-provider-edge.ts","../../../src/edge/google-vertex-auth-edge.ts","../../../src/version.ts","../../../src/maas/google-vertex-maas-provider.ts"],"sourcesContent":["export {\n createVertexMaas,\n vertexMaas,\n} from './google-vertex-maas-provider-edge';\nexport type {\n GoogleVertexMaasProvider,\n GoogleVertexMaasProviderSettings,\n} from './google-vertex-maas-provider-edge';\nexport type { GoogleVertexMaasModelId } from '../google-vertex-maas-options';\n","import { FetchFunction, resolve } from '@ai-sdk/provider-utils';\nimport {\n generateAuthToken,\n GoogleCredentials,\n} from '../../edge/google-vertex-auth-edge';\nimport {\n createVertexMaas as createVertexMaasOriginal,\n GoogleVertexMaasProvider,\n GoogleVertexMaasProviderSettings as GoogleVertexMaasProviderSettingsOriginal,\n} from '../google-vertex-maas-provider';\n\nexport type { GoogleVertexMaasProvider };\n\nexport interface GoogleVertexMaasProviderSettings extends GoogleVertexMaasProviderSettingsOriginal {\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 MaaS (Model as a Service) provider instance for Edge runtimes.\n * Uses the OpenAI-compatible Chat Completions API for partner and open models.\n * Automatically handles Google Cloud authentication.\n *\n * @see https://cloud.google.com/vertex-ai/generative-ai/docs/maas/use-open-models\n */\nexport function createVertexMaas(\n options: GoogleVertexMaasProviderSettings = {},\n): GoogleVertexMaasProvider {\n // Create a custom fetch wrapper that adds auth headers\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 // Merge auth headers with existing headers from init\n const fetchInit = {\n ...init,\n headers: {\n ...init?.headers,\n ...authHeaders,\n },\n };\n\n // Call the original fetch or user's custom fetch\n return (options.fetch ?? fetch)(url, fetchInit);\n };\n\n return createVertexMaasOriginal({\n ...options,\n fetch: customFetch,\n headers: undefined, // Don't pass headers, we handle them in fetch\n });\n}\n\n/**\n * Default Google Vertex AI MaaS provider instance for Edge runtimes.\n */\nexport const vertexMaas = createVertexMaas();\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 { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';\nimport {\n FetchFunction,\n loadOptionalSetting,\n loadSetting,\n Resolvable,\n withoutTrailingSlash,\n} from '@ai-sdk/provider-utils';\nimport type { GoogleVertexMaasModelId } from './google-vertex-maas-options';\n\nexport interface GoogleVertexMaasProvider extends OpenAICompatibleProvider<\n GoogleVertexMaasModelId,\n string,\n string,\n string\n> {}\n\nexport interface GoogleVertexMaasProviderSettings {\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\n/**\n * Create a Google Vertex AI MaaS (Model as a Service) provider instance.\n * Uses the OpenAI-compatible Chat Completions API for partner and open models.\n *\n * @see https://cloud.google.com/vertex-ai/generative-ai/docs/maas/use-open-models\n */\nexport function createVertexMaas(\n options: GoogleVertexMaasProviderSettings = {},\n): GoogleVertexMaasProvider {\n // Lazy-load settings to support loading from environment variables at runtime\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 // Construct base URL: https://aiplatform.googleapis.com/v1/projects/{project}/locations/{location}/endpoints/openapi\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: GoogleVertexMaasProvider | undefined;\n const getProvider = () =>\n (cachedProvider ??= createOpenAICompatible({\n name: 'vertex.maas',\n baseURL: loadBaseURL(),\n fetch: options.fetch,\n }));\n\n const provider = (modelId: GoogleVertexMaasModelId) => getProvider()(modelId);\n\n provider.specificationVersion = 'v4' as const;\n provider.languageModel = (modelId: GoogleVertexMaasModelId) =>\n getProvider().languageModel(modelId);\n provider.chatModel = (modelId: GoogleVertexMaasModelId) =>\n getProvider().chatModel(modelId);\n provider.completionModel = (modelId: string) =>\n getProvider().completionModel(modelId);\n provider.embeddingModel = (modelId: string) =>\n getProvider().embeddingModel(modelId);\n provider.textEmbeddingModel = (modelId: string) =>\n getProvider().textEmbeddingModel(modelId);\n provider.imageModel = (modelId: string) => getProvider().imageModel(modelId);\n\n return provider as GoogleVertexMaasProvider;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA,0BAAAA;AAAA,EAAA;AAAA;AAAA;;;ACAA,IAAAC,yBAAuC;;;ACAvC,4BAKO;;;ACHA,IAAM,UACX,OACI,kBACA;;;ADuBN,IAAM,kBAAkB,YAAwC;AAC9D,MAAI;AACF,WAAO;AAAA,MACL,iBAAa,mCAAY;AAAA,QACvB,cAAc;AAAA,QACd,aAAa;AAAA,QACb,yBAAyB;AAAA,QACzB,aAAa;AAAA,MACf,CAAC;AAAA,MACD,gBAAY,mCAAY;AAAA,QACtB,cAAc;AAAA,QACd,aAAa;AAAA,QACb,yBAAyB;AAAA,QACzB,aAAa;AAAA,MACf,CAAC;AAAA,MACD,kBAAc,2CAAoB;AAAA,QAChC,cAAc;AAAA,QACd,yBAAyB;AAAA,MAC3B,CAAC;AAAA,IACH;AAAA,EACF,SAAS,OAAY;AACnB,UAAM,IAAI,MAAM,sCAAsC,MAAM,OAAO,EAAE;AAAA,EACvE;AACF;AAGA,IAAM,YAAY,CAAC,QAAgB;AACjC,SAAO,KAAK,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,MAAM,EAAE;AAC3E;AACA,IAAM,mBAAmB,OAAO,WAAmB;AACjD,QAAM,YAAY;AAClB,QAAM,YAAY;AAGlB,QAAM,cAAc,OACjB,QAAQ,WAAW,EAAE,EACrB,QAAQ,WAAW,EAAE,EACrB,QAAQ,OAAO,EAAE;AAGpB,QAAM,eAAe,KAAK,WAAW;AAGrC,QAAM,aAAa,IAAI,WAAW,aAAa,MAAM;AACrD,WAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,eAAW,CAAC,IAAI,aAAa,WAAW,CAAC;AAAA,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