@ai-sdk/google-vertex 5.0.98 → 5.0.99

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,283 +1,243 @@
1
- // src/anthropic/edge/google-vertex-anthropic-provider-edge.ts
2
- import { resolve } from "@ai-sdk/provider-utils";
3
-
4
- // src/edge/google-vertex-auth-edge.ts
5
- import {
6
- loadOptionalSetting,
7
- loadSetting,
8
- withUserAgentSuffix,
9
- getRuntimeEnvironmentUserAgent
10
- } from "@ai-sdk/provider-utils";
11
-
12
- // src/version.ts
13
- var VERSION = true ? "5.0.98" : "0.0.0-test";
14
-
15
- // src/edge/google-vertex-auth-edge.ts
16
- var loadCredentials = async () => {
17
- try {
18
- return {
19
- clientEmail: loadSetting({
20
- settingValue: void 0,
21
- settingName: "clientEmail",
22
- environmentVariableName: "GOOGLE_CLIENT_EMAIL",
23
- description: "Google client email"
24
- }),
25
- privateKey: loadSetting({
26
- settingValue: void 0,
27
- settingName: "privateKey",
28
- environmentVariableName: "GOOGLE_PRIVATE_KEY",
29
- description: "Google private key"
30
- }),
31
- privateKeyId: loadOptionalSetting({
32
- settingValue: void 0,
33
- environmentVariableName: "GOOGLE_PRIVATE_KEY_ID"
34
- })
35
- };
36
- } catch (error) {
37
- throw new Error(`Failed to load Google credentials: ${error.message}`);
38
- }
1
+ import { getRuntimeEnvironmentUserAgent, loadOptionalSetting, loadSetting, resolve, withUserAgentSuffix, withoutTrailingSlash } from "@ai-sdk/provider-utils";
2
+ import { NoSuchModelError } from "@ai-sdk/provider";
3
+ import { AnthropicLanguageModel, anthropicTools } from "@ai-sdk/anthropic/internal";
4
+ //#region src/version.ts
5
+ const VERSION = "5.0.99";
6
+ //#endregion
7
+ //#region src/edge/google-vertex-auth-edge.ts
8
+ const loadCredentials = async () => {
9
+ try {
10
+ return {
11
+ clientEmail: loadSetting({
12
+ settingValue: void 0,
13
+ settingName: "clientEmail",
14
+ environmentVariableName: "GOOGLE_CLIENT_EMAIL",
15
+ description: "Google client email"
16
+ }),
17
+ privateKey: loadSetting({
18
+ settingValue: void 0,
19
+ settingName: "privateKey",
20
+ environmentVariableName: "GOOGLE_PRIVATE_KEY",
21
+ description: "Google private key"
22
+ }),
23
+ privateKeyId: loadOptionalSetting({
24
+ settingValue: void 0,
25
+ environmentVariableName: "GOOGLE_PRIVATE_KEY_ID"
26
+ })
27
+ };
28
+ } catch (error) {
29
+ throw new Error(`Failed to load Google credentials: ${error.message}`);
30
+ }
39
31
  };
40
- var base64url = (str) => {
41
- return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
32
+ const base64url = (str) => {
33
+ return btoa(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
42
34
  };
43
- var importPrivateKey = async (pemKey) => {
44
- const pemHeader = "-----BEGIN PRIVATE KEY-----";
45
- const pemFooter = "-----END PRIVATE KEY-----";
46
- const pemContents = pemKey.replace(pemHeader, "").replace(pemFooter, "").replace(/\s/g, "");
47
- const binaryString = atob(pemContents);
48
- const binaryData = new Uint8Array(binaryString.length);
49
- for (let i = 0; i < binaryString.length; i++) {
50
- binaryData[i] = binaryString.charCodeAt(i);
51
- }
52
- return await crypto.subtle.importKey(
53
- "pkcs8",
54
- binaryData,
55
- { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },
56
- true,
57
- ["sign"]
58
- );
35
+ const importPrivateKey = async (pemKey) => {
36
+ const pemContents = pemKey.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").replace(/\s/g, "");
37
+ const binaryString = atob(pemContents);
38
+ const binaryData = new Uint8Array(binaryString.length);
39
+ for (let i = 0; i < binaryString.length; i++) binaryData[i] = binaryString.charCodeAt(i);
40
+ return await crypto.subtle.importKey("pkcs8", binaryData, {
41
+ name: "RSASSA-PKCS1-v1_5",
42
+ hash: "SHA-256"
43
+ }, true, ["sign"]);
59
44
  };
60
- var buildJwt = async (credentials) => {
61
- const now = Math.floor(Date.now() / 1e3);
62
- const header = {
63
- alg: "RS256",
64
- typ: "JWT"
65
- };
66
- if (credentials.privateKeyId) {
67
- header.kid = credentials.privateKeyId;
68
- }
69
- const payload = {
70
- iss: credentials.clientEmail,
71
- scope: "https://www.googleapis.com/auth/cloud-platform",
72
- aud: "https://oauth2.googleapis.com/token",
73
- exp: now + 3600,
74
- iat: now
75
- };
76
- const privateKey = await importPrivateKey(credentials.privateKey);
77
- const signingInput = `${base64url(JSON.stringify(header))}.${base64url(
78
- JSON.stringify(payload)
79
- )}`;
80
- const encoder = new TextEncoder();
81
- const data = encoder.encode(signingInput);
82
- const signature = await crypto.subtle.sign(
83
- "RSASSA-PKCS1-v1_5",
84
- privateKey,
85
- data
86
- );
87
- const signatureBase64 = base64url(
88
- String.fromCharCode(...new Uint8Array(signature))
89
- );
90
- return `${base64url(JSON.stringify(header))}.${base64url(
91
- JSON.stringify(payload)
92
- )}.${signatureBase64}`;
45
+ const buildJwt = async (credentials) => {
46
+ const now = Math.floor(Date.now() / 1e3);
47
+ const header = {
48
+ alg: "RS256",
49
+ typ: "JWT"
50
+ };
51
+ if (credentials.privateKeyId) header.kid = credentials.privateKeyId;
52
+ const payload = {
53
+ iss: credentials.clientEmail,
54
+ scope: "https://www.googleapis.com/auth/cloud-platform",
55
+ aud: "https://oauth2.googleapis.com/token",
56
+ exp: now + 3600,
57
+ iat: now
58
+ };
59
+ const privateKey = await importPrivateKey(credentials.privateKey);
60
+ const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`;
61
+ const data = new TextEncoder().encode(signingInput);
62
+ const signature = await crypto.subtle.sign("RSASSA-PKCS1-v1_5", privateKey, data);
63
+ const signatureBase64 = base64url(String.fromCharCode(...new Uint8Array(signature)));
64
+ return `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}.${signatureBase64}`;
93
65
  };
66
+ /**
67
+ * Generate an authentication token for Google Vertex AI in a manner compatible
68
+ * with the Edge runtime.
69
+ */
94
70
  async function generateAuthToken(credentials) {
95
- const creds = credentials || await loadCredentials();
96
- const jwt = await buildJwt(creds);
97
- const response = await fetch("https://oauth2.googleapis.com/token", {
98
- method: "POST",
99
- headers: withUserAgentSuffix(
100
- { "Content-Type": "application/x-www-form-urlencoded" },
101
- `ai-sdk-google-vertex/${VERSION}`,
102
- getRuntimeEnvironmentUserAgent()
103
- ),
104
- body: new URLSearchParams({
105
- grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
106
- assertion: jwt
107
- })
108
- });
109
- if (!response.ok) {
110
- throw new Error(`Token request failed: ${response.statusText}`);
111
- }
112
- const data = await response.json();
113
- return data.access_token;
71
+ const creds = credentials || await loadCredentials();
72
+ const jwt = await buildJwt(creds);
73
+ const response = await fetch("https://oauth2.googleapis.com/token", {
74
+ method: "POST",
75
+ headers: withUserAgentSuffix({ "Content-Type": "application/x-www-form-urlencoded" }, `ai-sdk-google-vertex/${VERSION}`, getRuntimeEnvironmentUserAgent()),
76
+ body: new URLSearchParams({
77
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
78
+ assertion: jwt
79
+ })
80
+ });
81
+ if (!response.ok) throw new Error(`Token request failed: ${response.statusText}`);
82
+ return (await response.json()).access_token;
114
83
  }
115
-
116
- // src/anthropic/google-vertex-anthropic-provider.ts
117
- import {
118
- NoSuchModelError
119
- } from "@ai-sdk/provider";
120
- import {
121
- loadOptionalSetting as loadOptionalSetting2,
122
- withoutTrailingSlash
123
- } from "@ai-sdk/provider-utils";
124
- import {
125
- anthropicTools,
126
- AnthropicLanguageModel
127
- } from "@ai-sdk/anthropic/internal";
128
- var googleVertexAnthropicTools = {
129
- /**
130
- * The bash tool enables Claude to execute shell commands in a persistent bash session,
131
- * allowing system operations, script execution, and command-line automation.
132
- *
133
- * Image results are supported.
134
- */
135
- bash_20241022: anthropicTools.bash_20241022,
136
- /**
137
- * The bash tool enables Claude to execute shell commands in a persistent bash session,
138
- * allowing system operations, script execution, and command-line automation.
139
- *
140
- * Image results are supported.
141
- */
142
- bash_20250124: anthropicTools.bash_20250124,
143
- /**
144
- * Claude can use an Anthropic-defined text editor tool to view and modify text files,
145
- * helping you debug, fix, and improve your code or other text documents.
146
- *
147
- * Supported models: Claude Sonnet 3.5
148
- */
149
- textEditor_20241022: anthropicTools.textEditor_20241022,
150
- /**
151
- * Claude can use an Anthropic-defined text editor tool to view and modify text files,
152
- * helping you debug, fix, and improve your code or other text documents.
153
- *
154
- * Supported models: Claude Sonnet 3.7
155
- */
156
- textEditor_20250124: anthropicTools.textEditor_20250124,
157
- /**
158
- * Claude can use an Anthropic-defined text editor tool to view and modify text files.
159
- * Note: This version does not support the "undo_edit" command.
160
- * @deprecated Use textEditor_20250728 instead
161
- */
162
- textEditor_20250429: anthropicTools.textEditor_20250429,
163
- /**
164
- * Claude can use an Anthropic-defined text editor tool to view and modify text files.
165
- * Note: This version does not support the "undo_edit" command and adds optional max_characters parameter.
166
- * Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1
167
- */
168
- textEditor_20250728: anthropicTools.textEditor_20250728,
169
- /**
170
- * Claude can interact with computer environments through the computer use tool, which
171
- * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
172
- *
173
- * Image results are supported.
174
- */
175
- computer_20241022: anthropicTools.computer_20241022,
176
- /**
177
- * Creates a web search tool that gives Claude direct access to real-time web content.
178
- */
179
- webSearch_20250305: anthropicTools.webSearch_20250305,
180
- /**
181
- * Creates a tool search tool that uses regex patterns to find tools.
182
- *
183
- * The tool search tool enables Claude to work with hundreds or thousands of tools
184
- * by dynamically discovering and loading them on-demand.
185
- *
186
- * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools
187
- * to mark them for deferred loading.
188
- */
189
- toolSearchRegex_20251119: anthropicTools.toolSearchRegex_20251119,
190
- /**
191
- * Creates a tool search tool that uses BM25 (natural language) to find tools.
192
- *
193
- * The tool search tool enables Claude to work with hundreds or thousands of tools
194
- * by dynamically discovering and loading them on-demand.
195
- *
196
- * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools
197
- * to mark them for deferred loading.
198
- */
199
- toolSearchBm25_20251119: anthropicTools.toolSearchBm25_20251119
84
+ //#endregion
85
+ //#region src/anthropic/google-vertex-anthropic-provider.ts
86
+ /**
87
+ * Tools supported by Google Vertex Anthropic.
88
+ * This is a subset of the full Anthropic tools - only these are recognized by the Vertex API.
89
+ */
90
+ const googleVertexAnthropicTools = {
91
+ /**
92
+ * The bash tool enables Claude to execute shell commands in a persistent bash session,
93
+ * allowing system operations, script execution, and command-line automation.
94
+ *
95
+ * Image results are supported.
96
+ */
97
+ bash_20241022: anthropicTools.bash_20241022,
98
+ /**
99
+ * The bash tool enables Claude to execute shell commands in a persistent bash session,
100
+ * allowing system operations, script execution, and command-line automation.
101
+ *
102
+ * Image results are supported.
103
+ */
104
+ bash_20250124: anthropicTools.bash_20250124,
105
+ /**
106
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
107
+ * helping you debug, fix, and improve your code or other text documents.
108
+ *
109
+ * Supported models: Claude Sonnet 3.5
110
+ */
111
+ textEditor_20241022: anthropicTools.textEditor_20241022,
112
+ /**
113
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files,
114
+ * helping you debug, fix, and improve your code or other text documents.
115
+ *
116
+ * Supported models: Claude Sonnet 3.7
117
+ */
118
+ textEditor_20250124: anthropicTools.textEditor_20250124,
119
+ /**
120
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files.
121
+ * Note: This version does not support the "undo_edit" command.
122
+ * @deprecated Use textEditor_20250728 instead
123
+ */
124
+ textEditor_20250429: anthropicTools.textEditor_20250429,
125
+ /**
126
+ * Claude can use an Anthropic-defined text editor tool to view and modify text files.
127
+ * Note: This version does not support the "undo_edit" command and adds optional max_characters parameter.
128
+ * Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1
129
+ */
130
+ textEditor_20250728: anthropicTools.textEditor_20250728,
131
+ /**
132
+ * Claude can interact with computer environments through the computer use tool, which
133
+ * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.
134
+ *
135
+ * Image results are supported.
136
+ */
137
+ computer_20241022: anthropicTools.computer_20241022,
138
+ /**
139
+ * Creates a web search tool that gives Claude direct access to real-time web content.
140
+ */
141
+ webSearch_20250305: anthropicTools.webSearch_20250305,
142
+ /**
143
+ * Creates a tool search tool that uses regex patterns to find tools.
144
+ *
145
+ * The tool search tool enables Claude to work with hundreds or thousands of tools
146
+ * by dynamically discovering and loading them on-demand.
147
+ *
148
+ * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools
149
+ * to mark them for deferred loading.
150
+ */
151
+ toolSearchRegex_20251119: anthropicTools.toolSearchRegex_20251119,
152
+ /**
153
+ * Creates a tool search tool that uses BM25 (natural language) to find tools.
154
+ *
155
+ * The tool search tool enables Claude to work with hundreds or thousands of tools
156
+ * by dynamically discovering and loading them on-demand.
157
+ *
158
+ * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools
159
+ * to mark them for deferred loading.
160
+ */
161
+ toolSearchBm25_20251119: anthropicTools.toolSearchBm25_20251119
200
162
  };
163
+ /**
164
+ * Create a Google Vertex Anthropic provider instance.
165
+ */
166
+ function createGoogleVertexAnthropic$1(options = {}) {
167
+ const getBaseURL = () => {
168
+ const location = loadOptionalSetting({
169
+ settingValue: options.location,
170
+ environmentVariableName: "GOOGLE_VERTEX_LOCATION"
171
+ });
172
+ const project = loadOptionalSetting({
173
+ settingValue: options.project,
174
+ environmentVariableName: "GOOGLE_VERTEX_PROJECT"
175
+ });
176
+ const getHost = () => {
177
+ if (location === "global") return "aiplatform.googleapis.com";
178
+ else if (location === "eu" || location === "us") return `aiplatform.${location}.rep.googleapis.com`;
179
+ else return `${location}-aiplatform.googleapis.com`;
180
+ };
181
+ return withoutTrailingSlash(options.baseURL) ?? `https://${getHost()}/v1/projects/${project}/locations/${location}/publishers/anthropic/models`;
182
+ };
183
+ const createChatModel = (modelId) => new AnthropicLanguageModel(modelId, {
184
+ provider: "googleVertex.anthropic.messages",
185
+ baseURL: getBaseURL(),
186
+ headers: options.headers ?? {},
187
+ fetch: options.fetch,
188
+ buildRequestUrl: (baseURL, isStreaming) => `${baseURL}/${modelId}:${isStreaming ? "streamRawPredict" : "rawPredict"}`,
189
+ transformRequestBody: (args) => {
190
+ const { model: _model, ...rest } = args;
191
+ return {
192
+ ...rest,
193
+ anthropic_version: "vertex-2023-10-16"
194
+ };
195
+ },
196
+ supportedUrls: () => ({}),
197
+ supportsNativeStructuredOutput: false,
198
+ supportsStrictTools: false
199
+ });
200
+ const provider = function(modelId) {
201
+ if (new.target) throw new Error("The Anthropic model function cannot be called with the new keyword.");
202
+ return createChatModel(modelId);
203
+ };
204
+ provider.specificationVersion = "v4";
205
+ provider.languageModel = createChatModel;
206
+ provider.chat = createChatModel;
207
+ provider.messages = createChatModel;
208
+ provider.embeddingModel = (modelId) => {
209
+ throw new NoSuchModelError({
210
+ modelId,
211
+ modelType: "embeddingModel"
212
+ });
213
+ };
214
+ provider.textEmbeddingModel = provider.embeddingModel;
215
+ provider.imageModel = (modelId) => {
216
+ throw new NoSuchModelError({
217
+ modelId,
218
+ modelType: "imageModel"
219
+ });
220
+ };
221
+ provider.tools = googleVertexAnthropicTools;
222
+ return provider;
223
+ }
224
+ //#endregion
225
+ //#region src/anthropic/edge/google-vertex-anthropic-provider-edge.ts
201
226
  function createGoogleVertexAnthropic(options = {}) {
202
- const getBaseURL = () => {
203
- const location = loadOptionalSetting2({
204
- settingValue: options.location,
205
- environmentVariableName: "GOOGLE_VERTEX_LOCATION"
206
- });
207
- const project = loadOptionalSetting2({
208
- settingValue: options.project,
209
- environmentVariableName: "GOOGLE_VERTEX_PROJECT"
210
- });
211
- const getHost = () => {
212
- if (location === "global") {
213
- return "aiplatform.googleapis.com";
214
- } else if (location === "eu" || location === "us") {
215
- return `aiplatform.${location}.rep.googleapis.com`;
216
- } else {
217
- return `${location}-aiplatform.googleapis.com`;
218
- }
219
- };
220
- return withoutTrailingSlash(options.baseURL) ?? `https://${getHost()}/v1/projects/${project}/locations/${location}/publishers/anthropic/models`;
221
- };
222
- const createChatModel = (modelId) => new AnthropicLanguageModel(modelId, {
223
- provider: "googleVertex.anthropic.messages",
224
- baseURL: getBaseURL(),
225
- headers: options.headers ?? {},
226
- fetch: options.fetch,
227
- buildRequestUrl: (baseURL, isStreaming) => `${baseURL}/${modelId}:${isStreaming ? "streamRawPredict" : "rawPredict"}`,
228
- transformRequestBody: (args) => {
229
- const { model: _model, ...rest } = args;
230
- return {
231
- ...rest,
232
- anthropic_version: "vertex-2023-10-16"
233
- };
234
- },
235
- // Google Vertex Anthropic doesn't support URL sources, force download and base64 conversion
236
- supportedUrls: () => ({}),
237
- // force the use of JSON tool fallback for structured outputs since beta header isn't supported
238
- supportsNativeStructuredOutput: false,
239
- // Vertex Anthropic doesn't support strict mode on tool definitions.
240
- supportsStrictTools: false
241
- });
242
- const provider = function(modelId) {
243
- if (new.target) {
244
- throw new Error(
245
- "The Anthropic model function cannot be called with the new keyword."
246
- );
247
- }
248
- return createChatModel(modelId);
249
- };
250
- provider.specificationVersion = "v4";
251
- provider.languageModel = createChatModel;
252
- provider.chat = createChatModel;
253
- provider.messages = createChatModel;
254
- provider.embeddingModel = (modelId) => {
255
- throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
256
- };
257
- provider.textEmbeddingModel = provider.embeddingModel;
258
- provider.imageModel = (modelId) => {
259
- throw new NoSuchModelError({ modelId, modelType: "imageModel" });
260
- };
261
- provider.tools = googleVertexAnthropicTools;
262
- return provider;
227
+ const generateAuthToken$1 = options.generateAuthToken ?? (() => generateAuthToken(options.googleCredentials));
228
+ return createGoogleVertexAnthropic$1({
229
+ ...options,
230
+ headers: async () => ({
231
+ Authorization: `Bearer ${await generateAuthToken$1()}`,
232
+ ...await resolve(options.headers)
233
+ })
234
+ });
263
235
  }
236
+ /**
237
+ * Default Google Vertex AI Anthropic provider instance.
238
+ */
239
+ const googleVertexAnthropic = createGoogleVertexAnthropic();
240
+ //#endregion
241
+ export { createGoogleVertexAnthropic, createGoogleVertexAnthropic as createVertexAnthropic, googleVertexAnthropic, googleVertexAnthropic as vertexAnthropic };
264
242
 
265
- // src/anthropic/edge/google-vertex-anthropic-provider-edge.ts
266
- function createGoogleVertexAnthropic2(options = {}) {
267
- const generateAuthToken2 = options.generateAuthToken ?? (() => generateAuthToken(options.googleCredentials));
268
- return createGoogleVertexAnthropic({
269
- ...options,
270
- headers: async () => ({
271
- Authorization: `Bearer ${await generateAuthToken2()}`,
272
- ...await resolve(options.headers)
273
- })
274
- });
275
- }
276
- var googleVertexAnthropic = createGoogleVertexAnthropic2();
277
- export {
278
- createGoogleVertexAnthropic2 as createGoogleVertexAnthropic,
279
- createGoogleVertexAnthropic2 as createVertexAnthropic,
280
- googleVertexAnthropic,
281
- googleVertexAnthropic as vertexAnthropic
282
- };
283
243
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/anthropic/edge/google-vertex-anthropic-provider-edge.ts","../../../src/edge/google-vertex-auth-edge.ts","../../../src/version.ts","../../../src/anthropic/google-vertex-anthropic-provider.ts"],"sourcesContent":["import { resolve } from '@ai-sdk/provider-utils';\nimport {\n generateAuthToken as defaultGenerateAuthToken,\n type GoogleCredentials,\n} from '../../edge/google-vertex-auth-edge';\nimport {\n createGoogleVertexAnthropic as createVertexAnthropicOriginal,\n type GoogleVertexAnthropicProvider,\n type GoogleVertexAnthropicProviderSettings as GoogleVertexAnthropicProviderSettingsOriginal,\n} from '../google-vertex-anthropic-provider';\nexport type { GoogleVertexAnthropicProvider };\n\nexport interface GoogleVertexAnthropicProviderSettings extends GoogleVertexAnthropicProviderSettingsOriginal {\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 * Optional. Override the Bearer token generator. Defaults to OAuth exchange\n * with `googleCredentials`.\n */\n generateAuthToken?: () => Promise<string>;\n}\n\nexport function createGoogleVertexAnthropic(\n options: GoogleVertexAnthropicProviderSettings = {},\n): GoogleVertexAnthropicProvider {\n const generateAuthToken =\n options.generateAuthToken ??\n (() => defaultGenerateAuthToken(options.googleCredentials));\n return createVertexAnthropicOriginal({\n ...options,\n headers: async () => ({\n Authorization: `Bearer ${await generateAuthToken()}`,\n ...(await resolve(options.headers)),\n }),\n });\n}\n\n/**\n * Default Google Vertex AI Anthropic provider instance.\n */\nexport const googleVertexAnthropic = createGoogleVertexAnthropic();\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 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}\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 ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n loadOptionalSetting,\n withoutTrailingSlash,\n type FetchFunction,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport {\n anthropicTools,\n AnthropicLanguageModel,\n} from '@ai-sdk/anthropic/internal';\nimport type { GoogleVertexAnthropicModelId } from './google-vertex-anthropic-options';\n\ntype GoogleVertexAnthropicTools = Pick<\n typeof anthropicTools,\n | 'bash_20241022'\n | 'bash_20250124'\n | 'textEditor_20241022'\n | 'textEditor_20250124'\n | 'textEditor_20250429'\n | 'textEditor_20250728'\n | 'computer_20241022'\n | 'webSearch_20250305'\n | 'toolSearchRegex_20251119'\n | 'toolSearchBm25_20251119'\n>;\n\n/**\n * Tools supported by Google Vertex Anthropic.\n * This is a subset of the full Anthropic tools - only these are recognized by the Vertex API.\n */\nexport const googleVertexAnthropicTools: GoogleVertexAnthropicTools = {\n /**\n * The bash tool enables Claude to execute shell commands in a persistent bash session,\n * allowing system operations, script execution, and command-line automation.\n *\n * Image results are supported.\n */\n bash_20241022: anthropicTools.bash_20241022,\n\n /**\n * The bash tool enables Claude to execute shell commands in a persistent bash session,\n * allowing system operations, script execution, and command-line automation.\n *\n * Image results are supported.\n */\n bash_20250124: anthropicTools.bash_20250124,\n\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents.\n *\n * Supported models: Claude Sonnet 3.5\n */\n textEditor_20241022: anthropicTools.textEditor_20241022,\n\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents.\n *\n * Supported models: Claude Sonnet 3.7\n */\n textEditor_20250124: anthropicTools.textEditor_20250124,\n\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files.\n * Note: This version does not support the \"undo_edit\" command.\n * @deprecated Use textEditor_20250728 instead\n */\n textEditor_20250429: anthropicTools.textEditor_20250429,\n\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files.\n * Note: This version does not support the \"undo_edit\" command and adds optional max_characters parameter.\n * Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1\n */\n textEditor_20250728: anthropicTools.textEditor_20250728,\n\n /**\n * Claude can interact with computer environments through the computer use tool, which\n * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * Image results are supported.\n */\n computer_20241022: anthropicTools.computer_20241022,\n\n /**\n * Creates a web search tool that gives Claude direct access to real-time web content.\n */\n webSearch_20250305: anthropicTools.webSearch_20250305,\n\n /**\n * Creates a tool search tool that uses regex patterns to find tools.\n *\n * The tool search tool enables Claude to work with hundreds or thousands of tools\n * by dynamically discovering and loading them on-demand.\n *\n * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools\n * to mark them for deferred loading.\n */\n toolSearchRegex_20251119: anthropicTools.toolSearchRegex_20251119,\n\n /**\n * Creates a tool search tool that uses BM25 (natural language) to find tools.\n *\n * The tool search tool enables Claude to work with hundreds or thousands of tools\n * by dynamically discovering and loading them on-demand.\n *\n * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools\n * to mark them for deferred loading.\n */\n toolSearchBm25_20251119: anthropicTools.toolSearchBm25_20251119,\n};\nexport interface GoogleVertexAnthropicProvider extends ProviderV4 {\n /**\n * Creates a model for text generation.\n */\n (modelId: GoogleVertexAnthropicModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation.\n */\n languageModel(modelId: GoogleVertexAnthropicModelId): LanguageModelV4;\n\n /**\n * Anthropic tools supported by Google Vertex.\n * Note: Only a subset of Anthropic tools are available on Vertex.\n * Supported tools: bash_20241022, bash_20250124, textEditor_20241022,\n * textEditor_20250124, textEditor_20250429, textEditor_20250728,\n * computer_20241022, webSearch_20250305, toolSearchRegex_20251119,\n * toolSearchBm25_20251119\n */\n tools: typeof googleVertexAnthropicTools;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface GoogleVertexAnthropicProviderSettings {\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 region. Defaults to the value of the `GOOGLE_VERTEX_LOCATION` environment variable.\n */\n location?: string;\n\n /**\n * Use a different URL prefix for API calls, e.g. to use proxy servers.\n * The default prefix is `https://api.anthropic.com/v1`.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\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 Anthropic provider instance.\n */\nexport function createGoogleVertexAnthropic(\n options: GoogleVertexAnthropicProviderSettings = {},\n): GoogleVertexAnthropicProvider {\n const getBaseURL = () => {\n const location = loadOptionalSetting({\n settingValue: options.location,\n environmentVariableName: 'GOOGLE_VERTEX_LOCATION',\n });\n const project = loadOptionalSetting({\n settingValue: options.project,\n environmentVariableName: 'GOOGLE_VERTEX_PROJECT',\n });\n\n const getHost = () => {\n if (location === 'global') {\n return 'aiplatform.googleapis.com';\n } else if (location === 'eu' || location === 'us') {\n return `aiplatform.${location}.rep.googleapis.com`;\n } else {\n return `${location}-aiplatform.googleapis.com`;\n }\n };\n\n return (\n withoutTrailingSlash(options.baseURL) ??\n `https://${getHost()}/v1/projects/${project}/locations/${location}/publishers/anthropic/models`\n );\n };\n\n const createChatModel = (modelId: GoogleVertexAnthropicModelId) =>\n new AnthropicLanguageModel(modelId, {\n provider: 'googleVertex.anthropic.messages',\n baseURL: getBaseURL(),\n headers: options.headers ?? {},\n fetch: options.fetch,\n\n buildRequestUrl: (baseURL, isStreaming) =>\n `${baseURL}/${modelId}:${\n isStreaming ? 'streamRawPredict' : 'rawPredict'\n }`,\n transformRequestBody: args => {\n // Remove model from args and add anthropic version\n const { model: _model, ...rest } = args;\n return {\n ...rest,\n anthropic_version: 'vertex-2023-10-16',\n };\n },\n // Google Vertex Anthropic doesn't support URL sources, force download and base64 conversion\n supportedUrls: () => ({}),\n // force the use of JSON tool fallback for structured outputs since beta header isn't supported\n supportsNativeStructuredOutput: false,\n // Vertex Anthropic doesn't support strict mode on tool definitions.\n supportsStrictTools: false,\n });\n\n const provider = function (modelId: GoogleVertexAnthropicModelId) {\n if (new.target) {\n throw new Error(\n 'The Anthropic 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.chat = createChatModel;\n provider.messages = createChatModel;\n\n provider.embeddingModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n provider.tools = googleVertexAnthropicTools;\n\n return provider;\n}\n"],"mappings":";AAAA,SAAS,eAAe;;;ACAxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACHA,IAAM,UACX,OACI,WACA;;;ADuBN,IAAM,kBAAkB,YAAwC;AAC9D,MAAI;AACF,WAAO;AAAA,MACL,aAAa,YAAY;AAAA,QACvB,cAAc;AAAA,QACd,aAAa;AAAA,QACb,yBAAyB;AAAA,QAC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AAA,EACF,CAAC;AACH;AAKO,IAAM,wBAAwBD,6BAA4B;","names":["loadOptionalSetting","createGoogleVertexAnthropic","generateAuthToken"]}
1
+ {"version":3,"file":"index.js","names":["createGoogleVertexAnthropic","generateAuthToken","defaultGenerateAuthToken","createVertexAnthropicOriginal"],"sources":["../../../src/version.ts","../../../src/edge/google-vertex-auth-edge.ts","../../../src/anthropic/google-vertex-anthropic-provider.ts","../../../src/anthropic/edge/google-vertex-anthropic-provider-edge.ts"],"sourcesContent":["// 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 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 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}\n","import {\n NoSuchModelError,\n type LanguageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n loadOptionalSetting,\n withoutTrailingSlash,\n type FetchFunction,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport {\n anthropicTools,\n AnthropicLanguageModel,\n} from '@ai-sdk/anthropic/internal';\nimport type { GoogleVertexAnthropicModelId } from './google-vertex-anthropic-options';\n\ntype GoogleVertexAnthropicTools = Pick<\n typeof anthropicTools,\n | 'bash_20241022'\n | 'bash_20250124'\n | 'textEditor_20241022'\n | 'textEditor_20250124'\n | 'textEditor_20250429'\n | 'textEditor_20250728'\n | 'computer_20241022'\n | 'webSearch_20250305'\n | 'toolSearchRegex_20251119'\n | 'toolSearchBm25_20251119'\n>;\n\n/**\n * Tools supported by Google Vertex Anthropic.\n * This is a subset of the full Anthropic tools - only these are recognized by the Vertex API.\n */\nexport const googleVertexAnthropicTools: GoogleVertexAnthropicTools = {\n /**\n * The bash tool enables Claude to execute shell commands in a persistent bash session,\n * allowing system operations, script execution, and command-line automation.\n *\n * Image results are supported.\n */\n bash_20241022: anthropicTools.bash_20241022,\n\n /**\n * The bash tool enables Claude to execute shell commands in a persistent bash session,\n * allowing system operations, script execution, and command-line automation.\n *\n * Image results are supported.\n */\n bash_20250124: anthropicTools.bash_20250124,\n\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents.\n *\n * Supported models: Claude Sonnet 3.5\n */\n textEditor_20241022: anthropicTools.textEditor_20241022,\n\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files,\n * helping you debug, fix, and improve your code or other text documents.\n *\n * Supported models: Claude Sonnet 3.7\n */\n textEditor_20250124: anthropicTools.textEditor_20250124,\n\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files.\n * Note: This version does not support the \"undo_edit\" command.\n * @deprecated Use textEditor_20250728 instead\n */\n textEditor_20250429: anthropicTools.textEditor_20250429,\n\n /**\n * Claude can use an Anthropic-defined text editor tool to view and modify text files.\n * Note: This version does not support the \"undo_edit\" command and adds optional max_characters parameter.\n * Supported models: Claude Sonnet 4, Opus 4, and Opus 4.1\n */\n textEditor_20250728: anthropicTools.textEditor_20250728,\n\n /**\n * Claude can interact with computer environments through the computer use tool, which\n * provides screenshot capabilities and mouse/keyboard control for autonomous desktop interaction.\n *\n * Image results are supported.\n */\n computer_20241022: anthropicTools.computer_20241022,\n\n /**\n * Creates a web search tool that gives Claude direct access to real-time web content.\n */\n webSearch_20250305: anthropicTools.webSearch_20250305,\n\n /**\n * Creates a tool search tool that uses regex patterns to find tools.\n *\n * The tool search tool enables Claude to work with hundreds or thousands of tools\n * by dynamically discovering and loading them on-demand.\n *\n * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools\n * to mark them for deferred loading.\n */\n toolSearchRegex_20251119: anthropicTools.toolSearchRegex_20251119,\n\n /**\n * Creates a tool search tool that uses BM25 (natural language) to find tools.\n *\n * The tool search tool enables Claude to work with hundreds or thousands of tools\n * by dynamically discovering and loading them on-demand.\n *\n * Use `providerOptions: { anthropic: { deferLoading: true } }` on other tools\n * to mark them for deferred loading.\n */\n toolSearchBm25_20251119: anthropicTools.toolSearchBm25_20251119,\n};\nexport interface GoogleVertexAnthropicProvider extends ProviderV4 {\n /**\n * Creates a model for text generation.\n */\n (modelId: GoogleVertexAnthropicModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation.\n */\n languageModel(modelId: GoogleVertexAnthropicModelId): LanguageModelV4;\n\n /**\n * Anthropic tools supported by Google Vertex.\n * Note: Only a subset of Anthropic tools are available on Vertex.\n * Supported tools: bash_20241022, bash_20250124, textEditor_20241022,\n * textEditor_20250124, textEditor_20250429, textEditor_20250728,\n * computer_20241022, webSearch_20250305, toolSearchRegex_20251119,\n * toolSearchBm25_20251119\n */\n tools: typeof googleVertexAnthropicTools;\n\n /**\n * @deprecated Use `embeddingModel` instead.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface GoogleVertexAnthropicProviderSettings {\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 region. Defaults to the value of the `GOOGLE_VERTEX_LOCATION` environment variable.\n */\n location?: string;\n\n /**\n * Use a different URL prefix for API calls, e.g. to use proxy servers.\n * The default prefix is `https://api.anthropic.com/v1`.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\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 Anthropic provider instance.\n */\nexport function createGoogleVertexAnthropic(\n options: GoogleVertexAnthropicProviderSettings = {},\n): GoogleVertexAnthropicProvider {\n const getBaseURL = () => {\n const location = loadOptionalSetting({\n settingValue: options.location,\n environmentVariableName: 'GOOGLE_VERTEX_LOCATION',\n });\n const project = loadOptionalSetting({\n settingValue: options.project,\n environmentVariableName: 'GOOGLE_VERTEX_PROJECT',\n });\n\n const getHost = () => {\n if (location === 'global') {\n return 'aiplatform.googleapis.com';\n } else if (location === 'eu' || location === 'us') {\n return `aiplatform.${location}.rep.googleapis.com`;\n } else {\n return `${location}-aiplatform.googleapis.com`;\n }\n };\n\n return (\n withoutTrailingSlash(options.baseURL) ??\n `https://${getHost()}/v1/projects/${project}/locations/${location}/publishers/anthropic/models`\n );\n };\n\n const createChatModel = (modelId: GoogleVertexAnthropicModelId) =>\n new AnthropicLanguageModel(modelId, {\n provider: 'googleVertex.anthropic.messages',\n baseURL: getBaseURL(),\n headers: options.headers ?? {},\n fetch: options.fetch,\n\n buildRequestUrl: (baseURL, isStreaming) =>\n `${baseURL}/${modelId}:${\n isStreaming ? 'streamRawPredict' : 'rawPredict'\n }`,\n transformRequestBody: args => {\n // Remove model from args and add anthropic version\n const { model: _model, ...rest } = args;\n return {\n ...rest,\n anthropic_version: 'vertex-2023-10-16',\n };\n },\n // Google Vertex Anthropic doesn't support URL sources, force download and base64 conversion\n supportedUrls: () => ({}),\n // force the use of JSON tool fallback for structured outputs since beta header isn't supported\n supportsNativeStructuredOutput: false,\n // Vertex Anthropic doesn't support strict mode on tool definitions.\n supportsStrictTools: false,\n });\n\n const provider = function (modelId: GoogleVertexAnthropicModelId) {\n if (new.target) {\n throw new Error(\n 'The Anthropic 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.chat = createChatModel;\n provider.messages = createChatModel;\n\n provider.embeddingModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'embeddingModel' });\n };\n provider.textEmbeddingModel = provider.embeddingModel;\n provider.imageModel = (modelId: string) => {\n throw new NoSuchModelError({ modelId, modelType: 'imageModel' });\n };\n\n provider.tools = googleVertexAnthropicTools;\n\n return provider;\n}\n","import { resolve } from '@ai-sdk/provider-utils';\nimport {\n generateAuthToken as defaultGenerateAuthToken,\n type GoogleCredentials,\n} from '../../edge/google-vertex-auth-edge';\nimport {\n createGoogleVertexAnthropic as createVertexAnthropicOriginal,\n type GoogleVertexAnthropicProvider,\n type GoogleVertexAnthropicProviderSettings as GoogleVertexAnthropicProviderSettingsOriginal,\n} from '../google-vertex-anthropic-provider';\nexport type { GoogleVertexAnthropicProvider };\n\nexport interface GoogleVertexAnthropicProviderSettings extends GoogleVertexAnthropicProviderSettingsOriginal {\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 * Optional. Override the Bearer token generator. Defaults to OAuth exchange\n * with `googleCredentials`.\n */\n generateAuthToken?: () => Promise<string>;\n}\n\nexport function createGoogleVertexAnthropic(\n options: GoogleVertexAnthropicProviderSettings = {},\n): GoogleVertexAnthropicProvider {\n const generateAuthToken =\n options.generateAuthToken ??\n (() => defaultGenerateAuthToken(options.googleCredentials));\n return createVertexAnthropicOriginal({\n ...options,\n headers: async () => ({\n Authorization: `Bearer ${await generateAuthToken()}`,\n ...(await resolve(options.headers)),\n }),\n });\n}\n\n/**\n * Default Google Vertex AI Anthropic provider instance.\n */\nexport const googleVertexAnthropic = createGoogleVertexAnthropic();\n"],"mappings":";;;;AAEA,MAAa,UAAA;;;AC0Bb,MAAM,kBAAkB,YAAwC;CAC9D,IAAI;EACF,OAAO;GACL,aAAa,YAAY;IACvB,cAAc,KAAA;IACd,aAAa;IACb,yBAAyB;IACzB,aAAa;GACf,CAAC;GACD,YAAY,YAAY;IACtB,cAAc,KAAA;IACd,aAAa;IACb,yBAAyB;IACzB,aAAa;GACf,CAAC;GACD,cAAc,oBAAoB;IAChC,cAAc,KAAA;IACd,yBAAyB;GAC3B,CAAC;EACH;CACF,SAAS,OAAY;EACnB,MAAM,IAAI,MAAM,sCAAsC,MAAM,SAAS;CACvE;AACF;AAGA,MAAM,aAAa,QAAgB;CACjC,OAAO,KAAK,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,MAAM,EAAE;AAC3E;AACA,MAAM,mBAAmB,OAAO,WAAmB;CAKjD,MAAM,cAAc,OACjB,QAAQ,+BAAW,EAAE,CAAC,CACtB,QAAQ,6BAAW,E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