diff --git a/clients/client-bedrock-runtime/.gitignore b/clients/client-bedrock-runtime/.gitignore new file mode 100644 index 0000000000000..54f14c9aef253 --- /dev/null +++ b/clients/client-bedrock-runtime/.gitignore @@ -0,0 +1,9 @@ +/node_modules/ +/build/ +/coverage/ +/docs/ +/dist-* +*.tsbuildinfo +*.tgz +*.log +package-lock.json diff --git a/clients/client-bedrock-runtime/LICENSE b/clients/client-bedrock-runtime/LICENSE new file mode 100644 index 0000000000000..5001cd317c44a --- /dev/null +++ b/clients/client-bedrock-runtime/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2018-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/clients/client-bedrock-runtime/README.md b/clients/client-bedrock-runtime/README.md new file mode 100644 index 0000000000000..fa460be15be44 --- /dev/null +++ b/clients/client-bedrock-runtime/README.md @@ -0,0 +1,221 @@ + + +# @aws-sdk/client-bedrock-runtime + +## Description + +AWS SDK for JavaScript BedrockRuntime Client for Node.js, Browser and React Native. + +

Describes the API operations for running inference using Bedrock models.

+ +## Installing + +To install the this package, simply type add or install @aws-sdk/client-bedrock-runtime +using your favorite package manager: + +- `npm install @aws-sdk/client-bedrock-runtime` +- `yarn add @aws-sdk/client-bedrock-runtime` +- `pnpm add @aws-sdk/client-bedrock-runtime` + +## Getting Started + +### Import + +The AWS SDK is modulized by clients and commands. +To send a request, you only need to import the `BedrockRuntimeClient` and +the commands you need, for example `InvokeModelCommand`: + +```js +// ES5 example +const { BedrockRuntimeClient, InvokeModelCommand } = require("@aws-sdk/client-bedrock-runtime"); +``` + +```ts +// ES6+ example +import { BedrockRuntimeClient, InvokeModelCommand } from "@aws-sdk/client-bedrock-runtime"; +``` + +### Usage + +To send a request, you: + +- Initiate client with configuration (e.g. credentials, region). +- Initiate command with input parameters. +- Call `send` operation on client with command object as input. +- If you are using a custom http handler, you may call `destroy()` to close open connections. + +```js +// a client can be shared by different commands. +const client = new BedrockRuntimeClient({ region: "REGION" }); + +const params = { + /** input parameters */ +}; +const command = new InvokeModelCommand(params); +``` + +#### Async/await + +We recommend using [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await) +operator to wait for the promise returned by send operation as follows: + +```js +// async/await. +try { + const data = await client.send(command); + // process data. +} catch (error) { + // error handling. +} finally { + // finally. +} +``` + +Async-await is clean, concise, intuitive, easy to debug and has better error handling +as compared to using Promise chains or callbacks. + +#### Promises + +You can also use [Promise chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#chaining) +to execute send operation. + +```js +client.send(command).then( + (data) => { + // process data. + }, + (error) => { + // error handling. + } +); +``` + +Promises can also be called using `.catch()` and `.finally()` as follows: + +```js +client + .send(command) + .then((data) => { + // process data. + }) + .catch((error) => { + // error handling. + }) + .finally(() => { + // finally. + }); +``` + +#### Callbacks + +We do not recommend using callbacks because of [callback hell](http://callbackhell.com/), +but they are supported by the send operation. + +```js +// callbacks. +client.send(command, (err, data) => { + // process err and data. +}); +``` + +#### v2 compatible style + +The client can also send requests using v2 compatible style. +However, it results in a bigger bundle size and may be dropped in next major version. More details in the blog post +on [modular packages in AWS SDK for JavaScript](https://aws.amazon.com/blogs/developer/modular-packages-in-aws-sdk-for-javascript/) + +```ts +import * as AWS from "@aws-sdk/client-bedrock-runtime"; +const client = new AWS.BedrockRuntime({ region: "REGION" }); + +// async/await. +try { + const data = await client.invokeModel(params); + // process data. +} catch (error) { + // error handling. +} + +// Promises. +client + .invokeModel(params) + .then((data) => { + // process data. + }) + .catch((error) => { + // error handling. + }); + +// callbacks. +client.invokeModel(params, (err, data) => { + // process err and data. +}); +``` + +### Troubleshooting + +When the service returns an exception, the error will include the exception information, +as well as response metadata (e.g. request id). + +```js +try { + const data = await client.send(command); + // process data. +} catch (error) { + const { requestId, cfId, extendedRequestId } = error.$$metadata; + console.log({ requestId, cfId, extendedRequestId }); + /** + * The keys within exceptions are also parsed. + * You can access them by specifying exception names: + * if (error.name === 'SomeServiceException') { + * const value = error.specialKeyInException; + * } + */ +} +``` + +## Getting Help + +Please use these community resources for getting help. +We use the GitHub issues for tracking bugs and feature requests, but have limited bandwidth to address them. + +- Visit [Developer Guide](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/welcome.html) + or [API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html). +- Check out the blog posts tagged with [`aws-sdk-js`](https://aws.amazon.com/blogs/developer/tag/aws-sdk-js/) + on AWS Developer Blog. +- Ask a question on [StackOverflow](https://stackoverflow.com/questions/tagged/aws-sdk-js) and tag it with `aws-sdk-js`. +- Join the AWS JavaScript community on [gitter](https://gitter.im/aws/aws-sdk-js-v3). +- If it turns out that you may have found a bug, please [open an issue](https://github.com/aws/aws-sdk-js-v3/issues/new/choose). + +To test your universal JavaScript code in Node.js, browser and react-native environments, +visit our [code samples repo](https://github.com/aws-samples/aws-sdk-js-tests). + +## Contributing + +This client code is generated automatically. Any modifications will be overwritten the next time the `@aws-sdk/client-bedrock-runtime` package is updated. +To contribute to client you can check our [generate clients scripts](https://github.com/aws/aws-sdk-js-v3/tree/main/scripts/generate-clients). + +## License + +This SDK is distributed under the +[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), +see LICENSE for more information. + +## Client Commands (Operations List) + +
+ +InvokeModel + + +[Command API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-bedrock-runtime/classes/invokemodelcommand.html) / [Input](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-bedrock-runtime/interfaces/invokemodelcommandinput.html) / [Output](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-bedrock-runtime/interfaces/invokemodelcommandoutput.html) + +
+
+ +InvokeModelWithResponseStream + + +[Command API Reference](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-bedrock-runtime/classes/invokemodelwithresponsestreamcommand.html) / [Input](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-bedrock-runtime/interfaces/invokemodelwithresponsestreamcommandinput.html) / [Output](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-bedrock-runtime/interfaces/invokemodelwithresponsestreamcommandoutput.html) + +
diff --git a/clients/client-bedrock-runtime/api-extractor.json b/clients/client-bedrock-runtime/api-extractor.json new file mode 100644 index 0000000000000..d5bf5ffeee851 --- /dev/null +++ b/clients/client-bedrock-runtime/api-extractor.json @@ -0,0 +1,4 @@ +{ + "extends": "../../api-extractor.json", + "mainEntryPointFilePath": "/dist-types/index.d.ts" +} diff --git a/clients/client-bedrock-runtime/package.json b/clients/client-bedrock-runtime/package.json new file mode 100644 index 0000000000000..06121b6becd6e --- /dev/null +++ b/clients/client-bedrock-runtime/package.json @@ -0,0 +1,104 @@ +{ + "name": "@aws-sdk/client-bedrock-runtime", + "description": "AWS SDK for JavaScript Bedrock Runtime Client for Node.js, Browser and React Native", + "version": "3.0.0", + "scripts": { + "build": "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'", + "build:cjs": "tsc -p tsconfig.cjs.json", + "build:docs": "typedoc", + "build:es": "tsc -p tsconfig.es.json", + "build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build", + "build:types": "tsc -p tsconfig.types.json", + "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4", + "clean": "rimraf ./dist-* && rimraf *.tsbuildinfo", + "extract:docs": "api-extractor run --local", + "generate:client": "node ../../scripts/generate-clients/single-service --solo bedrock-runtime" + }, + "main": "./dist-cjs/index.js", + "types": "./dist-types/index.d.ts", + "module": "./dist-es/index.js", + "sideEffects": false, + "dependencies": { + "@aws-crypto/sha256-browser": "3.0.0", + "@aws-crypto/sha256-js": "3.0.0", + "@aws-sdk/client-sts": "*", + "@aws-sdk/credential-provider-node": "*", + "@aws-sdk/middleware-host-header": "*", + "@aws-sdk/middleware-logger": "*", + "@aws-sdk/middleware-recursion-detection": "*", + "@aws-sdk/middleware-signing": "*", + "@aws-sdk/middleware-user-agent": "*", + "@aws-sdk/region-config-resolver": "*", + "@aws-sdk/types": "*", + "@aws-sdk/util-endpoints": "*", + "@aws-sdk/util-user-agent-browser": "*", + "@aws-sdk/util-user-agent-node": "*", + "@smithy/config-resolver": "^2.0.10", + "@smithy/eventstream-serde-browser": "^2.0.9", + "@smithy/eventstream-serde-config-resolver": "^2.0.9", + "@smithy/eventstream-serde-node": "^2.0.9", + "@smithy/fetch-http-handler": "^2.1.5", + "@smithy/hash-node": "^2.0.9", + "@smithy/invalid-dependency": "^2.0.9", + "@smithy/middleware-content-length": "^2.0.11", + "@smithy/middleware-endpoint": "^2.0.9", + "@smithy/middleware-retry": "^2.0.12", + "@smithy/middleware-serde": "^2.0.9", + "@smithy/middleware-stack": "^2.0.2", + "@smithy/node-config-provider": "^2.0.12", + "@smithy/node-http-handler": "^2.1.5", + "@smithy/protocol-http": "^3.0.5", + "@smithy/smithy-client": "^2.1.6", + "@smithy/types": "^2.3.3", + "@smithy/url-parser": "^2.0.9", + "@smithy/util-base64": "^2.0.0", + "@smithy/util-body-length-browser": "^2.0.0", + "@smithy/util-body-length-node": "^2.1.0", + "@smithy/util-defaults-mode-browser": "^2.0.10", + "@smithy/util-defaults-mode-node": "^2.0.12", + "@smithy/util-retry": "^2.0.2", + "@smithy/util-stream": "^2.0.12", + "@smithy/util-utf8": "^2.0.0", + "tslib": "^2.5.0" + }, + "devDependencies": { + "@smithy/service-client-documentation-generator": "^2.0.0", + "@tsconfig/node14": "1.0.3", + "@types/node": "^14.14.31", + "concurrently": "7.0.0", + "downlevel-dts": "0.10.1", + "rimraf": "3.0.2", + "typedoc": "0.23.23", + "typescript": "~4.9.5" + }, + "engines": { + "node": ">=14.0.0" + }, + "typesVersions": { + "<4.0": { + "dist-types/*": [ + "dist-types/ts3.4/*" + ] + } + }, + "files": [ + "dist-*/**" + ], + "author": { + "name": "AWS SDK for JavaScript Team", + "url": "https://aws.amazon.com/javascript/" + }, + "license": "Apache-2.0", + "browser": { + "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser" + }, + "react-native": { + "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native" + }, + "homepage": "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-bedrock-runtime", + "repository": { + "type": "git", + "url": "https://github.com/aws/aws-sdk-js-v3.git", + "directory": "clients/client-bedrock-runtime" + } +} diff --git a/clients/client-bedrock-runtime/src/BedrockRuntime.ts b/clients/client-bedrock-runtime/src/BedrockRuntime.ts new file mode 100644 index 0000000000000..a1815453d46da --- /dev/null +++ b/clients/client-bedrock-runtime/src/BedrockRuntime.ts @@ -0,0 +1,53 @@ +// smithy-typescript generated code +import { createAggregatedClient } from "@smithy/smithy-client"; +import { HttpHandlerOptions as __HttpHandlerOptions } from "@smithy/types"; + +import { BedrockRuntimeClient, BedrockRuntimeClientConfig } from "./BedrockRuntimeClient"; +import { InvokeModelCommand, InvokeModelCommandInput, InvokeModelCommandOutput } from "./commands/InvokeModelCommand"; +import { + InvokeModelWithResponseStreamCommand, + InvokeModelWithResponseStreamCommandInput, + InvokeModelWithResponseStreamCommandOutput, +} from "./commands/InvokeModelWithResponseStreamCommand"; + +const commands = { + InvokeModelCommand, + InvokeModelWithResponseStreamCommand, +}; + +export interface BedrockRuntime { + /** + * @see {@link InvokeModelCommand} + */ + invokeModel(args: InvokeModelCommandInput, options?: __HttpHandlerOptions): Promise; + invokeModel(args: InvokeModelCommandInput, cb: (err: any, data?: InvokeModelCommandOutput) => void): void; + invokeModel( + args: InvokeModelCommandInput, + options: __HttpHandlerOptions, + cb: (err: any, data?: InvokeModelCommandOutput) => void + ): void; + + /** + * @see {@link InvokeModelWithResponseStreamCommand} + */ + invokeModelWithResponseStream( + args: InvokeModelWithResponseStreamCommandInput, + options?: __HttpHandlerOptions + ): Promise; + invokeModelWithResponseStream( + args: InvokeModelWithResponseStreamCommandInput, + cb: (err: any, data?: InvokeModelWithResponseStreamCommandOutput) => void + ): void; + invokeModelWithResponseStream( + args: InvokeModelWithResponseStreamCommandInput, + options: __HttpHandlerOptions, + cb: (err: any, data?: InvokeModelWithResponseStreamCommandOutput) => void + ): void; +} + +/** + * @public + *

Describes the API operations for running inference using Bedrock models.

