@ai-sdk/amazon-bedrock 5.0.128 → 5.0.129
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 +16 -0
- package/dist/anthropic/index.d.ts +2 -1
- package/dist/anthropic/index.d.ts.map +1 -1
- package/dist/anthropic/index.js +8 -6
- package/dist/anthropic/index.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -6
- package/dist/index.js.map +1 -1
- package/dist/mantle/index.cjs +7 -5
- package/dist/mantle/index.cjs.map +1 -1
- package/dist/mantle/index.d.cts +3 -2
- package/dist/mantle/index.d.cts.map +1 -1
- package/dist/mantle/index.d.ts +3 -2
- package/dist/mantle/index.d.ts.map +1 -1
- package/dist/mantle/index.js +9 -7
- package/dist/mantle/index.js.map +1 -1
- package/docs/08-amazon-bedrock.mdx +18 -3
- package/package.json +5 -5
- package/src/amazon-bedrock-provider.ts +11 -6
- package/src/amazon-bedrock-sigv4-fetch.ts +15 -2
- package/src/anthropic/amazon-bedrock-anthropic-provider.ts +10 -6
- package/src/mantle/bedrock-mantle-provider.ts +11 -6
package/dist/mantle/index.cjs
CHANGED
|
@@ -4,7 +4,7 @@ let _ai_sdk_provider = require("@ai-sdk/provider");
|
|
|
4
4
|
let _ai_sdk_provider_utils = require("@ai-sdk/provider-utils");
|
|
5
5
|
let aws4fetch = require("aws4fetch");
|
|
6
6
|
//#region src/version.ts
|
|
7
|
-
const VERSION = "5.0.
|
|
7
|
+
const VERSION = "5.0.129";
|
|
8
8
|
//#endregion
|
|
9
9
|
//#region src/amazon-bedrock-sigv4-fetch.ts
|
|
10
10
|
/**
|
|
@@ -73,7 +73,9 @@ function createApiKeyFetchFunction(apiKey, fetch) {
|
|
|
73
73
|
const effectiveFetch = fetch ?? globalThis.fetch;
|
|
74
74
|
const originalHeaders = (0, _ai_sdk_provider_utils.normalizeHeaders)(init?.headers);
|
|
75
75
|
const headersWithUserAgent = (0, _ai_sdk_provider_utils.withUserAgentSuffix)(originalHeaders, `ai-sdk-amazon-bedrock/${VERSION}`, (0, _ai_sdk_provider_utils.getRuntimeEnvironmentUserAgent)());
|
|
76
|
-
const
|
|
76
|
+
const resolvedApiKey = await (0, _ai_sdk_provider_utils.resolve)(apiKey);
|
|
77
|
+
if (typeof apiKey !== "string" && (typeof resolvedApiKey !== "string" || !resolvedApiKey.trim())) throw new _ai_sdk_provider.LoadAPIKeyError({ message: "Amazon Bedrock API key must be a non-empty string." });
|
|
78
|
+
const finalHeaders = (0, _ai_sdk_provider_utils.combineHeaders)(headersWithUserAgent, { Authorization: `Bearer ${typeof apiKey === "string" ? resolvedApiKey : resolvedApiKey.trim()}` });
|
|
77
79
|
return effectiveFetch(input, {
|
|
78
80
|
...init,
|
|
79
81
|
headers: finalHeaders
|
|
@@ -88,11 +90,11 @@ function createApiKeyFetchFunction(apiKey, fetch) {
|
|
|
88
90
|
* only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).
|
|
89
91
|
*/
|
|
90
92
|
function createBedrockMantle(options = {}) {
|
|
91
|
-
const rawApiKey = (0, _ai_sdk_provider_utils.loadOptionalSetting)({
|
|
93
|
+
const rawApiKey = typeof options.apiKey === "string" || options.apiKey == null ? (0, _ai_sdk_provider_utils.loadOptionalSetting)({
|
|
92
94
|
settingValue: options.apiKey,
|
|
93
95
|
environmentVariableName: "AWS_BEARER_TOKEN_BEDROCK"
|
|
94
|
-
});
|
|
95
|
-
const apiKey =
|
|
96
|
+
}) : options.apiKey;
|
|
97
|
+
const apiKey = typeof rawApiKey === "string" ? rawApiKey.trim() || void 0 : rawApiKey;
|
|
96
98
|
const fetchFunction = apiKey ? createApiKeyFetchFunction(apiKey, options.fetch) : createSigV4FetchFunction(async () => {
|
|
97
99
|
const region = (0, _ai_sdk_provider_utils.loadSetting)({
|
|
98
100
|
settingValue: options.region,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["combineHeaders","normalizeHeaders","withUserAgentSuffix","getRuntimeEnvironmentUserAgent","AwsV4Signer","loadOptionalSetting","loadSetting","withoutTrailingSlash","isValidHostnamePart","InvalidArgumentError","withUserAgentSuffix","OpenAIChatLanguageModel","OpenAIResponsesLanguageModel","NoSuchModelError"],"sources":["../../src/version.ts","../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-provider.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 combineHeaders,\n normalizeHeaders,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { AwsV4Signer } from 'aws4fetch';\nimport { VERSION } from './version';\n\nexport interface AmazonBedrockCredentials {\n region: string;\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n}\n\n/**\n * Creates a fetch function that applies AWS Signature Version 4 signing.\n *\n * @param getCredentials - Function that returns the AWS credentials to use when signing.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @param service - The AWS service name to use for SigV4 signing scope. Defaults to 'bedrock'.\n * @returns A FetchFunction that signs requests before passing them to the underlying fetch.\n */\nexport function createSigV4FetchFunction(\n getCredentials: () =>\n | AmazonBedrockCredentials\n | PromiseLike<AmazonBedrockCredentials>,\n fetch?: FetchFunction,\n service: string = 'bedrock',\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const request = input instanceof Request ? input : undefined;\n const originalHeaders = combineHeaders(\n normalizeHeaders(request?.headers),\n normalizeHeaders(init?.headers),\n );\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n let effectiveBody: BodyInit | undefined = init?.body ?? undefined;\n if (effectiveBody === undefined && request && request.body !== null) {\n try {\n effectiveBody = await request.clone().text();\n } catch {}\n }\n\n const effectiveMethod = init?.method ?? request?.method;\n\n if (effectiveMethod?.toUpperCase() !== 'POST' || !effectiveBody) {\n return effectiveFetch(input, {\n ...init,\n headers: headersWithUserAgent as HeadersInit,\n });\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n\n const body = prepareBodyString(effectiveBody);\n const credentials = await getCredentials();\n const signer = new AwsV4Signer({\n url,\n method: 'POST',\n headers: Object.entries(headersWithUserAgent).filter(([, value]) =>\n isAscii(value),\n ),\n body,\n region: credentials.region,\n accessKeyId: credentials.accessKeyId,\n secretAccessKey: credentials.secretAccessKey,\n sessionToken: credentials.sessionToken,\n service,\n });\n\n const signingResult = await signer.sign();\n const signedHeaders = normalizeHeaders(signingResult.headers);\n\n // Use the combined headers directly as HeadersInit\n const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);\n\n return effectiveFetch(input, {\n ...init,\n body,\n headers: combinedHeaders as HeadersInit,\n });\n };\n}\n\nfunction prepareBodyString(body: BodyInit | undefined): string {\n if (typeof body === 'string') {\n return body;\n } else if (body instanceof Uint8Array) {\n return new TextDecoder().decode(body);\n } else if (body instanceof ArrayBuffer) {\n return new TextDecoder().decode(new Uint8Array(body));\n } else {\n return JSON.stringify(body);\n }\n}\n\nfunction isAscii(value: string): boolean {\n return !/[\\u0080-\\uffff]/.test(value);\n}\n\n/**\n * Creates a fetch function that applies Bearer token authentication.\n *\n * @param apiKey - The API key to use for Bearer token authentication.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @returns A FetchFunction that adds Authorization header with Bearer token to requests.\n */\nexport function createApiKeyFetchFunction(\n apiKey: string,\n fetch?: FetchFunction,\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const originalHeaders = normalizeHeaders(init?.headers);\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const finalHeaders = combineHeaders(headersWithUserAgent, {\n Authorization: `Bearer ${apiKey}`,\n });\n\n return effectiveFetch(input, {\n ...init,\n headers: finalHeaders as HeadersInit,\n });\n };\n}\n","import {\n OpenAIChatLanguageModel,\n OpenAIResponsesLanguageModel,\n} from '@ai-sdk/openai/internal';\nimport {\n InvalidArgumentError,\n NoSuchModelError,\n type LanguageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n isValidHostnamePart,\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport {\n createApiKeyFetchFunction,\n createSigV4FetchFunction,\n type AmazonBedrockCredentials,\n} from '../amazon-bedrock-sigv4-fetch';\nimport type {\n BedrockMantleChatModelId,\n BedrockMantleResponsesModelId,\n} from './bedrock-mantle-options';\nimport { VERSION } from '../version';\n\nexport interface BedrockMantleProvider extends ProviderV4 {\n /**\n * Creates a model for text generation using the Chat Completions API.\n * Chat Completions has the broadest model support on Mantle.\n */\n (modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n languageModel(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n chat(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Responses API.\n * Not all Mantle models support this API. Notably, gpt-oss-safeguard models\n * are Chat-only.\n */\n responses(modelId: BedrockMantleResponsesModelId): LanguageModelV4;\n\n /**\n * @deprecated Mantle does not support embedding models.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface BedrockMantleProviderSettings {\n /**\n * The AWS region to use for the Bedrock Mantle endpoint. Defaults to the value of the\n * `AWS_REGION` environment variable.\n */\n region?: string;\n\n /**\n * API key for authenticating requests using Bearer token authentication.\n * When provided, this will be used instead of AWS SigV4 authentication.\n * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.\n */\n apiKey?: string;\n\n /**\n * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the\n * `AWS_ACCESS_KEY_ID` environment variable.\n */\n accessKeyId?: string;\n\n /**\n * The AWS secret access key to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SECRET_ACCESS_KEY` environment variable.\n */\n secretAccessKey?: string;\n\n /**\n * The AWS session token to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SESSION_TOKEN` environment variable.\n */\n sessionToken?: string;\n\n /**\n * Base URL for the Bedrock Mantle API calls.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: 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 * The AWS credential provider to use for SigV4 authentication to get dynamic\n * credentials similar to the AWS SDK. Setting a provider here will cause its\n * credential values to be used instead of the `accessKeyId`, `secretAccessKey`,\n * and `sessionToken` settings.\n */\n credentialProvider?: () => PromiseLike<\n Omit<AmazonBedrockCredentials, 'region'>\n >;\n}\n\n/**\n * Create an Amazon Bedrock Mantle provider instance.\n * This provider uses the OpenAI-compatible Mantle API for models that are\n * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).\n */\nexport function createBedrockMantle(\n options: BedrockMantleProviderSettings = {},\n): BedrockMantleProvider {\n // Check for API key authentication first\n const rawApiKey = loadOptionalSetting({\n settingValue: options.apiKey,\n environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',\n });\n\n // Only use API key if it's a non-empty, non-whitespace string\n const apiKey =\n rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : undefined;\n\n // Use API key authentication if available, otherwise fall back to SigV4\n const fetchFunction = apiKey\n ? createApiKeyFetchFunction(apiKey, options.fetch)\n : createSigV4FetchFunction(\n async () => {\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n\n // If a credential provider is provided, use it to get the credentials.\n if (options.credentialProvider) {\n try {\n return {\n ...(await options.credentialProvider()),\n region,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `AWS credential provider failed: ${errorMessage}. ` +\n 'Please ensure your credential provider returns valid AWS credentials ' +\n 'with accessKeyId and secretAccessKey properties.',\n );\n }\n }\n\n try {\n return {\n region,\n accessKeyId: loadSetting({\n settingValue: options.accessKeyId,\n settingName: 'accessKeyId',\n environmentVariableName: 'AWS_ACCESS_KEY_ID',\n description: 'AWS access key ID',\n }),\n secretAccessKey: loadSetting({\n settingValue: options.secretAccessKey,\n settingName: 'secretAccessKey',\n environmentVariableName: 'AWS_SECRET_ACCESS_KEY',\n description: 'AWS secret access key',\n }),\n sessionToken: loadOptionalSetting({\n settingValue: options.sessionToken,\n environmentVariableName: 'AWS_SESSION_TOKEN',\n }),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n if (\n errorMessage.includes('AWS_ACCESS_KEY_ID') ||\n errorMessage.includes('accessKeyId')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires AWS credentials. Please provide either:\\n' +\n '1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables\\n' +\n '2. Provide accessKeyId and secretAccessKey in options\\n' +\n '3. Use a credentialProvider function\\n' +\n '4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n if (\n errorMessage.includes('AWS_SECRET_ACCESS_KEY') ||\n errorMessage.includes('secretAccessKey')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. ' +\n 'Please ensure both credentials are provided.\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n throw error;\n }\n },\n options.fetch,\n 'bedrock-mantle',\n );\n\n const getBaseURL = (modelId: string): string => {\n const baseURL = withoutTrailingSlash(options.baseURL);\n if (baseURL != null) {\n return baseURL;\n }\n\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n if (!isValidHostnamePart(region)) {\n throw new InvalidArgumentError({\n argument: 'region',\n message:\n 'Invalid AWS region. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return `https://bedrock-mantle.${region}.api.aws/${\n // Mantle serves these models under its separate OpenAI route.\n /^(?:openai\\.gpt-(?!oss-)|google\\.gemma-4|xai\\.)/.test(modelId)\n ? 'openai/v1'\n : 'v1'\n }`;\n };\n\n const getHeaders = (): Record<string, string | undefined> =>\n withUserAgentSuffix(\n options.headers ?? {},\n `ai-sdk-amazon-bedrock/${VERSION}`,\n );\n\n const url = ({ path, modelId }: { path: string; modelId: string }): string =>\n `${getBaseURL(modelId)}${path}`;\n\n const createChatModel = (modelId: BedrockMantleChatModelId) =>\n new OpenAIChatLanguageModel(modelId, {\n provider: 'bedrock-mantle.chat',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n });\n\n const createResponsesModel = (modelId: BedrockMantleResponsesModelId) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'bedrock-mantle.responses',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n supportsWebSearchSourcesInclude: false,\n });\n\n const provider = function (modelId: BedrockMantleChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Bedrock Mantle 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.responses = createResponsesModel;\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 return provider as BedrockMantleProvider;\n}\n\n/**\n * Default Bedrock Mantle provider instance.\n */\nexport const bedrockMantle = createBedrockMantle();\n"],"mappings":";;;;;;AAEA,MAAa,UAAA;;;;;;;;;;;ACuBb,SAAgB,yBACd,gBAGA,OACA,UAAkB,WACH;CACf,OAAO,OACL,OACA,SACsB;EAEtB,MAAM,iBAAiB,SAAS,WAAW;EAC3C,MAAM,UAAU,iBAAiB,UAAU,QAAQ,KAAA;EACnD,MAAM,mBAAA,GAAkBA,uBAAAA,eAAAA,EAAAA,GACtBC,uBAAAA,iBAAAA,CAAiB,SAAS,OAAO,IAAA,GACjCA,uBAAAA,iBAAAA,CAAiB,MAAM,OAAO,CAChC;EACA,MAAM,wBAAA,GAAuBC,uBAAAA,oBAAAA,CAC3B,iBACA,yBAAyB,YAAA,GACzBC,uBAAAA,+BAAAA,CAA+B,CACjC;EAEA,IAAI,gBAAsC,MAAM,QAAQ,KAAA;EACxD,IAAI,kBAAkB,KAAA,KAAa,WAAW,QAAQ,SAAS,MAC7D,IAAI;GACF,gBAAgB,MAAM,QAAQ,MAAM,CAAC,CAAC,KAAK;EAC7C,QAAQ,CAAC;EAKX,KAFwB,MAAM,UAAU,SAAS,OAAA,EAE5B,YAAY,MAAM,UAAU,CAAC,eAChD,OAAO,eAAe,OAAO;GAC3B,GAAG;GACH,SAAS;EACX,CAAC;EAGH,MAAM,MACJ,OAAO,UAAU,WACb,QACA,iBAAiB,MACf,MAAM,OACN,MAAM;EAEd,MAAM,OAAO,kBAAkB,aAAa;EAC5C,MAAM,cAAc,MAAM,eAAe;EAezC,MAAM,gBAAgB,MAAM,IAdTC,UAAAA,YAAY;GAC7B;GACA,QA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oBAAoB"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["combineHeaders","normalizeHeaders","withUserAgentSuffix","getRuntimeEnvironmentUserAgent","AwsV4Signer","resolve","LoadAPIKeyError","loadOptionalSetting","loadSetting","withoutTrailingSlash","isValidHostnamePart","InvalidArgumentError","withUserAgentSuffix","OpenAIChatLanguageModel","OpenAIResponsesLanguageModel","NoSuchModelError"],"sources":["../../src/version.ts","../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-provider.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 { LoadAPIKeyError } from '@ai-sdk/provider';\nimport {\n combineHeaders,\n resolve,\n type Resolvable,\n normalizeHeaders,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { AwsV4Signer } from 'aws4fetch';\nimport { VERSION } from './version';\n\nexport interface AmazonBedrockCredentials {\n region: string;\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n}\n\n/**\n * Creates a fetch function that applies AWS Signature Version 4 signing.\n *\n * @param getCredentials - Function that returns the AWS credentials to use when signing.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @param service - The AWS service name to use for SigV4 signing scope. Defaults to 'bedrock'.\n * @returns A FetchFunction that signs requests before passing them to the underlying fetch.\n */\nexport function createSigV4FetchFunction(\n getCredentials: () =>\n | AmazonBedrockCredentials\n | PromiseLike<AmazonBedrockCredentials>,\n fetch?: FetchFunction,\n service: string = 'bedrock',\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const request = input instanceof Request ? input : undefined;\n const originalHeaders = combineHeaders(\n normalizeHeaders(request?.headers),\n normalizeHeaders(init?.headers),\n );\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n let effectiveBody: BodyInit | undefined = init?.body ?? undefined;\n if (effectiveBody === undefined && request && request.body !== null) {\n try {\n effectiveBody = await request.clone().text();\n } catch {}\n }\n\n const effectiveMethod = init?.method ?? request?.method;\n\n if (effectiveMethod?.toUpperCase() !== 'POST' || !effectiveBody) {\n return effectiveFetch(input, {\n ...init,\n headers: headersWithUserAgent as HeadersInit,\n });\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n\n const body = prepareBodyString(effectiveBody);\n const credentials = await getCredentials();\n const signer = new AwsV4Signer({\n url,\n method: 'POST',\n headers: Object.entries(headersWithUserAgent).filter(([, value]) =>\n isAscii(value),\n ),\n body,\n region: credentials.region,\n accessKeyId: credentials.accessKeyId,\n secretAccessKey: credentials.secretAccessKey,\n sessionToken: credentials.sessionToken,\n service,\n });\n\n const signingResult = await signer.sign();\n const signedHeaders = normalizeHeaders(signingResult.headers);\n\n // Use the combined headers directly as HeadersInit\n const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);\n\n return effectiveFetch(input, {\n ...init,\n body,\n headers: combinedHeaders as HeadersInit,\n });\n };\n}\n\nfunction prepareBodyString(body: BodyInit | undefined): string {\n if (typeof body === 'string') {\n return body;\n } else if (body instanceof Uint8Array) {\n return new TextDecoder().decode(body);\n } else if (body instanceof ArrayBuffer) {\n return new TextDecoder().decode(new Uint8Array(body));\n } else {\n return JSON.stringify(body);\n }\n}\n\nfunction isAscii(value: string): boolean {\n return !/[\\u0080-\\uffff]/.test(value);\n}\n\n/**\n * Creates a fetch function that applies Bearer token authentication.\n *\n * @param apiKey - The API key to use for Bearer token authentication.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @returns A FetchFunction that adds Authorization header with Bearer token to requests.\n */\nexport function createApiKeyFetchFunction(\n apiKey: Resolvable<string>,\n fetch?: FetchFunction,\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const originalHeaders = normalizeHeaders(init?.headers);\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const resolvedApiKey = await resolve(apiKey);\n if (\n typeof apiKey !== 'string' &&\n (typeof resolvedApiKey !== 'string' || !resolvedApiKey.trim())\n ) {\n throw new LoadAPIKeyError({\n message: 'Amazon Bedrock API key must be a non-empty string.',\n });\n }\n\n const finalHeaders = combineHeaders(headersWithUserAgent, {\n Authorization: `Bearer ${typeof apiKey === 'string' ? resolvedApiKey : resolvedApiKey.trim()}`,\n });\n\n return effectiveFetch(input, {\n ...init,\n headers: finalHeaders as HeadersInit,\n });\n };\n}\n","import {\n OpenAIChatLanguageModel,\n OpenAIResponsesLanguageModel,\n} from '@ai-sdk/openai/internal';\nimport {\n InvalidArgumentError,\n NoSuchModelError,\n type LanguageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n isValidHostnamePart,\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport {\n createApiKeyFetchFunction,\n createSigV4FetchFunction,\n type AmazonBedrockCredentials,\n} from '../amazon-bedrock-sigv4-fetch';\nimport type {\n BedrockMantleChatModelId,\n BedrockMantleResponsesModelId,\n} from './bedrock-mantle-options';\nimport { VERSION } from '../version';\n\nexport interface BedrockMantleProvider extends ProviderV4 {\n /**\n * Creates a model for text generation using the Chat Completions API.\n * Chat Completions has the broadest model support on Mantle.\n */\n (modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n languageModel(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n chat(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Responses API.\n * Not all Mantle models support this API. Notably, gpt-oss-safeguard models\n * are Chat-only.\n */\n responses(modelId: BedrockMantleResponsesModelId): LanguageModelV4;\n\n /**\n * @deprecated Mantle does not support embedding models.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface BedrockMantleProviderSettings {\n /**\n * The AWS region to use for the Bedrock Mantle endpoint. Defaults to the value of the\n * `AWS_REGION` environment variable.\n */\n region?: string;\n\n /**\n * API key for authenticating requests using Bearer token authentication.\n * A callback is resolved before each request and must return a non-empty key.\n * When provided, this will be used instead of AWS SigV4 authentication.\n * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.\n */\n apiKey?: Resolvable<string>;\n\n /**\n * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the\n * `AWS_ACCESS_KEY_ID` environment variable.\n */\n accessKeyId?: string;\n\n /**\n * The AWS secret access key to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SECRET_ACCESS_KEY` environment variable.\n */\n secretAccessKey?: string;\n\n /**\n * The AWS session token to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SESSION_TOKEN` environment variable.\n */\n sessionToken?: string;\n\n /**\n * Base URL for the Bedrock Mantle API calls.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: 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 * The AWS credential provider to use for SigV4 authentication to get dynamic\n * credentials similar to the AWS SDK. Setting a provider here will cause its\n * credential values to be used instead of the `accessKeyId`, `secretAccessKey`,\n * and `sessionToken` settings.\n */\n credentialProvider?: () => PromiseLike<\n Omit<AmazonBedrockCredentials, 'region'>\n >;\n}\n\n/**\n * Create an Amazon Bedrock Mantle provider instance.\n * This provider uses the OpenAI-compatible Mantle API for models that are\n * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).\n */\nexport function createBedrockMantle(\n options: BedrockMantleProviderSettings = {},\n): BedrockMantleProvider {\n // Check for API key authentication first\n const rawApiKey =\n typeof options.apiKey === 'string' || options.apiKey == null\n ? loadOptionalSetting({\n settingValue: options.apiKey,\n environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',\n })\n : options.apiKey;\n\n // Only use API key if it's a non-empty, non-whitespace string\n const apiKey =\n typeof rawApiKey === 'string' ? rawApiKey.trim() || undefined : rawApiKey;\n\n // Use API key authentication if available, otherwise fall back to SigV4\n const fetchFunction = apiKey\n ? createApiKeyFetchFunction(apiKey, options.fetch)\n : createSigV4FetchFunction(\n async () => {\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n\n // If a credential provider is provided, use it to get the credentials.\n if (options.credentialProvider) {\n try {\n return {\n ...(await options.credentialProvider()),\n region,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `AWS credential provider failed: ${errorMessage}. ` +\n 'Please ensure your credential provider returns valid AWS credentials ' +\n 'with accessKeyId and secretAccessKey properties.',\n );\n }\n }\n\n try {\n return {\n region,\n accessKeyId: loadSetting({\n settingValue: options.accessKeyId,\n settingName: 'accessKeyId',\n environmentVariableName: 'AWS_ACCESS_KEY_ID',\n description: 'AWS access key ID',\n }),\n secretAccessKey: loadSetting({\n settingValue: options.secretAccessKey,\n settingName: 'secretAccessKey',\n environmentVariableName: 'AWS_SECRET_ACCESS_KEY',\n description: 'AWS secret access key',\n }),\n sessionToken: loadOptionalSetting({\n settingValue: options.sessionToken,\n environmentVariableName: 'AWS_SESSION_TOKEN',\n }),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n if (\n errorMessage.includes('AWS_ACCESS_KEY_ID') ||\n errorMessage.includes('accessKeyId')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires AWS credentials. Please provide either:\\n' +\n '1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables\\n' +\n '2. Provide accessKeyId and secretAccessKey in options\\n' +\n '3. Use a credentialProvider function\\n' +\n '4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n if (\n errorMessage.includes('AWS_SECRET_ACCESS_KEY') ||\n errorMessage.includes('secretAccessKey')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. ' +\n 'Please ensure both credentials are provided.\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n throw error;\n }\n },\n options.fetch,\n 'bedrock-mantle',\n );\n\n const getBaseURL = (modelId: string): string => {\n const baseURL = withoutTrailingSlash(options.baseURL);\n if (baseURL != null) {\n return baseURL;\n }\n\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n if (!isValidHostnamePart(region)) {\n throw new InvalidArgumentError({\n argument: 'region',\n message:\n 'Invalid AWS region. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return `https://bedrock-mantle.${region}.api.aws/${\n // Mantle serves these models under its separate OpenAI route.\n /^(?:openai\\.gpt-(?!oss-)|google\\.gemma-4|xai\\.)/.test(modelId)\n ? 'openai/v1'\n : 'v1'\n }`;\n };\n\n const getHeaders = (): Record<string, string | undefined> =>\n withUserAgentSuffix(\n options.headers ?? {},\n `ai-sdk-amazon-bedrock/${VERSION}`,\n );\n\n const url = ({ path, modelId }: { path: string; modelId: string }): string =>\n `${getBaseURL(modelId)}${path}`;\n\n const createChatModel = (modelId: BedrockMantleChatModelId) =>\n new OpenAIChatLanguageModel(modelId, {\n provider: 'bedrock-mantle.chat',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n });\n\n const createResponsesModel = (modelId: BedrockMantleResponsesModelId) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'bedrock-mantle.responses',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n supportsWebSearchSourcesInclude: false,\n });\n\n const provider = function (modelId: BedrockMantleChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Bedrock Mantle 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.responses = createResponsesModel;\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 return provider as BedrockMantleProvider;\n}\n\n/**\n * Default Bedrock Mantle provider instance.\n */\nexport const bedrockMantle = createBedrockMantle();\n"],"mappings":";;;;;;AAEA,MAAa,UAAA;;;;;;;;;;;AC0Bb,SAAgB,yBACd,gBAGA,OACA,UAAkB,WACH;CACf,OAAO,OACL,OACA,SACsB;EAEtB,MAAM,iBAAiB,SAAS,WAAW;EAC3C,MAAM,UAAU,iBAAiB,UAAU,QAAQ,KAAA;EACnD,MAAM,mBAAA,GAAkBA,uBAAAA,eAAAA,EAAAA,GACtBC,uBAAAA,iBAAAA,CAAiB,SAAS,OAAO,IAAA,GACjCA,uBAAAA,iBAAAA,CAAiB,MAAM,OAAO,CAChC;EACA,MAAM,wBAAA,GAAuBC,uBAAAA,oBAAAA,CAC3B,iBACA,yBAAyB,YAAA,GACzBC,uBAAAA,+BAAAA,CAA+B,CACjC;EAEA,IAAI,gBAAsC,MAAM,QAAQ,KAAA;EACxD,IAAI,kBAAkB,KAAA,KAAa,WAAW,QAAQ,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AAI;CAE3B,MAAM,mBAAmB,YACvB,IAAIC,wBAAAA,wBAAwB,SAAS;EACnC,UAAU;EACV;EACA,SAAS;EACT,OAAO;CACT,CAAC;CAEH,MAAM,wBAAwB,YAC5B,IAAIC,wBAAAA,6BAA6B,SAAS;EACxC,UAAU;EACV;EACA,SAAS;EACT,OAAO;EACP,iCAAiC;CACnC,CAAC;CAEH,MAAM,WAAW,SAAU,SAAmC;EAC5D,IAAI,YACF,MAAM,IAAI,MACR,0EACF;EAGF,OAAO,gBAAgB,OAAO;CAChC;CAEA,SAAS,uBAAuB;CAChC,SAAS,gBAAgB;CACzB,SAAS,OAAO;CAChB,SAAS,YAAY;CAErB,SAAS,kBAAkB,YAAoB;EAC7C,MAAM,IAAIC,iBAAAA,iBAAiB;GAAE;GAAS,WAAW;EAAiB,CAAC;CACrE;CACA,SAAS,qBAAqB,SAAS;CACvC,SAAS,cAAc,YAAoB;EACzC,MAAM,IAAIA,iBAAAA,iBAAiB;GAAE;GAAS,WAAW;EAAa,CAAC;CACjE;CAEA,OAAO;AACT;;;;AAKA,MAAa,gBAAgB,oBAAoB"}
|
package/dist/mantle/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { LanguageModelV4, ProviderV4 } from "@ai-sdk/provider";
|
|
2
|
-
import { FetchFunction } from "@ai-sdk/provider-utils";
|
|
2
|
+
import { FetchFunction, Resolvable } from "@ai-sdk/provider-utils";
|
|
3
3
|
//#region src/amazon-bedrock-sigv4-fetch.d.ts
|
|
4
4
|
interface AmazonBedrockCredentials {
|
|
5
5
|
region: string;
|
|
@@ -47,10 +47,11 @@ interface BedrockMantleProviderSettings {
|
|
|
47
47
|
region?: string;
|
|
48
48
|
/**
|
|
49
49
|
* API key for authenticating requests using Bearer token authentication.
|
|
50
|
+
* A callback is resolved before each request and must return a non-empty key.
|
|
50
51
|
* When provided, this will be used instead of AWS SigV4 authentication.
|
|
51
52
|
* Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
|
|
52
53
|
*/
|
|
53
|
-
apiKey?: string
|
|
54
|
+
apiKey?: Resolvable<string>;
|
|
54
55
|
/**
|
|
55
56
|
* The AWS access key ID to use for SigV4 authentication. Defaults to the value of the
|
|
56
57
|
* `AWS_ACCESS_KEY_ID` environment variable.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-options.ts","../../src/mantle/bedrock-mantle-provider.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-options.ts","../../src/mantle/bedrock-mantle-provider.ts"],"mappings":";;;UAaiB;EACf;EACA;EACA;EACA;;;;KCjBU;KAOA;KAKA,uBACR,2BACA;;;UCgBa,8BAA8B;;;;;GAK5C,SAAS,2BAA2B;;;;EAKrC,cAAc,SAAS,2BAA2B;;;;EAKlD,KAAK,SAAS,2BAA2B;;;;;;EAOzC,UAAU,SAAS,gCAAgC;;;;EAKnD,mBAAmB;;UAGJ;;;;;EAKf;;;;;;;EAQA,SAAS;;;;;EAMT;;;;;EAMA;;;;;EAMA;;;;EAKA;;;;EAKA,UAAU;;;;;EAMV,QAAQ;;;;;;;EAQR,2BAA2B,YACzB,KAAK;;;;;;;wBASO,oBACd,UAAS,gCACR;;;;qBAoLU,eAAa"}
|
package/dist/mantle/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { LanguageModelV4, ProviderV4 } from "@ai-sdk/provider";
|
|
2
|
-
import { FetchFunction } from "@ai-sdk/provider-utils";
|
|
2
|
+
import { FetchFunction, Resolvable } from "@ai-sdk/provider-utils";
|
|
3
3
|
//#region src/amazon-bedrock-sigv4-fetch.d.ts
|
|
4
4
|
interface AmazonBedrockCredentials {
|
|
5
5
|
region: string;
|
|
@@ -47,10 +47,11 @@ interface BedrockMantleProviderSettings {
|
|
|
47
47
|
region?: string;
|
|
48
48
|
/**
|
|
49
49
|
* API key for authenticating requests using Bearer token authentication.
|
|
50
|
+
* A callback is resolved before each request and must return a non-empty key.
|
|
50
51
|
* When provided, this will be used instead of AWS SigV4 authentication.
|
|
51
52
|
* Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
|
|
52
53
|
*/
|
|
53
|
-
apiKey?: string
|
|
54
|
+
apiKey?: Resolvable<string>;
|
|
54
55
|
/**
|
|
55
56
|
* The AWS access key ID to use for SigV4 authentication. Defaults to the value of the
|
|
56
57
|
* `AWS_ACCESS_KEY_ID` environment variable.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-options.ts","../../src/mantle/bedrock-mantle-provider.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-options.ts","../../src/mantle/bedrock-mantle-provider.ts"],"mappings":";;;UAaiB;EACf;EACA;EACA;EACA;;;;KCjBU;KAOA;KAKA,uBACR,2BACA;;;UCgBa,8BAA8B;;;;;GAK5C,SAAS,2BAA2B;;;;EAKrC,cAAc,SAAS,2BAA2B;;;;EAKlD,KAAK,SAAS,2BAA2B;;;;;;EAOzC,UAAU,SAAS,gCAAgC;;;;EAKnD,mBAAmB;;UAGJ;;;;;EAKf;;;;;;;EAQA,SAAS;;;;;EAMT;;;;;EAMA;;;;;EAMA;;;;EAKA;;;;EAKA,UAAU;;;;;EAMV,QAAQ;;;;;;;EAQR,2BAA2B,YACzB,KAAK;;;;;;;wBASO,oBACd,UAAS,gCACR;;;;qBAoLU,eAAa"}
|
package/dist/mantle/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { OpenAIChatLanguageModel, OpenAIResponsesLanguageModel } from "@ai-sdk/openai/internal";
|
|
2
|
-
import { InvalidArgumentError, NoSuchModelError } from "@ai-sdk/provider";
|
|
3
|
-
import { combineHeaders, getRuntimeEnvironmentUserAgent, isValidHostnamePart, loadOptionalSetting, loadSetting, normalizeHeaders, withUserAgentSuffix, withoutTrailingSlash } from "@ai-sdk/provider-utils";
|
|
2
|
+
import { InvalidArgumentError, LoadAPIKeyError, NoSuchModelError } from "@ai-sdk/provider";
|
|
3
|
+
import { combineHeaders, getRuntimeEnvironmentUserAgent, isValidHostnamePart, loadOptionalSetting, loadSetting, normalizeHeaders, resolve, withUserAgentSuffix, withoutTrailingSlash } from "@ai-sdk/provider-utils";
|
|
4
4
|
import { AwsV4Signer } from "aws4fetch";
|
|
5
5
|
//#region src/version.ts
|
|
6
|
-
const VERSION = "5.0.
|
|
6
|
+
const VERSION = "5.0.129";
|
|
7
7
|
//#endregion
|
|
8
8
|
//#region src/amazon-bedrock-sigv4-fetch.ts
|
|
9
9
|
/**
|
|
@@ -72,7 +72,9 @@ function createApiKeyFetchFunction(apiKey, fetch) {
|
|
|
72
72
|
const effectiveFetch = fetch ?? globalThis.fetch;
|
|
73
73
|
const originalHeaders = normalizeHeaders(init?.headers);
|
|
74
74
|
const headersWithUserAgent = withUserAgentSuffix(originalHeaders, `ai-sdk-amazon-bedrock/${VERSION}`, getRuntimeEnvironmentUserAgent());
|
|
75
|
-
const
|
|
75
|
+
const resolvedApiKey = await resolve(apiKey);
|
|
76
|
+
if (typeof apiKey !== "string" && (typeof resolvedApiKey !== "string" || !resolvedApiKey.trim())) throw new LoadAPIKeyError({ message: "Amazon Bedrock API key must be a non-empty string." });
|
|
77
|
+
const finalHeaders = combineHeaders(headersWithUserAgent, { Authorization: `Bearer ${typeof apiKey === "string" ? resolvedApiKey : resolvedApiKey.trim()}` });
|
|
76
78
|
return effectiveFetch(input, {
|
|
77
79
|
...init,
|
|
78
80
|
headers: finalHeaders
|
|
@@ -87,11 +89,11 @@ function createApiKeyFetchFunction(apiKey, fetch) {
|
|
|
87
89
|
* only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).
|
|
88
90
|
*/
|
|
89
91
|
function createBedrockMantle(options = {}) {
|
|
90
|
-
const rawApiKey = loadOptionalSetting({
|
|
92
|
+
const rawApiKey = typeof options.apiKey === "string" || options.apiKey == null ? loadOptionalSetting({
|
|
91
93
|
settingValue: options.apiKey,
|
|
92
94
|
environmentVariableName: "AWS_BEARER_TOKEN_BEDROCK"
|
|
93
|
-
});
|
|
94
|
-
const apiKey =
|
|
95
|
+
}) : options.apiKey;
|
|
96
|
+
const apiKey = typeof rawApiKey === "string" ? rawApiKey.trim() || void 0 : rawApiKey;
|
|
95
97
|
const fetchFunction = apiKey ? createApiKeyFetchFunction(apiKey, options.fetch) : createSigV4FetchFunction(async () => {
|
|
96
98
|
const region = loadSetting({
|
|
97
99
|
settingValue: options.region,
|
package/dist/mantle/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/version.ts","../../src/amazon-bedrock-sigv4-fetch.ts","../../src/mantle/bedrock-mantle-provider.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 combineHeaders,\n normalizeHeaders,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { AwsV4Signer } from 'aws4fetch';\nimport { VERSION } from './version';\n\nexport interface AmazonBedrockCredentials {\n region: string;\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n}\n\n/**\n * Creates a fetch function that applies AWS Signature Version 4 signing.\n *\n * @param getCredentials - Function that returns the AWS credentials to use when signing.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @param service - The AWS service name to use for SigV4 signing scope. Defaults to 'bedrock'.\n * @returns A FetchFunction that signs requests before passing them to the underlying fetch.\n */\nexport function createSigV4FetchFunction(\n getCredentials: () =>\n | AmazonBedrockCredentials\n | PromiseLike<AmazonBedrockCredentials>,\n fetch?: FetchFunction,\n service: string = 'bedrock',\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const request = input instanceof Request ? input : undefined;\n const originalHeaders = combineHeaders(\n normalizeHeaders(request?.headers),\n normalizeHeaders(init?.headers),\n );\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n let effectiveBody: BodyInit | undefined = init?.body ?? undefined;\n if (effectiveBody === undefined && request && request.body !== null) {\n try {\n effectiveBody = await request.clone().text();\n } catch {}\n }\n\n const effectiveMethod = init?.method ?? request?.method;\n\n if (effectiveMethod?.toUpperCase() !== 'POST' || !effectiveBody) {\n return effectiveFetch(input, {\n ...init,\n headers: headersWithUserAgent as HeadersInit,\n });\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n\n const body = prepareBodyString(effectiveBody);\n const credentials = await getCredentials();\n const signer = new AwsV4Signer({\n url,\n method: 'POST',\n headers: Object.entries(headersWithUserAgent).filter(([, value]) =>\n isAscii(value),\n ),\n body,\n region: credentials.region,\n accessKeyId: credentials.accessKeyId,\n secretAccessKey: credentials.secretAccessKey,\n sessionToken: credentials.sessionToken,\n service,\n });\n\n const signingResult = await signer.sign();\n const signedHeaders = normalizeHeaders(signingResult.headers);\n\n // Use the combined headers directly as HeadersInit\n const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);\n\n return effectiveFetch(input, {\n ...init,\n body,\n headers: combinedHeaders as HeadersInit,\n });\n };\n}\n\nfunction prepareBodyString(body: BodyInit | undefined): string {\n if (typeof body === 'string') {\n return body;\n } else if (body instanceof Uint8Array) {\n return new TextDecoder().decode(body);\n } else if (body instanceof ArrayBuffer) {\n return new TextDecoder().decode(new Uint8Array(body));\n } else {\n return JSON.stringify(body);\n }\n}\n\nfunction isAscii(value: string): boolean {\n return !/[\\u0080-\\uffff]/.test(value);\n}\n\n/**\n * Creates a fetch function that applies Bearer token authentication.\n *\n * @param apiKey - The API key to use for Bearer token authentication.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @returns A FetchFunction that adds Authorization header with Bearer token to requests.\n */\nexport function createApiKeyFetchFunction(\n apiKey: string,\n fetch?: FetchFunction,\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const originalHeaders = normalizeHeaders(init?.headers);\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const finalHeaders = combineHeaders(headersWithUserAgent, {\n Authorization: `Bearer ${apiKey}`,\n });\n\n return effectiveFetch(input, {\n ...init,\n headers: finalHeaders as HeadersInit,\n });\n };\n}\n","import {\n OpenAIChatLanguageModel,\n OpenAIResponsesLanguageModel,\n} from '@ai-sdk/openai/internal';\nimport {\n InvalidArgumentError,\n NoSuchModelError,\n type LanguageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n isValidHostnamePart,\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport {\n createApiKeyFetchFunction,\n createSigV4FetchFunction,\n type AmazonBedrockCredentials,\n} from '../amazon-bedrock-sigv4-fetch';\nimport type {\n BedrockMantleChatModelId,\n BedrockMantleResponsesModelId,\n} from './bedrock-mantle-options';\nimport { VERSION } from '../version';\n\nexport interface BedrockMantleProvider extends ProviderV4 {\n /**\n * Creates a model for text generation using the Chat Completions API.\n * Chat Completions has the broadest model support on Mantle.\n */\n (modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n languageModel(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n chat(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Responses API.\n * Not all Mantle models support this API. Notably, gpt-oss-safeguard models\n * are Chat-only.\n */\n responses(modelId: BedrockMantleResponsesModelId): LanguageModelV4;\n\n /**\n * @deprecated Mantle does not support embedding models.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface BedrockMantleProviderSettings {\n /**\n * The AWS region to use for the Bedrock Mantle endpoint. Defaults to the value of the\n * `AWS_REGION` environment variable.\n */\n region?: string;\n\n /**\n * API key for authenticating requests using Bearer token authentication.\n * When provided, this will be used instead of AWS SigV4 authentication.\n * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.\n */\n apiKey?: string;\n\n /**\n * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the\n * `AWS_ACCESS_KEY_ID` environment variable.\n */\n accessKeyId?: string;\n\n /**\n * The AWS secret access key to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SECRET_ACCESS_KEY` environment variable.\n */\n secretAccessKey?: string;\n\n /**\n * The AWS session token to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SESSION_TOKEN` environment variable.\n */\n sessionToken?: string;\n\n /**\n * Base URL for the Bedrock Mantle API calls.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: 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 * The AWS credential provider to use for SigV4 authentication to get dynamic\n * credentials similar to the AWS SDK. Setting a provider here will cause its\n * credential values to be used instead of the `accessKeyId`, `secretAccessKey`,\n * and `sessionToken` settings.\n */\n credentialProvider?: () => PromiseLike<\n Omit<AmazonBedrockCredentials, 'region'>\n >;\n}\n\n/**\n * Create an Amazon Bedrock Mantle provider instance.\n * This provider uses the OpenAI-compatible Mantle API for models that are\n * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).\n */\nexport function createBedrockMantle(\n options: BedrockMantleProviderSettings = {},\n): BedrockMantleProvider {\n // Check for API key authentication first\n const rawApiKey = loadOptionalSetting({\n settingValue: options.apiKey,\n environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',\n });\n\n // Only use API key if it's a non-empty, non-whitespace string\n const apiKey =\n rawApiKey && rawApiKey.trim().length > 0 ? rawApiKey.trim() : undefined;\n\n // Use API key authentication if available, otherwise fall back to SigV4\n const fetchFunction = apiKey\n ? createApiKeyFetchFunction(apiKey, options.fetch)\n : createSigV4FetchFunction(\n async () => {\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n\n // If a credential provider is provided, use it to get the credentials.\n if (options.credentialProvider) {\n try {\n return {\n ...(await options.credentialProvider()),\n region,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `AWS credential provider failed: ${errorMessage}. ` +\n 'Please ensure your credential provider returns valid AWS credentials ' +\n 'with accessKeyId and secretAccessKey properties.',\n );\n }\n }\n\n try {\n return {\n region,\n accessKeyId: loadSetting({\n settingValue: options.accessKeyId,\n settingName: 'accessKeyId',\n environmentVariableName: 'AWS_ACCESS_KEY_ID',\n description: 'AWS access key ID',\n }),\n secretAccessKey: loadSetting({\n settingValue: options.secretAccessKey,\n settingName: 'secretAccessKey',\n environmentVariableName: 'AWS_SECRET_ACCESS_KEY',\n description: 'AWS secret access key',\n }),\n sessionToken: loadOptionalSetting({\n settingValue: options.sessionToken,\n environmentVariableName: 'AWS_SESSION_TOKEN',\n }),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n if (\n errorMessage.includes('AWS_ACCESS_KEY_ID') ||\n errorMessage.includes('accessKeyId')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires AWS credentials. Please provide either:\\n' +\n '1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables\\n' +\n '2. Provide accessKeyId and secretAccessKey in options\\n' +\n '3. Use a credentialProvider function\\n' +\n '4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n if (\n errorMessage.includes('AWS_SECRET_ACCESS_KEY') ||\n errorMessage.includes('secretAccessKey')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. ' +\n 'Please ensure both credentials are provided.\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n throw error;\n }\n },\n options.fetch,\n 'bedrock-mantle',\n );\n\n const getBaseURL = (modelId: string): string => {\n const baseURL = withoutTrailingSlash(options.baseURL);\n if (baseURL != null) {\n return baseURL;\n }\n\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n if (!isValidHostnamePart(region)) {\n throw new InvalidArgumentError({\n argument: 'region',\n message:\n 'Invalid AWS region. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return `https://bedrock-mantle.${region}.api.aws/${\n // Mantle serves these models under its separate OpenAI route.\n /^(?:openai\\.gpt-(?!oss-)|google\\.gemma-4|xai\\.)/.test(modelId)\n ? 'openai/v1'\n : 'v1'\n }`;\n };\n\n const getHeaders = (): Record<string, string | undefined> =>\n withUserAgentSuffix(\n options.headers ?? {},\n `ai-sdk-amazon-bedrock/${VERSION}`,\n );\n\n const url = ({ path, modelId }: { path: string; modelId: string }): string =>\n `${getBaseURL(modelId)}${path}`;\n\n const createChatModel = (modelId: BedrockMantleChatModelId) =>\n new OpenAIChatLanguageModel(modelId, {\n provider: 'bedrock-mantle.chat',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n });\n\n const createResponsesModel = (modelId: BedrockMantleResponsesModelId) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'bedrock-mantle.responses',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n supportsWebSearchSourcesInclude: false,\n });\n\n const provider = function (modelId: BedrockMantleChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Bedrock Mantle 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.responses = createResponsesModel;\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 return provider as BedrockMantleProvider;\n}\n\n/**\n * Default Bedrock Mantle provider instance.\n */\nexport const bedrockMantle = createBedrockMantle();\n"],"mappings":";;;;;AAEA,MAAa,UAAA;;;;;;;;;;;ACuBb,SAAgB,yBACd,gBAGA,OACA,UAAkB,WACH;CACf,OAAO,OACL,OACA,SACsB;EAEtB,MAAM,iBAAiB,SAAS,WAAW;EAC3C,MAAM,UAAU,iBAAiB,UAAU,QAAQ,KAAA;EACnD,MAAM,kBAAkB,eACtB,iBAAiB,SAAS,OAAO,GACjC,iBAAiB,MAAM,OAAO,CAChC;EACA,MAAM,uBAAuB,oBAC3B,iBACA,yBAAyB,WACzB,+BAA+B,CACjC;EAEA,IAAI,gBAAsC,MAAM,QAAQ,KAAA;EACxD,IAAI,kBAAkB,KAAA,KAAa,WAAW,QAAQ,SAAS,MAC7D,IAAI;GACF,gBAAgB,MAAM,QAAQ,MAAM,CAAC,CAAC,KAAK;EAC7C,QAAQ,CAAC;EAKX,KAF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fetch.ts","../../src/mantle/bedrock-mantle-provider.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 { LoadAPIKeyError } from '@ai-sdk/provider';\nimport {\n combineHeaders,\n resolve,\n type Resolvable,\n normalizeHeaders,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n type FetchFunction,\n} from '@ai-sdk/provider-utils';\nimport { AwsV4Signer } from 'aws4fetch';\nimport { VERSION } from './version';\n\nexport interface AmazonBedrockCredentials {\n region: string;\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n}\n\n/**\n * Creates a fetch function that applies AWS Signature Version 4 signing.\n *\n * @param getCredentials - Function that returns the AWS credentials to use when signing.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @param service - The AWS service name to use for SigV4 signing scope. Defaults to 'bedrock'.\n * @returns A FetchFunction that signs requests before passing them to the underlying fetch.\n */\nexport function createSigV4FetchFunction(\n getCredentials: () =>\n | AmazonBedrockCredentials\n | PromiseLike<AmazonBedrockCredentials>,\n fetch?: FetchFunction,\n service: string = 'bedrock',\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const request = input instanceof Request ? input : undefined;\n const originalHeaders = combineHeaders(\n normalizeHeaders(request?.headers),\n normalizeHeaders(init?.headers),\n );\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n let effectiveBody: BodyInit | undefined = init?.body ?? undefined;\n if (effectiveBody === undefined && request && request.body !== null) {\n try {\n effectiveBody = await request.clone().text();\n } catch {}\n }\n\n const effectiveMethod = init?.method ?? request?.method;\n\n if (effectiveMethod?.toUpperCase() !== 'POST' || !effectiveBody) {\n return effectiveFetch(input, {\n ...init,\n headers: headersWithUserAgent as HeadersInit,\n });\n }\n\n const url =\n typeof input === 'string'\n ? input\n : input instanceof URL\n ? input.href\n : input.url;\n\n const body = prepareBodyString(effectiveBody);\n const credentials = await getCredentials();\n const signer = new AwsV4Signer({\n url,\n method: 'POST',\n headers: Object.entries(headersWithUserAgent).filter(([, value]) =>\n isAscii(value),\n ),\n body,\n region: credentials.region,\n accessKeyId: credentials.accessKeyId,\n secretAccessKey: credentials.secretAccessKey,\n sessionToken: credentials.sessionToken,\n service,\n });\n\n const signingResult = await signer.sign();\n const signedHeaders = normalizeHeaders(signingResult.headers);\n\n // Use the combined headers directly as HeadersInit\n const combinedHeaders = combineHeaders(headersWithUserAgent, signedHeaders);\n\n return effectiveFetch(input, {\n ...init,\n body,\n headers: combinedHeaders as HeadersInit,\n });\n };\n}\n\nfunction prepareBodyString(body: BodyInit | undefined): string {\n if (typeof body === 'string') {\n return body;\n } else if (body instanceof Uint8Array) {\n return new TextDecoder().decode(body);\n } else if (body instanceof ArrayBuffer) {\n return new TextDecoder().decode(new Uint8Array(body));\n } else {\n return JSON.stringify(body);\n }\n}\n\nfunction isAscii(value: string): boolean {\n return !/[\\u0080-\\uffff]/.test(value);\n}\n\n/**\n * Creates a fetch function that applies Bearer token authentication.\n *\n * @param apiKey - The API key to use for Bearer token authentication.\n * @param fetch - Optional original fetch implementation to wrap. Defaults to global fetch.\n * @returns A FetchFunction that adds Authorization header with Bearer token to requests.\n */\nexport function createApiKeyFetchFunction(\n apiKey: Resolvable<string>,\n fetch?: FetchFunction,\n): FetchFunction {\n return async (\n input: RequestInfo | URL,\n init?: RequestInit,\n ): Promise<Response> => {\n // avoid caching globalThis.fetch in case it is patched by other libraries\n const effectiveFetch = fetch ?? globalThis.fetch;\n const originalHeaders = normalizeHeaders(init?.headers);\n const headersWithUserAgent = withUserAgentSuffix(\n originalHeaders,\n `ai-sdk-amazon-bedrock/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const resolvedApiKey = await resolve(apiKey);\n if (\n typeof apiKey !== 'string' &&\n (typeof resolvedApiKey !== 'string' || !resolvedApiKey.trim())\n ) {\n throw new LoadAPIKeyError({\n message: 'Amazon Bedrock API key must be a non-empty string.',\n });\n }\n\n const finalHeaders = combineHeaders(headersWithUserAgent, {\n Authorization: `Bearer ${typeof apiKey === 'string' ? resolvedApiKey : resolvedApiKey.trim()}`,\n });\n\n return effectiveFetch(input, {\n ...init,\n headers: finalHeaders as HeadersInit,\n });\n };\n}\n","import {\n OpenAIChatLanguageModel,\n OpenAIResponsesLanguageModel,\n} from '@ai-sdk/openai/internal';\nimport {\n InvalidArgumentError,\n NoSuchModelError,\n type LanguageModelV4,\n type ProviderV4,\n} from '@ai-sdk/provider';\nimport {\n isValidHostnamePart,\n loadOptionalSetting,\n loadSetting,\n withoutTrailingSlash,\n withUserAgentSuffix,\n type FetchFunction,\n type Resolvable,\n} from '@ai-sdk/provider-utils';\nimport {\n createApiKeyFetchFunction,\n createSigV4FetchFunction,\n type AmazonBedrockCredentials,\n} from '../amazon-bedrock-sigv4-fetch';\nimport type {\n BedrockMantleChatModelId,\n BedrockMantleResponsesModelId,\n} from './bedrock-mantle-options';\nimport { VERSION } from '../version';\n\nexport interface BedrockMantleProvider extends ProviderV4 {\n /**\n * Creates a model for text generation using the Chat Completions API.\n * Chat Completions has the broadest model support on Mantle.\n */\n (modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n languageModel(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Chat Completions API.\n */\n chat(modelId: BedrockMantleChatModelId): LanguageModelV4;\n\n /**\n * Creates a model for text generation using the Responses API.\n * Not all Mantle models support this API. Notably, gpt-oss-safeguard models\n * are Chat-only.\n */\n responses(modelId: BedrockMantleResponsesModelId): LanguageModelV4;\n\n /**\n * @deprecated Mantle does not support embedding models.\n */\n textEmbeddingModel(modelId: string): never;\n}\n\nexport interface BedrockMantleProviderSettings {\n /**\n * The AWS region to use for the Bedrock Mantle endpoint. Defaults to the value of the\n * `AWS_REGION` environment variable.\n */\n region?: string;\n\n /**\n * API key for authenticating requests using Bearer token authentication.\n * A callback is resolved before each request and must return a non-empty key.\n * When provided, this will be used instead of AWS SigV4 authentication.\n * Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.\n */\n apiKey?: Resolvable<string>;\n\n /**\n * The AWS access key ID to use for SigV4 authentication. Defaults to the value of the\n * `AWS_ACCESS_KEY_ID` environment variable.\n */\n accessKeyId?: string;\n\n /**\n * The AWS secret access key to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SECRET_ACCESS_KEY` environment variable.\n */\n secretAccessKey?: string;\n\n /**\n * The AWS session token to use for SigV4 authentication. Defaults to the value of the\n * `AWS_SESSION_TOKEN` environment variable.\n */\n sessionToken?: string;\n\n /**\n * Base URL for the Bedrock Mantle API calls.\n */\n baseURL?: string;\n\n /**\n * Custom headers to include in the requests.\n */\n headers?: 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 * The AWS credential provider to use for SigV4 authentication to get dynamic\n * credentials similar to the AWS SDK. Setting a provider here will cause its\n * credential values to be used instead of the `accessKeyId`, `secretAccessKey`,\n * and `sessionToken` settings.\n */\n credentialProvider?: () => PromiseLike<\n Omit<AmazonBedrockCredentials, 'region'>\n >;\n}\n\n/**\n * Create an Amazon Bedrock Mantle provider instance.\n * This provider uses the OpenAI-compatible Mantle API for models that are\n * only available through the Mantle endpoint (e.g. openai.gpt-oss-20b).\n */\nexport function createBedrockMantle(\n options: BedrockMantleProviderSettings = {},\n): BedrockMantleProvider {\n // Check for API key authentication first\n const rawApiKey =\n typeof options.apiKey === 'string' || options.apiKey == null\n ? loadOptionalSetting({\n settingValue: options.apiKey,\n environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',\n })\n : options.apiKey;\n\n // Only use API key if it's a non-empty, non-whitespace string\n const apiKey =\n typeof rawApiKey === 'string' ? rawApiKey.trim() || undefined : rawApiKey;\n\n // Use API key authentication if available, otherwise fall back to SigV4\n const fetchFunction = apiKey\n ? createApiKeyFetchFunction(apiKey, options.fetch)\n : createSigV4FetchFunction(\n async () => {\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n\n // If a credential provider is provided, use it to get the credentials.\n if (options.credentialProvider) {\n try {\n return {\n ...(await options.credentialProvider()),\n region,\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n throw new Error(\n `AWS credential provider failed: ${errorMessage}. ` +\n 'Please ensure your credential provider returns valid AWS credentials ' +\n 'with accessKeyId and secretAccessKey properties.',\n );\n }\n }\n\n try {\n return {\n region,\n accessKeyId: loadSetting({\n settingValue: options.accessKeyId,\n settingName: 'accessKeyId',\n environmentVariableName: 'AWS_ACCESS_KEY_ID',\n description: 'AWS access key ID',\n }),\n secretAccessKey: loadSetting({\n settingValue: options.secretAccessKey,\n settingName: 'secretAccessKey',\n environmentVariableName: 'AWS_SECRET_ACCESS_KEY',\n description: 'AWS secret access key',\n }),\n sessionToken: loadOptionalSetting({\n settingValue: options.sessionToken,\n environmentVariableName: 'AWS_SESSION_TOKEN',\n }),\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n if (\n errorMessage.includes('AWS_ACCESS_KEY_ID') ||\n errorMessage.includes('accessKeyId')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires AWS credentials. Please provide either:\\n' +\n '1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables\\n' +\n '2. Provide accessKeyId and secretAccessKey in options\\n' +\n '3. Use a credentialProvider function\\n' +\n '4. Use API key authentication with AWS_BEARER_TOKEN_BEDROCK or apiKey option\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n if (\n errorMessage.includes('AWS_SECRET_ACCESS_KEY') ||\n errorMessage.includes('secretAccessKey')\n ) {\n throw new Error(\n 'AWS SigV4 authentication requires both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. ' +\n 'Please ensure both credentials are provided.\\n' +\n `Original error: ${errorMessage}`,\n );\n }\n throw error;\n }\n },\n options.fetch,\n 'bedrock-mantle',\n );\n\n const getBaseURL = (modelId: string): string => {\n const baseURL = withoutTrailingSlash(options.baseURL);\n if (baseURL != null) {\n return baseURL;\n }\n\n const region = loadSetting({\n settingValue: options.region,\n settingName: 'region',\n environmentVariableName: 'AWS_REGION',\n description: 'AWS region',\n });\n if (!isValidHostnamePart(region)) {\n throw new InvalidArgumentError({\n argument: 'region',\n message:\n 'Invalid AWS region. Expected a single DNS label (letters, digits, and hyphens). Use `baseURL` for custom endpoints.',\n });\n }\n\n return `https://bedrock-mantle.${region}.api.aws/${\n // Mantle serves these models under its separate OpenAI route.\n /^(?:openai\\.gpt-(?!oss-)|google\\.gemma-4|xai\\.)/.test(modelId)\n ? 'openai/v1'\n : 'v1'\n }`;\n };\n\n const getHeaders = (): Record<string, string | undefined> =>\n withUserAgentSuffix(\n options.headers ?? {},\n `ai-sdk-amazon-bedrock/${VERSION}`,\n );\n\n const url = ({ path, modelId }: { path: string; modelId: string }): string =>\n `${getBaseURL(modelId)}${path}`;\n\n const createChatModel = (modelId: BedrockMantleChatModelId) =>\n new OpenAIChatLanguageModel(modelId, {\n provider: 'bedrock-mantle.chat',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n });\n\n const createResponsesModel = (modelId: BedrockMantleResponsesModelId) =>\n new OpenAIResponsesLanguageModel(modelId, {\n provider: 'bedrock-mantle.responses',\n url,\n headers: getHeaders,\n fetch: fetchFunction,\n supportsWebSearchSourcesInclude: false,\n });\n\n const provider = function (modelId: BedrockMantleChatModelId) {\n if (new.target) {\n throw new Error(\n 'The Bedrock Mantle 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.responses = createResponsesModel;\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 return provider as BedrockMantleProvider;\n}\n\n/**\n * Default Bedrock Mantle provider instance.\n */\nexport const bedrockMantle = createBedrockMantle();\n"],"mappings":";;;;;AAEA,MAAa,UAAA;;;;;;;;;;;AC0Bb,SAAgB,yBACd,gBAGA,OACA,UAAkB,WACH;CACf,OAAO,OACL,OACA,SACsB;EAEtB,MAAM,iBAAiB,SAAS,WAAW;EAC3C,MAAM,UAAU,iBAAiB,UAAU,QAAQ,KAAA;EACnD,MAAM,kBAAkB,eACtB,iBAAiB,SAAS,OAAO,GACjC,iBAAiB,MAAM,OAAO,CAChC;EACA,MAAM,uBAAuB,oBAC3B,iBACA,yBAAyB,WACzB,+BAA+B,CACjC;EAEA,IAAI,gBAAsC,MAAM,QAAQ,KAAA;EACxD,IAAI,kBAAkB,KAAA,KAAa,WAAW,QAAQ,SAAS,MAC7D,IAAI;GACF,gBAAgB,MAAM,QAAQ,MAAM,CAAC,CAAC,KAAK;EAC7C,QAAQ,CAAC;EAKX,KAFwB,MAAM,UAAU,SAAS,OAAA,EAE5B,YAAY,MAAM,UAAU,CAAC,eAChD,OAAO,eAAe,OAAO;GAC3B,GAAG;GACH,SAAS;EACX,CAAC;EAGH,MAAM,MACJ,OAAO,UAAU,WACb,QACA,iBAAiB,MACf,MAAM,OACN,MAAM;EAEd,MAAM,OAAO,kBAAkB,aAAa;EAC5C,MAAM,cAAc,MAAM,eAAe;EAezC,MAAM,gBAAgB,MAAM,IAdT,YAAY;GAC7B;GACA,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,MAAM,UAAU,qBAAqB,QAAQ,OAAO;EACpD,IAAI,WAAW,MACb,OAAO;EAGT,MAAM,SAAS,YAAY;GACzB,cAAc,QAAQ;GACtB,aAAa;GACb,yBAAyB;GACzB,aAAa;EACf,CAAC;EACD,IAAI,CAAC,oBAAoB,MAAM,GAC7B,MAAM,IAAI,qBAAqB;GAC7B,UAAU;GACV,SACE;EACJ,CAAC;EAGH,OAAO,0BAA0B,OAAO,WAEtC,kDAAkD,KAAK,OAAO,IAC1D,cACA;CAER;CAEA,MAAM,mBACJ,oBACE,QAAQ,WAAW,CAAC,GACpB,yBAAyB,SAC3B;CAEF,MAAM,OAAO,EAAE,MAAM,cACnB,GAAG,WAAW,OAAO,IAAI;CAE3B,MAAM,mBAAmB,YACvB,IAAI,wBAAwB,SAAS;EACnC,UAAU;EACV;EACA,SAAS;EACT,OAAO;CACT,CAAC;CAEH,MAAM,wBAAwB,YAC5B,IAAI,6BAA6B,SAAS;EACxC,UAAU;EACV;EACA,SAAS;EACT,OAAO;EACP,iCAAiC;CACnC,CAAC;CAEH,MAAM,WAAW,SAAU,SAAmC;EAC5D,IAAI,YACF,MAAM,IAAI,MACR,0EACF;EAGF,OAAO,gBAAgB,OAAO;CAChC;CAEA,SAAS,uBAAuB;CAChC,SAAS,gBAAgB;CACzB,SAAS,OAAO;CAChB,SAAS,YAAY;CAErB,SAAS,kBAAkB,YAAoB;EAC7C,MAAM,IAAI,iBAAiB;GAAE;GAAS,WAAW;EAAiB,CAAC;CACrE;CACA,SAAS,qBAAqB,SAAS;CACvC,SAAS,cAAc,YAAoB;EACzC,MAAM,IAAI,iBAAiB;GAAE;GAAS,WAAW;EAAa,CAAC;CACjE;CAEA,OAAO;AACT;;;;AAKA,MAAa,gBAAgB,oBAAoB"}
|
|
@@ -213,7 +213,12 @@ You can use the following optional settings to customize the Amazon Bedrock prov
|
|
|
213
213
|
Optional. The AWS credential provider chain that you want to use for the API calls.
|
|
214
214
|
It uses the specified credentials by default.
|
|
215
215
|
|
|
216
|
-
- **apiKey**
|
|
216
|
+
- **apiKey** _string | PromiseLike<string> | (() => string | PromiseLike<string>)_
|
|
217
|
+
|
|
218
|
+
Pass a callback to resolve the API key before each request. The callback can
|
|
219
|
+
return a string or a promise; token caching and renewal are handled by the caller.
|
|
220
|
+
A callback or promise selects API key authentication and must resolve to a
|
|
221
|
+
non-empty string; lookup failures do not switch authentication methods.
|
|
217
222
|
|
|
218
223
|
Optional. API key for authenticating requests using Bearer token authentication.
|
|
219
224
|
When provided, this will be used instead of AWS SigV4 authentication.
|
|
@@ -1634,7 +1639,12 @@ You can use the following optional settings to customize the Bedrock Anthropic p
|
|
|
1634
1639
|
used. If either key is taken from the environment, omitting `sessionToken`
|
|
1635
1640
|
allows `AWS_SESSION_TOKEN`.
|
|
1636
1641
|
|
|
1637
|
-
- **apiKey**
|
|
1642
|
+
- **apiKey** _string | PromiseLike<string> | (() => string | PromiseLike<string>)_
|
|
1643
|
+
|
|
1644
|
+
Pass a callback to resolve the API key before each request. The callback can
|
|
1645
|
+
return a string or a promise; token caching and renewal are handled by the caller.
|
|
1646
|
+
A callback or promise selects API key authentication and must resolve to a
|
|
1647
|
+
non-empty string; lookup failures do not switch authentication methods.
|
|
1638
1648
|
|
|
1639
1649
|
API key for authenticating requests using Bearer token authentication.
|
|
1640
1650
|
When provided, this will be used instead of AWS SigV4 authentication.
|
|
@@ -1951,7 +1961,12 @@ You can use the following optional settings to customize the Bedrock Mantle prov
|
|
|
1951
1961
|
Optional. The AWS session token that you want to use for the API calls.
|
|
1952
1962
|
It uses the `AWS_SESSION_TOKEN` environment variable by default.
|
|
1953
1963
|
|
|
1954
|
-
- **apiKey**
|
|
1964
|
+
- **apiKey** _string | PromiseLike<string> | (() => string | PromiseLike<string>)_
|
|
1965
|
+
|
|
1966
|
+
Pass a callback to resolve the API key before each request. The callback can
|
|
1967
|
+
return a string or a promise; token caching and renewal are handled by the caller.
|
|
1968
|
+
A callback or promise selects API key authentication and must resolve to a
|
|
1969
|
+
non-empty string; lookup failures do not switch authentication methods.
|
|
1955
1970
|
|
|
1956
1971
|
API key for authenticating requests using Bearer token authentication.
|
|
1957
1972
|
When provided, this will be used instead of AWS SigV4 authentication.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-sdk/amazon-bedrock",
|
|
3
|
-
"version": "5.0.
|
|
3
|
+
"version": "5.0.129",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -41,10 +41,10 @@
|
|
|
41
41
|
}
|
|
42
42
|
},
|
|
43
43
|
"dependencies": {
|
|
44
|
-
"@ai-sdk/anthropic": "4.0.
|
|
45
|
-
"@ai-sdk/openai": "4.0.
|
|
46
|
-
"@ai-sdk/provider": "4.0.
|
|
47
|
-
"@ai-sdk/provider-utils": "5.0.
|
|
44
|
+
"@ai-sdk/anthropic": "4.0.93",
|
|
45
|
+
"@ai-sdk/openai": "4.0.106",
|
|
46
|
+
"@ai-sdk/provider": "4.0.35",
|
|
47
|
+
"@ai-sdk/provider-utils": "5.0.72",
|
|
48
48
|
"@smithy/eventstream-codec": "^4.3.3",
|
|
49
49
|
"@smithy/util-utf8": "^4.3.3",
|
|
50
50
|
"aws4fetch": "^1.0.20"
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
loadSetting,
|
|
13
13
|
withUserAgentSuffix,
|
|
14
14
|
type FetchFunction,
|
|
15
|
+
type Resolvable,
|
|
15
16
|
} from '@ai-sdk/provider-utils';
|
|
16
17
|
import { AmazonBedrockChatLanguageModel } from './amazon-bedrock-chat-language-model';
|
|
17
18
|
import type {
|
|
@@ -44,6 +45,7 @@ export interface AmazonBedrockProviderSettings {
|
|
|
44
45
|
|
|
45
46
|
/**
|
|
46
47
|
* API key for authenticating requests using Bearer token authentication.
|
|
48
|
+
* A callback is resolved before each request and must return a non-empty key.
|
|
47
49
|
* When provided, this will be used instead of AWS SigV4 authentication.
|
|
48
50
|
* Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
|
|
49
51
|
*
|
|
@@ -65,7 +67,7 @@ export interface AmazonBedrockProviderSettings {
|
|
|
65
67
|
* If neither `apiKey` nor `AWS_BEARER_TOKEN_BEDROCK` environment variable is set,
|
|
66
68
|
* the provider will fall back to AWS SigV4 authentication using AWS credentials.
|
|
67
69
|
*/
|
|
68
|
-
apiKey?: string
|
|
70
|
+
apiKey?: Resolvable<string>;
|
|
69
71
|
|
|
70
72
|
/**
|
|
71
73
|
* The AWS access key ID to use for the Bedrock provider. Defaults to the value of the
|
|
@@ -193,15 +195,18 @@ export function createAmazonBedrock(
|
|
|
193
195
|
options: AmazonBedrockProviderSettings = {},
|
|
194
196
|
): AmazonBedrockProvider {
|
|
195
197
|
// Check for API key authentication first
|
|
196
|
-
const rawApiKey =
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
198
|
+
const rawApiKey =
|
|
199
|
+
typeof options.apiKey === 'string' || options.apiKey == null
|
|
200
|
+
? loadOptionalSetting({
|
|
201
|
+
settingValue: options.apiKey,
|
|
202
|
+
environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',
|
|
203
|
+
})
|
|
204
|
+
: options.apiKey;
|
|
200
205
|
|
|
201
206
|
// FIX 1: Validate API key to ensure proper fallback to SigV4
|
|
202
207
|
// Only use API key if it's a non-empty, non-whitespace string
|
|
203
208
|
const apiKey =
|
|
204
|
-
|
|
209
|
+
typeof rawApiKey === 'string' ? rawApiKey.trim() || undefined : rawApiKey;
|
|
205
210
|
|
|
206
211
|
// Use API key authentication if available, otherwise fall back to SigV4
|
|
207
212
|
const fetchFunction = apiKey
|
|
@@ -1,5 +1,8 @@
|
|
|
1
|
+
import { LoadAPIKeyError } from '@ai-sdk/provider';
|
|
1
2
|
import {
|
|
2
3
|
combineHeaders,
|
|
4
|
+
resolve,
|
|
5
|
+
type Resolvable,
|
|
3
6
|
normalizeHeaders,
|
|
4
7
|
withUserAgentSuffix,
|
|
5
8
|
getRuntimeEnvironmentUserAgent,
|
|
@@ -124,7 +127,7 @@ function isAscii(value: string): boolean {
|
|
|
124
127
|
* @returns A FetchFunction that adds Authorization header with Bearer token to requests.
|
|
125
128
|
*/
|
|
126
129
|
export function createApiKeyFetchFunction(
|
|
127
|
-
apiKey: string
|
|
130
|
+
apiKey: Resolvable<string>,
|
|
128
131
|
fetch?: FetchFunction,
|
|
129
132
|
): FetchFunction {
|
|
130
133
|
return async (
|
|
@@ -140,8 +143,18 @@ export function createApiKeyFetchFunction(
|
|
|
140
143
|
getRuntimeEnvironmentUserAgent(),
|
|
141
144
|
);
|
|
142
145
|
|
|
146
|
+
const resolvedApiKey = await resolve(apiKey);
|
|
147
|
+
if (
|
|
148
|
+
typeof apiKey !== 'string' &&
|
|
149
|
+
(typeof resolvedApiKey !== 'string' || !resolvedApiKey.trim())
|
|
150
|
+
) {
|
|
151
|
+
throw new LoadAPIKeyError({
|
|
152
|
+
message: 'Amazon Bedrock API key must be a non-empty string.',
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
143
156
|
const finalHeaders = combineHeaders(headersWithUserAgent, {
|
|
144
|
-
Authorization: `Bearer ${apiKey}`,
|
|
157
|
+
Authorization: `Bearer ${typeof apiKey === 'string' ? resolvedApiKey : resolvedApiKey.trim()}`,
|
|
145
158
|
});
|
|
146
159
|
|
|
147
160
|
return effectiveFetch(input, {
|
|
@@ -88,10 +88,11 @@ export interface AmazonBedrockAnthropicProviderSettings {
|
|
|
88
88
|
|
|
89
89
|
/**
|
|
90
90
|
* API key for authenticating requests using Bearer token authentication.
|
|
91
|
+
* A callback is resolved before each request and must return a non-empty key.
|
|
91
92
|
* When provided, this will be used instead of AWS SigV4 authentication.
|
|
92
93
|
* Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
|
|
93
94
|
*/
|
|
94
|
-
apiKey?: string
|
|
95
|
+
apiKey?: Resolvable<string>;
|
|
95
96
|
|
|
96
97
|
/**
|
|
97
98
|
* The AWS access key ID to use for the Bedrock provider. Defaults to the value of the
|
|
@@ -147,14 +148,17 @@ export function createAmazonBedrockAnthropic(
|
|
|
147
148
|
options: AmazonBedrockAnthropicProviderSettings = {},
|
|
148
149
|
): AmazonBedrockAnthropicProvider {
|
|
149
150
|
// Check for API key authentication first
|
|
150
|
-
const rawApiKey =
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
151
|
+
const rawApiKey =
|
|
152
|
+
typeof options.apiKey === 'string' || options.apiKey == null
|
|
153
|
+
? loadOptionalSetting({
|
|
154
|
+
settingValue: options.apiKey,
|
|
155
|
+
environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',
|
|
156
|
+
})
|
|
157
|
+
: options.apiKey;
|
|
154
158
|
|
|
155
159
|
// Only use API key if it's a non-empty, non-whitespace string
|
|
156
160
|
const apiKey =
|
|
157
|
-
|
|
161
|
+
typeof rawApiKey === 'string' ? rawApiKey.trim() || undefined : rawApiKey;
|
|
158
162
|
|
|
159
163
|
// Use API key authentication if available, otherwise fall back to SigV4
|
|
160
164
|
const baseFetchFunction = apiKey
|
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
withoutTrailingSlash,
|
|
16
16
|
withUserAgentSuffix,
|
|
17
17
|
type FetchFunction,
|
|
18
|
+
type Resolvable,
|
|
18
19
|
} from '@ai-sdk/provider-utils';
|
|
19
20
|
import {
|
|
20
21
|
createApiKeyFetchFunction,
|
|
@@ -66,10 +67,11 @@ export interface BedrockMantleProviderSettings {
|
|
|
66
67
|
|
|
67
68
|
/**
|
|
68
69
|
* API key for authenticating requests using Bearer token authentication.
|
|
70
|
+
* A callback is resolved before each request and must return a non-empty key.
|
|
69
71
|
* When provided, this will be used instead of AWS SigV4 authentication.
|
|
70
72
|
* Defaults to the value of the `AWS_BEARER_TOKEN_BEDROCK` environment variable.
|
|
71
73
|
*/
|
|
72
|
-
apiKey?: string
|
|
74
|
+
apiKey?: Resolvable<string>;
|
|
73
75
|
|
|
74
76
|
/**
|
|
75
77
|
* The AWS access key ID to use for SigV4 authentication. Defaults to the value of the
|
|
@@ -125,14 +127,17 @@ export function createBedrockMantle(
|
|
|
125
127
|
options: BedrockMantleProviderSettings = {},
|
|
126
128
|
): BedrockMantleProvider {
|
|
127
129
|
// Check for API key authentication first
|
|
128
|
-
const rawApiKey =
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
130
|
+
const rawApiKey =
|
|
131
|
+
typeof options.apiKey === 'string' || options.apiKey == null
|
|
132
|
+
? loadOptionalSetting({
|
|
133
|
+
settingValue: options.apiKey,
|
|
134
|
+
environmentVariableName: 'AWS_BEARER_TOKEN_BEDROCK',
|
|
135
|
+
})
|
|
136
|
+
: options.apiKey;
|
|
132
137
|
|
|
133
138
|
// Only use API key if it's a non-empty, non-whitespace string
|
|
134
139
|
const apiKey =
|
|
135
|
-
|
|
140
|
+
typeof rawApiKey === 'string' ? rawApiKey.trim() || undefined : rawApiKey;
|
|
136
141
|
|
|
137
142
|
// Use API key authentication if available, otherwise fall back to SigV4
|
|
138
143
|
const fetchFunction = apiKey
|