+ */ +export class BedrockRuntime extends BedrockRuntimeClient implements BedrockRuntime {} +createAggregatedClient(commands, BedrockRuntime); diff --git a/clients/client-bedrock-runtime/src/BedrockRuntimeClient.ts b/clients/client-bedrock-runtime/src/BedrockRuntimeClient.ts new file mode 100644 index 0000000000000..819d5f128f636 --- /dev/null +++ b/clients/client-bedrock-runtime/src/BedrockRuntimeClient.ts @@ -0,0 +1,305 @@ +// smithy-typescript generated code +import { + getHostHeaderPlugin, + HostHeaderInputConfig, + HostHeaderResolvedConfig, + resolveHostHeaderConfig, +} from "@aws-sdk/middleware-host-header"; +import { getLoggerPlugin } from "@aws-sdk/middleware-logger"; +import { getRecursionDetectionPlugin } from "@aws-sdk/middleware-recursion-detection"; +import { + AwsAuthInputConfig, + AwsAuthResolvedConfig, + getAwsAuthPlugin, + resolveAwsAuthConfig, +} from "@aws-sdk/middleware-signing"; +import { + getUserAgentPlugin, + resolveUserAgentConfig, + UserAgentInputConfig, + UserAgentResolvedConfig, +} from "@aws-sdk/middleware-user-agent"; +import { Credentials as __Credentials } from "@aws-sdk/types"; +import { RegionInputConfig, RegionResolvedConfig, resolveRegionConfig } from "@smithy/config-resolver"; +import { + EventStreamSerdeInputConfig, + EventStreamSerdeResolvedConfig, + resolveEventStreamSerdeConfig, +} from "@smithy/eventstream-serde-config-resolver"; +import { getContentLengthPlugin } from "@smithy/middleware-content-length"; +import { EndpointInputConfig, EndpointResolvedConfig, resolveEndpointConfig } from "@smithy/middleware-endpoint"; +import { getRetryPlugin, resolveRetryConfig, RetryInputConfig, RetryResolvedConfig } from "@smithy/middleware-retry"; +import { HttpHandler as __HttpHandler } from "@smithy/protocol-http"; +import { + Client as __Client, + DefaultsMode as __DefaultsMode, + SmithyConfiguration as __SmithyConfiguration, + SmithyResolvedConfiguration as __SmithyResolvedConfiguration, +} from "@smithy/smithy-client"; +import { + BodyLengthCalculator as __BodyLengthCalculator, + CheckOptionalClientConfig as __CheckOptionalClientConfig, + Checksum as __Checksum, + ChecksumConstructor as __ChecksumConstructor, + Decoder as __Decoder, + Encoder as __Encoder, + EndpointV2 as __EndpointV2, + EventStreamSerdeProvider as __EventStreamSerdeProvider, + Hash as __Hash, + HashConstructor as __HashConstructor, + HttpHandlerOptions as __HttpHandlerOptions, + Logger as __Logger, + Provider as __Provider, + Provider, + StreamCollector as __StreamCollector, + UrlParser as __UrlParser, + UserAgent as __UserAgent, +} from "@smithy/types"; + +import { InvokeModelCommandInput, InvokeModelCommandOutput } from "./commands/InvokeModelCommand"; +import { + InvokeModelWithResponseStreamCommandInput, + InvokeModelWithResponseStreamCommandOutput, +} from "./commands/InvokeModelWithResponseStreamCommand"; +import { + ClientInputEndpointParameters, + ClientResolvedEndpointParameters, + EndpointParameters, + resolveClientEndpointParameters, +} from "./endpoint/EndpointParameters"; +import { getRuntimeConfig as __getRuntimeConfig } from "./runtimeConfig"; +import { resolveRuntimeExtensions, RuntimeExtension, RuntimeExtensionsConfig } from "./runtimeExtensions"; + +export { __Client }; + +/** + * @public + */ +export type ServiceInputTypes = InvokeModelCommandInput | InvokeModelWithResponseStreamCommandInput; + +/** + * @public + */ +export type ServiceOutputTypes = InvokeModelCommandOutput | InvokeModelWithResponseStreamCommandOutput; + +/** + * @public + */ +export interface ClientDefaults extends Partial<__SmithyResolvedConfiguration<__HttpHandlerOptions>> { + /** + * The HTTP handler to use. Fetch in browser and Https in Nodejs. + */ + requestHandler?: __HttpHandler; + + /** + * A constructor for a class implementing the {@link @smithy/types#ChecksumConstructor} interface + * that computes the SHA-256 HMAC or checksum of a string or binary buffer. + * @internal + */ + sha256?: __ChecksumConstructor | __HashConstructor; + + /** + * The function that will be used to convert strings into HTTP endpoints. + * @internal + */ + urlParser?: __UrlParser; + + /** + * A function that can calculate the length of a request body. + * @internal + */ + bodyLengthChecker?: __BodyLengthCalculator; + + /** + * A function that converts a stream into an array of bytes. + * @internal + */ + streamCollector?: __StreamCollector; + + /** + * The function that will be used to convert a base64-encoded string to a byte array. + * @internal + */ + base64Decoder?: __Decoder; + + /** + * The function that will be used to convert binary data to a base64-encoded string. + * @internal + */ + base64Encoder?: __Encoder; + + /** + * The function that will be used to convert a UTF8-encoded string to a byte array. + * @internal + */ + utf8Decoder?: __Decoder; + + /** + * The function that will be used to convert binary data to a UTF-8 encoded string. + * @internal + */ + utf8Encoder?: __Encoder; + + /** + * The runtime environment. + * @internal + */ + runtime?: string; + + /** + * Disable dynamically changing the endpoint of the client based on the hostPrefix + * trait of an operation. + */ + disableHostPrefix?: boolean; + + /** + * Unique service identifier. + * @internal + */ + serviceId?: string; + + /** + * Enables IPv6/IPv4 dualstack endpoint. + */ + useDualstackEndpoint?: boolean | __Provider; + + /** + * Enables FIPS compatible endpoints. + */ + useFipsEndpoint?: boolean | __Provider; + + /** + * The AWS region to which this client will send requests + */ + region?: string | __Provider; + + /** + * Default credentials provider; Not available in browser runtime. + * @internal + */ + credentialDefaultProvider?: (input: any) => __Provider<__Credentials>; + + /** + * The provider populating default tracking information to be sent with `user-agent`, `x-amz-user-agent` header + * @internal + */ + defaultUserAgentProvider?: Provider<__UserAgent>; + + /** + * Value for how many times a request will be made at most in case of retry. + */ + maxAttempts?: number | __Provider; + + /** + * Specifies which retry algorithm to use. + */ + retryMode?: string | __Provider; + + /** + * Optional logger for logging debug/info/warn/error. + */ + logger?: __Logger; + + /** + * Optional extensions + */ + extensions?: RuntimeExtension[]; + + /** + * The function that provides necessary utilities for generating and parsing event stream + */ + eventStreamSerdeProvider?: __EventStreamSerdeProvider; + + /** + * The {@link @smithy/smithy-client#DefaultsMode} that will be used to determine how certain default configuration options are resolved in the SDK. + */ + defaultsMode?: __DefaultsMode | __Provider<__DefaultsMode>; +} + +/** + * @public + */ +export type BedrockRuntimeClientConfigType = Partial<__SmithyConfiguration<__HttpHandlerOptions>> & + ClientDefaults & + RegionInputConfig & + EndpointInputConfig & + RetryInputConfig & + HostHeaderInputConfig & + AwsAuthInputConfig & + UserAgentInputConfig & + EventStreamSerdeInputConfig & + ClientInputEndpointParameters; +/** + * @public + * + * The configuration interface of BedrockRuntimeClient class constructor that set the region, credentials and other options. + */ +export interface BedrockRuntimeClientConfig extends BedrockRuntimeClientConfigType {} + +/** + * @public + */ +export type BedrockRuntimeClientResolvedConfigType = __SmithyResolvedConfiguration<__HttpHandlerOptions> & + Required & + RuntimeExtensionsConfig & + RegionResolvedConfig & + EndpointResolvedConfig & + RetryResolvedConfig & + HostHeaderResolvedConfig & + AwsAuthResolvedConfig & + UserAgentResolvedConfig & + EventStreamSerdeResolvedConfig & + ClientResolvedEndpointParameters; +/** + * @public + * + * The resolved configuration interface of BedrockRuntimeClient class. This is resolved and normalized from the {@link BedrockRuntimeClientConfig | constructor configuration interface}. + */ +export interface BedrockRuntimeClientResolvedConfig extends BedrockRuntimeClientResolvedConfigType {} + +/** + * @public + *

Describes the API operations for running inference using Bedrock models.

+ */ +export class BedrockRuntimeClient extends __Client< + __HttpHandlerOptions, + ServiceInputTypes, + ServiceOutputTypes, + BedrockRuntimeClientResolvedConfig +> { + /** + * The resolved configuration of BedrockRuntimeClient class. This is resolved and normalized from the {@link BedrockRuntimeClientConfig | constructor configuration interface}. + */ + readonly config: BedrockRuntimeClientResolvedConfig; + + constructor(...[configuration]: __CheckOptionalClientConfig) { + const _config_0 = __getRuntimeConfig(configuration || {}); + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = resolveRegionConfig(_config_1); + const _config_3 = resolveEndpointConfig(_config_2); + const _config_4 = resolveRetryConfig(_config_3); + const _config_5 = resolveHostHeaderConfig(_config_4); + const _config_6 = resolveAwsAuthConfig(_config_5); + const _config_7 = resolveUserAgentConfig(_config_6); + const _config_8 = resolveEventStreamSerdeConfig(_config_7); + const _config_9 = resolveRuntimeExtensions(_config_8, configuration?.extensions || []); + super(_config_9); + this.config = _config_9; + this.middlewareStack.use(getRetryPlugin(this.config)); + this.middlewareStack.use(getContentLengthPlugin(this.config)); + this.middlewareStack.use(getHostHeaderPlugin(this.config)); + this.middlewareStack.use(getLoggerPlugin(this.config)); + this.middlewareStack.use(getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(getAwsAuthPlugin(this.config)); + this.middlewareStack.use(getUserAgentPlugin(this.config)); + } + + /** + * Destroy underlying resources, like sockets. It's usually not necessary to do this. + * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed. + * Otherwise, sockets might stay open for quite a long time before the server terminates them. + */ + destroy(): void { + super.destroy(); + } +} diff --git a/clients/client-bedrock-runtime/src/commands/InvokeModelCommand.ts b/clients/client-bedrock-runtime/src/commands/InvokeModelCommand.ts new file mode 100644 index 0000000000000..211d4597d68cb --- /dev/null +++ b/clients/client-bedrock-runtime/src/commands/InvokeModelCommand.ts @@ -0,0 +1,200 @@ +// smithy-typescript generated code +import { EndpointParameterInstructions, getEndpointPlugin } from "@smithy/middleware-endpoint"; +import { getSerdePlugin } from "@smithy/middleware-serde"; +import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@smithy/protocol-http"; +import { Command as $Command } from "@smithy/smithy-client"; +import { + BlobPayloadInputTypes, + FinalizeHandlerArguments, + Handler, + HandlerExecutionContext, + HttpHandlerOptions as __HttpHandlerOptions, + MetadataBearer as __MetadataBearer, + MiddlewareStack, + SerdeContext as __SerdeContext, + SMITHY_CONTEXT_KEY, +} from "@smithy/types"; +import { Uint8ArrayBlobAdapter } from "@smithy/util-stream"; + +import { BedrockRuntimeClientResolvedConfig, ServiceInputTypes, ServiceOutputTypes } from "../BedrockRuntimeClient"; +import { + InvokeModelRequest, + InvokeModelRequestFilterSensitiveLog, + InvokeModelResponse, + InvokeModelResponseFilterSensitiveLog, +} from "../models/models_0"; +import { de_InvokeModelCommand, se_InvokeModelCommand } from "../protocols/Aws_restJson1"; + +/** + * @public + */ +export { __MetadataBearer, $Command }; +/** + * @public + */ +export type InvokeModelCommandInputType = Omit & { + body: BlobPayloadInputTypes; +}; + +/** + * @public + * + * The input for {@link InvokeModelCommand}. + */ +export interface InvokeModelCommandInput extends InvokeModelCommandInputType {} +/** + * @public + */ +export type InvokeModelCommandOutputType = Omit & { + body: Uint8ArrayBlobAdapter; +}; + +/** + * @public + * + * The output of {@link InvokeModelCommand}. + */ +export interface InvokeModelCommandOutput extends InvokeModelCommandOutputType, __MetadataBearer {} + +/** + * @public + *

Invokes the specified Bedrock model to run inference using the input provided in the request body. + * You use InvokeModel to run inference for text models, image models, and embedding models.

+ *

For more information about invoking models, see Using the API in the Bedrock User Guide.

+ *

For example requests, see Examples (after the Errors section).

+ * @example + * Use a bare-bones client and the command you need to make an API call. + * ```javascript + * import { BedrockRuntimeClient, InvokeModelCommand } from "@aws-sdk/client-bedrock-runtime"; // ES Modules import + * // const { BedrockRuntimeClient, InvokeModelCommand } = require("@aws-sdk/client-bedrock-runtime"); // CommonJS import + * const client = new BedrockRuntimeClient(config); + * const input = { // InvokeModelRequest + * body: "BLOB_VALUE", // required + * contentType: "STRING_VALUE", + * accept: "STRING_VALUE", + * modelId: "STRING_VALUE", // required + * }; + * const command = new InvokeModelCommand(input); + * const response = await client.send(command); + * // { // InvokeModelResponse + * // body: "BLOB_VALUE", // required + * // contentType: "STRING_VALUE", // required + * // }; + * + * ``` + * + * @param InvokeModelCommandInput - {@link InvokeModelCommandInput} + * @returns {@link InvokeModelCommandOutput} + * @see {@link InvokeModelCommandInput} for command's `input` shape. + * @see {@link InvokeModelCommandOutput} for command's `response` shape. + * @see {@link BedrockRuntimeClientResolvedConfig | config} for BedrockRuntimeClient's `config` shape. + * + * @throws {@link AccessDeniedException} (client fault) + *

The request is denied because of missing access permissions.

+ * + * @throws {@link InternalServerException} (server fault) + *

An internal server error occurred. Retry your request.

+ * + * @throws {@link ModelErrorException} (client fault) + *

The request failed due to an error while processing the model.

+ * + * @throws {@link ModelNotReadyException} (client fault) + *

The model specified in the request is not ready to serve inference requests.

+ * + * @throws {@link ModelTimeoutException} (client fault) + *

The request took too long to process. Processing time exceeded the model timeout length.

+ * + * @throws {@link ResourceNotFoundException} (client fault) + *

The specified resource ARN was not found. Check the ARN and try your request again.

+ * + * @throws {@link ServiceQuotaExceededException} (client fault) + *

The number of requests exceeds the service quota. Resubmit your request later.

+ * + * @throws {@link ThrottlingException} (client fault) + *

The number of requests exceeds the limit. Resubmit your request later.

+ * + * @throws {@link ValidationException} (client fault) + *

Input validation failed. Check your request parameters and retry the request.

+ * + * @throws {@link BedrockRuntimeServiceException} + *

Base exception class for all service exceptions from BedrockRuntime service.

+ * + */ +export class InvokeModelCommand extends $Command< + InvokeModelCommandInput, + InvokeModelCommandOutput, + BedrockRuntimeClientResolvedConfig +> { + // Start section: command_properties + // End section: command_properties + + public static getEndpointParameterInstructions(): EndpointParameterInstructions { + return { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, + }; + } + + /** + * @public + */ + constructor(readonly input: InvokeModelCommandInput) { + // Start section: command_constructor + super(); + // End section: command_constructor + } + + /** + * @internal + */ + resolveMiddleware( + clientStack: MiddlewareStack, + configuration: BedrockRuntimeClientResolvedConfig, + options?: __HttpHandlerOptions + ): Handler { + this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize)); + this.middlewareStack.use(getEndpointPlugin(configuration, InvokeModelCommand.getEndpointParameterInstructions())); + + const stack = clientStack.concat(this.middlewareStack); + + const { logger } = configuration; + const clientName = "BedrockRuntimeClient"; + const commandName = "InvokeModelCommand"; + const handlerExecutionContext: HandlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog: InvokeModelRequestFilterSensitiveLog, + outputFilterSensitiveLog: InvokeModelResponseFilterSensitiveLog, + [SMITHY_CONTEXT_KEY]: { + service: "AmazonBedrockFrontendService", + operation: "InvokeModel", + }, + }; + const { requestHandler } = configuration; + return stack.resolve( + (request: FinalizeHandlerArguments) => + requestHandler.handle(request.request as __HttpRequest, options || {}), + handlerExecutionContext + ); + } + + /** + * @internal + */ + private serialize(input: InvokeModelCommandInput, context: __SerdeContext): Promise<__HttpRequest> { + return se_InvokeModelCommand(input, context); + } + + /** + * @internal + */ + private deserialize(output: __HttpResponse, context: __SerdeContext): Promise { + return de_InvokeModelCommand(output, context); + } + + // Start section: command_body_extra + // End section: command_body_extra +} diff --git a/clients/client-bedrock-runtime/src/commands/InvokeModelWithResponseStreamCommand.ts b/clients/client-bedrock-runtime/src/commands/InvokeModelWithResponseStreamCommand.ts new file mode 100644 index 0000000000000..4cf68e3cdff6a --- /dev/null +++ b/clients/client-bedrock-runtime/src/commands/InvokeModelWithResponseStreamCommand.ts @@ -0,0 +1,224 @@ +// smithy-typescript generated code +import { EndpointParameterInstructions, getEndpointPlugin } from "@smithy/middleware-endpoint"; +import { getSerdePlugin } from "@smithy/middleware-serde"; +import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@smithy/protocol-http"; +import { Command as $Command } from "@smithy/smithy-client"; +import { + BlobPayloadInputTypes, + EventStreamSerdeContext as __EventStreamSerdeContext, + FinalizeHandlerArguments, + Handler, + HandlerExecutionContext, + HttpHandlerOptions as __HttpHandlerOptions, + MetadataBearer as __MetadataBearer, + MiddlewareStack, + SerdeContext as __SerdeContext, + SMITHY_CONTEXT_KEY, +} from "@smithy/types"; + +import { BedrockRuntimeClientResolvedConfig, ServiceInputTypes, ServiceOutputTypes } from "../BedrockRuntimeClient"; +import { + InvokeModelWithResponseStreamRequest, + InvokeModelWithResponseStreamRequestFilterSensitiveLog, + InvokeModelWithResponseStreamResponse, + InvokeModelWithResponseStreamResponseFilterSensitiveLog, +} from "../models/models_0"; +import { + de_InvokeModelWithResponseStreamCommand, + se_InvokeModelWithResponseStreamCommand, +} from "../protocols/Aws_restJson1"; + +/** + * @public + */ +export { __MetadataBearer, $Command }; +/** + * @public + */ +export type InvokeModelWithResponseStreamCommandInputType = Omit & { + body: BlobPayloadInputTypes; +}; + +/** + * @public + * + * The input for {@link InvokeModelWithResponseStreamCommand}. + */ +export interface InvokeModelWithResponseStreamCommandInput extends InvokeModelWithResponseStreamCommandInputType {} +/** + * @public + * + * The output of {@link InvokeModelWithResponseStreamCommand}. + */ +export interface InvokeModelWithResponseStreamCommandOutput + extends InvokeModelWithResponseStreamResponse, + __MetadataBearer {} + +/** + * @public + *

Invoke the specified Bedrock model to run inference using the input provided. + * Return the response in a stream.

+ *

For more information about invoking models, see Using the API in the Bedrock User Guide.

+ *

For an example request and response, see Examples (after the Errors section).

+ * @example + * Use a bare-bones client and the command you need to make an API call. + * ```javascript + * import { BedrockRuntimeClient, InvokeModelWithResponseStreamCommand } from "@aws-sdk/client-bedrock-runtime"; // ES Modules import + * // const { BedrockRuntimeClient, InvokeModelWithResponseStreamCommand } = require("@aws-sdk/client-bedrock-runtime"); // CommonJS import + * const client = new BedrockRuntimeClient(config); + * const input = { // InvokeModelWithResponseStreamRequest + * body: "BLOB_VALUE", // required + * contentType: "STRING_VALUE", + * accept: "STRING_VALUE", + * modelId: "STRING_VALUE", // required + * }; + * const command = new InvokeModelWithResponseStreamCommand(input); + * const response = await client.send(command); + * // { // InvokeModelWithResponseStreamResponse + * // body: { // ResponseStream Union: only one key present + * // chunk: { // PayloadPart + * // bytes: "BLOB_VALUE", + * // }, + * // internalServerException: { // InternalServerException + * // message: "STRING_VALUE", + * // }, + * // modelStreamErrorException: { // ModelStreamErrorException + * // message: "STRING_VALUE", + * // originalStatusCode: Number("int"), + * // originalMessage: "STRING_VALUE", + * // }, + * // validationException: { // ValidationException + * // message: "STRING_VALUE", + * // }, + * // throttlingException: { // ThrottlingException + * // message: "STRING_VALUE", + * // }, + * // }, + * // contentType: "STRING_VALUE", // required + * // }; + * + * ``` + * + * @param InvokeModelWithResponseStreamCommandInput - {@link InvokeModelWithResponseStreamCommandInput} + * @returns {@link InvokeModelWithResponseStreamCommandOutput} + * @see {@link InvokeModelWithResponseStreamCommandInput} for command's `input` shape. + * @see {@link InvokeModelWithResponseStreamCommandOutput} for command's `response` shape. + * @see {@link BedrockRuntimeClientResolvedConfig | config} for BedrockRuntimeClient's `config` shape. + * + * @throws {@link AccessDeniedException} (client fault) + *

The request is denied because of missing access permissions.

+ * + * @throws {@link InternalServerException} (server fault) + *

An internal server error occurred. Retry your request.

+ * + * @throws {@link ModelErrorException} (client fault) + *

The request failed due to an error while processing the model.

+ * + * @throws {@link ModelNotReadyException} (client fault) + *

The model specified in the request is not ready to serve inference requests.

+ * + * @throws {@link ModelStreamErrorException} (client fault) + *

An error occurred while streaming the response.

+ * + * @throws {@link ModelTimeoutException} (client fault) + *

The request took too long to process. Processing time exceeded the model timeout length.

+ * + * @throws {@link ResourceNotFoundException} (client fault) + *

The specified resource ARN was not found. Check the ARN and try your request again.

+ * + * @throws {@link ServiceQuotaExceededException} (client fault) + *

The number of requests exceeds the service quota. Resubmit your request later.

+ * + * @throws {@link ThrottlingException} (client fault) + *

The number of requests exceeds the limit. Resubmit your request later.

+ * + * @throws {@link ValidationException} (client fault) + *

Input validation failed. Check your request parameters and retry the request.

+ * + * @throws {@link BedrockRuntimeServiceException} + *

Base exception class for all service exceptions from BedrockRuntime service.

+ * + */ +export class InvokeModelWithResponseStreamCommand extends $Command< + InvokeModelWithResponseStreamCommandInput, + InvokeModelWithResponseStreamCommandOutput, + BedrockRuntimeClientResolvedConfig +> { + // Start section: command_properties + // End section: command_properties + + public static getEndpointParameterInstructions(): EndpointParameterInstructions { + return { + UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, + Endpoint: { type: "builtInParams", name: "endpoint" }, + Region: { type: "builtInParams", name: "region" }, + UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, + }; + } + + /** + * @public + */ + constructor(readonly input: InvokeModelWithResponseStreamCommandInput) { + // Start section: command_constructor + super(); + // End section: command_constructor + } + + /** + * @internal + */ + resolveMiddleware( + clientStack: MiddlewareStack, + configuration: BedrockRuntimeClientResolvedConfig, + options?: __HttpHandlerOptions + ): Handler { + this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize)); + this.middlewareStack.use( + getEndpointPlugin(configuration, InvokeModelWithResponseStreamCommand.getEndpointParameterInstructions()) + ); + + const stack = clientStack.concat(this.middlewareStack); + + const { logger } = configuration; + const clientName = "BedrockRuntimeClient"; + const commandName = "InvokeModelWithResponseStreamCommand"; + const handlerExecutionContext: HandlerExecutionContext = { + logger, + clientName, + commandName, + inputFilterSensitiveLog: InvokeModelWithResponseStreamRequestFilterSensitiveLog, + outputFilterSensitiveLog: InvokeModelWithResponseStreamResponseFilterSensitiveLog, + [SMITHY_CONTEXT_KEY]: { + service: "AmazonBedrockFrontendService", + operation: "InvokeModelWithResponseStream", + }, + }; + const { requestHandler } = configuration; + return stack.resolve( + (request: FinalizeHandlerArguments) => + requestHandler.handle(request.request as __HttpRequest, options || {}), + handlerExecutionContext + ); + } + + /** + * @internal + */ + private serialize(input: InvokeModelWithResponseStreamCommandInput, context: __SerdeContext): Promise<__HttpRequest> { + return se_InvokeModelWithResponseStreamCommand(input, context); + } + + /** + * @internal + */ + private deserialize( + output: __HttpResponse, + context: __SerdeContext & __EventStreamSerdeContext + ): Promise { + return de_InvokeModelWithResponseStreamCommand(output, context); + } + + // Start section: command_body_extra + // End section: command_body_extra +} diff --git a/clients/client-bedrock-runtime/src/commands/index.ts b/clients/client-bedrock-runtime/src/commands/index.ts new file mode 100644 index 0000000000000..4b63b4a661b51 --- /dev/null +++ b/clients/client-bedrock-runtime/src/commands/index.ts @@ -0,0 +1,3 @@ +// smithy-typescript generated code +export * from "./InvokeModelCommand"; +export * from "./InvokeModelWithResponseStreamCommand"; diff --git a/clients/client-bedrock-runtime/src/endpoint/EndpointParameters.ts b/clients/client-bedrock-runtime/src/endpoint/EndpointParameters.ts new file mode 100644 index 0000000000000..5f8d2e564e421 --- /dev/null +++ b/clients/client-bedrock-runtime/src/endpoint/EndpointParameters.ts @@ -0,0 +1,34 @@ +// smithy-typescript generated code +import { Endpoint, EndpointParameters as __EndpointParameters, EndpointV2, Provider } from "@smithy/types"; + +/** + * @public + */ +export interface ClientInputEndpointParameters { + region?: string | Provider; + useDualstackEndpoint?: boolean | Provider; + useFipsEndpoint?: boolean | Provider; + endpoint?: string | Provider | Endpoint | Provider | EndpointV2 | Provider; +} + +export type ClientResolvedEndpointParameters = ClientInputEndpointParameters & { + defaultSigningName: string; +}; + +export const resolveClientEndpointParameters = ( + options: T & ClientInputEndpointParameters +): T & ClientResolvedEndpointParameters => { + return { + ...options, + useDualstackEndpoint: options.useDualstackEndpoint ?? false, + useFipsEndpoint: options.useFipsEndpoint ?? false, + defaultSigningName: "bedrock", + }; +}; + +export interface EndpointParameters extends __EndpointParameters { + Region?: string; + UseDualStack?: boolean; + UseFIPS?: boolean; + Endpoint?: string; +} diff --git a/clients/client-bedrock-runtime/src/endpoint/endpointResolver.ts b/clients/client-bedrock-runtime/src/endpoint/endpointResolver.ts new file mode 100644 index 0000000000000..3fbea60c40b6e --- /dev/null +++ b/clients/client-bedrock-runtime/src/endpoint/endpointResolver.ts @@ -0,0 +1,16 @@ +// smithy-typescript generated code +import { EndpointParams, resolveEndpoint } from "@aws-sdk/util-endpoints"; +import { EndpointV2, Logger } from "@smithy/types"; + +import { EndpointParameters } from "./EndpointParameters"; +import { ruleSet } from "./ruleset"; + +export const defaultEndpointResolver = ( + endpointParams: EndpointParameters, + context: { logger?: Logger } = {} +): EndpointV2 => { + return resolveEndpoint(ruleSet, { + endpointParams: endpointParams as EndpointParams, + logger: context.logger, + }); +}; diff --git a/clients/client-bedrock-runtime/src/endpoint/ruleset.ts b/clients/client-bedrock-runtime/src/endpoint/ruleset.ts new file mode 100644 index 0000000000000..85b11dbdb2a67 --- /dev/null +++ b/clients/client-bedrock-runtime/src/endpoint/ruleset.ts @@ -0,0 +1,30 @@ +// @ts-nocheck +// generated code, do not edit +import { RuleSetObject } from "@smithy/types"; + +/* This file is compressed. Log this object + or see "smithy.rules#endpointRuleSet" + in codegen/sdk-codegen/aws-models/bedrock-runtime.json */ + +const q="required", +r="fn", +s="argv", +t="ref"; +const a="isSet", +b="tree", +c="error", +d="endpoint", +e="PartitionResult", +f={[q]:false,"type":"String"}, +g={[q]:true,"default":false,"type":"Boolean"}, +h={[t]:"Endpoint"}, +i={[r]:"booleanEquals",[s]:[{[t]:"UseFIPS"},true]}, +j={[r]:"booleanEquals",[s]:[{[t]:"UseDualStack"},true]}, +k={}, +l={[r]:"booleanEquals",[s]:[true,{[r]:"getAttr",[s]:[{[t]:e},"supportsFIPS"]}]}, +m={[r]:"booleanEquals",[s]:[true,{[r]:"getAttr",[s]:[{[t]:e},"supportsDualStack"]}]}, +n=[i], +o=[j], +p=[{[t]:"Region"}]; +const _data={version:"1.0",parameters:{Region:f,UseDualStack:g,UseFIPS:g,Endpoint:f},rules:[{conditions:[{[r]:a,[s]:[h]}],type:b,rules:[{conditions:n,error:"Invalid Configuration: FIPS and custom endpoint are not supported",type:c},{type:b,rules:[{conditions:o,error:"Invalid Configuration: Dualstack and custom endpoint are not supported",type:c},{endpoint:{url:h,properties:k,headers:k},type:d}]}]},{type:b,rules:[{conditions:[{[r]:a,[s]:p}],type:b,rules:[{conditions:[{[r]:"aws.partition",[s]:p,assign:e}],type:b,rules:[{conditions:[i,j],type:b,rules:[{conditions:[l,m],type:b,rules:[{type:b,rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:k,headers:k},type:d}]}]},{error:"FIPS and DualStack are enabled, but this partition does not support one or both",type:c}]},{conditions:n,type:b,rules:[{conditions:[l],type:b,rules:[{type:b,rules:[{endpoint:{url:"https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}",properties:k,headers:k},type:d}]}]},{error:"FIPS is enabled but this partition does not support FIPS",type:c}]},{conditions:o,type:b,rules:[{conditions:[m],type:b,rules:[{type:b,rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}",properties:k,headers:k},type:d}]}]},{error:"DualStack is enabled but this partition does not support DualStack",type:c}]},{type:b,rules:[{endpoint:{url:"https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}",properties:k,headers:k},type:d}]}]}]},{error:"Invalid Configuration: Missing Region",type:c}]}]}; +export const ruleSet: RuleSetObject = _data; diff --git a/clients/client-bedrock-runtime/src/extensionConfiguration.ts b/clients/client-bedrock-runtime/src/extensionConfiguration.ts new file mode 100644 index 0000000000000..ad359fff94681 --- /dev/null +++ b/clients/client-bedrock-runtime/src/extensionConfiguration.ts @@ -0,0 +1,12 @@ +// smithy-typescript generated code +import { AwsRegionExtensionConfiguration } from "@aws-sdk/types"; +import { HttpHandlerExtensionConfiguration } from "@smithy/protocol-http"; +import { DefaultExtensionConfiguration } from "@smithy/types"; + +/** + * @internal + */ +export interface BedrockRuntimeExtensionConfiguration + extends HttpHandlerExtensionConfiguration, + DefaultExtensionConfiguration, + AwsRegionExtensionConfiguration {} diff --git a/clients/client-bedrock-runtime/src/index.ts b/clients/client-bedrock-runtime/src/index.ts new file mode 100644 index 0000000000000..b1ca0ac953acc --- /dev/null +++ b/clients/client-bedrock-runtime/src/index.ts @@ -0,0 +1,14 @@ +// smithy-typescript generated code +/* eslint-disable */ +/** + *

Describes the API operations for running inference using Bedrock models.

+ * + * @packageDocumentation + */ +export * from "./BedrockRuntimeClient"; +export * from "./BedrockRuntime"; +export { ClientInputEndpointParameters } from "./endpoint/EndpointParameters"; +export * from "./commands"; +export * from "./models"; + +export { BedrockRuntimeServiceException } from "./models/BedrockRuntimeServiceException"; diff --git a/clients/client-bedrock-runtime/src/models/BedrockRuntimeServiceException.ts b/clients/client-bedrock-runtime/src/models/BedrockRuntimeServiceException.ts new file mode 100644 index 0000000000000..59f81e38a5416 --- /dev/null +++ b/clients/client-bedrock-runtime/src/models/BedrockRuntimeServiceException.ts @@ -0,0 +1,22 @@ +// smithy-typescript generated code +import { + ServiceException as __ServiceException, + ServiceExceptionOptions as __ServiceExceptionOptions, +} from "@smithy/smithy-client"; + +export { __ServiceException, __ServiceExceptionOptions }; + +/** + * @public + * + * Base exception class for all service exceptions from BedrockRuntime service. + */ +export class BedrockRuntimeServiceException extends __ServiceException { + /** + * @internal + */ + constructor(options: __ServiceExceptionOptions) { + super(options); + Object.setPrototypeOf(this, BedrockRuntimeServiceException.prototype); + } +} diff --git a/clients/client-bedrock-runtime/src/models/index.ts b/clients/client-bedrock-runtime/src/models/index.ts new file mode 100644 index 0000000000000..9eaceb12865f8 --- /dev/null +++ b/clients/client-bedrock-runtime/src/models/index.ts @@ -0,0 +1,2 @@ +// smithy-typescript generated code +export * from "./models_0"; diff --git a/clients/client-bedrock-runtime/src/models/models_0.ts b/clients/client-bedrock-runtime/src/models/models_0.ts new file mode 100644 index 0000000000000..2196b6942119a --- /dev/null +++ b/clients/client-bedrock-runtime/src/models/models_0.ts @@ -0,0 +1,511 @@ +// smithy-typescript generated code +import { ExceptionOptionType as __ExceptionOptionType, SENSITIVE_STRING } from "@smithy/smithy-client"; + +import { BedrockRuntimeServiceException as __BaseException } from "./BedrockRuntimeServiceException"; + +/** + * @public + *

The request is denied because of missing access permissions.

+ */ +export class AccessDeniedException extends __BaseException { + readonly name: "AccessDeniedException" = "AccessDeniedException"; + readonly $fault: "client" = "client"; + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "AccessDeniedException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, AccessDeniedException.prototype); + } +} + +/** + * @public + *

An internal server error occurred. Retry your request.

+ */ +export class InternalServerException extends __BaseException { + readonly name: "InternalServerException" = "InternalServerException"; + readonly $fault: "server" = "server"; + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "InternalServerException", + $fault: "server", + ...opts, + }); + Object.setPrototypeOf(this, InternalServerException.prototype); + } +} + +/** + * @public + */ +export interface InvokeModelRequest { + /** + * @public + *

Input data in the format specified in the content-type request header. To see the format and content of this field for different models, refer to Inference parameters.

+ */ + body: Uint8Array | undefined; + + /** + * @public + *

The MIME type of the input data in the request. The default value is + * application/json.

+ */ + contentType?: string; + + /** + * @public + *

The desired MIME type of the inference body in the response. The default value is + * application/json.

+ */ + accept?: string; + + /** + * @public + *

Identifier of the model.

+ */ + modelId: string | undefined; +} + +/** + * @public + */ +export interface InvokeModelResponse { + /** + * @public + *

Inference response from the model in the format specified in the content-type header field. To see the format and content of this field for different models, refer to Inference parameters.

+ */ + body: Uint8Array | undefined; + + /** + * @public + *

The MIME type of the inference result.

+ */ + contentType: string | undefined; +} + +/** + * @public + *

The request failed due to an error while processing the model.

+ */ +export class ModelErrorException extends __BaseException { + readonly name: "ModelErrorException" = "ModelErrorException"; + readonly $fault: "client" = "client"; + /** + * @public + *

The original status code.

+ */ + originalStatusCode?: number; + + /** + * @public + *

The resource name.

+ */ + resourceName?: string; + + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "ModelErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelErrorException.prototype); + this.originalStatusCode = opts.originalStatusCode; + this.resourceName = opts.resourceName; + } +} + +/** + * @public + *

The model specified in the request is not ready to serve inference requests.

+ */ +export class ModelNotReadyException extends __BaseException { + readonly name: "ModelNotReadyException" = "ModelNotReadyException"; + readonly $fault: "client" = "client"; + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "ModelNotReadyException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelNotReadyException.prototype); + } +} + +/** + * @public + *

The request took too long to process. Processing time exceeded the model timeout length.

+ */ +export class ModelTimeoutException extends __BaseException { + readonly name: "ModelTimeoutException" = "ModelTimeoutException"; + readonly $fault: "client" = "client"; + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "ModelTimeoutException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelTimeoutException.prototype); + } +} + +/** + * @public + *

The specified resource ARN was not found. Check the ARN and try your request again.

+ */ +export class ResourceNotFoundException extends __BaseException { + readonly name: "ResourceNotFoundException" = "ResourceNotFoundException"; + readonly $fault: "client" = "client"; + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "ResourceNotFoundException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ResourceNotFoundException.prototype); + } +} + +/** + * @public + *

The number of requests exceeds the service quota. Resubmit your request later.

+ */ +export class ServiceQuotaExceededException extends __BaseException { + readonly name: "ServiceQuotaExceededException" = "ServiceQuotaExceededException"; + readonly $fault: "client" = "client"; + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "ServiceQuotaExceededException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ServiceQuotaExceededException.prototype); + } +} + +/** + * @public + *

The number of requests exceeds the limit. Resubmit your request later.

+ */ +export class ThrottlingException extends __BaseException { + readonly name: "ThrottlingException" = "ThrottlingException"; + readonly $fault: "client" = "client"; + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "ThrottlingException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ThrottlingException.prototype); + } +} + +/** + * @public + *

Input validation failed. Check your request parameters and retry the request.

+ */ +export class ValidationException extends __BaseException { + readonly name: "ValidationException" = "ValidationException"; + readonly $fault: "client" = "client"; + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "ValidationException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ValidationException.prototype); + } +} + +/** + * @public + */ +export interface InvokeModelWithResponseStreamRequest { + /** + * @public + *

Inference input in the format specified by the + * content-type. To see the format and content of this field for different models, refer to Inference parameters.

+ */ + body: Uint8Array | undefined; + + /** + * @public + *

The MIME type of the input data in the request. The default value is + * application/json.

+ */ + contentType?: string; + + /** + * @public + *

The desired MIME type of the inference body in the response. The default value is + * application/json.

+ */ + accept?: string; + + /** + * @public + *

Id of the model to invoke using the streaming request.

+ */ + modelId: string | undefined; +} + +/** + * @public + *

Payload content included in the response.

+ */ +export interface PayloadPart { + /** + * @public + *

Base64-encoded bytes of payload data.

+ */ + bytes?: Uint8Array; +} + +/** + * @public + *

An error occurred while streaming the response.

+ */ +export class ModelStreamErrorException extends __BaseException { + readonly name: "ModelStreamErrorException" = "ModelStreamErrorException"; + readonly $fault: "client" = "client"; + /** + * @public + *

The original status code.

+ */ + originalStatusCode?: number; + + /** + * @public + *

The original message.

+ */ + originalMessage?: string; + + /** + * @internal + */ + constructor(opts: __ExceptionOptionType) { + super({ + name: "ModelStreamErrorException", + $fault: "client", + ...opts, + }); + Object.setPrototypeOf(this, ModelStreamErrorException.prototype); + this.originalStatusCode = opts.originalStatusCode; + this.originalMessage = opts.originalMessage; + } +} + +/** + * @public + *

Definition of content in the response stream.

+ */ +export type ResponseStream = + | ResponseStream.ChunkMember + | ResponseStream.InternalServerExceptionMember + | ResponseStream.ModelStreamErrorExceptionMember + | ResponseStream.ThrottlingExceptionMember + | ResponseStream.ValidationExceptionMember + | ResponseStream.$UnknownMember; + +/** + * @public + */ +export namespace ResponseStream { + /** + * @public + *

Content included in the response.

+ */ + export interface ChunkMember { + chunk: PayloadPart; + internalServerException?: never; + modelStreamErrorException?: never; + validationException?: never; + throttlingException?: never; + $unknown?: never; + } + + /** + * @public + *

An internal server error occurred. Retry your request.

+ */ + export interface InternalServerExceptionMember { + chunk?: never; + internalServerException: InternalServerException; + modelStreamErrorException?: never; + validationException?: never; + throttlingException?: never; + $unknown?: never; + } + + /** + * @public + *

An error occurred while streaming the response.

+ */ + export interface ModelStreamErrorExceptionMember { + chunk?: never; + internalServerException?: never; + modelStreamErrorException: ModelStreamErrorException; + validationException?: never; + throttlingException?: never; + $unknown?: never; + } + + /** + * @public + *

Input validation failed. Check your request parameters and retry the request.

+ */ + export interface ValidationExceptionMember { + chunk?: never; + internalServerException?: never; + modelStreamErrorException?: never; + validationException: ValidationException; + throttlingException?: never; + $unknown?: never; + } + + /** + * @public + *

The number of requests exceeds the limit. Resubmit your request later.

+ */ + export interface ThrottlingExceptionMember { + chunk?: never; + internalServerException?: never; + modelStreamErrorException?: never; + validationException?: never; + throttlingException: ThrottlingException; + $unknown?: never; + } + + /** + * @public + */ + export interface $UnknownMember { + chunk?: never; + internalServerException?: never; + modelStreamErrorException?: never; + validationException?: never; + throttlingException?: never; + $unknown: [string, any]; + } + + export interface Visitor { + chunk: (value: PayloadPart) => T; + internalServerException: (value: InternalServerException) => T; + modelStreamErrorException: (value: ModelStreamErrorException) => T; + validationException: (value: ValidationException) => T; + throttlingException: (value: ThrottlingException) => T; + _: (name: string, value: any) => T; + } + + export const visit = (value: ResponseStream, visitor: Visitor): T => { + if (value.chunk !== undefined) return visitor.chunk(value.chunk); + if (value.internalServerException !== undefined) + return visitor.internalServerException(value.internalServerException); + if (value.modelStreamErrorException !== undefined) + return visitor.modelStreamErrorException(value.modelStreamErrorException); + if (value.validationException !== undefined) return visitor.validationException(value.validationException); + if (value.throttlingException !== undefined) return visitor.throttlingException(value.throttlingException); + return visitor._(value.$unknown[0], value.$unknown[1]); + }; +} + +/** + * @public + */ +export interface InvokeModelWithResponseStreamResponse { + /** + * @public + *

Inference response from the model in the format specified by Content-Type. To see the format and content of this field for different models, refer to Inference parameters.

+ */ + body: AsyncIterable | undefined; + + /** + * @public + *

The MIME type of the inference result.

+ */ + contentType: string | undefined; +} + +/** + * @internal + */ +export const InvokeModelRequestFilterSensitiveLog = (obj: InvokeModelRequest): any => ({ + ...obj, + ...(obj.body && { body: SENSITIVE_STRING }), +}); + +/** + * @internal + */ +export const InvokeModelResponseFilterSensitiveLog = (obj: InvokeModelResponse): any => ({ + ...obj, + ...(obj.body && { body: SENSITIVE_STRING }), +}); + +/** + * @internal + */ +export const InvokeModelWithResponseStreamRequestFilterSensitiveLog = ( + obj: InvokeModelWithResponseStreamRequest +): any => ({ + ...obj, + ...(obj.body && { body: SENSITIVE_STRING }), +}); + +/** + * @internal + */ +export const PayloadPartFilterSensitiveLog = (obj: PayloadPart): any => ({ + ...obj, + ...(obj.bytes && { bytes: SENSITIVE_STRING }), +}); + +/** + * @internal + */ +export const ResponseStreamFilterSensitiveLog = (obj: ResponseStream): any => { + if (obj.chunk !== undefined) return { chunk: SENSITIVE_STRING }; + if (obj.internalServerException !== undefined) return { internalServerException: obj.internalServerException }; + if (obj.modelStreamErrorException !== undefined) return { modelStreamErrorException: obj.modelStreamErrorException }; + if (obj.validationException !== undefined) return { validationException: obj.validationException }; + if (obj.throttlingException !== undefined) return { throttlingException: obj.throttlingException }; + if (obj.$unknown !== undefined) return { [obj.$unknown[0]]: "UNKNOWN" }; +}; + +/** + * @internal + */ +export const InvokeModelWithResponseStreamResponseFilterSensitiveLog = ( + obj: InvokeModelWithResponseStreamResponse +): any => ({ + ...obj, + ...(obj.body && { body: "STREAMING_CONTENT" }), +}); diff --git a/clients/client-bedrock-runtime/src/protocols/Aws_restJson1.ts b/clients/client-bedrock-runtime/src/protocols/Aws_restJson1.ts new file mode 100644 index 0000000000000..7f6332d488371 --- /dev/null +++ b/clients/client-bedrock-runtime/src/protocols/Aws_restJson1.ts @@ -0,0 +1,595 @@ +// smithy-typescript generated code +import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@smithy/protocol-http"; +import { + _json, + collectBody, + decorateServiceException as __decorateServiceException, + expectInt32 as __expectInt32, + expectString as __expectString, + map, + resolvedPath as __resolvedPath, + take, + withBaseException, +} from "@smithy/smithy-client"; +import { + Endpoint as __Endpoint, + EventStreamSerdeContext as __EventStreamSerdeContext, + ResponseMetadata as __ResponseMetadata, + SerdeContext as __SerdeContext, +} from "@smithy/types"; + +import { InvokeModelCommandInput, InvokeModelCommandOutput } from "../commands/InvokeModelCommand"; +import { + InvokeModelWithResponseStreamCommandInput, + InvokeModelWithResponseStreamCommandOutput, +} from "../commands/InvokeModelWithResponseStreamCommand"; +import { BedrockRuntimeServiceException as __BaseException } from "../models/BedrockRuntimeServiceException"; +import { + AccessDeniedException, + InternalServerException, + ModelErrorException, + ModelNotReadyException, + ModelStreamErrorException, + ModelTimeoutException, + PayloadPart, + ResourceNotFoundException, + ResponseStream, + ServiceQuotaExceededException, + ThrottlingException, + ValidationException, +} from "../models/models_0"; + +/** + * serializeAws_restJson1InvokeModelCommand + */ +export const se_InvokeModelCommand = async ( + input: InvokeModelCommandInput, + context: __SerdeContext +): Promise<__HttpRequest> => { + const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); + const headers: any = map({}, isSerializableHeaderValue, { + "content-type": input.contentType! || "application/octet-stream", + accept: input.accept!, + }); + let resolvedPath = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + "/model/{modelId}/invoke"; + resolvedPath = __resolvedPath(resolvedPath, input, "modelId", () => input.modelId!, "{modelId}", false); + let body: any; + if (input.body !== undefined) { + body = input.body; + } + return new __HttpRequest({ + protocol, + hostname, + port, + method: "POST", + headers, + path: resolvedPath, + body, + }); +}; + +/** + * serializeAws_restJson1InvokeModelWithResponseStreamCommand + */ +export const se_InvokeModelWithResponseStreamCommand = async ( + input: InvokeModelWithResponseStreamCommandInput, + context: __SerdeContext +): Promise<__HttpRequest> => { + const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); + const headers: any = map({}, isSerializableHeaderValue, { + "content-type": input.contentType! || "application/octet-stream", + "x-amzn-bedrock-accept": input.accept!, + }); + let resolvedPath = + `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + + "/model/{modelId}/invoke-with-response-stream"; + resolvedPath = __resolvedPath(resolvedPath, input, "modelId", () => input.modelId!, "{modelId}", false); + let body: any; + if (input.body !== undefined) { + body = input.body; + } + return new __HttpRequest({ + protocol, + hostname, + port, + method: "POST", + headers, + path: resolvedPath, + body, + }); +}; + +/** + * deserializeAws_restJson1InvokeModelCommand + */ +export const de_InvokeModelCommand = async ( + output: __HttpResponse, + context: __SerdeContext +): Promise => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_InvokeModelCommandError(output, context); + } + const contents: any = map({ + $metadata: deserializeMetadata(output), + contentType: [, output.headers["content-type"]], + }); + const data: any = await collectBody(output.body, context); + contents.body = data; + return contents; +}; + +/** + * deserializeAws_restJson1InvokeModelCommandError + */ +const de_InvokeModelCommandError = async ( + output: __HttpResponse, + context: __SerdeContext +): Promise => { + const parsedOutput: any = { + ...output, + body: await parseErrorBody(output.body, context), + }; + const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); + switch (errorCode) { + case "AccessDeniedException": + case "com.amazonaws.bedrockruntime#AccessDeniedException": + throw await de_AccessDeniedExceptionRes(parsedOutput, context); + case "InternalServerException": + case "com.amazonaws.bedrockruntime#InternalServerException": + throw await de_InternalServerExceptionRes(parsedOutput, context); + case "ModelErrorException": + case "com.amazonaws.bedrockruntime#ModelErrorException": + throw await de_ModelErrorExceptionRes(parsedOutput, context); + case "ModelNotReadyException": + case "com.amazonaws.bedrockruntime#ModelNotReadyException": + throw await de_ModelNotReadyExceptionRes(parsedOutput, context); + case "ModelTimeoutException": + case "com.amazonaws.bedrockruntime#ModelTimeoutException": + throw await de_ModelTimeoutExceptionRes(parsedOutput, context); + case "ResourceNotFoundException": + case "com.amazonaws.bedrockruntime#ResourceNotFoundException": + throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); + case "ServiceQuotaExceededException": + case "com.amazonaws.bedrockruntime#ServiceQuotaExceededException": + throw await de_ServiceQuotaExceededExceptionRes(parsedOutput, context); + case "ThrottlingException": + case "com.amazonaws.bedrockruntime#ThrottlingException": + throw await de_ThrottlingExceptionRes(parsedOutput, context); + case "ValidationException": + case "com.amazonaws.bedrockruntime#ValidationException": + throw await de_ValidationExceptionRes(parsedOutput, context); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody, + errorCode, + }); + } +}; + +/** + * deserializeAws_restJson1InvokeModelWithResponseStreamCommand + */ +export const de_InvokeModelWithResponseStreamCommand = async ( + output: __HttpResponse, + context: __SerdeContext & __EventStreamSerdeContext +): Promise => { + if (output.statusCode !== 200 && output.statusCode >= 300) { + return de_InvokeModelWithResponseStreamCommandError(output, context); + } + const contents: any = map({ + $metadata: deserializeMetadata(output), + contentType: [, output.headers["x-amzn-bedrock-content-type"]], + }); + const data: any = output.body; + contents.body = de_ResponseStream(data, context); + return contents; +}; + +/** + * deserializeAws_restJson1InvokeModelWithResponseStreamCommandError + */ +const de_InvokeModelWithResponseStreamCommandError = async ( + output: __HttpResponse, + context: __SerdeContext +): Promise => { + const parsedOutput: any = { + ...output, + body: await parseErrorBody(output.body, context), + }; + const errorCode = loadRestJsonErrorCode(output, parsedOutput.body); + switch (errorCode) { + case "AccessDeniedException": + case "com.amazonaws.bedrockruntime#AccessDeniedException": + throw await de_AccessDeniedExceptionRes(parsedOutput, context); + case "InternalServerException": + case "com.amazonaws.bedrockruntime#InternalServerException": + throw await de_InternalServerExceptionRes(parsedOutput, context); + case "ModelErrorException": + case "com.amazonaws.bedrockruntime#ModelErrorException": + throw await de_ModelErrorExceptionRes(parsedOutput, context); + case "ModelNotReadyException": + case "com.amazonaws.bedrockruntime#ModelNotReadyException": + throw await de_ModelNotReadyExceptionRes(parsedOutput, context); + case "ModelStreamErrorException": + case "com.amazonaws.bedrockruntime#ModelStreamErrorException": + throw await de_ModelStreamErrorExceptionRes(parsedOutput, context); + case "ModelTimeoutException": + case "com.amazonaws.bedrockruntime#ModelTimeoutException": + throw await de_ModelTimeoutExceptionRes(parsedOutput, context); + case "ResourceNotFoundException": + case "com.amazonaws.bedrockruntime#ResourceNotFoundException": + throw await de_ResourceNotFoundExceptionRes(parsedOutput, context); + case "ServiceQuotaExceededException": + case "com.amazonaws.bedrockruntime#ServiceQuotaExceededException": + throw await de_ServiceQuotaExceededExceptionRes(parsedOutput, context); + case "ThrottlingException": + case "com.amazonaws.bedrockruntime#ThrottlingException": + throw await de_ThrottlingExceptionRes(parsedOutput, context); + case "ValidationException": + case "com.amazonaws.bedrockruntime#ValidationException": + throw await de_ValidationExceptionRes(parsedOutput, context); + default: + const parsedBody = parsedOutput.body; + return throwDefaultError({ + output, + parsedBody, + errorCode, + }); + } +}; + +const throwDefaultError = withBaseException(__BaseException); +/** + * deserializeAws_restJson1AccessDeniedExceptionRes + */ +const de_AccessDeniedExceptionRes = async ( + parsedOutput: any, + context: __SerdeContext +): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new AccessDeniedException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1InternalServerExceptionRes + */ +const de_InternalServerExceptionRes = async ( + parsedOutput: any, + context: __SerdeContext +): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new InternalServerException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1ModelErrorExceptionRes + */ +const de_ModelErrorExceptionRes = async (parsedOutput: any, context: __SerdeContext): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + originalStatusCode: __expectInt32, + resourceName: __expectString, + }); + Object.assign(contents, doc); + const exception = new ModelErrorException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1ModelNotReadyExceptionRes + */ +const de_ModelNotReadyExceptionRes = async ( + parsedOutput: any, + context: __SerdeContext +): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new ModelNotReadyException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1ModelStreamErrorExceptionRes + */ +const de_ModelStreamErrorExceptionRes = async ( + parsedOutput: any, + context: __SerdeContext +): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + originalMessage: __expectString, + originalStatusCode: __expectInt32, + }); + Object.assign(contents, doc); + const exception = new ModelStreamErrorException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1ModelTimeoutExceptionRes + */ +const de_ModelTimeoutExceptionRes = async ( + parsedOutput: any, + context: __SerdeContext +): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new ModelTimeoutException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1ResourceNotFoundExceptionRes + */ +const de_ResourceNotFoundExceptionRes = async ( + parsedOutput: any, + context: __SerdeContext +): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new ResourceNotFoundException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1ServiceQuotaExceededExceptionRes + */ +const de_ServiceQuotaExceededExceptionRes = async ( + parsedOutput: any, + context: __SerdeContext +): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new ServiceQuotaExceededException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1ThrottlingExceptionRes + */ +const de_ThrottlingExceptionRes = async (parsedOutput: any, context: __SerdeContext): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new ThrottlingException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1ValidationExceptionRes + */ +const de_ValidationExceptionRes = async (parsedOutput: any, context: __SerdeContext): Promise => { + const contents: any = map({}); + const data: any = parsedOutput.body; + const doc = take(data, { + message: __expectString, + }); + Object.assign(contents, doc); + const exception = new ValidationException({ + $metadata: deserializeMetadata(parsedOutput), + ...contents, + }); + return __decorateServiceException(exception, parsedOutput.body); +}; + +/** + * deserializeAws_restJson1ResponseStream + */ +const de_ResponseStream = ( + output: any, + context: __SerdeContext & __EventStreamSerdeContext +): AsyncIterable => { + return context.eventStreamMarshaller.deserialize(output, async (event) => { + if (event["chunk"] != null) { + return { + chunk: await de_PayloadPart_event(event["chunk"], context), + }; + } + if (event["internalServerException"] != null) { + return { + internalServerException: await de_InternalServerException_event(event["internalServerException"], context), + }; + } + if (event["modelStreamErrorException"] != null) { + return { + modelStreamErrorException: await de_ModelStreamErrorException_event( + event["modelStreamErrorException"], + context + ), + }; + } + if (event["validationException"] != null) { + return { + validationException: await de_ValidationException_event(event["validationException"], context), + }; + } + if (event["throttlingException"] != null) { + return { + throttlingException: await de_ThrottlingException_event(event["throttlingException"], context), + }; + } + return { $unknown: output }; + }); +}; +const de_InternalServerException_event = async ( + output: any, + context: __SerdeContext +): Promise => { + const parsedOutput: any = { + ...output, + body: await parseBody(output.body, context), + }; + return de_InternalServerExceptionRes(parsedOutput, context); +}; +const de_ModelStreamErrorException_event = async ( + output: any, + context: __SerdeContext +): Promise => { + const parsedOutput: any = { + ...output, + body: await parseBody(output.body, context), + }; + return de_ModelStreamErrorExceptionRes(parsedOutput, context); +}; +const de_PayloadPart_event = async (output: any, context: __SerdeContext): Promise => { + const contents: PayloadPart = {} as any; + const data: any = await parseBody(output.body, context); + Object.assign(contents, de_PayloadPart(data, context)); + return contents; +}; +const de_ThrottlingException_event = async (output: any, context: __SerdeContext): Promise => { + const parsedOutput: any = { + ...output, + body: await parseBody(output.body, context), + }; + return de_ThrottlingExceptionRes(parsedOutput, context); +}; +const de_ValidationException_event = async (output: any, context: __SerdeContext): Promise => { + const parsedOutput: any = { + ...output, + body: await parseBody(output.body, context), + }; + return de_ValidationExceptionRes(parsedOutput, context); +}; +/** + * deserializeAws_restJson1PayloadPart + */ +const de_PayloadPart = (output: any, context: __SerdeContext): PayloadPart => { + return take(output, { + bytes: context.base64Decoder, + }) as any; +}; + +const deserializeMetadata = (output: __HttpResponse): __ResponseMetadata => ({ + httpStatusCode: output.statusCode, + requestId: + output.headers["x-amzn-requestid"] ?? output.headers["x-amzn-request-id"] ?? output.headers["x-amz-request-id"], + extendedRequestId: output.headers["x-amz-id-2"], + cfId: output.headers["x-amz-cf-id"], +}); + +// Encode Uint8Array data into string with utf-8. +const collectBodyString = (streamBody: any, context: __SerdeContext): Promise => + collectBody(streamBody, context).then((body) => context.utf8Encoder(body)); + +const isSerializableHeaderValue = (value: any): boolean => + value !== undefined && + value !== null && + value !== "" && + (!Object.getOwnPropertyNames(value).includes("length") || value.length != 0) && + (!Object.getOwnPropertyNames(value).includes("size") || value.size != 0); + +const parseBody = (streamBody: any, context: __SerdeContext): any => + collectBodyString(streamBody, context).then((encoded) => { + if (encoded.length) { + return JSON.parse(encoded); + } + return {}; + }); + +const parseErrorBody = async (errorBody: any, context: __SerdeContext) => { + const value = await parseBody(errorBody, context); + value.message = value.message ?? value.Message; + return value; +}; + +/** + * Load an error code for the aws.rest-json-1.1 protocol. + */ +const loadRestJsonErrorCode = (output: __HttpResponse, data: any): string | undefined => { + const findKey = (object: any, key: string) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); + + const sanitizeErrorCode = (rawValue: string | number): string => { + let cleanValue = rawValue; + if (typeof cleanValue === "number") { + cleanValue = cleanValue.toString(); + } + if (cleanValue.indexOf(",") >= 0) { + cleanValue = cleanValue.split(",")[0]; + } + if (cleanValue.indexOf(":") >= 0) { + cleanValue = cleanValue.split(":")[0]; + } + if (cleanValue.indexOf("#") >= 0) { + cleanValue = cleanValue.split("#")[1]; + } + return cleanValue; + }; + + const headerKey = findKey(output.headers, "x-amzn-errortype"); + if (headerKey !== undefined) { + return sanitizeErrorCode(output.headers[headerKey]); + } + + if (data.code !== undefined) { + return sanitizeErrorCode(data.code); + } + + if (data["__type"] !== undefined) { + return sanitizeErrorCode(data["__type"]); + } +}; diff --git a/clients/client-bedrock-runtime/src/runtimeConfig.browser.ts b/clients/client-bedrock-runtime/src/runtimeConfig.browser.ts new file mode 100644 index 0000000000000..daff8b525fe1c --- /dev/null +++ b/clients/client-bedrock-runtime/src/runtimeConfig.browser.ts @@ -0,0 +1,46 @@ +// smithy-typescript generated code +// @ts-ignore: package.json will be imported from dist folders +import packageInfo from "../package.json"; // eslint-disable-line + +import { Sha256 } from "@aws-crypto/sha256-browser"; +import { defaultUserAgent } from "@aws-sdk/util-user-agent-browser"; +import { DEFAULT_USE_DUALSTACK_ENDPOINT, DEFAULT_USE_FIPS_ENDPOINT } from "@smithy/config-resolver"; +import { eventStreamSerdeProvider } from "@smithy/eventstream-serde-browser"; +import { FetchHttpHandler as RequestHandler, streamCollector } from "@smithy/fetch-http-handler"; +import { invalidProvider } from "@smithy/invalid-dependency"; +import { calculateBodyLength } from "@smithy/util-body-length-browser"; +import { DEFAULT_MAX_ATTEMPTS, DEFAULT_RETRY_MODE } from "@smithy/util-retry"; +import { BedrockRuntimeClientConfig } from "./BedrockRuntimeClient"; +import { getRuntimeConfig as getSharedRuntimeConfig } from "./runtimeConfig.shared"; +import { loadConfigsForDefaultMode } from "@smithy/smithy-client"; +import { resolveDefaultsModeConfig } from "@smithy/util-defaults-mode-browser"; + +/** + * @internal + */ +export const getRuntimeConfig = (config: BedrockRuntimeClientConfig) => { + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getSharedRuntimeConfig(config); + return { + ...clientSharedValues, + ...config, + runtime: "browser", + defaultsMode, + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + credentialDefaultProvider: + config?.credentialDefaultProvider ?? ((_: unknown) => () => Promise.reject(new Error("Credential is missing"))), + defaultUserAgentProvider: + config?.defaultUserAgentProvider ?? + defaultUserAgent({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }), + eventStreamSerdeProvider: config?.eventStreamSerdeProvider ?? eventStreamSerdeProvider, + maxAttempts: config?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS, + region: config?.region ?? invalidProvider("Region is missing"), + requestHandler: config?.requestHandler ?? new RequestHandler(defaultConfigProvider), + retryMode: config?.retryMode ?? (async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE), + sha256: config?.sha256 ?? Sha256, + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? (() => Promise.resolve(DEFAULT_USE_DUALSTACK_ENDPOINT)), + useFipsEndpoint: config?.useFipsEndpoint ?? (() => Promise.resolve(DEFAULT_USE_FIPS_ENDPOINT)), + }; +}; diff --git a/clients/client-bedrock-runtime/src/runtimeConfig.native.ts b/clients/client-bedrock-runtime/src/runtimeConfig.native.ts new file mode 100644 index 0000000000000..0066bdf58d487 --- /dev/null +++ b/clients/client-bedrock-runtime/src/runtimeConfig.native.ts @@ -0,0 +1,18 @@ +// smithy-typescript generated code +import { Sha256 } from "@aws-crypto/sha256-js"; + +import { BedrockRuntimeClientConfig } from "./BedrockRuntimeClient"; +import { getRuntimeConfig as getBrowserRuntimeConfig } from "./runtimeConfig.browser"; + +/** + * @internal + */ +export const getRuntimeConfig = (config: BedrockRuntimeClientConfig) => { + const browserDefaults = getBrowserRuntimeConfig(config); + return { + ...browserDefaults, + ...config, + runtime: "react-native", + sha256: config?.sha256 ?? Sha256, + }; +}; diff --git a/clients/client-bedrock-runtime/src/runtimeConfig.shared.ts b/clients/client-bedrock-runtime/src/runtimeConfig.shared.ts new file mode 100644 index 0000000000000..01a65ab76bb8d --- /dev/null +++ b/clients/client-bedrock-runtime/src/runtimeConfig.shared.ts @@ -0,0 +1,25 @@ +// smithy-typescript generated code +import { NoOpLogger } from "@smithy/smithy-client"; +import { parseUrl } from "@smithy/url-parser"; +import { fromBase64, toBase64 } from "@smithy/util-base64"; +import { fromUtf8, toUtf8 } from "@smithy/util-utf8"; + +import { BedrockRuntimeClientConfig } from "./BedrockRuntimeClient"; +import { defaultEndpointResolver } from "./endpoint/endpointResolver"; + +/** + * @internal + */ +export const getRuntimeConfig = (config: BedrockRuntimeClientConfig) => ({ + apiVersion: "2023-09-30", + base64Decoder: config?.base64Decoder ?? fromBase64, + base64Encoder: config?.base64Encoder ?? toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, + extensions: config?.extensions ?? [], + logger: config?.logger ?? new NoOpLogger(), + serviceId: config?.serviceId ?? "Bedrock Runtime", + urlParser: config?.urlParser ?? parseUrl, + utf8Decoder: config?.utf8Decoder ?? fromUtf8, + utf8Encoder: config?.utf8Encoder ?? toUtf8, +}); diff --git a/clients/client-bedrock-runtime/src/runtimeConfig.ts b/clients/client-bedrock-runtime/src/runtimeConfig.ts new file mode 100644 index 0000000000000..c620370911c08 --- /dev/null +++ b/clients/client-bedrock-runtime/src/runtimeConfig.ts @@ -0,0 +1,61 @@ +// smithy-typescript generated code +// @ts-ignore: package.json will be imported from dist folders +import packageInfo from "../package.json"; // eslint-disable-line + +import { decorateDefaultCredentialProvider } from "@aws-sdk/client-sts"; +import { defaultProvider as credentialDefaultProvider } from "@aws-sdk/credential-provider-node"; +import { defaultUserAgent } from "@aws-sdk/util-user-agent-node"; +import { + NODE_REGION_CONFIG_FILE_OPTIONS, + NODE_REGION_CONFIG_OPTIONS, + NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, + NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, +} from "@smithy/config-resolver"; +import { eventStreamSerdeProvider } from "@smithy/eventstream-serde-node"; +import { Hash } from "@smithy/hash-node"; +import { NODE_MAX_ATTEMPT_CONFIG_OPTIONS, NODE_RETRY_MODE_CONFIG_OPTIONS } from "@smithy/middleware-retry"; +import { loadConfig as loadNodeConfig } from "@smithy/node-config-provider"; +import { NodeHttpHandler as RequestHandler, streamCollector } from "@smithy/node-http-handler"; +import { calculateBodyLength } from "@smithy/util-body-length-node"; +import { DEFAULT_RETRY_MODE } from "@smithy/util-retry"; +import { BedrockRuntimeClientConfig } from "./BedrockRuntimeClient"; +import { getRuntimeConfig as getSharedRuntimeConfig } from "./runtimeConfig.shared"; +import { loadConfigsForDefaultMode } from "@smithy/smithy-client"; +import { resolveDefaultsModeConfig } from "@smithy/util-defaults-mode-node"; +import { emitWarningIfUnsupportedVersion } from "@smithy/smithy-client"; + +/** + * @internal + */ +export const getRuntimeConfig = (config: BedrockRuntimeClientConfig) => { + emitWarningIfUnsupportedVersion(process.version); + const defaultsMode = resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(loadConfigsForDefaultMode); + const clientSharedValues = getSharedRuntimeConfig(config); + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + bodyLengthChecker: config?.bodyLengthChecker ?? calculateBodyLength, + credentialDefaultProvider: + config?.credentialDefaultProvider ?? decorateDefaultCredentialProvider(credentialDefaultProvider), + defaultUserAgentProvider: + config?.defaultUserAgentProvider ?? + defaultUserAgent({ serviceId: clientSharedValues.serviceId, clientVersion: packageInfo.version }), + eventStreamSerdeProvider: config?.eventStreamSerdeProvider ?? eventStreamSerdeProvider, + maxAttempts: config?.maxAttempts ?? loadNodeConfig(NODE_MAX_ATTEMPT_CONFIG_OPTIONS), + region: config?.region ?? loadNodeConfig(NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS), + requestHandler: config?.requestHandler ?? new RequestHandler(defaultConfigProvider), + retryMode: + config?.retryMode ?? + loadNodeConfig({ + ...NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || DEFAULT_RETRY_MODE, + }), + sha256: config?.sha256 ?? Hash.bind(null, "sha256"), + streamCollector: config?.streamCollector ?? streamCollector, + useDualstackEndpoint: config?.useDualstackEndpoint ?? loadNodeConfig(NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS), + useFipsEndpoint: config?.useFipsEndpoint ?? loadNodeConfig(NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS), + }; +}; diff --git a/clients/client-bedrock-runtime/src/runtimeExtensions.ts b/clients/client-bedrock-runtime/src/runtimeExtensions.ts new file mode 100644 index 0000000000000..ecf070f5f2af7 --- /dev/null +++ b/clients/client-bedrock-runtime/src/runtimeExtensions.ts @@ -0,0 +1,45 @@ +// smithy-typescript generated code +import { + getAwsRegionExtensionConfiguration, + resolveAwsRegionExtensionConfiguration, +} from "@aws-sdk/region-config-resolver"; +import { getHttpHandlerExtensionConfiguration, resolveHttpHandlerRuntimeConfig } from "@smithy/protocol-http"; +import { getDefaultExtensionConfiguration, resolveDefaultRuntimeConfig } from "@smithy/smithy-client"; + +import { BedrockRuntimeExtensionConfiguration } from "./extensionConfiguration"; + +/** + * @public + */ +export interface RuntimeExtension { + configure(extensionConfiguration: BedrockRuntimeExtensionConfiguration): void; +} + +/** + * @public + */ +export interface RuntimeExtensionsConfig { + extensions: RuntimeExtension[]; +} + +const asPartial = >(t: T) => t; + +/** + * @internal + */ +export const resolveRuntimeExtensions = (runtimeConfig: any, extensions: RuntimeExtension[]) => { + const extensionConfiguration: BedrockRuntimeExtensionConfiguration = { + ...asPartial(getAwsRegionExtensionConfiguration(runtimeConfig)), + ...asPartial(getDefaultExtensionConfiguration(runtimeConfig)), + ...asPartial(getHttpHandlerExtensionConfiguration(runtimeConfig)), + }; + + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + + return { + ...runtimeConfig, + ...resolveAwsRegionExtensionConfiguration(extensionConfiguration), + ...resolveDefaultRuntimeConfig(extensionConfiguration), + ...resolveHttpHandlerRuntimeConfig(extensionConfiguration), + }; +}; diff --git a/clients/client-bedrock-runtime/tsconfig.cjs.json b/clients/client-bedrock-runtime/tsconfig.cjs.json new file mode 100644 index 0000000000000..3567d85ba8460 --- /dev/null +++ b/clients/client-bedrock-runtime/tsconfig.cjs.json @@ -0,0 +1,6 @@ +{ + "extends": "./tsconfig", + "compilerOptions": { + "outDir": "dist-cjs" + } +} diff --git a/clients/client-bedrock-runtime/tsconfig.es.json b/clients/client-bedrock-runtime/tsconfig.es.json new file mode 100644 index 0000000000000..809f57bde65e6 --- /dev/null +++ b/clients/client-bedrock-runtime/tsconfig.es.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig", + "compilerOptions": { + "lib": ["dom"], + "module": "esnext", + "outDir": "dist-es" + } +} diff --git a/clients/client-bedrock-runtime/tsconfig.json b/clients/client-bedrock-runtime/tsconfig.json new file mode 100644 index 0000000000000..344909de21289 --- /dev/null +++ b/clients/client-bedrock-runtime/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "@tsconfig/node14/tsconfig.json", + "compilerOptions": { + "downlevelIteration": true, + "importHelpers": true, + "incremental": true, + "removeComments": true, + "resolveJsonModule": true, + "rootDir": "src", + "useUnknownInCatchVariables": false + }, + "exclude": ["test/"] +} diff --git a/clients/client-bedrock-runtime/tsconfig.types.json b/clients/client-bedrock-runtime/tsconfig.types.json new file mode 100644 index 0000000000000..4c3dfa7b3d25f --- /dev/null +++ b/clients/client-bedrock-runtime/tsconfig.types.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig", + "compilerOptions": { + "removeComments": false, + "declaration": true, + "declarationDir": "dist-types", + "emitDeclarationOnly": true + }, + "exclude": ["test/**/*", "dist-types/**/*"] +} diff --git a/clients/client-bedrock-runtime/typedoc.json b/clients/client-bedrock-runtime/typedoc.json new file mode 100644 index 0000000000000..8a364aa93b692 --- /dev/null +++ b/clients/client-bedrock-runtime/typedoc.json @@ -0,0 +1,6 @@ +{ + "extends": ["../../typedoc.client.json"], + "entryPoints": ["src/index.ts"], + "out": "docs", + "readme": "README.md" +} diff --git a/codegen/sdk-codegen/aws-models/bedrock-runtime.json b/codegen/sdk-codegen/aws-models/bedrock-runtime.json new file mode 100644 index 0000000000000..fc51cf492928e --- /dev/null +++ b/codegen/sdk-codegen/aws-models/bedrock-runtime.json @@ -0,0 +1,1163 @@ +{ + "smithy": "2.0", + "shapes": { + "com.amazonaws.bedrockruntime#AccessDeniedException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + } + }, + "traits": { + "smithy.api#documentation": "

The request is denied because of missing access permissions.

", + "smithy.api#error": "client", + "smithy.api#httpError": 403 + } + }, + "com.amazonaws.bedrockruntime#AmazonBedrockFrontendService": { + "type": "service", + "version": "2023-09-30", + "resources": [ + { + "target": "com.amazonaws.bedrockruntime#InferenceResource" + } + ], + "traits": { + "aws.api#service": { + "sdkId": "Bedrock Runtime", + "endpointPrefix": "bedrock-runtime", + "cloudTrailEventSource": "bedrock.amazonaws.com" + }, + "aws.auth#sigv4": { + "name": "bedrock" + }, + "aws.protocols#restJson1": {}, + "smithy.api#documentation": "

Describes the API operations for running inference using Bedrock models.

", + "smithy.api#title": "Amazon Bedrock Runtime", + "smithy.rules#endpointRuleSet": { + "version": "1.0", + "parameters": { + "Region": { + "builtIn": "AWS::Region", + "required": false, + "documentation": "The AWS region used to dispatch the request.", + "type": "String" + }, + "UseDualStack": { + "builtIn": "AWS::UseDualStack", + "required": true, + "default": false, + "documentation": "When true, use the dual-stack endpoint. If the configured endpoint does not support dual-stack, dispatching the request MAY return an error.", + "type": "Boolean" + }, + "UseFIPS": { + "builtIn": "AWS::UseFIPS", + "required": true, + "default": false, + "documentation": "When true, send this request to the FIPS-compliant regional endpoint. If the configured endpoint does not have a FIPS compliant endpoint, dispatching the request will return an error.", + "type": "Boolean" + }, + "Endpoint": { + "builtIn": "SDK::Endpoint", + "required": false, + "documentation": "Override the endpoint used to send this request", + "type": "String" + } + }, + "rules": [ + { + "conditions": [ + { + "fn": "isSet", + "argv": [ + { + "ref": "Endpoint" + } + ] + } + ], + "type": "tree", + "rules": [ + { + "conditions": [ + { + "fn": "booleanEquals", + "argv": [ + { + "ref": "UseFIPS" + }, + true + ] + } + ], + "error": "Invalid Configuration: FIPS and custom endpoint are not supported", + "type": "error" + }, + { + "conditions": [], + "type": "tree", + "rules": [ + { + "conditions": [ + { + "fn": "booleanEquals", + "argv": [ + { + "ref": "UseDualStack" + }, + true + ] + } + ], + "error": "Invalid Configuration: Dualstack and custom endpoint are not supported", + "type": "error" + }, + { + "conditions": [], + "endpoint": { + "url": { + "ref": "Endpoint" + }, + "properties": {}, + "headers": {} + }, + "type": "endpoint" + } + ] + } + ] + }, + { + "conditions": [], + "type": "tree", + "rules": [ + { + "conditions": [ + { + "fn": "isSet", + "argv": [ + { + "ref": "Region" + } + ] + } + ], + "type": "tree", + "rules": [ + { + "conditions": [ + { + "fn": "aws.partition", + "argv": [ + { + "ref": "Region" + } + ], + "assign": "PartitionResult" + } + ], + "type": "tree", + "rules": [ + { + "conditions": [ + { + "fn": "booleanEquals", + "argv": [ + { + "ref": "UseFIPS" + }, + true + ] + }, + { + "fn": "booleanEquals", + "argv": [ + { + "ref": "UseDualStack" + }, + true + ] + } + ], + "type": "tree", + "rules": [ + { + "conditions": [ + { + "fn": "booleanEquals", + "argv": [ + true, + { + "fn": "getAttr", + "argv": [ + { + "ref": "PartitionResult" + }, + "supportsFIPS" + ] + } + ] + }, + { + "fn": "booleanEquals", + "argv": [ + true, + { + "fn": "getAttr", + "argv": [ + { + "ref": "PartitionResult" + }, + "supportsDualStack" + ] + } + ] + } + ], + "type": "tree", + "rules": [ + { + "conditions": [], + "type": "tree", + "rules": [ + { + "conditions": [], + "endpoint": { + "url": "https://bedrock-runtime-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", + "properties": {}, + "headers": {} + }, + "type": "endpoint" + } + ] + } + ] + }, + { + "conditions": [], + "error": "FIPS and DualStack are enabled, but this partition does not support one or both", + "type": "error" + } + ] + }, + { + "conditions": [ + { + "fn": "booleanEquals", + "argv": [ + { + "ref": "UseFIPS" + }, + true + ] + } + ], + "type": "tree", + "rules": [ + { + "conditions": [ + { + "fn": "booleanEquals", + "argv": [ + true, + { + "fn": "getAttr", + "argv": [ + { + "ref": "PartitionResult" + }, + "supportsFIPS" + ] + } + ] + } + ], + "type": "tree", + "rules": [ + { + "conditions": [], + "type": "tree", + "rules": [ + { + "conditions": [], + "endpoint": { + "url": "https://bedrock-runtime-fips.{Region}.{PartitionResult#dnsSuffix}", + "properties": {}, + "headers": {} + }, + "type": "endpoint" + } + ] + } + ] + }, + { + "conditions": [], + "error": "FIPS is enabled but this partition does not support FIPS", + "type": "error" + } + ] + }, + { + "conditions": [ + { + "fn": "booleanEquals", + "argv": [ + { + "ref": "UseDualStack" + }, + true + ] + } + ], + "type": "tree", + "rules": [ + { + "conditions": [ + { + "fn": "booleanEquals", + "argv": [ + true, + { + "fn": "getAttr", + "argv": [ + { + "ref": "PartitionResult" + }, + "supportsDualStack" + ] + } + ] + } + ], + "type": "tree", + "rules": [ + { + "conditions": [], + "type": "tree", + "rules": [ + { + "conditions": [], + "endpoint": { + "url": "https://bedrock-runtime.{Region}.{PartitionResult#dualStackDnsSuffix}", + "properties": {}, + "headers": {} + }, + "type": "endpoint" + } + ] + } + ] + }, + { + "conditions": [], + "error": "DualStack is enabled but this partition does not support DualStack", + "type": "error" + } + ] + }, + { + "conditions": [], + "type": "tree", + "rules": [ + { + "conditions": [], + "endpoint": { + "url": "https://bedrock-runtime.{Region}.{PartitionResult#dnsSuffix}", + "properties": {}, + "headers": {} + }, + "type": "endpoint" + } + ] + } + ] + } + ] + }, + { + "conditions": [], + "error": "Invalid Configuration: Missing Region", + "type": "error" + } + ] + } + ] + }, + "smithy.rules#endpointTests": { + "testCases": [ + { + "documentation": "For region us-east-1 with FIPS enabled and DualStack enabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime-fips.us-east-1.api.aws" + } + }, + "params": { + "Region": "us-east-1", + "UseFIPS": true, + "UseDualStack": true + } + }, + { + "documentation": "For region us-east-1 with FIPS enabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime-fips.us-east-1.amazonaws.com" + } + }, + "params": { + "Region": "us-east-1", + "UseFIPS": true, + "UseDualStack": false + } + }, + { + "documentation": "For region us-east-1 with FIPS disabled and DualStack enabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime.us-east-1.api.aws" + } + }, + "params": { + "Region": "us-east-1", + "UseFIPS": false, + "UseDualStack": true + } + }, + { + "documentation": "For region us-east-1 with FIPS disabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime.us-east-1.amazonaws.com" + } + }, + "params": { + "Region": "us-east-1", + "UseFIPS": false, + "UseDualStack": false + } + }, + { + "documentation": "For region cn-north-1 with FIPS enabled and DualStack enabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime-fips.cn-north-1.api.amazonwebservices.com.cn" + } + }, + "params": { + "Region": "cn-north-1", + "UseFIPS": true, + "UseDualStack": true + } + }, + { + "documentation": "For region cn-north-1 with FIPS enabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime-fips.cn-north-1.amazonaws.com.cn" + } + }, + "params": { + "Region": "cn-north-1", + "UseFIPS": true, + "UseDualStack": false + } + }, + { + "documentation": "For region cn-north-1 with FIPS disabled and DualStack enabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime.cn-north-1.api.amazonwebservices.com.cn" + } + }, + "params": { + "Region": "cn-north-1", + "UseFIPS": false, + "UseDualStack": true + } + }, + { + "documentation": "For region cn-north-1 with FIPS disabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime.cn-north-1.amazonaws.com.cn" + } + }, + "params": { + "Region": "cn-north-1", + "UseFIPS": false, + "UseDualStack": false + } + }, + { + "documentation": "For region us-gov-east-1 with FIPS enabled and DualStack enabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime-fips.us-gov-east-1.api.aws" + } + }, + "params": { + "Region": "us-gov-east-1", + "UseFIPS": true, + "UseDualStack": true + } + }, + { + "documentation": "For region us-gov-east-1 with FIPS enabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime-fips.us-gov-east-1.amazonaws.com" + } + }, + "params": { + "Region": "us-gov-east-1", + "UseFIPS": true, + "UseDualStack": false + } + }, + { + "documentation": "For region us-gov-east-1 with FIPS disabled and DualStack enabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime.us-gov-east-1.api.aws" + } + }, + "params": { + "Region": "us-gov-east-1", + "UseFIPS": false, + "UseDualStack": true + } + }, + { + "documentation": "For region us-gov-east-1 with FIPS disabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime.us-gov-east-1.amazonaws.com" + } + }, + "params": { + "Region": "us-gov-east-1", + "UseFIPS": false, + "UseDualStack": false + } + }, + { + "documentation": "For region us-iso-east-1 with FIPS enabled and DualStack enabled", + "expect": { + "error": "FIPS and DualStack are enabled, but this partition does not support one or both" + }, + "params": { + "Region": "us-iso-east-1", + "UseFIPS": true, + "UseDualStack": true + } + }, + { + "documentation": "For region us-iso-east-1 with FIPS enabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime-fips.us-iso-east-1.c2s.ic.gov" + } + }, + "params": { + "Region": "us-iso-east-1", + "UseFIPS": true, + "UseDualStack": false + } + }, + { + "documentation": "For region us-iso-east-1 with FIPS disabled and DualStack enabled", + "expect": { + "error": "DualStack is enabled but this partition does not support DualStack" + }, + "params": { + "Region": "us-iso-east-1", + "UseFIPS": false, + "UseDualStack": true + } + }, + { + "documentation": "For region us-iso-east-1 with FIPS disabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime.us-iso-east-1.c2s.ic.gov" + } + }, + "params": { + "Region": "us-iso-east-1", + "UseFIPS": false, + "UseDualStack": false + } + }, + { + "documentation": "For region us-isob-east-1 with FIPS enabled and DualStack enabled", + "expect": { + "error": "FIPS and DualStack are enabled, but this partition does not support one or both" + }, + "params": { + "Region": "us-isob-east-1", + "UseFIPS": true, + "UseDualStack": true + } + }, + { + "documentation": "For region us-isob-east-1 with FIPS enabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime-fips.us-isob-east-1.sc2s.sgov.gov" + } + }, + "params": { + "Region": "us-isob-east-1", + "UseFIPS": true, + "UseDualStack": false + } + }, + { + "documentation": "For region us-isob-east-1 with FIPS disabled and DualStack enabled", + "expect": { + "error": "DualStack is enabled but this partition does not support DualStack" + }, + "params": { + "Region": "us-isob-east-1", + "UseFIPS": false, + "UseDualStack": true + } + }, + { + "documentation": "For region us-isob-east-1 with FIPS disabled and DualStack disabled", + "expect": { + "endpoint": { + "url": "https://bedrock-runtime.us-isob-east-1.sc2s.sgov.gov" + } + }, + "params": { + "Region": "us-isob-east-1", + "UseFIPS": false, + "UseDualStack": false + } + }, + { + "documentation": "For custom endpoint with region set and fips disabled and dualstack disabled", + "expect": { + "endpoint": { + "url": "https://example.com" + } + }, + "params": { + "Region": "us-east-1", + "UseFIPS": false, + "UseDualStack": false, + "Endpoint": "https://example.com" + } + }, + { + "documentation": "For custom endpoint with region not set and fips disabled and dualstack disabled", + "expect": { + "endpoint": { + "url": "https://example.com" + } + }, + "params": { + "UseFIPS": false, + "UseDualStack": false, + "Endpoint": "https://example.com" + } + }, + { + "documentation": "For custom endpoint with fips enabled and dualstack disabled", + "expect": { + "error": "Invalid Configuration: FIPS and custom endpoint are not supported" + }, + "params": { + "Region": "us-east-1", + "UseFIPS": true, + "UseDualStack": false, + "Endpoint": "https://example.com" + } + }, + { + "documentation": "For custom endpoint with fips disabled and dualstack enabled", + "expect": { + "error": "Invalid Configuration: Dualstack and custom endpoint are not supported" + }, + "params": { + "Region": "us-east-1", + "UseFIPS": false, + "UseDualStack": true, + "Endpoint": "https://example.com" + } + }, + { + "documentation": "Missing region", + "expect": { + "error": "Invalid Configuration: Missing Region" + } + } + ], + "version": "1.0" + } + } + }, + "com.amazonaws.bedrockruntime#Body": { + "type": "blob", + "traits": { + "smithy.api#length": { + "max": 25000000 + }, + "smithy.api#sensitive": {} + } + }, + "com.amazonaws.bedrockruntime#InferenceResource": { + "type": "resource", + "operations": [ + { + "target": "com.amazonaws.bedrockruntime#InvokeModel" + }, + { + "target": "com.amazonaws.bedrockruntime#InvokeModelWithResponseStream" + } + ] + }, + "com.amazonaws.bedrockruntime#InternalServerException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + } + }, + "traits": { + "smithy.api#documentation": "

An internal server error occurred. Retry your request.

", + "smithy.api#error": "server", + "smithy.api#httpError": 500 + } + }, + "com.amazonaws.bedrockruntime#InvokeModel": { + "type": "operation", + "input": { + "target": "com.amazonaws.bedrockruntime#InvokeModelRequest" + }, + "output": { + "target": "com.amazonaws.bedrockruntime#InvokeModelResponse" + }, + "errors": [ + { + "target": "com.amazonaws.bedrockruntime#AccessDeniedException" + }, + { + "target": "com.amazonaws.bedrockruntime#InternalServerException" + }, + { + "target": "com.amazonaws.bedrockruntime#ModelErrorException" + }, + { + "target": "com.amazonaws.bedrockruntime#ModelNotReadyException" + }, + { + "target": "com.amazonaws.bedrockruntime#ModelTimeoutException" + }, + { + "target": "com.amazonaws.bedrockruntime#ResourceNotFoundException" + }, + { + "target": "com.amazonaws.bedrockruntime#ServiceQuotaExceededException" + }, + { + "target": "com.amazonaws.bedrockruntime#ThrottlingException" + }, + { + "target": "com.amazonaws.bedrockruntime#ValidationException" + } + ], + "traits": { + "smithy.api#documentation": "

Invokes the specified Bedrock model to run inference using the input provided in the request body. \n You use InvokeModel to run inference for text models, image models, and embedding models.

\n

For more information about invoking models, see Using the API in the Bedrock User Guide.

\n

For example requests, see Examples (after the Errors section).

", + "smithy.api#http": { + "code": 200, + "method": "POST", + "uri": "/model/{modelId}/invoke" + } + } + }, + "com.amazonaws.bedrockruntime#InvokeModelIdentifier": { + "type": "string", + "traits": { + "smithy.api#length": { + "min": 1, + "max": 2048 + }, + "smithy.api#pattern": "^(arn:aws(-[^:]+)?:bedrock:[a-z0-9-]{1,20}:(([0-9]{12}:custom-model/[a-z0-9-]{1,63}[.]{1}[a-z0-9-]{1,63}/[a-z0-9]{12})|(:foundation-model/[a-z0-9-]{1,63}[.]{1}[a-z0-9-]{1,63}([.]?[a-z0-9-]{1,63})([:][a-z0-9-]{1,63}){0,2})|([0-9]{12}:provisioned-model/[a-z0-9]{12})))|([a-z0-9-]{1,63}[.]{1}[a-z0-9-]{1,63}([.]?[a-z0-9-]{1,63})([:][a-z0-9-]{1,63}){0,2})|(([0-9a-zA-Z][_-]?)+)$" + } + }, + "com.amazonaws.bedrockruntime#InvokeModelRequest": { + "type": "structure", + "members": { + "body": { + "target": "com.amazonaws.bedrockruntime#Body", + "traits": { + "smithy.api#documentation": "

Input data in the format specified in the content-type request header. To see the format and content of this field for different models, refer to Inference parameters.

", + "smithy.api#httpPayload": {}, + "smithy.api#required": {} + } + }, + "contentType": { + "target": "com.amazonaws.bedrockruntime#MimeType", + "traits": { + "smithy.api#documentation": "

The MIME type of the input data in the request. The default value is\n application/json.

", + "smithy.api#httpHeader": "Content-Type" + } + }, + "accept": { + "target": "com.amazonaws.bedrockruntime#MimeType", + "traits": { + "smithy.api#documentation": "

The desired MIME type of the inference body in the response. The default value is\n application/json.

", + "smithy.api#httpHeader": "Accept" + } + }, + "modelId": { + "target": "com.amazonaws.bedrockruntime#InvokeModelIdentifier", + "traits": { + "smithy.api#documentation": "

Identifier of the model.

", + "smithy.api#httpLabel": {}, + "smithy.api#required": {} + } + } + }, + "traits": { + "smithy.api#input": {} + } + }, + "com.amazonaws.bedrockruntime#InvokeModelResponse": { + "type": "structure", + "members": { + "body": { + "target": "com.amazonaws.bedrockruntime#Body", + "traits": { + "smithy.api#documentation": "

Inference response from the model in the format specified in the content-type header field. To see the format and content of this field for different models, refer to Inference parameters.

", + "smithy.api#httpPayload": {}, + "smithy.api#required": {} + } + }, + "contentType": { + "target": "com.amazonaws.bedrockruntime#MimeType", + "traits": { + "smithy.api#documentation": "

The MIME type of the inference result.

", + "smithy.api#httpHeader": "Content-Type", + "smithy.api#required": {} + } + } + }, + "traits": { + "smithy.api#output": {} + } + }, + "com.amazonaws.bedrockruntime#InvokeModelWithResponseStream": { + "type": "operation", + "input": { + "target": "com.amazonaws.bedrockruntime#InvokeModelWithResponseStreamRequest" + }, + "output": { + "target": "com.amazonaws.bedrockruntime#InvokeModelWithResponseStreamResponse" + }, + "errors": [ + { + "target": "com.amazonaws.bedrockruntime#AccessDeniedException" + }, + { + "target": "com.amazonaws.bedrockruntime#InternalServerException" + }, + { + "target": "com.amazonaws.bedrockruntime#ModelErrorException" + }, + { + "target": "com.amazonaws.bedrockruntime#ModelNotReadyException" + }, + { + "target": "com.amazonaws.bedrockruntime#ModelStreamErrorException" + }, + { + "target": "com.amazonaws.bedrockruntime#ModelTimeoutException" + }, + { + "target": "com.amazonaws.bedrockruntime#ResourceNotFoundException" + }, + { + "target": "com.amazonaws.bedrockruntime#ServiceQuotaExceededException" + }, + { + "target": "com.amazonaws.bedrockruntime#ThrottlingException" + }, + { + "target": "com.amazonaws.bedrockruntime#ValidationException" + } + ], + "traits": { + "smithy.api#documentation": "

Invoke the specified Bedrock model to run inference using the input provided.\n Return the response in a stream.

\n

For more information about invoking models, see Using the API in the Bedrock User Guide.

\n

For an example request and response, see Examples (after the Errors section).

", + "smithy.api#http": { + "code": 200, + "method": "POST", + "uri": "/model/{modelId}/invoke-with-response-stream" + } + } + }, + "com.amazonaws.bedrockruntime#InvokeModelWithResponseStreamRequest": { + "type": "structure", + "members": { + "body": { + "target": "com.amazonaws.bedrockruntime#Body", + "traits": { + "smithy.api#documentation": "

Inference input in the format specified by the \n content-type. To see the format and content of this field for different models, refer to Inference parameters.

", + "smithy.api#httpPayload": {}, + "smithy.api#required": {} + } + }, + "contentType": { + "target": "com.amazonaws.bedrockruntime#MimeType", + "traits": { + "smithy.api#documentation": "

The MIME type of the input data in the request. The default value is\n application/json.

", + "smithy.api#httpHeader": "Content-Type" + } + }, + "accept": { + "target": "com.amazonaws.bedrockruntime#MimeType", + "traits": { + "smithy.api#documentation": "

The desired MIME type of the inference body in the response. The default value is\n application/json.

", + "smithy.api#httpHeader": "X-Amzn-Bedrock-Accept" + } + }, + "modelId": { + "target": "com.amazonaws.bedrockruntime#InvokeModelIdentifier", + "traits": { + "smithy.api#documentation": "

Id of the model to invoke using the streaming request.

", + "smithy.api#httpLabel": {}, + "smithy.api#required": {} + } + } + }, + "traits": { + "smithy.api#input": {} + } + }, + "com.amazonaws.bedrockruntime#InvokeModelWithResponseStreamResponse": { + "type": "structure", + "members": { + "body": { + "target": "com.amazonaws.bedrockruntime#ResponseStream", + "traits": { + "smithy.api#documentation": "

Inference response from the model in the format specified by Content-Type. To see the format and content of this field for different models, refer to Inference parameters.

", + "smithy.api#httpPayload": {}, + "smithy.api#required": {} + } + }, + "contentType": { + "target": "com.amazonaws.bedrockruntime#MimeType", + "traits": { + "smithy.api#documentation": "

The MIME type of the inference result.

", + "smithy.api#httpHeader": "X-Amzn-Bedrock-Content-Type", + "smithy.api#required": {} + } + } + }, + "traits": { + "smithy.api#output": {} + } + }, + "com.amazonaws.bedrockruntime#MimeType": { + "type": "string" + }, + "com.amazonaws.bedrockruntime#ModelErrorException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + }, + "originalStatusCode": { + "target": "com.amazonaws.bedrockruntime#StatusCode", + "traits": { + "smithy.api#documentation": "

The original status code.

" + } + }, + "resourceName": { + "target": "com.amazonaws.bedrockruntime#NonBlankString", + "traits": { + "smithy.api#documentation": "

The resource name.

" + } + } + }, + "traits": { + "smithy.api#documentation": "

The request failed due to an error while processing the model.

", + "smithy.api#error": "client", + "smithy.api#httpError": 424 + } + }, + "com.amazonaws.bedrockruntime#ModelNotReadyException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + } + }, + "traits": { + "smithy.api#documentation": "

The model specified in the request is not ready to serve inference requests.

", + "smithy.api#error": "client", + "smithy.api#httpError": 429 + } + }, + "com.amazonaws.bedrockruntime#ModelStreamErrorException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + }, + "originalStatusCode": { + "target": "com.amazonaws.bedrockruntime#StatusCode", + "traits": { + "smithy.api#documentation": "

The original status code.

" + } + }, + "originalMessage": { + "target": "com.amazonaws.bedrockruntime#NonBlankString", + "traits": { + "smithy.api#documentation": "

The original message.

" + } + } + }, + "traits": { + "smithy.api#documentation": "

An error occurred while streaming the response.

", + "smithy.api#error": "client", + "smithy.api#httpError": 424 + } + }, + "com.amazonaws.bedrockruntime#ModelTimeoutException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + } + }, + "traits": { + "smithy.api#documentation": "

The request took too long to process. Processing time exceeded the model timeout length.

", + "smithy.api#error": "client", + "smithy.api#httpError": 408 + } + }, + "com.amazonaws.bedrockruntime#NonBlankString": { + "type": "string", + "traits": { + "smithy.api#pattern": "^[\\s\\S]*$" + } + }, + "com.amazonaws.bedrockruntime#PartBody": { + "type": "blob", + "traits": { + "smithy.api#length": { + "max": 1000000 + }, + "smithy.api#sensitive": {} + } + }, + "com.amazonaws.bedrockruntime#PayloadPart": { + "type": "structure", + "members": { + "bytes": { + "target": "com.amazonaws.bedrockruntime#PartBody", + "traits": { + "smithy.api#documentation": "

Base64-encoded bytes of payload data.

" + } + } + }, + "traits": { + "smithy.api#documentation": "

Payload content included in the response.

", + "smithy.api#sensitive": {} + } + }, + "com.amazonaws.bedrockruntime#ResourceNotFoundException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + } + }, + "traits": { + "smithy.api#documentation": "

The specified resource ARN was not found. Check the ARN and try your request again.

", + "smithy.api#error": "client", + "smithy.api#httpError": 404 + } + }, + "com.amazonaws.bedrockruntime#ResponseStream": { + "type": "union", + "members": { + "chunk": { + "target": "com.amazonaws.bedrockruntime#PayloadPart", + "traits": { + "smithy.api#documentation": "

Content included in the response.

" + } + }, + "internalServerException": { + "target": "com.amazonaws.bedrockruntime#InternalServerException" + }, + "modelStreamErrorException": { + "target": "com.amazonaws.bedrockruntime#ModelStreamErrorException" + }, + "validationException": { + "target": "com.amazonaws.bedrockruntime#ValidationException" + }, + "throttlingException": { + "target": "com.amazonaws.bedrockruntime#ThrottlingException" + } + }, + "traits": { + "smithy.api#documentation": "

Definition of content in the response stream.

", + "smithy.api#streaming": {} + } + }, + "com.amazonaws.bedrockruntime#ServiceQuotaExceededException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + } + }, + "traits": { + "smithy.api#documentation": "

The number of requests exceeds the service quota. Resubmit your request later.

", + "smithy.api#error": "client", + "smithy.api#httpError": 400 + } + }, + "com.amazonaws.bedrockruntime#StatusCode": { + "type": "integer", + "traits": { + "smithy.api#range": { + "min": 100, + "max": 599 + } + } + }, + "com.amazonaws.bedrockruntime#ThrottlingException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + } + }, + "traits": { + "smithy.api#documentation": "

The number of requests exceeds the limit. Resubmit your request later.

", + "smithy.api#error": "client", + "smithy.api#httpError": 429 + } + }, + "com.amazonaws.bedrockruntime#ValidationException": { + "type": "structure", + "members": { + "message": { + "target": "com.amazonaws.bedrockruntime#NonBlankString" + } + }, + "traits": { + "smithy.api#documentation": "

Input validation failed. Check your request parameters and retry the request.

", + "smithy.api#error": "client", + "smithy.api#httpError": 400 + } + } + } +}