diff --git a/.doc_gen/metadata/batch_metadata.yaml b/.doc_gen/metadata/batch_metadata.yaml index e50b4b1594b..3d3c07b1ddc 100644 --- a/.doc_gen/metadata/batch_metadata.yaml +++ b/.doc_gen/metadata/batch_metadata.yaml @@ -174,8 +174,6 @@ batch_CreateComputeEnvironment: services: batch: {CreateComputeEnvironment} batch_Scenario: - title: Learn core operations for'&BATCHlong; using an &AWS; SDK - title_abbrev: Learn &BATCH; core operations synopsis_list: - Create an &BATCH; compute environment. - Check the status of the compute environment. @@ -185,7 +183,7 @@ batch_Scenario: - Get a list of jobs applicable to the job queue. - Check the status of job. - Delete &BATCH; resources. - category: Scenarios + category: Basics languages: Java: versions: diff --git a/.doc_gen/metadata/bedrock-runtime_metadata.yaml b/.doc_gen/metadata/bedrock-runtime_metadata.yaml index 76c13342060..36cb8c49cab 100644 --- a/.doc_gen/metadata/bedrock-runtime_metadata.yaml +++ b/.doc_gen/metadata/bedrock-runtime_metadata.yaml @@ -21,6 +21,20 @@ bedrock-runtime_Hello: - description: snippet_files: - javascriptv3/example_code/bedrock-runtime/hello.js + + Python: + versions: + - sdk_version: 3 + github: python/example_code/bedrock-runtime + sdkguide: + excerpts: + - description: Send a prompt to a model with the InvokeModel operation. + snippet_tags: + - bedrock-runtime.example_code.hello_bedrock_invoke.complete + - description: Send a user message to a model with the Converse operation. + snippet_tags: + - bedrock-runtime.example_code.hello_bedrock_converse.complete + services: bedrock-runtime: {InvokeModel} @@ -94,6 +108,26 @@ bedrock-runtime_Converse_AmazonNovaText: - description: Send a text message to Amazon Nova, using Bedrock's Converse API. snippet_tags: - javascript.v3.bedrock-runtime.Converse_AmazonTitanText + .NET: + versions: + - sdk_version: 3 + github: dotnetv3/Bedrock-runtime + excerpts: + - description: Send a text message to Amazon Nova, using Bedrock's Converse API. + snippet_tags: + - BedrockRuntime.dotnetv3.Converse_AmazonNovaText + - description: Send a conversation of messages to Amazon Nova using Bedrock's Converse API with a tool configuration. + genai: some + snippet_tags: + - Bedrock.ConverseTool.dotnetv3.SendConverseRequest + Python: + versions: + - sdk_version: 3 + github: python/example_code/bedrock-runtime + excerpts: + - description: Send a text message to Amazon Nova, using Bedrock's Converse API. + snippet_tags: + - python.example_code.bedrock-runtime.Converse_AmazonNovaText services: bedrock-runtime: {Converse} @@ -141,6 +175,60 @@ bedrock-runtime_Converse_AmazonTitanText: services: bedrock-runtime: {Converse} +bedrock-runtime_Scenario_ToolUse: + title: "A tool use example illustrating how to connect AI models on &BR; with a custom tool or API" + title_abbrev: "Tool use with the Converse API" + synopsis: "build a typical interaction between an application, a generative AI model, and connected tools or APIs to mediate interactions between the AI and the outside world. It uses the example of connecting an external weather API to the AI model so it can provide real-time weather information based on user input." + category: Scenarios + languages: + .NET: + versions: + - sdk_version: 3 + github: dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario + excerpts: + - description: "The primary execution of the scenario flow. This scenario orchestrates the conversation between the user, the &BR; Converse API, and a weather tool." + genai: some + snippet_tags: + - Bedrock.ConverseTool.dotnetv3.Scenario + - description: "The weather tool used by the demo. This file defines the tool specification and implements the logic to retrieve weather data using from the Open-Meteo API." + genai: some + snippet_tags: + - Bedrock.ConverseTool.dotnetv3.WeatherTool + - description: "The Converse API action with a tool configuration." + genai: some + snippet_tags: + - Bedrock.ConverseTool.dotnetv3.SendConverseRequest + Python: + versions: + - sdk_version: 3 + github: python/example_code/bedrock-runtime + excerpts: + - description: "The primary execution script of the demo. This script orchestrates the conversation between the user, the &BR; Converse API, and a weather tool." + snippet_files: + - python/example_code/bedrock-runtime/cross-model-scenarios/tool_use_demo/tool_use_demo.py + - description: "The weather tool used by the demo. This script defines the tool specification and implements the logic to retrieve weather data using from the Open-Meteo API." + snippet_files: + - python/example_code/bedrock-runtime/cross-model-scenarios/tool_use_demo/weather_tool.py + Rust: + versions: + - sdk_version: 1 + github: rustv1/examples/bedrock-runtime + excerpts: + - description: "The primary scenario and logic for the demo. This orchestrates the conversation between the user, the &BR; Converse API, and a weather tool." + snippet_tags: + - rust.bedrock-runtime.Converse_AnthropicClaude.tool-use + - description: "The weather tool used by the demo. This script defines the tool specification and implements the logic to retrieve weather data using from the Open-Meteo API." + snippet_tags: + - rust.bedrock-runtime.Converse_AnthropicClaude.tool-use.weather-tool + - description: "Utilities to print the Message Content Blocks." + snippet_tags: + - rust.bedrock-runtime.Converse_AnthropicClaude.tool-use.user-interface + - description: "Use statements, Error utility, and constants." + snippet_tags: + - rust.bedrock-runtime.Converse_AnthropicClaude.tool-use.supporting + services: + bedrock-runtime: {Converse} + bedrock-runtime_Converse_AnthropicClaude: title: Invoke Anthropic Claude on &BR; using Bedrock's Converse API title_abbrev: "Converse" @@ -351,6 +439,22 @@ bedrock-runtime_ConverseStream_AmazonNovaText: - description: Send a text message to Amazon Nova using Bedrock's Converse API and process the response stream in real-time. snippet_tags: - javascript.v3.bedrock-runtime.Converse_Mistral + .NET: + versions: + - sdk_version: 3 + github: dotnetv3/Bedrock-runtime + excerpts: + - description: Send a text message to Amazon Nova, using Bedrock's Converse API and process the response stream in real-time. + snippet_tags: + - BedrockRuntime.dotnetv3.ConverseStream_AmazonNovaText + Python: + versions: + - sdk_version: 3 + github: python/example_code/bedrock-runtime + excerpts: + - description: Send a text message to Amazon Nova, using Bedrock's Converse API and process the response stream in real-time. + snippet_tags: + - python.example_code.bedrock-runtime.ConverseStream_AmazonNovaText services: bedrock-runtime: {ConverseStream} @@ -643,6 +747,14 @@ bedrock-runtime_InvokeModel_TitanText: - description: Use the Invoke Model API to send a text message. snippet_tags: - bedrock-runtime.java2.InvokeModel_AmazonTitanText + Kotlin: + versions: + - sdk_version: 1 + github: kotlin/services/bedrock-runtime + excerpts: + - description: Use the Invoke Model API to generate a short story. + snippet_tags: + - bedrock-runtime.kotlin.InvokeModel_AmazonTitanText .NET: versions: - sdk_version: 3 @@ -1147,6 +1259,22 @@ bedrock-runtime_InvokeModel_AmazonNovaImageGeneration: - description: Create an image with Amazon Nova Canvas. snippet_tags: - javascript.v3.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration + .NET: + versions: + - sdk_version: 3 + github: dotnetv3/Bedrock-runtime + excerpts: + - description: Create an image with Amazon Nova Canvas. + snippet_tags: + - BedrockRuntime.dotnetv3.InvokeModel_AmazonNovaImageGeneration + Python: + versions: + - sdk_version: 3 + github: python/example_code/bedrock-runtime + excerpts: + - description: Create an image with the Amazon Nova Canvas. + snippet_tags: + - python.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration services: bedrock-runtime: {InvokeModel} @@ -1269,6 +1397,32 @@ bedrock-runtime_InvokeModelWithResponseStream_TitanTextEmbeddings: bedrock-runtime: {InvokeModel} # Tool use scenarios +bedrock-runtime_Scenario_ToolUseDemo_AmazonNova: + title: "A tool use demo illustrating how to connect AI models on &BR; with a custom tool or API" + title_abbrev: "Scenario: Tool use with the Converse API" + synopsis: "build a typical interaction between an application, a generative AI model, and connected tools or APIs to mediate interactions between the AI and the outside world. It uses the example of connecting an external weather API to the AI model so it can provide real-time weather information based on user input." + category: Amazon Nova + languages: + .NET: + versions: + - sdk_version: 3 + github: dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario + excerpts: + - description: "The primary execution of the scenario flow. This scenario orchestrates the conversation between the user, the &BR; Converse API, and a weather tool." + genai: some + snippet_tags: + - Bedrock.ConverseTool.dotnetv3.Scenario + - description: "The weather tool used by the demo. This file defines the tool specification and implements the logic to retrieve weather data using from the Open-Meteo API." + genai: some + snippet_tags: + - Bedrock.ConverseTool.dotnetv3.WeatherTool + - description: "The Converse API action with a tool configuration." + genai: some + snippet_tags: + - Bedrock.ConverseTool.dotnetv3.SendConverseRequest + services: + bedrock-runtime: {Converse} + bedrock-runtime_Scenario_ToolUseDemo_AnthropicClaude: title: "A tool use demo illustrating how to connect AI models on &BR; with a custom tool or API" title_abbrev: "Scenario: Tool use with the Converse API" @@ -1303,7 +1457,6 @@ bedrock-runtime_Scenario_ToolUseDemo_AnthropicClaude: - description: "Use statements, Error utility, and constants." snippet_tags: - rust.bedrock-runtime.Converse_AnthropicClaude.tool-use.supporting - services: bedrock-runtime: {Converse} diff --git a/.doc_gen/metadata/cross_metadata.yaml b/.doc_gen/metadata/cross_metadata.yaml index db05286b430..01931cd3ea2 100644 --- a/.doc_gen/metadata/cross_metadata.yaml +++ b/.doc_gen/metadata/cross_metadata.yaml @@ -16,7 +16,8 @@ cross_MessageProcessingFrameworkTutorial: cross_FSA: title: Create an application that analyzes customer feedback and synthesizes audio title_abbrev: Create an application to analyze customer feedback - synopsis: create an application that analyzes customer comment cards, translates them from their original language, determines + synopsis: + create an application that analyzes customer comment cards, translates them from their original language, determines their sentiment, and generates an audio file from the translated text. category: Scenarios languages: @@ -128,7 +129,8 @@ cross_SQSMessageApp: cross_RDSDataTracker: title: Create an &AUR; Serverless work item tracker title_abbrev: Create an &AUR; Serverless work item tracker - synopsis: create a web application that tracks work items in an &AURlong; Serverless database and uses &SESlong; (&SES;) + synopsis: + create a web application that tracks work items in an &AURlong; Serverless database and uses &SESlong; (&SES;) to send reports. category: Scenarios languages: @@ -242,7 +244,8 @@ cross_DynamoDBDataTracker: cross_ApiGatewayDataTracker: title: Create an &ABP; REST API to track COVID-19 data title_abbrev: Create a REST API to track COVID-19 data - synopsis: create a REST API that simulates a system to track daily cases of COVID-19 in the United States, using fictional + synopsis: + create a REST API that simulates a system to track daily cases of COVID-19 in the United States, using fictional data. category: Scenarios languages: @@ -276,7 +279,8 @@ cross_ApiGatewayWebsocketChat: cross_AuroraRestLendingLibrary: title: Create a lending library REST API title_abbrev: Create a lending library REST API - synopsis: create a lending library where patrons can borrow and return books by using a REST API backed by an &AURlong; + synopsis: + create a lending library where patrons can borrow and return books by using a REST API backed by an &AURlong; database. category: Scenarios languages: @@ -318,8 +322,6 @@ cross_TextractExplorer: versions: - sdk_version: 3 block_content: cross_TextractExplorer_JavaScript_block.xml - add_services: - cognito-identity: Python: versions: - sdk_version: 3 @@ -327,6 +329,7 @@ cross_TextractExplorer: block_content: cross_TextractExplorer_Python_block.xml service_main: textract services: + cognito-identity: s3: sns: sqs: @@ -379,16 +382,10 @@ cross_LambdaAPIGateway: versions: - sdk_version: 2 block_content: cross_LambdaAPIGateway_Java_block.xml - add_services: - dynamodb: - sns: JavaScript: versions: - sdk_version: 3 block_content: cross_LambdaAPIGateway_JavaScript_block.xml - add_services: - dynamodb: - sns: Python: versions: - sdk_version: 3 @@ -397,7 +394,9 @@ cross_LambdaAPIGateway: service_main: lambda services: api-gateway: + dynamodb: lambda: + sns: cross_LambdaScheduledEvents: title: Use scheduled events to invoke a &LAM; function title_abbrev: Use scheduled events to invoke a &LAM; function @@ -408,27 +407,22 @@ cross_LambdaScheduledEvents: versions: - sdk_version: 2 block_content: cross_LambdaScheduledEvents_Java_block.xml - add_services: - dynamodb: - sns: JavaScript: versions: - sdk_version: 3 block_content: cross_LambdaScheduledEvents_JavaScript_block.xml - add_services: - dynamodb: - sns: Python: versions: - sdk_version: 3 github: python/example_code/lambda block_content: cross_LambdaScheduledEvents_Python_block.xml - add_services: - cloudwatch-logs: service_main: lambda services: + cloudwatch-logs: + dynamodb: eventbridge: lambda: + sns: cross_ServerlessWorkflows: title: Use &SFN; to invoke &LAM; functions title_abbrev: Use &SFN; to invoke &LAM; functions @@ -520,20 +514,18 @@ cross_RekognitionVideoDetection: versions: - sdk_version: 2 block_content: cross_RekognitionVideoAnalyzer_Java_block.xml - add_services: - s3: - ses: Python: versions: - sdk_version: 3 github: python/example_code/rekognition block_content: cross_RekognitionVideoDetection_Python_block.xml - add_services: - sns: - sqs: service_main: rekognition services: rekognition: + s3: + ses: + sns: + sqs: cross_DetectFaces: title: Detect faces in an image using an &AWS; SDK title_abbrev: Detect faces in an image @@ -608,7 +600,8 @@ cross_LambdaForBrowser: cross_ResilientService: title: Build and manage a resilient service using an &AWS; SDK title_abbrev: Build and manage a resilient service - synopsis: create a load-balanced web service that returns book, movie, and song recommendations. The example shows how the + synopsis: + create a load-balanced web service that returns book, movie, and song recommendations. The example shows how the service responds to failures, and how to restructure the service for more resilience when failures occur. synopsis_list: - Use an &ASlong; group to create &EC2long; (&EC2;) instances based on a launch template and to keep the number of instances @@ -699,12 +692,38 @@ cross_ResilientService: snippet_files: - javascriptv3/example_code/cross-services/wkflw-resilient-service/steps-destroy.js services: - auto-scaling: {CreateAutoScalingGroup, DescribeAutoScalingGroups, TerminateInstanceInAutoScalingGroup, AttachLoadBalancerTargetGroups, - DeleteAutoScalingGroup, UpdateAutoScalingGroup} - ec2: {DescribeIamInstanceProfileAssociations, ReplaceIamInstanceProfileAssociation, RebootInstances, CreateLaunchTemplate, - DeleteLaunchTemplate, DescribeAvailabilityZones, DescribeInstances, DescribeVpcs, DescribeSubnets} - elastic-load-balancing-v2: {DescribeLoadBalancers, CreateTargetGroup, DescribeTargetGroups, DeleteTargetGroup, CreateLoadBalancer, - CreateListener, DeleteLoadBalancer, DescribeTargetHealth} + auto-scaling: + { + CreateAutoScalingGroup, + DescribeAutoScalingGroups, + TerminateInstanceInAutoScalingGroup, + AttachLoadBalancerTargetGroups, + DeleteAutoScalingGroup, + UpdateAutoScalingGroup, + } + ec2: + { + DescribeIamInstanceProfileAssociations, + ReplaceIamInstanceProfileAssociation, + RebootInstances, + CreateLaunchTemplate, + DeleteLaunchTemplate, + DescribeAvailabilityZones, + DescribeInstances, + DescribeVpcs, + DescribeSubnets, + } + elastic-load-balancing-v2: + { + DescribeLoadBalancers, + CreateTargetGroup, + DescribeTargetGroups, + DeleteTargetGroup, + CreateLoadBalancer, + CreateListener, + DeleteLoadBalancer, + DescribeTargetHealth, + } iam: {CreateInstanceProfile, DeleteInstanceProfile} cross_FMPlayground: title: Create a sample application that offers playgrounds to interact with &BR; foundation models using an &AWS; SDK @@ -854,7 +873,8 @@ cross_CognitoAutoConfirmUser: snippet_files: - javascriptv3/example_code/cross-services/wkflw-pools-triggers/actions/dynamodb-actions.js services: - cognito-identity-provider: {UpdateUserPool, SignUp, InitiateAuth, DeleteUser} + cognito-identity-provider: + {UpdateUserPool, SignUp, InitiateAuth, DeleteUser} lambda: {} cross_CognitoAutoMigrateUser: title: Automatically migrate known &COG; users with a &LAM; function using an &AWS; SDK @@ -899,7 +919,15 @@ cross_CognitoAutoMigrateUser: snippet_tags: - gov2.cognito-identity-provider.Resources.complete services: - cognito-identity-provider: {UpdateUserPool, SignUp, InitiateAuth, ForgotPassword, ConfirmForgotPassword, DeleteUser} + cognito-identity-provider: + { + UpdateUserPool, + SignUp, + InitiateAuth, + ForgotPassword, + ConfirmForgotPassword, + DeleteUser, + } lambda: {} cross_CognitoCustomActivityLog: title: Write custom activity data with a &LAM; function after &COG; user authentication using an &AWS; SDK @@ -944,7 +972,14 @@ cross_CognitoCustomActivityLog: snippet_tags: - gov2.cognito-identity-provider.Resources.complete services: - cognito-identity-provider: {UpdateUserPool, InitiateAuth, DeleteUser, AdminCreateUser, AdminSetUserPassword} + cognito-identity-provider: + { + UpdateUserPool, + InitiateAuth, + DeleteUser, + AdminCreateUser, + AdminSetUserPassword, + } lambda: {} cross_MonitorDynamoDB: title: Monitor performance of &DDBlong; using an &AWS; SDK diff --git a/.doc_gen/metadata/iot_metadata.yaml b/.doc_gen/metadata/iot_metadata.yaml index 8c75fada4d3..6339c137a6f 100644 --- a/.doc_gen/metadata/iot_metadata.yaml +++ b/.doc_gen/metadata/iot_metadata.yaml @@ -429,7 +429,18 @@ iot_CreateThing: services: iot: {CreateThing} iot_Scenario: - synopsis: work with &IoT; device management. + synopsis_list: + - Create an &IoT; Thing. + - Generate a device certificate. + - Update an &IoT; Thing with Attributes. + - Return a unique endpoint. + - List your &IoT; certificates. + - Create an &IoT; shadow. + - Write out state information. + - Creates a rule. + - List your rules. + - Search things using the Thing name. + - Delete an &IoT; Thing. category: Basics languages: Kotlin: diff --git a/.doc_gen/metadata/iot_sitewise_metadata.yaml b/.doc_gen/metadata/iot_sitewise_metadata.yaml index 6b067573271..d6dd34950e5 100644 --- a/.doc_gen/metadata/iot_sitewise_metadata.yaml +++ b/.doc_gen/metadata/iot_sitewise_metadata.yaml @@ -444,7 +444,16 @@ iotsitewise_CreateAssetModel: services: iotsitewise: {CreateAssetModel} iotsitewise_Scenario: - synopsis: learn core operations for &ITSWlong; using an &AWS; SDK. + synopsis_list: + - Create an &ITSWlong; Asset Model. + - Create an &ITSWlong; Asset. + - Retrieve the property ID values. + - Send data to an &ITSWlong; Asset. + - Retrieve the value of the &ITSWlong; Asset property. + - Create an &ITSWlong; Portal. + - Create an &ITSWlong; Gateway. + - Describe the &ITSWlong; Gateway. + - Delete the &ITSWlong; Assets. category: Basics languages: Java: diff --git a/.doc_gen/metadata/redshift_metadata.yaml b/.doc_gen/metadata/redshift_metadata.yaml index 2f4392bf8b7..d9627603d72 100644 --- a/.doc_gen/metadata/redshift_metadata.yaml +++ b/.doc_gen/metadata/redshift_metadata.yaml @@ -346,7 +346,14 @@ redshift_ExecuteStatement: services: redshift: {ExecuteStatement} redshift_Scenario: - synopsis: learn core operations for &RS; using an &AWS; SDK. + synopsis_list: + - Create a Redshift cluster. + - List databases in the cluster. + - Create a table named Movies. + - Populate the Movies table. + - Query the Movies table by year. + - Modify the Redshift cluster. + - Delete the Amazon Redshift cluster. category: Basics languages: Go: diff --git a/.doc_gen/metadata/sqs_metadata.yaml b/.doc_gen/metadata/sqs_metadata.yaml index 166119d1930..f3553187992 100644 --- a/.doc_gen/metadata/sqs_metadata.yaml +++ b/.doc_gen/metadata/sqs_metadata.yaml @@ -58,6 +58,18 @@ sqs_Hello: - description: Initialize an &SQS; client and list queues. snippet_tags: - javascript.v3.sqs.hello + Swift: + versions: + - sdk_version: 1 + github: swift/example_code/sqs + sdkguide: + excerpts: + - description: The Package.swift file. + snippet_tags: + - swift.sqs.basics.package + - description: The Swift source code, entry.swift. + snippet_tags: + - swift.sqs.basics services: sqs: {ListQueues} sqs_CreateQueue: @@ -163,6 +175,15 @@ sqs_CreateQueue: snippet_tags: - cpp.example_code.sqs.CreateQueue.config - cpp.example_code.sqs.CreateQueue + Swift: + versions: + - sdk_version: 1 + github: swift/example_code/sqs + sdkguide: + excerpts: + - description: + snippet_tags: + - swift.sqs.CreateQueue services: sqs: {CreateQueue} sqs_GetQueueUrl: @@ -320,6 +341,15 @@ sqs_ListQueues: snippet_tags: - cpp.example_code.sqs.ListQueues.config - cpp.example_code.sqs.ListQueues + Swift: + versions: + - sdk_version: 1 + github: swift/example_code/sqs + sdkguide: + excerpts: + - description: + snippet_tags: + - swift.sqs.ListQueues services: sqs: {ListQueues} sqs_DeleteQueue: @@ -414,6 +444,15 @@ sqs_DeleteQueue: snippet_tags: - cpp.example_code.sqs.DeleteQueue.config - cpp.example_code.sqs.DeleteQueue + Swift: + versions: + - sdk_version: 1 + github: swift/example_code/sqs + sdkguide: + excerpts: + - description: + snippet_tags: + - swift.sqs.DeleteQueue services: sqs: {DeleteQueue} sqs_SendMessage: @@ -649,6 +688,15 @@ sqs_ReceiveMessage: snippet_tags: - cpp.example_code.sqs.ReceiveMessage.config - cpp.example_code.sqs.ReceiveMessage + Swift: + versions: + - sdk_version: 1 + github: swift/example_code/sqs + sdkguide: + excerpts: + - description: + snippet_tags: + - swift.sqs.ReceiveMessage services: sqs: {ReceiveMessage} sqs_DeleteMessage: @@ -765,6 +813,15 @@ sqs_DeleteMessageBatch: - description: snippet_tags: - sqs.JavaScript.messages.receiveMessageV3 + Swift: + versions: + - sdk_version: 1 + github: swift/example_code/sqs + sdkguide: + excerpts: + - description: + snippet_tags: + - swift.sqs.DeleteMessageBatch services: sqs: {DeleteMessageBatch} sqs_Scenario_SendReceiveBatch: @@ -836,6 +893,15 @@ sqs_GetQueueAttributes: - description: snippet_tags: - javascript.v3.sqs.actions.GetQueueAttributes + Swift: + versions: + - sdk_version: 1 + github: swift/example_code/sqs + sdkguide: + excerpts: + - description: + snippet_tags: + - swift.sqs.GetQueueAttributes services: sqs: {GetQueueAttributes} sqs_ChangeMessageVisibility: @@ -931,6 +997,15 @@ sqs_SetQueueAttributes: - description: Configure a dead-letter queue. snippet_tags: - sqs.JavaScript.deadLetter.setQueueAttributesV3 + Swift: + versions: + - sdk_version: 1 + github: swift/example_code/sqs + sdkguide: + excerpts: + - description: + snippet_tags: + - swift.sqs.SetQueueAttributes services: sqs: {SetQueueAttributes} sqs_Scenario_TopicsAndQueues: diff --git a/.doc_gen/metadata/ssm_metadata.yaml b/.doc_gen/metadata/ssm_metadata.yaml index b3cc04d35b1..ed81ab102a8 100644 --- a/.doc_gen/metadata/ssm_metadata.yaml +++ b/.doc_gen/metadata/ssm_metadata.yaml @@ -412,7 +412,14 @@ ssm_UpdateOpsItem: services: ssm: {UpdateOpsItem} ssm_Scenario: - synopsis: work with &SYS; maintenance windows, documents, and OpsItems. + synopsis_list: + - Create a maintenance window. + - Modify the maintenance window schedule. + - Create a document. + - Send a command to a specified EC2 instance. + - Create an OpsItem. + - Update and resolve the OpsItem. + - Delete the maintenance window, OpsItem, and document. category: Basics languages: Java: diff --git a/.github/allowed-labels.yml b/.github/allowed-labels.yml index 2dd39429d1c..f6d223588a0 100644 --- a/.github/allowed-labels.yml +++ b/.github/allowed-labels.yml @@ -12,7 +12,7 @@ - name: MVP color: f5f7f9 description: "A Minimum Viable Product example to show the bare bones of how to use a service via an SDK." -- name: Workflow +- name: Feature Scenario color: f5f7f9 description: "A simple code example to show how certain tasks can be accomplished using several services and SDKs." - name: Basics diff --git a/.github/workflows/label-checker.yml b/.github/workflows/label-checker.yml index 6d26deb93d8..3c3893ecef9 100644 --- a/.github/workflows/label-checker.yml +++ b/.github/workflows/label-checker.yml @@ -26,5 +26,5 @@ jobs: steps: - uses: docker://agilepathway/pull-request-label-checker:latest with: - one_of: Application,MVP,Workflow,Task,Bug,Basics + one_of: Application,MVP,Feature Scenario,Task,Bug,Basics repo_token: ${{ secrets.GITHUB_TOKEN }} diff --git a/applications/feedback_sentiment_analyzer/client/package-lock.json b/applications/feedback_sentiment_analyzer/client/package-lock.json index 69247a2bd80..6db1c4f50c8 100644 --- a/applications/feedback_sentiment_analyzer/client/package-lock.json +++ b/applications/feedback_sentiment_analyzer/client/package-lock.json @@ -20,7 +20,7 @@ "@types/react-dom": "^18.2.4", "@vitejs/plugin-react": "^4.0.1", "typescript": "^5.1.3", - "vite": "^4.5.5" + "vite": "^4.5.9" } }, "node_modules/@ampproject/remapping": { @@ -1685,10 +1685,11 @@ } }, "node_modules/vite": { - "version": "4.5.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.5.tgz", - "integrity": "sha512-ifW3Lb2sMdX+WU91s3R0FyQlAyLxOzCSCP37ujw0+r5POeHPwe6udWVIElKQq8gk3t7b8rkmvqC6IHBpCff4GQ==", + "version": "4.5.9", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz", + "integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==", "dev": true, + "license": "MIT", "dependencies": { "esbuild": "^0.18.10", "postcss": "^8.4.27", @@ -2894,9 +2895,9 @@ "requires": {} }, "vite": { - "version": "4.5.5", - "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.5.tgz", - "integrity": "sha512-ifW3Lb2sMdX+WU91s3R0FyQlAyLxOzCSCP37ujw0+r5POeHPwe6udWVIElKQq8gk3t7b8rkmvqC6IHBpCff4GQ==", + "version": "4.5.9", + "resolved": "https://registry.npmjs.org/vite/-/vite-4.5.9.tgz", + "integrity": "sha512-qK9W4xjgD3gXbC0NmdNFFnVFLMWSNiR3swj957yutwzzN16xF/E7nmtAyp1rT9hviDroQANjE4HK3H4WqWdFtw==", "dev": true, "requires": { "esbuild": "^0.18.10", diff --git a/applications/feedback_sentiment_analyzer/client/package.json b/applications/feedback_sentiment_analyzer/client/package.json index 52e08a08e67..332c5a9ce7c 100644 --- a/applications/feedback_sentiment_analyzer/client/package.json +++ b/applications/feedback_sentiment_analyzer/client/package.json @@ -21,6 +21,6 @@ "@types/react-dom": "^18.2.4", "@vitejs/plugin-react": "^4.0.1", "typescript": "^5.1.3", - "vite": "^4.5.5" + "vite": "^4.5.9" } } diff --git a/cpp/example_code/iot/README.md b/cpp/example_code/iot/README.md index 9839fed6638..9497e020860 100644 --- a/cpp/example_code/iot/README.md +++ b/cpp/example_code/iot/README.md @@ -99,8 +99,19 @@ This example shows you how to get started using AWS IoT. #### Learn the basics -This example shows you how to work with AWS IoT device management. - +This example shows you how to do the following: + +- Create an AWS IoT Thing. +- Generate a device certificate. +- Update an AWS IoT Thing with Attributes. +- Return a unique endpoint. +- List your AWS IoT certificates. +- Create an AWS IoT shadow. +- Write out state information. +- Creates a rule. +- List your rules. +- Search things using the Thing name. +- Delete an AWS IoT Thing. @@ -140,4 +151,4 @@ This example shows you how to work with AWS IoT device management. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/dotnetv3/Bedrock-runtime/.gitignore b/dotnetv3/Bedrock-runtime/.gitignore index ba964e2a8e7..98ae3975334 100644 --- a/dotnetv3/Bedrock-runtime/.gitignore +++ b/dotnetv3/Bedrock-runtime/.gitignore @@ -1,2 +1,3 @@ /.vs/ /Tools/ +**/generated-images/ diff --git a/dotnetv3/Bedrock-runtime/BedrockRuntimeExamples.sln b/dotnetv3/Bedrock-runtime/BedrockRuntimeExamples.sln index f495e60e9b1..dd290cac66d 100644 --- a/dotnetv3/Bedrock-runtime/BedrockRuntimeExamples.sln +++ b/dotnetv3/Bedrock-runtime/BedrockRuntimeExamples.sln @@ -94,6 +94,26 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InvokeModelWithResponseStre EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "InvokeModelWithResponseStream", "Models\AnthropicClaude\InvokeModelWithResponseStream\InvokeModelWithResponseStream.csproj", "{C75F2BBE-7C84-4B01-9836-7279DAE41499}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AmazonNovaText", "AmazonNovaText", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AmazonNova", "AmazonNova", "{3AF63EC9-2EB0-4A0B-8C3B-0CA3595080F6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Converse", "Models\AmazonNova\AmazonNovaText\Converse\Converse.csproj", "{2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConverseStream", "Models\AmazonNova\AmazonNovaText\ConverseStream\ConverseStream.csproj", "{E144492A-337A-0755-EAB4-DA083C3A2DDB}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AmazonNovaCanvas", "AmazonNovaCanvas", "{4D3E429C-CCAE-42DE-A062-4717E71D8403}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "InvokeModel", "Models\AmazonNova\AmazonNovaCanvas\InvokeModel\InvokeModel.csproj", "{2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Actions", "Actions", "{FDC95D1E-41C6-45A5-BF29-F76FCC3DAEF9}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BedrockRuntimeActions", "Actions\BedrockRuntimeActions.csproj", "{ABA0C307-C7A1-4BBE-A7E2-4BA7163559FC}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Scenarios", "Scenarios", "{045D214B-6181-43B0-ABFE-246675F4D967}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConverseToolScenario", "Scenarios\ConverseToolScenario\ConverseToolScenario.csproj", "{C0A5B872-03F5-4865-9349-7A403591C50E}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -200,6 +220,26 @@ Global {C75F2BBE-7C84-4B01-9836-7279DAE41499}.Debug|Any CPU.Build.0 = Debug|Any CPU {C75F2BBE-7C84-4B01-9836-7279DAE41499}.Release|Any CPU.ActiveCfg = Release|Any CPU {C75F2BBE-7C84-4B01-9836-7279DAE41499}.Release|Any CPU.Build.0 = Release|Any CPU + {2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2E4C9BFE-C49C-0567-D73C-F2915AB62CA6}.Release|Any CPU.Build.0 = Release|Any CPU + {E144492A-337A-0755-EAB4-DA083C3A2DDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E144492A-337A-0755-EAB4-DA083C3A2DDB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E144492A-337A-0755-EAB4-DA083C3A2DDB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E144492A-337A-0755-EAB4-DA083C3A2DDB}.Release|Any CPU.Build.0 = Release|Any CPU + {2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D}.Release|Any CPU.Build.0 = Release|Any CPU + {ABA0C307-C7A1-4BBE-A7E2-4BA7163559FC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ABA0C307-C7A1-4BBE-A7E2-4BA7163559FC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {ABA0C307-C7A1-4BBE-A7E2-4BA7163559FC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ABA0C307-C7A1-4BBE-A7E2-4BA7163559FC}.Release|Any CPU.Build.0 = Release|Any CPU + {C0A5B872-03F5-4865-9349-7A403591C50E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C0A5B872-03F5-4865-9349-7A403591C50E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C0A5B872-03F5-4865-9349-7A403591C50E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C0A5B872-03F5-4865-9349-7A403591C50E}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -227,6 +267,7 @@ Global {3D6441FC-0FE8-4D0C-910D-3D9310599C71} = {3F96ECB4-1644-43E8-8643-2CDCF9E679F1} {D1B0719F-4F84-4DBC-BCAD-E856FB3193D7} = {8BAC2322-AD3C-484A-B51D-8263BC4E6646} {1E62D4FB-CC59-4F1E-BB22-574CEC08C94B} = {BBB79D3E-5DF2-4FF6-B467-52D0EEB91C4B} + {B753CEB9-EA53-4AE1-997E-B7D54A299D58} = {65504C76-7E32-4A12-A42E-BCDA4FE79BC1} {2A6989CB-B273-4841-BD3E-7B1BBA4DD25F} = {EF45C0B9-ED76-4B7A-A0A7-F102E979B71C} {BCC66C37-4980-484F-819D-066D2FF2669C} = {EF45C0B9-ED76-4B7A-A0A7-F102E979B71C} {52CDA3F4-F090-4224-978A-5F42388DCF92} = {3F96ECB4-1644-43E8-8643-2CDCF9E679F1} @@ -235,6 +276,14 @@ Global {4B5A00D6-B9F1-449F-A9D2-80E860D6BD75} = {65504C76-7E32-4A12-A42E-BCDA4FE79BC1} {EFC7D088-EF45-464B-97CD-0BBA486B224A} = {BBB79D3E-5DF2-4FF6-B467-52D0EEB91C4B} {C75F2BBE-7C84-4B01-9836-7279DAE41499} = {8BAC2322-AD3C-484A-B51D-8263BC4E6646} + {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} = {3AF63EC9-2EB0-4A0B-8C3B-0CA3595080F6} + {3AF63EC9-2EB0-4A0B-8C3B-0CA3595080F6} = {41B69207-8F29-41BC-9114-78EE740485C8} + {2E4C9BFE-C49C-0567-D73C-F2915AB62CA6} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {E144492A-337A-0755-EAB4-DA083C3A2DDB} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {4D3E429C-CCAE-42DE-A062-4717E71D8403} = {3AF63EC9-2EB0-4A0B-8C3B-0CA3595080F6} + {2B39D4E2-C6B6-4340-A9AD-5F5C25CA8C1D} = {4D3E429C-CCAE-42DE-A062-4717E71D8403} + {ABA0C307-C7A1-4BBE-A7E2-4BA7163559FC} = {FDC95D1E-41C6-45A5-BF29-F76FCC3DAEF9} + {C0A5B872-03F5-4865-9349-7A403591C50E} = {045D214B-6181-43B0-ABFE-246675F4D967} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {E48A5088-1BBB-4A8B-9AB2-CC5CE0482466} diff --git a/dotnetv3/Bedrock-runtime/Models/Ai21LabsJurassic2/Converse/Converse.csproj b/dotnetv3/Bedrock-runtime/Models/Ai21LabsJurassic2/Converse/Converse.csproj index 8475494e76e..c26f412667b 100644 --- a/dotnetv3/Bedrock-runtime/Models/Ai21LabsJurassic2/Converse/Converse.csproj +++ b/dotnetv3/Bedrock-runtime/Models/Ai21LabsJurassic2/Converse/Converse.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/Ai21LabsJurassic2/InvokeModel/InvokeModel.csproj b/dotnetv3/Bedrock-runtime/Models/Ai21LabsJurassic2/InvokeModel/InvokeModel.csproj index bf2403af903..986018da574 100644 --- a/dotnetv3/Bedrock-runtime/Models/Ai21LabsJurassic2/InvokeModel/InvokeModel.csproj +++ b/dotnetv3/Bedrock-runtime/Models/Ai21LabsJurassic2/InvokeModel/InvokeModel.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaCanvas/InvokeModel/InvokeModel.cs b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaCanvas/InvokeModel/InvokeModel.cs new file mode 100644 index 00000000000..6db2f957aef --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaCanvas/InvokeModel/InvokeModel.cs @@ -0,0 +1,128 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[BedrockRuntime.dotnetv3.InvokeModel_AmazonNovaImageGeneration] +// Use the native inference API to create an image with Amazon Nova Canvas. + +using System; +using System.IO; +using System.Text.Json; +using System.Text.Json.Nodes; +using Amazon; +using Amazon.BedrockRuntime; +using Amazon.BedrockRuntime.Model; + +// Create a Bedrock Runtime client in the AWS Region you want to use. +var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1); + +// Set the model ID. +var modelId = "amazon.nova-canvas-v1:0"; + +// Define the image generation prompt for the model. +var prompt = "A stylized picture of a cute old steampunk robot."; + +// Create a random seed between 0 and 858,993,459 +int seed = new Random().Next(0, 858993460); + +//Format the request payload using the model's native structure. +var nativeRequest = JsonSerializer.Serialize(new +{ + taskType = "TEXT_IMAGE", + textToImageParams = new + { + text = prompt + }, + imageGenerationConfig = new + { + seed, + quality = "standard", + width = 512, + height = 512, + numberOfImages = 1 + } +}); + +// Create a request with the model ID and the model's native request payload. +var request = new InvokeModelRequest() +{ + ModelId = modelId, + Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)), + ContentType = "application/json" +}; + +try +{ + // Send the request to the Bedrock Runtime and wait for the response. + var response = await client.InvokeModelAsync(request); + + // Decode the response body. + var modelResponse = await JsonNode.ParseAsync(response.Body); + + // Extract the image data. + var base64Image = modelResponse["images"]?[0].ToString() ?? ""; + + // Save the image in a local folder + string savedPath = AmazonNovaCanvas.InvokeModel.SaveBase64Image(base64Image); + Console.WriteLine($"Image saved to: {savedPath}"); +} +catch (AmazonBedrockRuntimeException e) +{ + Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); + throw; +} + +// snippet-end:[BedrockRuntime.dotnetv3.InvokeModel_AmazonNovaImageGeneration] + +// Create a partial class to make the top-level script testable. +namespace AmazonNovaCanvas +{ + public partial class InvokeModel + { + public static string SaveBase64Image(string base64String, string outputFolderName = "generated-images") + { + // Get the directory where the script is located + string scriptDirectory = AppDomain.CurrentDomain.BaseDirectory; + + // Navigate to the script's folder + if (scriptDirectory.Contains("bin")) + { + scriptDirectory = Directory.GetParent(scriptDirectory)?.Parent?.Parent?.Parent?.FullName + ?? throw new DirectoryNotFoundException("Could not find script directory"); + } + + // Combine script directory with output folder + string outputPath = Path.Combine(scriptDirectory, outputFolderName); + + // Create directory if it doesn't exist + if (!Directory.Exists(outputPath)) + { + Directory.CreateDirectory(outputPath); + } + + // Remove base64 header if present (e.g., "data:image/jpeg;base64,") + string base64Data = base64String; + if (base64String.Contains(",")) + { + base64Data = base64String.Split(',')[1]; + } + + // Convert base64 to bytes + byte[] imageBytes = Convert.FromBase64String(base64Data); + + // Find the next available number + int fileNumber = 1; + string filePath; + do + { + string paddedNumber = fileNumber.ToString("D2"); // Pads with leading zero + filePath = Path.Combine(outputPath, $"image_{paddedNumber}.jpg"); + fileNumber++; + } while (File.Exists(filePath)); + + // Save the image + File.WriteAllBytes(filePath, imageBytes); + + return filePath; + } + } +} \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaCanvas/InvokeModel/InvokeModel.csproj b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaCanvas/InvokeModel/InvokeModel.csproj new file mode 100644 index 00000000000..0db5411af0b --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaCanvas/InvokeModel/InvokeModel.csproj @@ -0,0 +1,12 @@ + + + Exe + net8.0 + AmazonNovaCanvas.$(MSBuildProjectName) + + + + + + + \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/Converse/Converse.cs b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/Converse/Converse.cs new file mode 100644 index 00000000000..46466fec1d2 --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/Converse/Converse.cs @@ -0,0 +1,60 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[BedrockRuntime.dotnetv3.Converse_AmazonNovaText] +// Use the Converse API to send a text message to Amazon Nova. + +using System; +using System.Collections.Generic; +using Amazon; +using Amazon.BedrockRuntime; +using Amazon.BedrockRuntime.Model; + +// Create a Bedrock Runtime client in the AWS Region you want to use. +var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1); + +// Set the model ID, e.g., Amazon Nova Lite. +var modelId = "amazon.nova-lite-v1:0"; + +// Define the user message. +var userMessage = "Describe the purpose of a 'hello world' program in one line."; + +// Create a request with the model ID, the user message, and an inference configuration. +var request = new ConverseRequest +{ + ModelId = modelId, + Messages = new List + { + new Message + { + Role = ConversationRole.User, + Content = new List { new ContentBlock { Text = userMessage } } + } + }, + InferenceConfig = new InferenceConfiguration() + { + MaxTokens = 512, + Temperature = 0.5F, + TopP = 0.9F + } +}; + +try +{ + // Send the request to the Bedrock Runtime and wait for the result. + var response = await client.ConverseAsync(request); + + // Extract and print the response text. + string responseText = response?.Output?.Message?.Content?[0]?.Text ?? ""; + Console.WriteLine(responseText); +} +catch (AmazonBedrockRuntimeException e) +{ + Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); + throw; +} + +// snippet-end:[BedrockRuntime.dotnetv3.Converse_AmazonNovaText] + +// Create a partial class to make the top-level script testable. +namespace AmazonNovaText { public partial class Converse { } } \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/Converse/Converse.csproj b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/Converse/Converse.csproj new file mode 100644 index 00000000000..5fa769392db --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/Converse/Converse.csproj @@ -0,0 +1,12 @@ + + + Exe + net8.0 + AmazonNovaText.$(MSBuildProjectName) + + + + + + + diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/ConverseStream/ConverseStream.cs b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/ConverseStream/ConverseStream.cs new file mode 100644 index 00000000000..69ff7825dd9 --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/ConverseStream/ConverseStream.cs @@ -0,0 +1,67 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[BedrockRuntime.dotnetv3.ConverseStream_AmazonNovaText] +// Use the Converse API to send a text message to Amazon Nova +// and print the response stream. + +using System; +using System.Collections.Generic; +using System.Linq; +using Amazon; +using Amazon.BedrockRuntime; +using Amazon.BedrockRuntime.Model; + +// Create a Bedrock Runtime client in the AWS Region you want to use. +var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1); + +// Set the model ID, e.g., Amazon Nova Lite. +var modelId = "amazon.nova-lite-v1:0"; + +// Define the user message. +var userMessage = "Describe the purpose of a 'hello world' program in one line."; + +// Create a request with the model ID, the user message, and an inference configuration. +var request = new ConverseStreamRequest +{ + ModelId = modelId, + Messages = new List + { + new Message + { + Role = ConversationRole.User, + Content = new List { new ContentBlock { Text = userMessage } } + } + }, + InferenceConfig = new InferenceConfiguration() + { + MaxTokens = 512, + Temperature = 0.5F, + TopP = 0.9F + } +}; + +try +{ + // Send the request to the Bedrock Runtime and wait for the result. + var response = await client.ConverseStreamAsync(request); + + // Extract and print the streamed response text in real-time. + foreach (var chunk in response.Stream.AsEnumerable()) + { + if (chunk is ContentBlockDeltaEvent) + { + Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text); + } + } +} +catch (AmazonBedrockRuntimeException e) +{ + Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); + throw; +} + +// snippet-end:[BedrockRuntime.dotnetv3.ConverseStream_AmazonNovaText] + +// Create a partial class to make the top-level script testable. +namespace AmazonNovaText { public partial class ConverseStream { } } \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/ConverseStream/ConverseStream.csproj b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/ConverseStream/ConverseStream.csproj new file mode 100644 index 00000000000..1260dc1d435 --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Models/AmazonNova/AmazonNovaText/ConverseStream/ConverseStream.csproj @@ -0,0 +1,12 @@ + + + Exe + net8.0 + AmazonNovaText.$(MSBuildProjectName) + + + + + + + \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/Converse/Converse.csproj b/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/Converse/Converse.csproj index e505af96607..3651f4be200 100644 --- a/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/Converse/Converse.csproj +++ b/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/Converse/Converse.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/ConverseStream/ConverseStream.csproj b/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/ConverseStream/ConverseStream.csproj index 5752f31c880..662bf35f3e1 100644 --- a/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/ConverseStream/ConverseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/ConverseStream/ConverseStream.csproj @@ -6,7 +6,7 @@ - - + + \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/InvokeModel/InvokeModel.csproj b/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/InvokeModel/InvokeModel.csproj index 5752f31c880..662bf35f3e1 100644 --- a/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/InvokeModel/InvokeModel.csproj +++ b/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/InvokeModel/InvokeModel.csproj @@ -6,7 +6,7 @@ - - + + \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj b/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj index 5752f31c880..662bf35f3e1 100644 --- a/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/AmazonTitanText/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj @@ -6,7 +6,7 @@ - - + + \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/Converse/Converse.csproj b/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/Converse/Converse.csproj index 7f752984648..9a843cc1582 100644 --- a/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/Converse/Converse.csproj +++ b/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/Converse/Converse.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/ConverseStream/ConverseStream.csproj b/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/ConverseStream/ConverseStream.csproj index e4e6c3bb250..72b5e19f0b8 100644 --- a/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/ConverseStream/ConverseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/ConverseStream/ConverseStream.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/InvokeModel/InvokeModel.csproj b/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/InvokeModel/InvokeModel.csproj index e4e6c3bb250..72b5e19f0b8 100644 --- a/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/InvokeModel/InvokeModel.csproj +++ b/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/InvokeModel/InvokeModel.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj b/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj index 0daad35f8b9..6e4dbdf489b 100644 --- a/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/AnthropicClaude/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj @@ -6,7 +6,7 @@ - - + + \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_InvokeModel/Command_InvokeModel.csproj b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_InvokeModel/Command_InvokeModel.csproj index 402f8c682cb..b79f0fd7312 100644 --- a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_InvokeModel/Command_InvokeModel.csproj +++ b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_InvokeModel/Command_InvokeModel.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_InvokeModelWithResponseStream/Command_InvokeModelWithResponseStream.csproj b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_InvokeModelWithResponseStream/Command_InvokeModelWithResponseStream.csproj index 402f8c682cb..b79f0fd7312 100644 --- a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_InvokeModelWithResponseStream/Command_InvokeModelWithResponseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_InvokeModelWithResponseStream/Command_InvokeModelWithResponseStream.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_R_InvokeModel/Command_R_InvokeModel.csproj b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_R_InvokeModel/Command_R_InvokeModel.csproj index 402f8c682cb..b79f0fd7312 100644 --- a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_R_InvokeModel/Command_R_InvokeModel.csproj +++ b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_R_InvokeModel/Command_R_InvokeModel.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_R_InvokeModelWithResponseStream/Command_R_InvokeModelWithResponseStream.csproj b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_R_InvokeModelWithResponseStream/Command_R_InvokeModelWithResponseStream.csproj index 402f8c682cb..b79f0fd7312 100644 --- a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_R_InvokeModelWithResponseStream/Command_R_InvokeModelWithResponseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Command_R_InvokeModelWithResponseStream/Command_R_InvokeModelWithResponseStream.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Converse/Converse.csproj b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Converse/Converse.csproj index 402f8c682cb..b79f0fd7312 100644 --- a/dotnetv3/Bedrock-runtime/Models/CohereCommand/Converse/Converse.csproj +++ b/dotnetv3/Bedrock-runtime/Models/CohereCommand/Converse/Converse.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/CohereCommand/ConverseStream/ConverseStream.csproj b/dotnetv3/Bedrock-runtime/Models/CohereCommand/ConverseStream/ConverseStream.csproj index 402f8c682cb..b79f0fd7312 100644 --- a/dotnetv3/Bedrock-runtime/Models/CohereCommand/ConverseStream/ConverseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/CohereCommand/ConverseStream/ConverseStream.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/MetaLlama/Converse/Converse.csproj b/dotnetv3/Bedrock-runtime/Models/MetaLlama/Converse/Converse.csproj index f91317c7fa6..6163a7486a7 100644 --- a/dotnetv3/Bedrock-runtime/Models/MetaLlama/Converse/Converse.csproj +++ b/dotnetv3/Bedrock-runtime/Models/MetaLlama/Converse/Converse.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/MetaLlama/ConverseStream/ConverseStream.csproj b/dotnetv3/Bedrock-runtime/Models/MetaLlama/ConverseStream/ConverseStream.csproj index f91317c7fa6..6163a7486a7 100644 --- a/dotnetv3/Bedrock-runtime/Models/MetaLlama/ConverseStream/ConverseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/MetaLlama/ConverseStream/ConverseStream.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/MetaLlama/Llama3_InvokeModel/Llama3_InvokeModel.csproj b/dotnetv3/Bedrock-runtime/Models/MetaLlama/Llama3_InvokeModel/Llama3_InvokeModel.csproj index f91317c7fa6..6163a7486a7 100644 --- a/dotnetv3/Bedrock-runtime/Models/MetaLlama/Llama3_InvokeModel/Llama3_InvokeModel.csproj +++ b/dotnetv3/Bedrock-runtime/Models/MetaLlama/Llama3_InvokeModel/Llama3_InvokeModel.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/MetaLlama/Llama3_InvokeModelWithResponseStream/Llama3_InvokeModelWithResponseStream.csproj b/dotnetv3/Bedrock-runtime/Models/MetaLlama/Llama3_InvokeModelWithResponseStream/Llama3_InvokeModelWithResponseStream.csproj index f91317c7fa6..6163a7486a7 100644 --- a/dotnetv3/Bedrock-runtime/Models/MetaLlama/Llama3_InvokeModelWithResponseStream/Llama3_InvokeModelWithResponseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/MetaLlama/Llama3_InvokeModelWithResponseStream/Llama3_InvokeModelWithResponseStream.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/Mistral/Converse/Converse.csproj b/dotnetv3/Bedrock-runtime/Models/Mistral/Converse/Converse.csproj index 27e936ccbc6..dfbd70d9fc3 100644 --- a/dotnetv3/Bedrock-runtime/Models/Mistral/Converse/Converse.csproj +++ b/dotnetv3/Bedrock-runtime/Models/Mistral/Converse/Converse.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/Mistral/ConverseStream/ConverseStream.csproj b/dotnetv3/Bedrock-runtime/Models/Mistral/ConverseStream/ConverseStream.csproj index 8297baab449..9f570ade55e 100644 --- a/dotnetv3/Bedrock-runtime/Models/Mistral/ConverseStream/ConverseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/Mistral/ConverseStream/ConverseStream.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/Mistral/InvokeModel/InvokeModel.csproj b/dotnetv3/Bedrock-runtime/Models/Mistral/InvokeModel/InvokeModel.csproj index 8297baab449..9f570ade55e 100644 --- a/dotnetv3/Bedrock-runtime/Models/Mistral/InvokeModel/InvokeModel.csproj +++ b/dotnetv3/Bedrock-runtime/Models/Mistral/InvokeModel/InvokeModel.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/Models/Mistral/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj b/dotnetv3/Bedrock-runtime/Models/Mistral/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj index 8297baab449..9f570ade55e 100644 --- a/dotnetv3/Bedrock-runtime/Models/Mistral/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj +++ b/dotnetv3/Bedrock-runtime/Models/Mistral/InvokeModelWithResponseStream/InvokeModelWithResponseStream.csproj @@ -6,7 +6,7 @@ - - + + diff --git a/dotnetv3/Bedrock-runtime/README.md b/dotnetv3/Bedrock-runtime/README.md index 9e153544bb9..174ab4345b8 100644 --- a/dotnetv3/Bedrock-runtime/README.md +++ b/dotnetv3/Bedrock-runtime/README.md @@ -28,11 +28,28 @@ For prerequisites, see the [README](../README.md#Prerequisites) in the `dotnetv3 +### Scenarios + +Code examples that show you how to accomplish a specific task by calling multiple +functions within the same service. + +- [Tool use with the Converse API](Scenarios/ConverseToolScenario/ConverseToolScenario.cs) + ### AI21 Labs Jurassic-2 - [Converse](Models/Ai21LabsJurassic2/Converse/Converse.cs#L4) - [InvokeModel](Models/Ai21LabsJurassic2/InvokeModel/InvokeModel.cs#L4) +### Amazon Nova + +- [Converse](Models/AmazonNova/AmazonNovaText/Converse/Converse.cs#L4) +- [ConverseStream](Models/AmazonNova/AmazonNovaText/ConverseStream/ConverseStream.cs#L4) +- [Scenario: Tool use with the Converse API](Scenarios/ConverseToolScenario/ConverseToolScenario.cs#L4) + +### Amazon Nova Canvas + +- [InvokeModel](Models/AmazonNova/AmazonNovaCanvas/InvokeModel/InvokeModel.cs#L4) + ### Amazon Titan Text - [Converse](Models/AmazonTitanText/Converse/Converse.cs#L4) @@ -101,6 +118,18 @@ Alternatively, you can run the example from within your IDE. +#### Tool use with the Converse API + +This example shows you how to build a typical interaction between an application, a generative AI model, and connected tools or APIs to mediate interactions between the AI and the outside world. It uses the example of connecting an external weather API to the AI model so it can provide real-time weather information based on user input. + + + + + + + + + ### Tests ⚠ Running tests might result in charges to your AWS account. @@ -127,4 +156,4 @@ in the `dotnetv3` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/BedrockActionsWrapper.cs b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/BedrockActionsWrapper.cs new file mode 100644 index 00000000000..af2d1859e16 --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/BedrockActionsWrapper.cs @@ -0,0 +1,82 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using Amazon.BedrockRuntime; +using Amazon.BedrockRuntime.Model; +using Microsoft.Extensions.Logging; + +namespace ConverseToolScenario; + +// snippet-start:[Bedrock.ConverseTool.dotnetv3.SendConverseRequest] + +/// +/// Wrapper class for interacting with the Amazon Bedrock Converse API. +/// +public class BedrockActionsWrapper +{ + private readonly IAmazonBedrockRuntime _bedrockClient; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The Bedrock Converse API client. + /// The logger instance. + public BedrockActionsWrapper(IAmazonBedrockRuntime bedrockClient, ILogger logger) + { + _bedrockClient = bedrockClient; + _logger = logger; + } + + /// + /// Sends a Converse request to the Amazon Bedrock Converse API. + /// + /// The Bedrock Model Id. + /// A system prompt instruction. + /// The array of messages in the conversation. + /// The specification for a tool. + /// The response of the model. + public async Task SendConverseRequestAsync(string modelId, string systemPrompt, List conversation, ToolSpecification toolSpec) + { + try + { + var request = new ConverseRequest() + { + ModelId = modelId, + System = new List() + { + new SystemContentBlock() + { + Text = systemPrompt + } + }, + Messages = conversation, + ToolConfig = new ToolConfiguration() + { + Tools = new List() + { + new Tool() + { + ToolSpec = toolSpec + } + } + } + }; + + var response = await _bedrockClient.ConverseAsync(request); + + return response; + } + catch (ModelNotReadyException ex) + { + _logger.LogError(ex, "Model not ready, please wait and try again."); + throw; + } + catch (AmazonBedrockRuntimeException ex) + { + _logger.LogError(ex, "Error occurred while sending Converse request."); + throw; + } + } +} +// snippet-end:[Bedrock.ConverseTool.dotnetv3.SendConverseRequest] \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/ConverseToolScenario.cs b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/ConverseToolScenario.cs new file mode 100644 index 00000000000..f220fd4c3d6 --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/ConverseToolScenario.cs @@ -0,0 +1,361 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[Bedrock.ConverseTool.dotnetv3.Scenario] + +using Amazon; +using Amazon.BedrockRuntime; +using Amazon.BedrockRuntime.Model; +using Amazon.Runtime.Documents; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Http; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Console; + +namespace ConverseToolScenario; + +public static class ConverseToolScenario +{ + /* + Before running this .NET code example, set up your development environment, including your credentials. + + This demo illustrates a tool use scenario using Amazon Bedrock's Converse API and a weather tool. + The script interacts with a foundation model on Amazon Bedrock to provide weather information based on user + input. It uses the Open-Meteo API (https://open-meteo.com) to retrieve current weather data for a given location. + */ + + public static BedrockActionsWrapper _bedrockActionsWrapper = null!; + public static WeatherTool _weatherTool = null!; + public static bool _interactive = true; + + // Change this string to use a different model with Converse API. + private static string model_id = "amazon.nova-lite-v1:0"; + + private static string system_prompt = @" + You are a weather assistant that provides current weather data for user-specified locations using only + the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself. + If the user provides coordinates, infer the approximate location and refer to it in your response. + To use the tool, you strictly apply the provided tool specification. + + - Explain your step-by-step process, and give brief updates before each step. + - Only use the Weather_Tool for data. Never guess or make up information. + - Repeat the tool use for subsequent requests if necessary. + - If the tool errors, apologize, explain weather is unavailable, and suggest other options. + - Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use + emojis where appropriate. + - Only respond to weather queries. Remind off-topic users of your purpose. + - Never claim to search online, access external data, or use tools besides Weather_Tool. + - Complete the entire process until you have all required data before sending the complete response. + " + ; + + private static string default_prompt = "What is the weather like in Seattle?"; + + // The maximum number of recursive calls allowed in the tool use function. + // This helps prevent infinite loops and potential performance issues. + private static int max_recursions = 5; + + public static async Task Main(string[] args) + { + // Set up dependency injection for the Amazon service. + using var host = Host.CreateDefaultBuilder(args) + .ConfigureLogging(logging => + logging.AddFilter("System", LogLevel.Error) + .AddFilter("Microsoft", LogLevel.Trace)) + .ConfigureServices((_, services) => + services.AddHttpClient() + .AddSingleton(_ => new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1)) // Specify a region that has access to the chosen model. + .AddTransient() + .AddTransient() + .RemoveAll() + ) + .Build(); + + ServicesSetup(host); + + try + { + await RunConversationAsync(); + + } + catch (Exception ex) + { + Console.WriteLine(new string('-', 80)); + Console.WriteLine($"There was a problem running the scenario: {ex.Message}"); + Console.WriteLine(new string('-', 80)); + } + finally + { + Console.WriteLine( + "Amazon Bedrock Converse API with Tool Use Feature Scenario is complete."); + Console.WriteLine(new string('-', 80)); + } + } + + /// + /// Populate the services for use within the console application. + /// + /// The services host. + private static void ServicesSetup(IHost host) + { + _bedrockActionsWrapper = host.Services.GetRequiredService(); + _weatherTool = host.Services.GetRequiredService(); + } + + /// + /// Starts the conversation with the user and handles the interaction with Bedrock. + /// + /// The conversation array. + public static async Task> RunConversationAsync() + { + // Print the greeting and a short user guide + PrintHeader(); + + // Start with an empty conversation + var conversation = new List(); + + // Get the first user input + var userInput = await GetUserInputAsync(); + + while (userInput != null) + { + // Create a new message with the user input and append it to the conversation + var message = new Message { Role = ConversationRole.User, Content = new List { new ContentBlock { Text = userInput } } }; + conversation.Add(message); + + // Send the conversation to Amazon Bedrock + var bedrockResponse = await SendConversationToBedrock(conversation); + + // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0 + await ProcessModelResponseAsync(bedrockResponse, conversation, max_recursions); + + // Repeat the loop until the user decides to exit the application + userInput = await GetUserInputAsync(); + } + + PrintFooter(); + return conversation; + } + + /// + /// Sends the conversation, the system prompt, and the tool spec to Amazon Bedrock, and returns the response. + /// + /// The conversation history including the next message to send. + /// The response from Amazon Bedrock. + private static async Task SendConversationToBedrock(List conversation) + { + Console.WriteLine("\tCalling Bedrock..."); + + // Send the conversation, system prompt, and tool configuration, and return the response + return await _bedrockActionsWrapper.SendConverseRequestAsync(model_id, system_prompt, conversation, _weatherTool.GetToolSpec()); + } + + /// + /// Processes the response received via Amazon Bedrock and performs the necessary actions based on the stop reason. + /// + /// The model's response returned via Amazon Bedrock. + /// The conversation history. + /// The maximum number of recursive calls allowed. + private static async Task ProcessModelResponseAsync(ConverseResponse modelResponse, List conversation, int maxRecursion) + { + if (maxRecursion <= 0) + { + // Stop the process, the number of recursive calls could indicate an infinite loop + Console.WriteLine("\tWarning: Maximum number of recursions reached. Please try again."); + } + + // Append the model's response to the ongoing conversation + conversation.Add(modelResponse.Output.Message); + + if (modelResponse.StopReason == "tool_use") + { + // If the stop reason is "tool_use", forward everything to the tool use handler + await HandleToolUseAsync(modelResponse.Output, conversation, maxRecursion - 1); + } + + if (modelResponse.StopReason == "end_turn") + { + // If the stop reason is "end_turn", print the model's response text, and finish the process + PrintModelResponse(modelResponse.Output.Message.Content[0].Text); + if (!_interactive) + { + default_prompt = "x"; + } + } + } + + /// + /// Handles the tool use case by invoking the specified tool and sending the tool's response back to Bedrock. + /// The tool response is appended to the conversation, and the conversation is sent back to Amazon Bedrock for further processing. + /// + /// The model's response containing the tool use request. + /// The conversation history. + /// The maximum number of recursive calls allowed. + public static async Task HandleToolUseAsync(ConverseOutput modelResponse, List conversation, int maxRecursion) + { + // Initialize an empty list of tool results + var toolResults = new List(); + + // The model's response can consist of multiple content blocks + foreach (var contentBlock in modelResponse.Message.Content) + { + if (!String.IsNullOrEmpty(contentBlock.Text)) + { + // If the content block contains text, print it to the console + PrintModelResponse(contentBlock.Text); + } + + if (contentBlock.ToolUse != null) + { + // If the content block is a tool use request, forward it to the tool + var toolResponse = await InvokeTool(contentBlock.ToolUse); + + // Add the tool use ID and the tool's response to the list of results + toolResults.Add(new ContentBlock + { + ToolResult = new ToolResultBlock() + { + ToolUseId = toolResponse.ToolUseId, + Content = new List() + { new ToolResultContentBlock { Json = toolResponse.Content } } + } + }); + } + } + + // Embed the tool results in a new user message + var message = new Message() { Role = ConversationRole.User, Content = toolResults }; + + // Append the new message to the ongoing conversation + conversation.Add(message); + + // Send the conversation to Amazon Bedrock + var response = await SendConversationToBedrock(conversation); + + // Recursively handle the model's response until the model has returned its final response or the recursion counter has reached 0 + await ProcessModelResponseAsync(response, conversation, maxRecursion); + } + + /// + /// Invokes the specified tool with the given payload and returns the tool's response. + /// If the requested tool does not exist, an error message is returned. + /// + /// The payload containing the tool name and input data. + /// The tool's response or an error message. + public static async Task InvokeTool(ToolUseBlock payload) + { + var toolName = payload.Name; + + if (toolName == "Weather_Tool") + { + var inputData = payload.Input.AsDictionary(); + PrintToolUse(toolName, inputData); + + // Invoke the weather tool with the input data provided + var weatherResponse = await _weatherTool.FetchWeatherDataAsync(inputData["latitude"].ToString(), inputData["longitude"].ToString()); + return new ToolResponse { ToolUseId = payload.ToolUseId, Content = weatherResponse }; + } + else + { + var errorMessage = $"\tThe requested tool with name '{toolName}' does not exist."; + return new ToolResponse { ToolUseId = payload.ToolUseId, Content = new { error = true, message = errorMessage } }; + } + } + + + /// + /// Prompts the user for input and returns the user's response. + /// Returns null if the user enters 'x' to exit. + /// + /// The prompt to display to the user. + /// The user's input or null if the user chooses to exit. + private static async Task GetUserInputAsync(string prompt = "\tYour weather info request:") + { + var userInput = default_prompt; + if (_interactive) + { + Console.WriteLine(new string('*', 80)); + Console.WriteLine($"{prompt} (x to exit): \n\t"); + userInput = Console.ReadLine(); + } + + if (string.IsNullOrWhiteSpace(userInput)) + { + prompt = "\tPlease enter your weather info request, e.g. the name of a city"; + return await GetUserInputAsync(prompt); + } + + if (userInput.ToLowerInvariant() == "x") + { + return null; + } + + return userInput; + } + + /// + /// Logs the welcome message and usage guide for the tool use demo. + /// + public static void PrintHeader() + { + Console.WriteLine(@" + ================================================= + Welcome to the Amazon Bedrock Tool Use demo! + ================================================= + + This assistant provides current weather information for user-specified locations. + You can ask for weather details by providing the location name or coordinates. Weather information + will be provided using a custom Tool and open-meteo API. + + Example queries: + - What's the weather like in New York? + - Current weather for latitude 40.70, longitude -74.01 + - Is it warmer in Rome or Barcelona today? + + To exit the program, simply type 'x' and press Enter. + + P.S.: You're not limited to single locations, or even to using English! + Have fun and experiment with the app! + "); + } + + /// + /// Logs the footer information for the tool use demo. + /// + public static void PrintFooter() + { + Console.WriteLine(@" + ================================================= + Thank you for checking out the Amazon Bedrock Tool Use demo. We hope you + learned something new, or got some inspiration for your own apps today! + + For more Bedrock examples in different programming languages, have a look at: + https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html + ================================================= + "); + } + + /// + /// Logs information about the tool use. + /// + /// The name of the tool being used. + /// The input data for the tool. + public static void PrintToolUse(string toolName, Dictionary inputData) + { + Console.WriteLine($"\n\tInvoking tool: {toolName} with input: {inputData["latitude"].ToString()}, {inputData["longitude"].ToString()}...\n"); + } + + /// + /// Logs the model's response. + /// + /// The model's response message. + public static void PrintModelResponse(string message) + { + Console.WriteLine("\tThe model's response:\n"); + Console.WriteLine(message); + Console.WriteLine(); + } +} +// snippet-end:[Bedrock.ConverseTool.dotnetv3.Scenario] \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/ConverseToolScenario.csproj b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/ConverseToolScenario.csproj new file mode 100644 index 00000000000..6d77e9066e9 --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/ConverseToolScenario.csproj @@ -0,0 +1,19 @@ + + + + Exe + net8.0 + enable + enable + + + + + + + + + + + + diff --git a/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/README.md b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/README.md new file mode 100644 index 00000000000..0c052ac1e45 --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/README.md @@ -0,0 +1,59 @@ +# Bedrock Runtime Converse API with Tool Feature Scenario + +## Overview + +This example shows how to use AWS SDKs and the Amazon Bedrock Converse API to call a custom tool from a large language model (LLM) as part of a multistep conversation. The example creates a weather tool that leverages the Open-Meteo API to retrieve current weather information based on user input. + +[Bedrock Converse API with Tool Definition](https://docs.aws.amazon.com/bedrock/latest/userguide/tool-use-inference-call.html). + +## ⚠ Important + +* Running this code might result in charges to your AWS account. +* Running the tests might result in charges to your AWS account. +* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). +* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services). + +## Scenario + +This example illustrates a typical interaction between a generative AI model, an application, and connected tools or APIs to solve a problem or achieve a specific goal. The scenario follows these steps: + +1. Set up the system prompt and tool configuration. +2. Specify the AI model to be used (e.g., Anthropic Claude 3 Sonnet). +3. Create a client to interact with Amazon Bedrock. +4. Prompt the user for their weather request. +5. Send the user input including the conversation history to the model. +6. The model processes the input and determines if a connected tool or API needs to be used. If this is the case, the model returns a tool use request with specific parameters needed to invoke the tool, and a unique tool use ID to correlate tool responses to the request. +7. The scenario application invokes the tool to fetch weather data, and append the response and tool use ID to the conversation. +8. The model uses the tool response to generate a final response. If additional tool requests are needed, the process is repeated. +9. Once the final response is received and printed, the application returns to the prompt. + +### Prerequisites + +For general prerequisites, see the [README](../../../README.md) in the `dotnetv3` folder. + +### Resources + +No additional resources are needed for this scenario. + +### Instructions + +After the example compiles, you can run it from the command line. To do so, navigate to +the folder that contains the .sln file and run the following command: + +``` +dotnet run +``` + +Alternatively, you can run the example from within your IDE. + +This starts an interactive scenario that walks you through exploring conditional requests for read, write, and copy operations. + +## Additional resources + +- [Documentation: The Amazon Bedrock User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) +- [Tutorials: A developer's guide to Bedrock's new Converse API](https://community.aws/content/2dtauBCeDa703x7fDS9Q30MJoBA/amazon-bedrock-converse-api-developer-guide) +- [More examples: Amazon Bedrock code examples and scenarios in multiple programming languages](https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html) + +--- + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 diff --git a/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/ToolResponse.cs b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/ToolResponse.cs new file mode 100644 index 00000000000..95dbb986fa1 --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/ToolResponse.cs @@ -0,0 +1,16 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[Bedrock.ConverseTool.dotnetv3.ToolResponse] + +namespace ConverseToolScenario; + +/// +/// Response object for the tool results. +/// +public class ToolResponse +{ + public string ToolUseId { get; set; } = null!; + public dynamic Content { get; set; } = null!; +} +// snippet-end:[Bedrock.ConverseTool.dotnetv3.ToolResponse] \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/WeatherTool.cs b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/WeatherTool.cs new file mode 100644 index 00000000000..1e87b25927b --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/WeatherTool.cs @@ -0,0 +1,98 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +// snippet-start:[Bedrock.ConverseTool.dotnetv3.WeatherTool] + +using Amazon.BedrockRuntime.Model; +using Amazon.Runtime.Documents; +using Microsoft.Extensions.Logging; + +namespace ConverseToolScenario; + +/// +/// Weather tool that will be invoked when requested by the Bedrock response. +/// +public class WeatherTool +{ + private readonly ILogger _logger; + private readonly IHttpClientFactory _httpClientFactory; + + public WeatherTool(ILogger logger, IHttpClientFactory httpClientFactory) + { + _logger = logger; + _httpClientFactory = httpClientFactory; + } + + /// + /// Returns the JSON Schema specification for the Weather tool. The tool specification + /// defines the input schema and describes the tool's functionality. + /// For more information, see https://json-schema.org/understanding-json-schema/reference. + /// + /// The tool specification for the Weather tool. + public ToolSpecification GetToolSpec() + { + ToolSpecification toolSpecification = new ToolSpecification(); + + toolSpecification.Name = "Weather_Tool"; + toolSpecification.Description = "Get the current weather for a given location, based on its WGS84 coordinates."; + + Document toolSpecDocument = Document.FromObject( + new + { + type = "object", + properties = new + { + latitude = new + { + type = "string", + description = "Geographical WGS84 latitude of the location." + }, + longitude = new + { + type = "string", + description = "Geographical WGS84 longitude of the location." + } + }, + required = new[] { "latitude", "longitude" } + }); + + toolSpecification.InputSchema = new ToolInputSchema() { Json = toolSpecDocument }; + return toolSpecification; + } + + /// + /// Fetches weather data for the given latitude and longitude using the Open-Meteo API. + /// Returns the weather data or an error message if the request fails. + /// + /// The latitude of the location. + /// The longitude of the location. + /// The weather data or an error message. + public async Task FetchWeatherDataAsync(string latitude, string longitude) + { + string endpoint = "https://api.open-meteo.com/v1/forecast"; + + try + { + var httpClient = _httpClientFactory.CreateClient(); + var response = await httpClient.GetAsync($"{endpoint}?latitude={latitude}&longitude={longitude}¤t_weather=True"); + response.EnsureSuccessStatusCode(); + var weatherData = await response.Content.ReadAsStringAsync(); + + Document weatherDocument = Document.FromObject( + new { weather_data = weatherData }); + + return weatherDocument; + } + catch (HttpRequestException e) + { + _logger.LogError(e, "Error fetching weather data: {Message}", e.Message); + throw; + } + catch (Exception e) + { + _logger.LogError(e, "Unexpected error fetching weather data: {Message}", e.Message); + throw; + } + } +} +// snippet-end:[Bedrock.ConverseTool.dotnetv3.WeatherTool] \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Tests/ActionTest_Converse.cs b/dotnetv3/Bedrock-runtime/Tests/ActionTest_Converse.cs index d57db96634e..bb3fafc643d 100644 --- a/dotnetv3/Bedrock-runtime/Tests/ActionTest_Converse.cs +++ b/dotnetv3/Bedrock-runtime/Tests/ActionTest_Converse.cs @@ -10,6 +10,7 @@ public class ActionTest_Converse [InlineData(typeof(MetaLlama.Converse))] [InlineData(typeof(CohereCommand.Converse))] [InlineData(typeof(AnthropicClaude.Converse))] + [InlineData(typeof(AmazonNovaText.Converse))] [InlineData(typeof(AmazonTitanText.Converse))] [InlineData(typeof(Ai21LabsJurassic2.Converse))] public void ConverseDoesNotThrow(Type type) diff --git a/dotnetv3/Bedrock-runtime/Tests/ActionTest_ConverseStream.cs b/dotnetv3/Bedrock-runtime/Tests/ActionTest_ConverseStream.cs index 3c4ab3417f0..0f6ca41ccac 100644 --- a/dotnetv3/Bedrock-runtime/Tests/ActionTest_ConverseStream.cs +++ b/dotnetv3/Bedrock-runtime/Tests/ActionTest_ConverseStream.cs @@ -10,6 +10,7 @@ public class ActionTest_ConverseStream [InlineData(typeof(MetaLlama.ConverseStream))] [InlineData(typeof(CohereCommand.ConverseStream))] [InlineData(typeof(AnthropicClaude.ConverseStream))] + [InlineData(typeof(AmazonNovaText.ConverseStream))] [InlineData(typeof(AmazonTitanText.ConverseStream))] public void ConverseStreamDoesNotThrow(Type type) { diff --git a/dotnetv3/Bedrock-runtime/Tests/ActionTests_InvokeModel.cs b/dotnetv3/Bedrock-runtime/Tests/ActionTests_InvokeModel.cs index 0584cf61793..0b561dc2176 100644 --- a/dotnetv3/Bedrock-runtime/Tests/ActionTests_InvokeModel.cs +++ b/dotnetv3/Bedrock-runtime/Tests/ActionTests_InvokeModel.cs @@ -13,6 +13,7 @@ public class ActionTest_InvokeModel [InlineData(typeof(AnthropicClaude.InvokeModel))] [InlineData(typeof(AmazonTitanText.InvokeModel))] [InlineData(typeof(Ai21LabsJurassic2.InvokeModel))] + [InlineData(typeof(AmazonNovaCanvas.InvokeModel))] public void InvokeModelDoesNotThrow(Type type) { var entryPoint = type.Assembly.EntryPoint!; diff --git a/dotnetv3/Bedrock-runtime/Tests/BedrockRuntimeTests.csproj b/dotnetv3/Bedrock-runtime/Tests/BedrockRuntimeTests.csproj index b499eb4f7a0..6c0e8620b3e 100644 --- a/dotnetv3/Bedrock-runtime/Tests/BedrockRuntimeTests.csproj +++ b/dotnetv3/Bedrock-runtime/Tests/BedrockRuntimeTests.csproj @@ -11,16 +11,16 @@ - - - - - - + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive all - + runtime; build; native; contentfiles; analyzers; buildtransitive all @@ -29,6 +29,10 @@ + + + + @@ -51,6 +55,7 @@ + \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Tests/ConverseToolScenarioTests.cs b/dotnetv3/Bedrock-runtime/Tests/ConverseToolScenarioTests.cs new file mode 100644 index 00000000000..f5660a3774b --- /dev/null +++ b/dotnetv3/Bedrock-runtime/Tests/ConverseToolScenarioTests.cs @@ -0,0 +1,65 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +using Amazon; +using Amazon.BedrockRuntime; +using ConverseToolScenario; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +namespace BedrockRuntimeTests; + +/// +/// Tests for the Converse Tool Use example. +/// +public class ConverseToolScenarioTests +{ + private readonly BedrockActionsWrapper _bedrockActionsWrapper = null!; + private readonly WeatherTool _weatherTool = null!; + private readonly ILoggerFactory _loggerFactory; + + /// + /// Constructor for the test class. + /// + public ConverseToolScenarioTests() + { + + _loggerFactory = LoggerFactory.Create(builder => + { + builder.AddConsole(); + }); + + IServiceCollection services = new ServiceCollection(); // [1] + + services.AddHttpClient(); + + IHttpClientFactory _httpClientFactory = services + .BuildServiceProvider() + .GetRequiredService(); + + _bedrockActionsWrapper = new BedrockActionsWrapper( + new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1), new Logger(_loggerFactory)); + _weatherTool = new WeatherTool(new Logger(_loggerFactory), + _httpClientFactory); + ConverseToolScenario.ConverseToolScenario._bedrockActionsWrapper = _bedrockActionsWrapper; + ConverseToolScenario.ConverseToolScenario._weatherTool = _weatherTool; + } + + /// + /// Run the non-interactive scenario. Should return a non-empty conversation. + /// + /// Async task. + [Fact] + [Trait("Category", "Integration")] + public async Task TestScenario() + { + // Arrange. + ConverseToolScenario.ConverseToolScenario._interactive = false; + + // Act. + var conversation = await ConverseToolScenario.ConverseToolScenario.RunConversationAsync(); + + // Assert. + Assert.NotEmpty(conversation); + } +} \ No newline at end of file diff --git a/dotnetv3/Bedrock-runtime/Tests/GlobalUsings.cs b/dotnetv3/Bedrock-runtime/Tests/GlobalUsings.cs index ef5ce323ba9..0f64a5599c7 100644 --- a/dotnetv3/Bedrock-runtime/Tests/GlobalUsings.cs +++ b/dotnetv3/Bedrock-runtime/Tests/GlobalUsings.cs @@ -2,11 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 global using Xunit; -global using Xunit.Extensions.Ordering; // Optional. -[assembly: CollectionBehavior(DisableTestParallelization = true)] -// Optional. -[assembly: TestCaseOrderer("Xunit.Extensions.Ordering.TestCaseOrderer", "Xunit.Extensions.Ordering")] -// Optional. -[assembly: TestCollectionOrderer("Xunit.Extensions.Ordering.CollectionOrderer", "Xunit.Extensions.Ordering")] \ No newline at end of file +[assembly: CollectionBehavior(DisableTestParallelization = true)] \ No newline at end of file diff --git a/dotnetv3/DotNetV3Examples.sln b/dotnetv3/DotNetV3Examples.sln index 54a02263eb2..c6f351d608b 100644 --- a/dotnetv3/DotNetV3Examples.sln +++ b/dotnetv3/DotNetV3Examples.sln @@ -837,6 +837,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "S3ObjectLockScenario", "S3\ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "S3ObjectLockTests", "S3\scenarios\S3ObjectLockScenario\S3ObjectLockTests\S3ObjectLockTests.csproj", "{BCCFBED0-E800-46C5-975B-7D404486F00F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConverseToolScenario", "Bedrock-runtime\Scenarios\ConverseToolScenario\ConverseToolScenario.csproj", "{83ED7BBE-5C9A-47AC-805B-351270069570}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -1915,6 +1917,10 @@ Global {BCCFBED0-E800-46C5-975B-7D404486F00F}.Debug|Any CPU.Build.0 = Debug|Any CPU {BCCFBED0-E800-46C5-975B-7D404486F00F}.Release|Any CPU.ActiveCfg = Release|Any CPU {BCCFBED0-E800-46C5-975B-7D404486F00F}.Release|Any CPU.Build.0 = Release|Any CPU + {83ED7BBE-5C9A-47AC-805B-351270069570}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {83ED7BBE-5C9A-47AC-805B-351270069570}.Debug|Any CPU.Build.0 = Debug|Any CPU + {83ED7BBE-5C9A-47AC-805B-351270069570}.Release|Any CPU.ActiveCfg = Release|Any CPU + {83ED7BBE-5C9A-47AC-805B-351270069570}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -2296,6 +2302,7 @@ Global {7EC94891-9A5F-47EF-9C97-8A280754525C} = {0169CEB9-B6A7-447D-921D-C79358DDCCE6} {93588ED1-A248-4F6C-85A4-27E9E65D8AC7} = {7EC94891-9A5F-47EF-9C97-8A280754525C} {BCCFBED0-E800-46C5-975B-7D404486F00F} = {7EC94891-9A5F-47EF-9C97-8A280754525C} + {83ED7BBE-5C9A-47AC-805B-351270069570} = {BA23BB28-EC63-4330-8CA7-DEB1B6489580} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {08502818-E8E1-4A91-A51C-4C8C8D4FF9CA} diff --git a/dotnetv4/Bedrock/Actions/BedrockActions.csproj b/dotnetv4/Bedrock/Actions/BedrockActions.csproj index 9f12aa3e3f2..ffee5ec19c7 100644 --- a/dotnetv4/Bedrock/Actions/BedrockActions.csproj +++ b/dotnetv4/Bedrock/Actions/BedrockActions.csproj @@ -9,6 +9,7 @@ + diff --git a/gov2/redshift/README.md b/gov2/redshift/README.md index 28b7417b7ee..95df3003dfa 100644 --- a/gov2/redshift/README.md +++ b/gov2/redshift/README.md @@ -80,8 +80,15 @@ go run ./cmd -h ``` #### Learn the basics -This example shows you how to learn core operations for Amazon Redshift using an AWS SDK. +This example shows you how to do the following: +- Create a Redshift cluster. +- List databases in the cluster. +- Create a table named Movies. +- Populate the Movies table. +- Query the Movies table by year. +- Modify the Redshift cluster. +- Delete the Amazon Redshift cluster. @@ -117,4 +124,4 @@ in the `gov2` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/javascriptv3/example_code/iotsitewise/README.md b/javascriptv3/example_code/iotsitewise/README.md index c4e88a366b7..f48868b20ca 100644 --- a/javascriptv3/example_code/iotsitewise/README.md +++ b/javascriptv3/example_code/iotsitewise/README.md @@ -107,8 +107,17 @@ node ./hello.js #### Learn the basics -This example shows you how to learn core operations for AWS IoT SiteWise using an AWS SDK. - +This example shows you how to do the following: + +- Create an AWS IoT SiteWise Asset Model. +- Create an AWS IoT SiteWise Asset. +- Retrieve the property ID values. +- Send data to an AWS IoT SiteWise Asset. +- Retrieve the value of the AWS IoT SiteWise Asset property. +- Create an AWS IoT SiteWise Portal. +- Create an AWS IoT SiteWise Gateway. +- Describe the AWS IoT SiteWise Gateway. +- Delete the AWS IoT SiteWise Assets. diff --git a/javascriptv3/example_code/ssm/README.md b/javascriptv3/example_code/ssm/README.md index 29d49814001..e5aad1ec993 100644 --- a/javascriptv3/example_code/ssm/README.md +++ b/javascriptv3/example_code/ssm/README.md @@ -103,8 +103,15 @@ node ./hello.js #### Learn the basics -This example shows you how to work with Systems Manager maintenance windows, documents, and OpsItems. +This example shows you how to do the following: +- Create a maintenance window. +- Modify the maintenance window schedule. +- Create a document. +- Send a command to a specified EC2 instance. +- Create an OpsItem. +- Update and resolve the OpsItem. +- Delete the maintenance window, OpsItem, and document. @@ -140,4 +147,4 @@ in the `javascriptv3` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/javav2/example_code/batch/README.md b/javav2/example_code/batch/README.md index 91c66ea73bd..5a11d043da6 100644 --- a/javav2/example_code/batch/README.md +++ b/javav2/example_code/batch/README.md @@ -34,6 +34,13 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `javav - [Hello AWS Batch](src/main/java/com/example/batch/HelloBatch.java#L6) (`listJobsPaginator`) +### Basics + +Code examples that show you how to perform the essential operations within a service. + +- [Learn the basics](src/main/java/com/example/batch/scenario/BatchScenario.java) + + ### Single actions Code excerpts that show you how to call individual service functions. @@ -52,13 +59,6 @@ Code excerpts that show you how to call individual service functions. - [UpdateComputeEnvironment](src/main/java/com/example/batch/scenario/BatchActions.java#L439) - [UpdateJobQueue](src/main/java/com/example/batch/scenario/BatchActions.java#L347) -### Scenarios - -Code examples that show you how to accomplish a specific task by calling multiple -functions within the same service. - -- [Learn AWS Batch core operations](src/main/java/com/example/batch/scenario/BatchScenario.java) - @@ -76,8 +76,7 @@ functions within the same service. This example shows you how to get started using AWS Batch. - -#### Learn AWS Batch core operations +#### Learn the basics This example shows you how to do the following: @@ -90,12 +89,13 @@ This example shows you how to do the following: - Check the status of job. - Delete AWS Batch resources. - - + + + + + - - ### Tests @@ -123,4 +123,4 @@ in the `javav2` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/javav2/example_code/iot/README.md b/javav2/example_code/iot/README.md index e77c9b3515a..5e99310cd7d 100644 --- a/javav2/example_code/iot/README.md +++ b/javav2/example_code/iot/README.md @@ -77,8 +77,19 @@ This example shows you how to get started using AWS IoT. #### Learn the basics -This example shows you how to work with AWS IoT device management. - +This example shows you how to do the following: + +- Create an AWS IoT Thing. +- Generate a device certificate. +- Update an AWS IoT Thing with Attributes. +- Return a unique endpoint. +- List your AWS IoT certificates. +- Create an AWS IoT shadow. +- Write out state information. +- Creates a rule. +- List your rules. +- Search things using the Thing name. +- Delete an AWS IoT Thing. @@ -114,4 +125,4 @@ in the `javav2` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/javav2/example_code/iotsitewise/README.md b/javav2/example_code/iotsitewise/README.md index 907d087a67a..a513b574029 100644 --- a/javav2/example_code/iotsitewise/README.md +++ b/javav2/example_code/iotsitewise/README.md @@ -79,8 +79,17 @@ This example shows you how to get started using AWS IoT SiteWise. #### Learn the basics -This example shows you how to learn core operations for AWS IoT SiteWise using an AWS SDK. - +This example shows you how to do the following: + +- Create an AWS IoT SiteWise Asset Model. +- Create an AWS IoT SiteWise Asset. +- Retrieve the property ID values. +- Send data to an AWS IoT SiteWise Asset. +- Retrieve the value of the AWS IoT SiteWise Asset property. +- Create an AWS IoT SiteWise Portal. +- Create an AWS IoT SiteWise Gateway. +- Describe the AWS IoT SiteWise Gateway. +- Delete the AWS IoT SiteWise Assets. diff --git a/javav2/example_code/redshift/README.md b/javav2/example_code/redshift/README.md index 74823ff8740..08fbc96fca1 100644 --- a/javav2/example_code/redshift/README.md +++ b/javav2/example_code/redshift/README.md @@ -73,8 +73,15 @@ This example shows you how to get started using Amazon Redshift. #### Learn the basics -This example shows you how to learn core operations for Amazon Redshift using an AWS SDK. +This example shows you how to do the following: +- Create a Redshift cluster. +- List databases in the cluster. +- Create a table named Movies. +- Populate the Movies table. +- Query the Movies table by year. +- Modify the Redshift cluster. +- Delete the Amazon Redshift cluster. @@ -110,4 +117,4 @@ in the `javav2` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/javav2/example_code/ssm/README.md b/javav2/example_code/ssm/README.md index b27a8dcb3da..a6396b58b0a 100644 --- a/javav2/example_code/ssm/README.md +++ b/javav2/example_code/ssm/README.md @@ -89,8 +89,15 @@ This example shows you how to get started using Systems Manager. #### Learn the basics -This example shows you how to work with Systems Manager maintenance windows, documents, and OpsItems. +This example shows you how to do the following: +- Create a maintenance window. +- Modify the maintenance window schedule. +- Create a document. +- Send a command to a specified EC2 instance. +- Create an OpsItem. +- Update and resolve the OpsItem. +- Delete the maintenance window, OpsItem, and document. @@ -126,4 +133,4 @@ in the `javav2` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/kotlin/services/bedrock-runtime/README.md b/kotlin/services/bedrock-runtime/README.md new file mode 100644 index 00000000000..2d5be2d977c --- /dev/null +++ b/kotlin/services/bedrock-runtime/README.md @@ -0,0 +1,77 @@ +# Amazon Bedrock Runtime code examples for the SDK for Kotlin + +## Overview + +Shows how to use the AWS SDK for Kotlin to work with Amazon Bedrock Runtime. + + +This section provides examples that show how to invoke foundation models using the Amazon Bedrock Runtime API with the AWS SDK for Kotlin. + + +_Amazon Bedrock Runtime is a fully managed service that makes it easy to use foundation models from third-party providers and Amazon._ + +## ⚠ Important + +* Running this code might result in charges to your AWS account. For more details, see [AWS Pricing](https://aws.amazon.com/pricing/) and [Free Tier](https://aws.amazon.com/free/). +* Running the tests might result in charges to your AWS account. +* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). +* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services). + + + + +## Code examples + +### Prerequisites + +For prerequisites, see the [README](../../README.md#Prerequisites) in the `kotlin` folder. + + + +> ⚠ You must request access to a model before you can use it. If you try to use the model (with the API or console) before you have requested access to it, you will receive an error message. For more information, see [Model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html). + +### Amazon Titan Text + +- [InvokeModel](src/main/kotlin/com/example/bedrockruntime/InvokeModel.kt#L6) + + + + + +## Run the examples + +### Instructions + + + + + + + +### Tests + +⚠ Running tests might result in charges to your AWS account. + + +To find instructions for running these tests, see the [README](../../README.md#Tests) +in the `kotlin` folder. + + + + + + +## Additional resources + +- [Amazon Bedrock Runtime User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) +- [Amazon Bedrock Runtime API Reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/welcome.html) +- [SDK for Kotlin Amazon Bedrock Runtime reference](https://sdk.amazonaws.com/kotlin/api/latest/bedrock-runtime/index.html) + + + + +--- + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 diff --git a/kotlin/services/bedrock-runtime/build.gradle.kts b/kotlin/services/bedrock-runtime/build.gradle.kts new file mode 100644 index 00000000000..b51ca6849ff --- /dev/null +++ b/kotlin/services/bedrock-runtime/build.gradle.kts @@ -0,0 +1,54 @@ +plugins { + kotlin("jvm") version "2.1.10" + id("org.jetbrains.kotlin.plugin.serialization") version "2.1.10" + id("org.jlleitschuh.gradle.ktlint") version "11.3.1" apply true + application +} + +group = "com.example.bedrockruntime" +version = "1.0-SNAPSHOT" + +repositories { + mavenCentral() +} + +buildscript { + repositories { + maven("https://plugins.gradle.org/m2/") + } + dependencies { + classpath("org.jlleitschuh.gradle:ktlint-gradle:11.3.1") + } +} + +dependencies { + implementation("aws.sdk.kotlin:bedrockruntime:1.4.11") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:1.8.0") + testImplementation("org.junit.jupiter:junit-jupiter:5.11.4") +} + +application { + mainClass.set("com.example.bedrockruntime.InvokeModelKt") +} + +// Java and Kotlin configuration +kotlin { + jvmToolchain(21) +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +tasks.test { + useJUnitPlatform() + testLogging { + events("passed", "skipped", "failed") + } + + // Define the test source set + testClassesDirs += files("build/classes/kotlin/test") + classpath += files("build/classes/kotlin/main", "build/resources/main") +} diff --git a/kotlin/services/bedrock-runtime/src/main/kotlin/com/example/bedrockruntime/InvokeModel.kt b/kotlin/services/bedrock-runtime/src/main/kotlin/com/example/bedrockruntime/InvokeModel.kt new file mode 100644 index 00000000000..167bccac5b0 --- /dev/null +++ b/kotlin/services/bedrock-runtime/src/main/kotlin/com/example/bedrockruntime/InvokeModel.kt @@ -0,0 +1,67 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package com.example.bedrockruntime + +// snippet-start:[bedrock-runtime.kotlin.InvokeModel_AmazonTitanText] +import aws.sdk.kotlin.services.bedrockruntime.BedrockRuntimeClient +import aws.sdk.kotlin.services.bedrockruntime.model.InvokeModelRequest +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.Json + +/** + * Before running this Kotlin code example, set up your development environment, including your credentials. + * + * This example demonstrates how to invoke the Titan Text model (amazon.titan-text-lite-v1). + * Remember that you must enable the model before you can use it. See notes in the README.md file. + * + * For more information, see the following documentation topic: + * https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html + */ +suspend fun main() { + val prompt = """ + Write a short, funny story about a time-traveling cat who + ends up in ancient Egypt at the time of the pyramids. + """.trimIndent() + + val response = invokeModel(prompt, "amazon.titan-text-lite-v1") + println("Generated story:\n$response") +} + +suspend fun invokeModel(prompt: String, modelId: String): String { + BedrockRuntimeClient { region = "eu-central-1" }.use { client -> + val request = InvokeModelRequest { + this.modelId = modelId + contentType = "application/json" + accept = "application/json" + body = """ + { + "inputText": "${prompt.replace(Regex("\\s+"), " ").trim()}", + "textGenerationConfig": { + "maxTokenCount": 1000, + "stopSequences": [], + "temperature": 1, + "topP": 0.7 + } + } + """.trimIndent().toByteArray() + } + + val response = client.invokeModel(request) + val responseBody = response.body.toString(Charsets.UTF_8) + + val jsonParser = Json { ignoreUnknownKeys = true } + return jsonParser + .decodeFromString(responseBody) + .results + .first() + .outputText + } +} + +@Serializable +private data class BedrockResponse(val results: List) + +@Serializable +private data class Result(val outputText: String) +// snippet-end:[bedrock-runtime.kotlin.InvokeModel_AmazonTitanText] diff --git a/kotlin/services/bedrock-runtime/src/test/kotlin/InvokeModelTest.kt b/kotlin/services/bedrock-runtime/src/test/kotlin/InvokeModelTest.kt new file mode 100644 index 00000000000..21d6eb43eb1 --- /dev/null +++ b/kotlin/services/bedrock-runtime/src/test/kotlin/InvokeModelTest.kt @@ -0,0 +1,24 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +import com.example.bedrockruntime.invokeModel +import kotlinx.coroutines.runBlocking +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.MethodOrderer.OrderAnnotation +import org.junit.jupiter.api.Order +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.TestInstance +import org.junit.jupiter.api.TestMethodOrder + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@TestMethodOrder(OrderAnnotation::class) +class InvokeModelTest { + @Test + @Order(1) + fun listFoundationModels() = runBlocking { + val prompt = "What is the capital of France?" + + val answer = invokeModel(prompt, "amazon.titan-text-lite-v1") + assertTrue(answer.isNotBlank()) + } +} diff --git a/kotlin/services/iot/README.md b/kotlin/services/iot/README.md index a20a8745d52..58a4fb91b24 100644 --- a/kotlin/services/iot/README.md +++ b/kotlin/services/iot/README.md @@ -77,8 +77,19 @@ This example shows you how to get started using AWS IoT. #### Learn the basics -This example shows you how to work with AWS IoT device management. - +This example shows you how to do the following: + +- Create an AWS IoT Thing. +- Generate a device certificate. +- Update an AWS IoT Thing with Attributes. +- Return a unique endpoint. +- List your AWS IoT certificates. +- Create an AWS IoT shadow. +- Write out state information. +- Creates a rule. +- List your rules. +- Search things using the Thing name. +- Delete an AWS IoT Thing. @@ -114,4 +125,4 @@ in the `kotlin` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/python/example_code/bedrock-runtime/README.md b/python/example_code/bedrock-runtime/README.md index 03eb70ca24b..68a71a78623 100644 --- a/python/example_code/bedrock-runtime/README.md +++ b/python/example_code/bedrock-runtime/README.md @@ -38,11 +38,32 @@ python -m pip install -r requirements.txt > see [Model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html). > + +### Get started + +- [Hello Amazon Bedrock Runtime](hello/hello_bedrock_runtime_invoke.py#L5) (`InvokeModel`) + +### Scenarios + +Code examples that show you how to accomplish a specific task by calling multiple +functions within the same service. + +- [Tool use with the Converse API](cross-model-scenarios/tool_use_demo/tool_use_demo.py) + ### AI21 Labs Jurassic-2 - [Converse](models/ai21_labs_jurassic2/converse.py#L4) - [InvokeModel](models/ai21_labs_jurassic2/invoke_model.py#L4) +### Amazon Nova + +- [Converse](models/amazon_nova/amazon_nova_text/converse.py#L4) +- [ConverseStream](models/amazon_nova/amazon_nova_text/converse_stream.py#L4) + +### Amazon Nova Canvas + +- [InvokeModel](models/amazon_nova/amazon_nova_canvas/invoke_model.py#L4) + ### Amazon Titan Image Generator - [InvokeModel](models/amazon_titan_image_generator/invoke_model.py#L4) @@ -120,7 +141,32 @@ Mistral AI. +#### Hello Amazon Bedrock Runtime + +This example shows you how to get started using Amazon Bedrock Runtime. + +``` +python hello/hello_bedrock_runtime_invoke.py +``` + + +#### Tool use with the Converse API + +This example shows you how to build a typical interaction between an application, a generative AI model, and connected tools or APIs to mediate interactions between the AI and the outside world. It uses the example of connecting an external weather API to the AI model so it can provide real-time weather information based on user input. + + + + + +Start the example by running the following at a command prompt: + +``` +python cross-model-scenarios/tool_use_demo/tool_use_demo.py +``` + + + ### Tests @@ -148,4 +194,4 @@ in the `python` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/python/example_code/bedrock-runtime/hello/hello_bedrock_runtime_converse.py b/python/example_code/bedrock-runtime/hello/hello_bedrock_runtime_converse.py new file mode 100644 index 00000000000..e6139428532 --- /dev/null +++ b/python/example_code/bedrock-runtime/hello/hello_bedrock_runtime_converse.py @@ -0,0 +1,83 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + + +# snippet-start:[bedrock-runtime.example_code.hello_bedrock_converse.complete] + +""" +Uses the Amazon Bedrock runtime client Converse operation to send a user message to a model. +""" +import logging +import boto3 + +from botocore.exceptions import ClientError + + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + + +def converse(brt, model_id, user_message): + """ + Uses the Converse operation to send a user message to the supplied model. + param brt: A bedrock runtime boto3 client + param model_id: The model ID for the model that you want to use. + param user message: The user message that you want to send to the model. + + :return: The text response from the model. + """ + + # Format the request payload using the model's native structure. + conversation = [ + { + "role": "user", + "content": [{"text": user_message}], + } +] + + try: + # Send the message to the model, using a basic inference configuration. + response = brt.converse( + modelId=model_id, + messages=conversation, + inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, + ) + + # Extract and print the response text. + response_text = response["output"]["message"]["content"][0]["text"] + return response_text + + except (ClientError, Exception) as e: + print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") + raise + + +def main(): + """Entry point for the example. Uses the AWS SDK for Python (Boto3) + to create an Amazon Bedrock runtime client. Then sends a user message to a model + in the region set in the callers profile and credentials. + """ + + # Create an Amazon Bedrock Runtime client. + brt = boto3.client("bedrock-runtime") + + # Set the model ID, e.g., Amazon Titan Text G1 - Express. + model_id = "amazon.titan-text-express-v1" + + # Define the message for the model. + message = "Describe the purpose of a 'hello world' program in one line." + + # Send the message to the model. + response = converse(brt, model_id, message) + + print(f"Response: {response}") + + logger.info("Done.") + + +if __name__ == "__main__": + main() + + # snippet-end:[bedrock-runtime.example_code.hello_bedrock_converse.complete] + + diff --git a/python/example_code/bedrock-runtime/hello/hello_bedrock_runtime_invoke.py b/python/example_code/bedrock-runtime/hello/hello_bedrock_runtime_invoke.py new file mode 100644 index 00000000000..d86268579dc --- /dev/null +++ b/python/example_code/bedrock-runtime/hello/hello_bedrock_runtime_invoke.py @@ -0,0 +1,87 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + + +# snippet-start:[bedrock-runtime.example_code.hello_bedrock_invoke.complete] + +""" +Uses the Amazon Bedrock runtime client InvokeModel operation to send a prompt to a model. +""" +import logging +import json +import boto3 + + +from botocore.exceptions import ClientError + + +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + + +def invoke_model(brt, model_id, prompt): + """ + Invokes the specified model with the supplied prompt. + param brt: A bedrock runtime boto3 client + param model_id: The model ID for the model that you want to use. + param prompt: The prompt that you want to send to the model. + + :return: The text response from the model. + """ + + # Format the request payload using the model's native structure. + native_request = { + "inputText": prompt, + "textGenerationConfig": { + "maxTokenCount": 512, + "temperature": 0.5, + "topP": 0.9 + } + } + + # Convert the native request to JSON. + request = json.dumps(native_request) + + try: + # Invoke the model with the request. + response = brt.invoke_model(modelId=model_id, body=request) + + # Decode the response body. + model_response = json.loads(response["body"].read()) + + # Extract and print the response text. + response_text = model_response["results"][0]["outputText"] + return response_text + + except (ClientError, Exception) as e: + print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") + raise + + +def main(): + """Entry point for the example. Uses the AWS SDK for Python (Boto3) + to create an Amazon Bedrock runtime client. Then sends a prompt to a model + in the region set in the callers profile and credentials. + """ + + # Create an Amazon Bedrock Runtime client. + brt = boto3.client("bedrock-runtime") + + # Set the model ID, e.g., Amazon Titan Text G1 - Express. + model_id = "amazon.titan-text-express-v1" + + # Define the prompt for the model. + prompt = "Describe the purpose of a 'hello world' program in one line." + + # Send the prompt to the model. + response = invoke_model(brt, model_id, prompt) + + print(f"Response: {response}") + + logger.info("Done.") + + +if __name__ == "__main__": + main() + + # snippet-end:[bedrock-runtime.example_code.hello_bedrock_invoke.complete] diff --git a/python/example_code/bedrock-runtime/models/amazon_nova/amazon_nova_canvas/invoke_model.py b/python/example_code/bedrock-runtime/models/amazon_nova/amazon_nova_canvas/invoke_model.py new file mode 100644 index 00000000000..0e479fbf832 --- /dev/null +++ b/python/example_code/bedrock-runtime/models/amazon_nova/amazon_nova_canvas/invoke_model.py @@ -0,0 +1,66 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# snippet-start:[python.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration] +# Use the native inference API to create an image with Amazon Nova Canvas + +import base64 +import json +import os +import random + +import boto3 + +# Create a Bedrock Runtime client in the AWS Region of your choice. +client = boto3.client("bedrock-runtime", region_name="us-east-1") + +# Set the model ID. +model_id = "amazon.nova-canvas-v1:0" + +# Define the image generation prompt for the model. +prompt = "A stylized picture of a cute old steampunk robot." + +# Generate a random seed between 0 and 858,993,459 +seed = random.randint(0, 858993460) + +# Format the request payload using the model's native structure. +native_request = { + "taskType": "TEXT_IMAGE", + "textToImageParams": {"text": prompt}, + "imageGenerationConfig": { + "seed": seed, + "quality": "standard", + "height": 512, + "width": 512, + "numberOfImages": 1, + }, +} + +# Convert the native request to JSON. +request = json.dumps(native_request) + +# Invoke the model with the request. +response = client.invoke_model(modelId=model_id, body=request) + +# Decode the response body. +model_response = json.loads(response["body"].read()) + +# Extract the image data. +base64_image_data = model_response["images"][0] + +# Save the generated image to a local folder. +i, output_dir = 1, "output" +if not os.path.exists(output_dir): + os.makedirs(output_dir) +while os.path.exists(os.path.join(output_dir, f"nova_canvas_{i}.png")): + i += 1 + +image_data = base64.b64decode(base64_image_data) + +image_path = os.path.join(output_dir, f"nova_canvas_{i}.png") +with open(image_path, "wb") as file: + file.write(image_data) + +print(f"The generated image has been saved to {image_path}") + +# snippet-end:[python.example_code.bedrock-runtime.InvokeModel_AmazonNovaImageGeneration] diff --git a/python/example_code/bedrock-runtime/models/amazon_nova/amazon_nova_text/converse.py b/python/example_code/bedrock-runtime/models/amazon_nova/amazon_nova_text/converse.py new file mode 100644 index 00000000000..3000a6a62f2 --- /dev/null +++ b/python/example_code/bedrock-runtime/models/amazon_nova/amazon_nova_text/converse.py @@ -0,0 +1,41 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# snippet-start:[python.example_code.bedrock-runtime.Converse_AmazonNovaText] +# Use the Conversation API to send a text message to Amazon Nova. + +import boto3 +from botocore.exceptions import ClientError + +# Create a Bedrock Runtime client in the AWS Region you want to use. +client = boto3.client("bedrock-runtime", region_name="us-east-1") + +# Set the model ID, e.g., Amazon Nova Lite. +model_id = "amazon.nova-lite-v1:0" + +# Start a conversation with the user message. +user_message = "Describe the purpose of a 'hello world' program in one line." +conversation = [ + { + "role": "user", + "content": [{"text": user_message}], + } +] + +try: + # Send the message to the model, using a basic inference configuration. + response = client.converse( + modelId=model_id, + messages=conversation, + inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, + ) + + # Extract and print the response text. + response_text = response["output"]["message"]["content"][0]["text"] + print(response_text) + +except (ClientError, Exception) as e: + print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") + exit(1) + +# snippet-end:[python.example_code.bedrock-runtime.Converse_AmazonNovaText] diff --git a/python/example_code/bedrock-runtime/models/amazon_nova/amazon_nova_text/converse_stream.py b/python/example_code/bedrock-runtime/models/amazon_nova/amazon_nova_text/converse_stream.py new file mode 100644 index 00000000000..a71bacf375f --- /dev/null +++ b/python/example_code/bedrock-runtime/models/amazon_nova/amazon_nova_text/converse_stream.py @@ -0,0 +1,44 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +# snippet-start:[python.example_code.bedrock-runtime.ConverseStream_AmazonNovaText] +# Use the Conversation API to send a text message to Amazon Nova Text +# and print the response stream. + +import boto3 +from botocore.exceptions import ClientError + +# Create a Bedrock Runtime client in the AWS Region you want to use. +client = boto3.client("bedrock-runtime", region_name="us-east-1") + +# Set the model ID, e.g., Amazon Nova Lite. +model_id = "amazon.nova-lite-v1:0" + +# Start a conversation with the user message. +user_message = "Describe the purpose of a 'hello world' program in one line." +conversation = [ + { + "role": "user", + "content": [{"text": user_message}], + } +] + +try: + # Send the message to the model, using a basic inference configuration. + streaming_response = client.converse_stream( + modelId=model_id, + messages=conversation, + inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9}, + ) + + # Extract and print the streamed response text in real-time. + for chunk in streaming_response["stream"]: + if "contentBlockDelta" in chunk: + text = chunk["contentBlockDelta"]["delta"]["text"] + print(text, end="") + +except (ClientError, Exception) as e: + print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}") + exit(1) + +# snippet-end:[python.example_code.bedrock-runtime.ConverseStream_AmazonNovaText] diff --git a/python/example_code/bedrock-runtime/requirements.txt b/python/example_code/bedrock-runtime/requirements.txt index e084f5d893a..2e935f7aa85 100644 --- a/python/example_code/bedrock-runtime/requirements.txt +++ b/python/example_code/bedrock-runtime/requirements.txt @@ -1,35 +1,12 @@ -beautifulsoup4==4.12.3 -boto3==1.35.28 -botocore==1.35.28 -certifi==2024.8.30 -charset-normalizer==3.3.2 +boto3==1.36.22 +botocore==1.36.22 colorama==0.4.6 -contourpy==1.3.0 -cycler==0.12.1 -fonttools==4.54.1 -geojson==3.1.0 -idna==3.10 iniconfig==2.0.0 jmespath==1.0.1 -kiwisolver==1.4.7 -lxml==5.3.0 -matplotlib==3.9.2 -numpy==2.1.1 -packaging==24.1 -pandas==2.2.3 -pillow==10.4.0 -pip-review==1.3.0 +packaging==24.2 pluggy==1.5.0 -pyparsing==3.1.4 -pytest==8.3.3 -pytest-asyncio==0.24.0 +pytest==8.3.4 python-dateutil==2.9.0.post0 -pytz==2024.2 -requests==2.32.3 -s3transfer==0.10.2 -six==1.16.0 -soupsieve==2.6 -tzdata==2024.2 -ujson==5.10.0 -urllib3==2.2.3 -xarray==2024.9.0 +s3transfer==0.11.2 +six==1.17.0 +urllib3==2.3.0 diff --git a/python/example_code/bedrock-runtime/test/test_converse.py b/python/example_code/bedrock-runtime/test/test_converse.py index a24b9c2fd42..4bcefb110ae 100644 --- a/python/example_code/bedrock-runtime/test/test_converse.py +++ b/python/example_code/bedrock-runtime/test/test_converse.py @@ -1,12 +1,14 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -import pytest import subprocess import sys +import pytest + files_under_test = [ "models/ai21_labs_jurassic2/converse.py", + "models/amazon_nova/amazon_nova_text/converse.py", "models/amazon_titan_text/converse.py", "models/anthropic_claude/converse.py", "models/cohere_command/converse.py", diff --git a/python/example_code/bedrock-runtime/test/test_hello_bedrock_runtime.py b/python/example_code/bedrock-runtime/test/test_hello_bedrock_runtime.py new file mode 100644 index 00000000000..f69602ba462 --- /dev/null +++ b/python/example_code/bedrock-runtime/test/test_hello_bedrock_runtime.py @@ -0,0 +1,23 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +import pytest +import subprocess +import sys + +files_under_test = [ + # Text models + "hello/hello_bedrock_runtime_invoke.py" +] + + +@pytest.mark.integ +@pytest.mark.parametrize("file", files_under_test) +def test_hello_bedrock(file): + result = subprocess.run( + [sys.executable, file], + capture_output=True, + text=True, + ) + assert result.stdout != "" + assert result.returncode == 0 diff --git a/python/example_code/bedrock-runtime/test/test_hello_bedrock_runtime_invoke.py b/python/example_code/bedrock-runtime/test/test_hello_bedrock_runtime_invoke.py new file mode 100644 index 00000000000..8de7d56b722 --- /dev/null +++ b/python/example_code/bedrock-runtime/test/test_hello_bedrock_runtime_invoke.py @@ -0,0 +1,24 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: Apache-2.0 + +import pytest +import subprocess +import sys + +files_under_test = [ + # Text models + "hello/hello_bedrock_runtime_invoke.py", + "hello/hello_bedrock_runtime_converse.py" +] + + +@pytest.mark.integ +@pytest.mark.parametrize("file", files_under_test) +def test_hello_bedrock(file): + result = subprocess.run( + [sys.executable, file], + capture_output=True, + text=True, + ) + assert result.stdout != "" + assert result.returncode == 0 diff --git a/python/example_code/bedrock-runtime/test/test_invoke_model.py b/python/example_code/bedrock-runtime/test/test_invoke_model.py index 1193de8d162..562ad785d8e 100644 --- a/python/example_code/bedrock-runtime/test/test_invoke_model.py +++ b/python/example_code/bedrock-runtime/test/test_invoke_model.py @@ -1,13 +1,15 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 -import pytest import subprocess import sys +import pytest + files_under_test = [ # Text models "models/ai21_labs_jurassic2/invoke_model.py", + "models/amazon_nova/amazon_nova_canvas/invoke_model.py", "models/amazon_titan_text/invoke_model.py", "models/anthropic_claude/invoke_model.py", "models/cohere_command/command_invoke_model.py", diff --git a/python/example_code/cloudwatch-logs/README.md b/python/example_code/cloudwatch-logs/README.md index a7da60c829c..63f8d0735c4 100644 --- a/python/example_code/cloudwatch-logs/README.md +++ b/python/example_code/cloudwatch-logs/README.md @@ -47,6 +47,7 @@ Code examples that show you how to accomplish a specific task by calling multipl functions within the same service. - [Run a large query](scenarios/large-query/exec.py) +- [Use scheduled events to invoke a Lambda function](../../example_code/lambda) @@ -80,6 +81,18 @@ python scenarios/large-query/exec.py +#### Use scheduled events to invoke a Lambda function + +This example shows you how to create an AWS Lambda function invoked by an Amazon EventBridge scheduled event. + + + + + + + + + ### Tests ⚠ Running tests might result in charges to your AWS account. diff --git a/python/example_code/dynamodb/README.md b/python/example_code/dynamodb/README.md index 0853a0648a6..b3d81a5cda4 100644 --- a/python/example_code/dynamodb/README.md +++ b/python/example_code/dynamodb/README.md @@ -77,6 +77,8 @@ functions within the same service. - [Create a websocket chat application](../../cross_service/apigateway_websocket_chat) - [Query a table by using batches of PartiQL statements](partiql/scenario_partiql_batch.py) - [Query a table using PartiQL](partiql/scenario_partiql_single.py) +- [Use API Gateway to invoke a Lambda function](../../example_code/lambda) +- [Use scheduled events to invoke a Lambda function](../../example_code/lambda) @@ -259,6 +261,30 @@ python partiql/scenario_partiql_single.py +#### Use API Gateway to invoke a Lambda function + +This example shows you how to create an AWS Lambda function invoked by Amazon API Gateway. + + + + + + + + + +#### Use scheduled events to invoke a Lambda function + +This example shows you how to create an AWS Lambda function invoked by an Amazon EventBridge scheduled event. + + + + + + + + + ### Tests ⚠ Running tests might result in charges to your AWS account. @@ -285,4 +311,4 @@ in the `python` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/python/example_code/iotsitewise/README.md b/python/example_code/iotsitewise/README.md index 7a44db848c8..9c0d4a4adda 100644 --- a/python/example_code/iotsitewise/README.md +++ b/python/example_code/iotsitewise/README.md @@ -86,8 +86,17 @@ python hello/hello_iot_sitewise.py #### Learn the basics -This example shows you how to learn core operations for AWS IoT SiteWise using an AWS SDK. - +This example shows you how to do the following: + +- Create an AWS IoT SiteWise Asset Model. +- Create an AWS IoT SiteWise Asset. +- Retrieve the property ID values. +- Send data to an AWS IoT SiteWise Asset. +- Retrieve the value of the AWS IoT SiteWise Asset property. +- Create an AWS IoT SiteWise Portal. +- Create an AWS IoT SiteWise Gateway. +- Describe the AWS IoT SiteWise Gateway. +- Delete the AWS IoT SiteWise Assets. diff --git a/python/example_code/redshift/README.md b/python/example_code/redshift/README.md index 865bbedb419..dbea462021c 100644 --- a/python/example_code/redshift/README.md +++ b/python/example_code/redshift/README.md @@ -79,8 +79,15 @@ python hello.py #### Learn the basics -This example shows you how to learn core operations for Amazon Redshift using an AWS SDK. +This example shows you how to do the following: +- Create a Redshift cluster. +- List databases in the cluster. +- Create a table named Movies. +- Populate the Movies table. +- Query the Movies table by year. +- Modify the Redshift cluster. +- Delete the Amazon Redshift cluster. @@ -122,4 +129,4 @@ in the `python` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/python/example_code/s3/README.md b/python/example_code/s3/README.md index b5568cded93..1a80d184754 100644 --- a/python/example_code/s3/README.md +++ b/python/example_code/s3/README.md @@ -88,6 +88,7 @@ functions within the same service. - [Create an Amazon Textract explorer application](../../cross_service/textract_explorer) - [Detect entities in text extracted from an image](../../cross_service/textract_comprehend_notebook) - [Detect objects in images](../../cross_service/photo_analyzer) +- [Detect people and objects in a video](../../example_code/rekognition) - [Make conditional requests](scenarios/conditional_requests/scenario.py) - [Manage versioned objects in batches with a Lambda function](../../example_code/s3/s3_versioning) - [Upload or download large files](file_transfer/file_transfer.py) @@ -191,6 +192,18 @@ This example shows you how to build an app that uses Amazon Rekognition to detec +#### Detect people and objects in a video + +This example shows you how to detect people and objects in a video with Amazon Rekognition. + + + + + + + + + #### Make conditional requests This example shows you how to add preconditions to Amazon S3 requests. @@ -290,4 +303,4 @@ in the `python` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/python/example_code/ses/README.md b/python/example_code/ses/README.md index 8424785731b..557a434322b 100644 --- a/python/example_code/ses/README.md +++ b/python/example_code/ses/README.md @@ -68,6 +68,7 @@ functions within the same service. - [Create a web application to track DynamoDB data](../../cross_service/dynamodb_item_tracker) - [Create an Aurora Serverless work item tracker](../../cross_service/aurora_item_tracker) - [Detect objects in images](../../cross_service/photo_analyzer) +- [Detect people and objects in a video](../../example_code/rekognition) - [Generate credentials to connect to an SMTP endpoint](ses_generate_smtp_credentials.py) - [Verify an email identity and send messages](ses_email.py) @@ -139,6 +140,18 @@ This example shows you how to build an app that uses Amazon Rekognition to detec +#### Detect people and objects in a video + +This example shows you how to detect people and objects in a video with Amazon Rekognition. + + + + + + + + + #### Generate credentials to connect to an SMTP endpoint This example shows you how to generate credentials to connect to an Amazon SES SMTP endpoint. @@ -205,4 +218,4 @@ in the `python` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/python/example_code/sns/README.md b/python/example_code/sns/README.md index 69a60fc45e4..6946b1c7285 100644 --- a/python/example_code/sns/README.md +++ b/python/example_code/sns/README.md @@ -54,7 +54,10 @@ functions within the same service. - [Create an Amazon Textract explorer application](../../cross_service/textract_explorer) - [Create and publish to a FIFO topic](sns_fifo_topic.py) +- [Detect people and objects in a video](../../example_code/rekognition) - [Publish an SMS text message](sns_basics.py) +- [Use API Gateway to invoke a Lambda function](../../example_code/lambda) +- [Use scheduled events to invoke a Lambda function](../../example_code/lambda) @@ -105,6 +108,18 @@ python sns_fifo_topic.py +#### Detect people and objects in a video + +This example shows you how to detect people and objects in a video with Amazon Rekognition. + + + + + + + + + #### Publish an SMS text message This example shows you how to publish SMS messages using Amazon SNS. @@ -123,6 +138,30 @@ python sns_basics.py +#### Use API Gateway to invoke a Lambda function + +This example shows you how to create an AWS Lambda function invoked by Amazon API Gateway. + + + + + + + + + +#### Use scheduled events to invoke a Lambda function + +This example shows you how to create an AWS Lambda function invoked by an Amazon EventBridge scheduled event. + + + + + + + + + ### Tests ⚠ Running tests might result in charges to your AWS account. @@ -149,4 +188,4 @@ in the `python` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/python/example_code/sqs/README.md b/python/example_code/sqs/README.md index 4bfc84d168e..a208669c236 100644 --- a/python/example_code/sqs/README.md +++ b/python/example_code/sqs/README.md @@ -56,6 +56,7 @@ functions within the same service. - [Create a messenger application](../../cross_service/stepfunctions_messenger) - [Create an Amazon Textract explorer application](../../cross_service/textract_explorer) - [Create and publish to a FIFO topic](../sns/sns_fifo_topic.py) +- [Detect people and objects in a video](../../example_code/rekognition) - [Send and receive batches of messages](message_wrapper.py) @@ -114,6 +115,18 @@ python ../sns/sns_fifo_topic.py +#### Detect people and objects in a video + +This example shows you how to detect people and objects in a video with Amazon Rekognition. + + + + + + + + + #### Send and receive batches of messages This example shows you how to do the following: @@ -162,4 +175,4 @@ in the `python` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/python/example_code/ssm/README.md b/python/example_code/ssm/README.md index cfa07dd0475..588e3a7059a 100644 --- a/python/example_code/ssm/README.md +++ b/python/example_code/ssm/README.md @@ -84,8 +84,15 @@ python hello.py #### Learn the basics -This example shows you how to work with Systems Manager maintenance windows, documents, and OpsItems. +This example shows you how to do the following: +- Create a maintenance window. +- Modify the maintenance window schedule. +- Create a document. +- Send a command to a specified EC2 instance. +- Create an OpsItem. +- Update and resolve the OpsItem. +- Delete the maintenance window, OpsItem, and document. @@ -127,4 +134,4 @@ in the `python` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/rustv1/examples/bedrock-runtime/README.md b/rustv1/examples/bedrock-runtime/README.md index ae64bcc7542..abb0df99ce4 100644 --- a/rustv1/examples/bedrock-runtime/README.md +++ b/rustv1/examples/bedrock-runtime/README.md @@ -28,6 +28,13 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `rustv +### Scenarios + +Code examples that show you how to accomplish a specific task by calling multiple +functions within the same service. + +- [Tool use with the Converse API](src/bin/tool-use.rs) + ### Anthropic Claude - [Converse](src/bin/converse.rs#L43) @@ -48,6 +55,18 @@ For prerequisites, see the [README](../../README.md#Prerequisites) in the `rustv +#### Tool use with the Converse API + +This example shows you how to build a typical interaction between an application, a generative AI model, and connected tools or APIs to mediate interactions between the AI and the outside world. It uses the example of connecting an external weather API to the AI model so it can provide real-time weather information based on user input. + + + + + + + + + ### Tests ⚠ Running tests might result in charges to your AWS account. @@ -74,4 +93,4 @@ in the `rustv1` folder. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -SPDX-License-Identifier: Apache-2.0 \ No newline at end of file +SPDX-License-Identifier: Apache-2.0 diff --git a/scenarios/features/bedrock_converse_tool/README.md b/scenarios/features/bedrock_converse_tool/README.md new file mode 100644 index 00000000000..3e8cb087dcf --- /dev/null +++ b/scenarios/features/bedrock_converse_tool/README.md @@ -0,0 +1,42 @@ +# Bedrock Runtime Converse API with Tool Feature Scenario + +## Overview + +This example shows how to use AWS SDKs and the Amazon Bedrock Converse API to call a custom tool from a large language model (LLM) as part of a multistep conversation. The example creates a weather tool that leverages the Open-Meteo API to retrieve current weather information based on user input. + +[Bedrock Converse API with Tool Definition](https://docs.aws.amazon.com/bedrock/latest/userguide/tool-use-inference-call.html). + +This example illustrates a typical interaction between a generative AI model, an application, and connected tools or APIs to solve a problem or achieve a specific goal. The scenario follows these steps: + +1. Set up the system prompt and tool configuration. +2. Create a client to interact with Amazon Bedrock. +3. Prompt the user for their weather request. +4. Send the user input including the conversation history to the model. +5. The model processes the input and determines if a connected tool or API needs to be used. If this is the case, the model returns a tool use request with specific parameters needed to invoke the tool, and a unique tool use ID to correlate tool responses to the request. +6. The scenario application invokes the tool to fetch weather data, and append the response and tool use ID to the conversation. +7. The model uses the tool response to generate a final response. If additional tool requests are needed, the process is repeated. If the max recursion is reached, the conversation is ended. +8. Once the final response is received and printed, the application returns to the prompt. + +![img.png](toolscenario.png) + +![img.png](toolscenario.png) + +### Resources + +No additional resources are needed for this scenario. + +## Implementations + +This example is implemented in the following languages: + +- [.NET](../../../dotnetv3/Bedrock-runtime/Scenarios/ConverseToolScenario/README.md) + +## Additional resources + +- [Documentation: The Amazon Bedrock User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) +- [Tutorials: A developer's guide to Bedrock's new Converse API](https://community.aws/content/2dtauBCeDa703x7fDS9Q30MJoBA/amazon-bedrock-converse-api-developer-guide) +- [More examples: Amazon Bedrock code examples and scenarios in multiple programming languages](https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html) + +--- + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 diff --git a/scenarios/features/bedrock_converse_tool/SPECIFICATION.md b/scenarios/features/bedrock_converse_tool/SPECIFICATION.md new file mode 100644 index 00000000000..474980999a9 --- /dev/null +++ b/scenarios/features/bedrock_converse_tool/SPECIFICATION.md @@ -0,0 +1,246 @@ +# Bedrock Runtime Converse API with Tool Feature Scenario - Technical specification + +This document contains the technical specifications for _Bedrock Runtime Converse API with Tool Feature Scenario_, a feature scenario that showcases AWS services and SDKs. It is primarily intended for the AWS code examples team to use while developing this example in additional languages. + +This document explains the following: + +- Architecture and features of the example scenario. +- Metadata information for the scenario. +- Sample reference output. + +For an introduction, see the [README.md](README.md). + +--- + +### Table of contents + +- [User Input](#user-input) +- [Example Output](#example-output) +- [Errors](#errors) +- [Metadata](#metadata) + +## User Input + +The user's input is used as the starting point for the Bedrock Runtime conversation, and each response is added to an array of messages. +The model should respond when it needs to invoke the tool, and the application should run the tool and append the response to the conversation. +This process can be repeated as needed until a maximum number of recursions (5). See the .NET implementation for an example of the processing of the messages. Following is an example of how the conversation could go: + +1. Greet the user and provide an overview of the application. +1. Handle the user's weather information request: + 1. The user requests weather information. This request is sent to the Bedrock model. + 2. The model response includes a tool request, with a latitude and longitude to provide to the tool. + 3. The application then uses the Weather_Tool to retrieve the current weather data for those coordinates, and appends that response as a tool response to the conversation. The conversation is sent back to the model. + 4. The model responds with either a final response, or a request for more information. The process repeats. + 5. The application prints the final response. +1. Any off topic requests should be handled according to the system prompt. This prompt is provided below. +1. The user can type 'x' to exit the application. + +#### System prompt +``` +You are a weather assistant that provides current weather data for user-specified locations using only +the Weather_Tool, which expects latitude and longitude. Infer the coordinates from the location yourself. +If the user provides coordinates, infer the approximate location and refer to it in your response. +To use the tool, you strictly apply the provided tool specification. + +- Explain your step-by-step process, and give brief updates before each step. +- Only use the Weather_Tool for data. Never guess or make up information. +- Repeat the tool use for subsequent requests if necessary. +- If the tool errors, apologize, explain weather is unavailable, and suggest other options. +- Report temperatures in °C (°F) and wind in km/h (mph). Keep weather reports concise. Sparingly use + emojis where appropriate. +- Only respond to weather queries. Remind off-topic users of your purpose. +- Never claim to search online, access external data, or use tools besides Weather_Tool. +- Complete the entire process until you have all required data before sending the complete response. +``` + +#### Weather tool specification +For strongly typed languages, you will need to use the Bedrock classes provided for tool specification. + +``` +"toolSpec": { + "name": "Weather_Tool", + "description": "Get the current weather for a given location, based on its WGS84 coordinates.", + "inputSchema": { + "json": { + "type": "object", + "properties": { + "latitude": { + "type": "string", + "description": "Geographical WGS84 latitude of the location.", + }, + "longitude": { + "type": "string", + "description": "Geographical WGS84 longitude of the location.", + }, + }, + "required": ["latitude", "longitude"], + } + }, + } +``` + + +## Example Output +``` +******************************************************************************** + Welcome to the Amazon Bedrock Tool Use demo! +******************************************************************************** + + This assistant provides current weather information for user-specified locations. + You can ask for weather details by providing the location name or coordinates. + + Example queries: + - What's the weather like in New York? + - Current weather for latitude 40.70, longitude -74.01 + - Is it warmer in Rome or Barcelona today? + + To exit the program, simply type 'x' and press Enter. + + P.S.: You're not limited to single locations, or even to using English! + Have fun and experiment with the app! + +******************************************************************************** + Your weather info request: (x to exit): + +>What's the weather like in Oklahoma City? + Calling Bedrock... + The model's response: + +Okay, let me get the current weather information for Oklahoma City: + +1) I will look up the latitude and longitude coordinates for Oklahoma City. +2) Then I will use the Weather_Tool to get the weather data for those coordinates. + + + Invoking tool: Weather_Tool with input: 35.4676, -97.5164... + + Calling Bedrock... + The model's response: + +According to the weather data, the current conditions in Oklahoma City are: + +??? Partly cloudy +Temperature: 2.7°C (36.9°F) +Wind: 22.3 km/h (13.9 mph) from the North + +The wind is breezy and it's a bit cool for this time of year in Oklahoma City. I'd recommend wearing a jacket if going outside for extended periods. + +******************************************************************************** + Your weather info request: (x to exit): + +>What's the best kind of cat? + Calling Bedrock... + The model's response: + +I'm an AI assistant focused on providing current weather information using the available Weather_Tool. I don't have any data or capabilities related to discussing different types of cats. Perhaps we could return to discussing weather conditions for a particular location? I'd be happy to look up the latest forecast if you provide a city or geographic coordinates. + +******************************************************************************** + Your weather info request: (x to exit): + +>Where is the warmest city in Oklahoma right now? + Calling Bedrock... + The model's response: + +Okay, let me see if I can find the warmest city in Oklahoma right now using the Weather_Tool: + +1) I will look up the coordinates for some major cities in Oklahoma. +2) Then I will use the Weather_Tool to get the current temperature for each city. +3) I will compare the temperatures to determine the warmest city. + + + Invoking tool: Weather_Tool with input: 35.4676, -97.5164... + + Calling Bedrock... + The model's response: + +Oklahoma City: 2.7°C + + + Invoking tool: Weather_Tool with input: 36.1539, -95.9925... + + Calling Bedrock... + The model's response: + +Tulsa: 5.5°C + +Based on the data from the Weather_Tool, the warmest major city in Oklahoma right now is Tulsa at 5.5°C (41.9°F). + +******************************************************************************** + Your weather info request: (x to exit): + +>What's the warmest city in California right now? + Calling Bedrock... + The model's response: + +OK, let me check the current temperatures in some major cities in California to find the warmest one: + + + Invoking tool: Weather_Tool with input: 34.0522, -118.2437... + + Calling Bedrock... + The model's response: + +Los Angeles: 10.6°C (51.1°F) + + + Invoking tool: Weather_Tool with input: 37.7749, -122.4194... + + Calling Bedrock... + The model's response: + + + +San Francisco: 11.6°C (52.9°F) + + + Invoking tool: Weather_Tool with input: 32.7157, -117.1611... + + Calling Bedrock... + Warning: Maximum number of recursions reached. Please try again. + The model's response: + +San Diego: 12.9°C (55.2°F) + +Based on the data from the Weather_Tool, the warmest major city in California right now appears to be San Diego at 12.9°C (55.2°F). + +******************************************************************************** + Your weather info request: (x to exit): +>x +******************************************************************************** + Thank you for checking out the Amazon Bedrock Tool Use demo. We hope you + learned something new, or got some inspiration for your own apps today! + + For more Bedrock examples in different programming languages, have a look at: + https://docs.aws.amazon.com/bedrock/latest/userguide/service_code_examples.html +******************************************************************************** + +Amazon Bedrock Converse API with Tool Use Feature Scenario is complete. +-------------------------------------------------------------------------------- + +``` +- Cleanup + - There are no resources needing cleanup in this scenario. + +--- + +## Errors +In addition to handling Bedrock Runtime errors on the Converse action, the scenario should also +handle errors related to the tool itself, such as an HTTP Request failure. + +| action | Error | Handling | +|----------------|------------------------|------------------------------------------------------| +| `Converse` | ModelNotReady | Notify the user to try again, and stop the scenario. | +| `HTTP Request` | HttpRequestException | Notify the user and stop the scenario. | + +--- + +## Metadata +For languages which already have an entry for the action, add a description for the snippet describing the scenario or action. + +| action / scenario | metadata file | metadata key | +|--------------------------------------------|--------------------------------|------------------------------------------------------| +| `Converse` | bedrock-runtime_metadata.yaml | bedrock-runtime_Converse_AmazonNovaText | +| `Tool use with the Converse API` | bedrock-runtime_metadata.yaml | bedrock-runtime_Scenario_ToolUse | +| `Scenario: Tool use with the Converse API` | bedrock-runtime_metadata.yaml | bedrock-runtime_Scenario_ToolUseDemo_AmazonNova | + + diff --git a/scenarios/features/bedrock_converse_tool/toolscenario.png b/scenarios/features/bedrock_converse_tool/toolscenario.png new file mode 100644 index 00000000000..45defe47143 Binary files /dev/null and b/scenarios/features/bedrock_converse_tool/toolscenario.png differ diff --git a/swift/example_code/sqs/CreateQueue/Package.swift b/swift/example_code/sqs/CreateQueue/Package.swift new file mode 100644 index 00000000000..bf475e99d8b --- /dev/null +++ b/swift/example_code/sqs/CreateQueue/Package.swift @@ -0,0 +1,40 @@ +// swift-tools-version: 5.9 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// The swift-tools-version declares the minimum version of Swift required to +// build this package. + +import PackageDescription + +let package = Package( + name: "createqueue", + // Let Xcode know the minimum Apple platforms supported. + platforms: [ + .macOS(.v13), + .iOS(.v15) + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package( + url: "https://github.com/awslabs/aws-sdk-swift", + from: "1.0.0"), + .package( + url: "https://github.com/apple/swift-argument-parser.git", + branch: "main" + ) + ], + targets: [ + // Targets are the basic building blocks of a package, defining a module or a test suite. + // Targets can depend on other targets in this package and products + // from dependencies. + .executableTarget( + name: "createqueue", + dependencies: [ + .product(name: "AWSSQS", package: "aws-sdk-swift"), + .product(name: "ArgumentParser", package: "swift-argument-parser") + ], + path: "Sources") + + ] +) diff --git a/swift/example_code/sqs/CreateQueue/Sources/entry.swift b/swift/example_code/sqs/CreateQueue/Sources/entry.swift new file mode 100644 index 00000000000..afb2b83fe48 --- /dev/null +++ b/swift/example_code/sqs/CreateQueue/Sources/entry.swift @@ -0,0 +1,61 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// An example demonstrating how to set up and use an Amazon Simple Queue +// Service client to create an available Amazon SQS queue. + +import ArgumentParser +import AWSClientRuntime +import AWSSQS +import Foundation + +struct ExampleCommand: ParsableCommand { + @Argument(help: "The name of the Amazon SQS queue to create") + var queueName: String + @Option(help: "Name of the Amazon Region to use (default: us-east-1)") + var region = "us-east-1" + + static var configuration = CommandConfiguration( + commandName: "createqueue", + abstract: """ + This example shows how to create a new Amazon SQS queue. + """, + discussion: """ + """ + ) + + /// Called by ``main()`` to run the bulk of the example. + func runAsync() async throws { + // snippet-start:[swift.sqs.CreateQueue] + let config = try await SQSClient.SQSClientConfiguration(region: region) + let sqsClient = SQSClient(config: config) + + let output = try await sqsClient.createQueue( + input: CreateQueueInput( + queueName: queueName + ) + ) + + guard let queueUrl = output.queueUrl else { + print("No queue URL returned.") + return + } + // snippet-end:[swift.sqs.CreateQueue] + print("Created queue named \(queueName) with URL \(queueUrl).") + } +} + +/// The program's asynchronous entry point. +@main +struct Main { + static func main() async { + let args = Array(CommandLine.arguments.dropFirst()) + + do { + let command = try ExampleCommand.parse(args) + try await command.runAsync() + } catch { + ExampleCommand.exit(withError: error) + } + } +} diff --git a/swift/example_code/sqs/DeleteMessageBatch/Package.swift b/swift/example_code/sqs/DeleteMessageBatch/Package.swift new file mode 100644 index 00000000000..13a005cf19f --- /dev/null +++ b/swift/example_code/sqs/DeleteMessageBatch/Package.swift @@ -0,0 +1,40 @@ +// swift-tools-version: 5.9 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// The swift-tools-version declares the minimum version of Swift required to +// build this package. + +import PackageDescription + +let package = Package( + name: "deletemessages", + // Let Xcode know the minimum Apple platforms supported. + platforms: [ + .macOS(.v13), + .iOS(.v15) + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package( + url: "https://github.com/awslabs/aws-sdk-swift", + from: "1.0.0"), + .package( + url: "https://github.com/apple/swift-argument-parser.git", + branch: "main" + ) + ], + targets: [ + // Targets are the basic building blocks of a package, defining a module or a test suite. + // Targets can depend on other targets in this package and products + // from dependencies. + .executableTarget( + name: "deletemessages", + dependencies: [ + .product(name: "AWSSQS", package: "aws-sdk-swift"), + .product(name: "ArgumentParser", package: "swift-argument-parser") + ], + path: "Sources") + + ] +) diff --git a/swift/example_code/sqs/DeleteMessageBatch/Sources/entry.swift b/swift/example_code/sqs/DeleteMessageBatch/Sources/entry.swift new file mode 100644 index 00000000000..d76157fe98b --- /dev/null +++ b/swift/example_code/sqs/DeleteMessageBatch/Sources/entry.swift @@ -0,0 +1,116 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// An example demonstrating how to set up and use an Amazon Simple Queue +// Service client to delete messages from an Amazon SQS queue. + +import ArgumentParser +import AWSClientRuntime +import AWSSQS +import Foundation + +struct ExampleCommand: ParsableCommand { + @Option(help: "The URL of the Amazon SQS queue from which to delete messages") + var queue: String + @Argument(help: "Receipt handle(s) of the message(s) to delete") + var handles: [String] + @Option(help: "Name of the Amazon Region to use (default: us-east-1)") + var region = "us-east-1" + + static var configuration = CommandConfiguration( + commandName: "deletemessages", + abstract: """ + This example shows how to delete a batch of messages from an Amazon SQS queue. + """, + discussion: """ + """ + ) + + /// Called by ``main()`` to run the bulk of the example. + func runAsync() async throws { + // snippet-start:[swift.sqs.DeleteMessageBatch] + let config = try await SQSClient.SQSClientConfiguration(region: region) + let sqsClient = SQSClient(config: config) + + // Create the list of message entries. + + var entries: [SQSClientTypes.DeleteMessageBatchRequestEntry] = [] + var messageNumber = 1 + + for handle in handles { + let entry = SQSClientTypes.DeleteMessageBatchRequestEntry( + id: "\(messageNumber)", + receiptHandle: handle + ) + entries.append(entry) + messageNumber += 1 + } + + // Delete the messages. + + let output = try await sqsClient.deleteMessageBatch( + input: DeleteMessageBatchInput( + entries: entries, + queueUrl: queue + ) + ) + + // Get the lists of failed and successful deletions from the output. + + guard let failedEntries = output.failed else { + print("Failed deletion list is missing!") + return + } + guard let successfulEntries = output.successful else { + print("Successful deletion list is missing!") + return + } + + // Display a list of the failed deletions along with their + // corresponding explanation messages. + + if failedEntries.count != 0 { + print("Failed deletions:") + + for entry in failedEntries { + print("Message #\(entry.id ?? "") failed: \(entry.message ?? "")") + } + } else { + print("No failed deletions.") + } + + // Output a list of the message numbers that were successfully deleted. + + if successfulEntries.count != 0 { + var successes = "" + + for entry in successfulEntries { + if successes.count == 0 { + successes = entry.id ?? "" + } else { + successes = "\(successes), \(entry.id ?? "")" + } + } + print("Succeeded: ", successes) + } else { + print("No successful deletions.") + } + + // snippet-end:[swift.sqs.DeleteMessageBatch] + } +} + +/// The program's asynchronous entry point. +@main +struct Main { + static func main() async { + let args = Array(CommandLine.arguments.dropFirst()) + + do { + let command = try ExampleCommand.parse(args) + try await command.runAsync() + } catch { + ExampleCommand.exit(withError: error) + } + } +} diff --git a/swift/example_code/sqs/DeleteQueue/Package.swift b/swift/example_code/sqs/DeleteQueue/Package.swift new file mode 100644 index 00000000000..37fc04c96dc --- /dev/null +++ b/swift/example_code/sqs/DeleteQueue/Package.swift @@ -0,0 +1,40 @@ +// swift-tools-version: 5.9 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// The swift-tools-version declares the minimum version of Swift required to +// build this package. + +import PackageDescription + +let package = Package( + name: "deletequeue", + // Let Xcode know the minimum Apple platforms supported. + platforms: [ + .macOS(.v13), + .iOS(.v15) + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package( + url: "https://github.com/awslabs/aws-sdk-swift", + from: "1.0.0"), + .package( + url: "https://github.com/apple/swift-argument-parser.git", + branch: "main" + ) + ], + targets: [ + // Targets are the basic building blocks of a package, defining a module or a test suite. + // Targets can depend on other targets in this package and products + // from dependencies. + .executableTarget( + name: "deletequeue", + dependencies: [ + .product(name: "AWSSQS", package: "aws-sdk-swift"), + .product(name: "ArgumentParser", package: "swift-argument-parser") + ], + path: "Sources") + + ] +) diff --git a/swift/example_code/sqs/DeleteQueue/Sources/entry.swift b/swift/example_code/sqs/DeleteQueue/Sources/entry.swift new file mode 100644 index 00000000000..4bb0a546e39 --- /dev/null +++ b/swift/example_code/sqs/DeleteQueue/Sources/entry.swift @@ -0,0 +1,61 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// An example demonstrating how to delete an Amazon SQS queue. + +// snippet-start:[swift.sqs.basics] +import ArgumentParser +import AWSClientRuntime +import AWSSQS +import Foundation + +struct ExampleCommand: ParsableCommand { + @Argument(help: "The URL of the Amazon SQS queue to delete") + var queueUrl: String + @Option(help: "Name of the Amazon Region to use (default: us-east-1)") + var region = "us-east-1" + + static var configuration = CommandConfiguration( + commandName: "deletequeue", + abstract: """ + This example shows how to delete an Amazon SQS queue. + """, + discussion: """ + """ + ) + + /// Called by ``main()`` to run the bulk of the example. + func runAsync() async throws { + // snippet-start:[swift.sqs.DeleteQueue] + let config = try await SQSClient.SQSClientConfiguration(region: region) + let sqsClient = SQSClient(config: config) + + do { + _ = try await sqsClient.deleteQueue( + input: DeleteQueueInput( + queueUrl: queueUrl + ) + ) + } catch _ as AWSSQS.QueueDoesNotExist { + print("Error: The specified queue doesn't exist.") + return + } + // snippet-end:[swift.sqs.DeleteQueue] + } +} + +/// The program's asynchronous entry point. +@main +struct Main { + static func main() async { + let args = Array(CommandLine.arguments.dropFirst()) + + do { + let command = try ExampleCommand.parse(args) + try await command.runAsync() + } catch { + ExampleCommand.exit(withError: error) + } + } +} +// snippet-end:[swift.sqs.basics] diff --git a/swift/example_code/sqs/GetQueueAttributes/Package.swift b/swift/example_code/sqs/GetQueueAttributes/Package.swift new file mode 100644 index 00000000000..a46032ef803 --- /dev/null +++ b/swift/example_code/sqs/GetQueueAttributes/Package.swift @@ -0,0 +1,40 @@ +// swift-tools-version: 5.9 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// The swift-tools-version declares the minimum version of Swift required to +// build this package. + +import PackageDescription + +let package = Package( + name: "getqueueattributes", + // Let Xcode know the minimum Apple platforms supported. + platforms: [ + .macOS(.v13), + .iOS(.v15) + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package( + url: "https://github.com/awslabs/aws-sdk-swift", + from: "1.0.0"), + .package( + url: "https://github.com/apple/swift-argument-parser.git", + branch: "main" + ) + ], + targets: [ + // Targets are the basic building blocks of a package, defining a module or a test suite. + // Targets can depend on other targets in this package and products + // from dependencies. + .executableTarget( + name: "getqueueattributes", + dependencies: [ + .product(name: "AWSSQS", package: "aws-sdk-swift"), + .product(name: "ArgumentParser", package: "swift-argument-parser") + ], + path: "Sources") + + ] +) diff --git a/swift/example_code/sqs/GetQueueAttributes/Sources/entry.swift b/swift/example_code/sqs/GetQueueAttributes/Sources/entry.swift new file mode 100644 index 00000000000..1255f3c7eb0 --- /dev/null +++ b/swift/example_code/sqs/GetQueueAttributes/Sources/entry.swift @@ -0,0 +1,75 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// An example demonstrating how to set up and use an Amazon Simple Queue +// Service client to get the attributes of an available Amazon SQS queue. + +import ArgumentParser +import AWSClientRuntime +import AWSSQS +import Foundation + +struct ExampleCommand: ParsableCommand { + @Argument(help: "The URL of the Amazon SQS queue to get the attributes of") + var url: String + @Option(help: "Name of the Amazon Region to use (default: us-east-1)") + var region = "us-east-1" + + static var configuration = CommandConfiguration( + commandName: "getqueueattributes", + abstract: """ + This example shows how to get an Amazon SQS queue's attributes. + """, + discussion: """ + """ + ) + + /// Called by ``main()`` to run the bulk of the example. + func runAsync() async throws { + // snippet-start:[swift.sqs.GetQueueAttributes] + let config = try await SQSClient.SQSClientConfiguration(region: region) + let sqsClient = SQSClient(config: config) + + let output = try await sqsClient.getQueueAttributes( + input: GetQueueAttributesInput( + attributeNames: [ + .approximatenumberofmessages, + .maximummessagesize + ], + queueUrl: url + ) + ) + + guard let attributes = output.attributes else { + print("No queue attributes returned.") + return + } + + for (attr, value) in attributes { + switch(attr) { + case "ApproximateNumberOfMessages": + print("Approximate message count: \(value)") + case "MaximumMessageSize": + print("Maximum message size: \(value)kB") + default: + continue + } + } + // snippet-end:[swift.sqs.GetQueueAttributes] + } +} + +/// The program's asynchronous entry point. +@main +struct Main { + static func main() async { + let args = Array(CommandLine.arguments.dropFirst()) + + do { + let command = try ExampleCommand.parse(args) + try await command.runAsync() + } catch { + ExampleCommand.exit(withError: error) + } + } +} diff --git a/swift/example_code/sqs/README.md b/swift/example_code/sqs/README.md new file mode 100644 index 00000000000..f9a0e79e12b --- /dev/null +++ b/swift/example_code/sqs/README.md @@ -0,0 +1,104 @@ +# Amazon SQS code examples for the SDK for Swift + +## Overview + +Shows how to use the AWS SDK for Swift to work with Amazon Simple Queue Service (Amazon SQS). + + + + +_Amazon SQS is a fully managed message queuing service that makes it easy to decouple and scale microservices, distributed systems, and serverless applications._ + +## ⚠ Important + +* Running this code might result in charges to your AWS account. For more details, see [AWS Pricing](https://aws.amazon.com/pricing/) and [Free Tier](https://aws.amazon.com/free/). +* Running the tests might result in charges to your AWS account. +* We recommend that you grant your code least privilege. At most, grant only the minimum permissions required to perform the task. For more information, see [Grant least privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege). +* This code is not tested in every AWS Region. For more information, see [AWS Regional Services](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services). + + + + +## Code examples + +### Prerequisites + +For prerequisites, see the [README](../../README.md#Prerequisites) in the `swift` folder. + + + + + +### Get started + +- [Hello Amazon SQS](basics/Package.swift#L8) (`ListQueues`) + + +### Single actions + +Code excerpts that show you how to call individual service functions. + +- [CreateQueue](CreateQueue/Sources/entry.swift#L29) +- [DeleteMessageBatch](DeleteMessageBatch/Sources/entry.swift#L31) +- [DeleteQueue](DeleteQueue/Sources/entry.swift#L29) +- [GetQueueAttributes](GetQueueAttributes/Sources/entry.swift#L29) +- [ListQueues](basics/Sources/entry.swift#L28) +- [ReceiveMessage](ReceiveMessage/Sources/entry.swift#L31) +- [SetQueueAttributes](SetQueueAttributes/Sources/entry.swift#L32) + + + + + +## Run the examples + +### Instructions + +To build any of these examples from a terminal window, navigate into its +directory, then use the following command: + +``` +$ swift build +``` + +To build one of these examples in Xcode, navigate to the example's directory +(such as the `ListUsers` directory, to build that example). Then type `xed.` +to open the example directory in Xcode. You can then use standard Xcode build +and run commands. + + + + +#### Hello Amazon SQS + +This example shows you how to get started using Amazon SQS. + + + +### Tests + +⚠ Running tests might result in charges to your AWS account. + + +To find instructions for running these tests, see the [README](../../README.md#Tests) +in the `swift` folder. + + + + + + +## Additional resources + +- [Amazon SQS Developer Guide](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) +- [Amazon SQS API Reference](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/Welcome.html) +- [SDK for Swift Amazon SQS reference](https://sdk.amazonaws.com/swift/api/awssqs/latest/documentation/awssqs) + + + + +--- + +Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: Apache-2.0 diff --git a/swift/example_code/sqs/ReceiveMessage/Package.swift b/swift/example_code/sqs/ReceiveMessage/Package.swift new file mode 100644 index 00000000000..12fac47b32e --- /dev/null +++ b/swift/example_code/sqs/ReceiveMessage/Package.swift @@ -0,0 +1,40 @@ +// swift-tools-version: 5.9 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// The swift-tools-version declares the minimum version of Swift required to +// build this package. + +import PackageDescription + +let package = Package( + name: "receivemessage", + // Let Xcode know the minimum Apple platforms supported. + platforms: [ + .macOS(.v13), + .iOS(.v15) + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package( + url: "https://github.com/awslabs/aws-sdk-swift", + from: "1.0.0"), + .package( + url: "https://github.com/apple/swift-argument-parser.git", + branch: "main" + ) + ], + targets: [ + // Targets are the basic building blocks of a package, defining a module or a test suite. + // Targets can depend on other targets in this package and products + // from dependencies. + .executableTarget( + name: "receivemessage", + dependencies: [ + .product(name: "AWSSQS", package: "aws-sdk-swift"), + .product(name: "ArgumentParser", package: "swift-argument-parser") + ], + path: "Sources") + + ] +) diff --git a/swift/example_code/sqs/ReceiveMessage/Sources/entry.swift b/swift/example_code/sqs/ReceiveMessage/Sources/entry.swift new file mode 100644 index 00000000000..73433736dcf --- /dev/null +++ b/swift/example_code/sqs/ReceiveMessage/Sources/entry.swift @@ -0,0 +1,71 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// An example demonstrating how to set up and use an Amazon Simple Queue +// Service client to get the attributes of an available Amazon SQS queue. + +import ArgumentParser +import AWSClientRuntime +import AWSSQS +import Foundation + +struct ExampleCommand: ParsableCommand { + @Option(help: "The maximum number of messages to receive") + var maxMessages = 10 + @Argument(help: "The URL of the Amazon SQS queue to get the attributes of") + var url: String + @Option(help: "Name of the Amazon Region to use (default: us-east-1)") + var region = "us-east-1" + + static var configuration = CommandConfiguration( + commandName: "receivemessage", + abstract: """ + This example shows how to receive messages from an Amazon SQS queue. + """, + discussion: """ + """ + ) + + /// Called by ``main()`` to run the bulk of the example. + func runAsync() async throws { + // snippet-start:[swift.sqs.ReceiveMessage] + let config = try await SQSClient.SQSClientConfiguration(region: region) + let sqsClient = SQSClient(config: config) + + let output = try await sqsClient.receiveMessage( + input: ReceiveMessageInput( + maxNumberOfMessages: maxMessages, + queueUrl: url + ) + ) + + guard let messages = output.messages else { + print("No messages received.") + return + } + + for message in messages { + print("Message ID: \(message.messageId ?? "")") + print("Receipt handle: \(message.receiptHandle ?? "")") + print(message.body ?? "") + print("---") + } + + // snippet-end:[swift.sqs.ReceiveMessage] + } +} + +/// The program's asynchronous entry point. +@main +struct Main { + static func main() async { + let args = Array(CommandLine.arguments.dropFirst()) + + do { + let command = try ExampleCommand.parse(args) + try await command.runAsync() + } catch { + ExampleCommand.exit(withError: error) + } + } +} diff --git a/swift/example_code/sqs/SetQueueAttributes/Package.swift b/swift/example_code/sqs/SetQueueAttributes/Package.swift new file mode 100644 index 00000000000..991a4a13f4b --- /dev/null +++ b/swift/example_code/sqs/SetQueueAttributes/Package.swift @@ -0,0 +1,40 @@ +// swift-tools-version: 5.9 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// The swift-tools-version declares the minimum version of Swift required to +// build this package. + +import PackageDescription + +let package = Package( + name: "configqueue", + // Let Xcode know the minimum Apple platforms supported. + platforms: [ + .macOS(.v13), + .iOS(.v15) + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package( + url: "https://github.com/awslabs/aws-sdk-swift", + from: "1.0.0"), + .package( + url: "https://github.com/apple/swift-argument-parser.git", + branch: "main" + ) + ], + targets: [ + // Targets are the basic building blocks of a package, defining a module or a test suite. + // Targets can depend on other targets in this package and products + // from dependencies. + .executableTarget( + name: "configqueue", + dependencies: [ + .product(name: "AWSSQS", package: "aws-sdk-swift"), + .product(name: "ArgumentParser", package: "swift-argument-parser") + ], + path: "Sources") + + ] +) diff --git a/swift/example_code/sqs/SetQueueAttributes/Sources/entry.swift b/swift/example_code/sqs/SetQueueAttributes/Sources/entry.swift new file mode 100644 index 00000000000..5477f331dba --- /dev/null +++ b/swift/example_code/sqs/SetQueueAttributes/Sources/entry.swift @@ -0,0 +1,65 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// An example demonstrating how to set up and use an Amazon Simple Queue +// Service client to get the attributes of an available Amazon SQS queue. + +import ArgumentParser +import AWSClientRuntime +import AWSSQS +import Foundation + +struct ExampleCommand: ParsableCommand { + @Argument(help: "The URL of the Amazon SQS queue to set attributes of") + var url: String + @Option(help: "Maximum size of a message in bytes, from 1024 to 262144") + var maxSize: Int + @Option(help: "Name of the Amazon Region to use (default: us-east-1)") + var region = "us-east-1" + + static var configuration = CommandConfiguration( + commandName: "configqueue", + abstract: """ + This example shows how to set attributes of an Amazon + SQS queue, using the SQS client's setQueueAttributes() function. + """, + discussion: """ + """ + ) + + /// Called by ``main()`` to run the bulk of the example. + func runAsync() async throws { + // snippet-start:[swift.sqs.SetQueueAttributes] + let config = try await SQSClient.SQSClientConfiguration(region: region) + let sqsClient = SQSClient(config: config) + + do { + _ = try await sqsClient.setQueueAttributes( + input: SetQueueAttributesInput( + attributes: [ + "MaximumMessageSize": "\(maxSize)" + ], + queueUrl: url + ) + ) + } catch _ as AWSSQS.InvalidAttributeValue { + print("Invalid maximum message size: \(maxSize) kB.") + } + // snippet-end:[swift.sqs.SetQueueAttributes] + } +} + +/// The program's asynchronous entry point. +@main +struct Main { + static func main() async { + let args = Array(CommandLine.arguments.dropFirst()) + + do { + let command = try ExampleCommand.parse(args) + try await command.runAsync() + } catch { + ExampleCommand.exit(withError: error) + } + } +} diff --git a/swift/example_code/sqs/basics/Package.swift b/swift/example_code/sqs/basics/Package.swift new file mode 100644 index 00000000000..c8cab043cef --- /dev/null +++ b/swift/example_code/sqs/basics/Package.swift @@ -0,0 +1,42 @@ +// swift-tools-version: 5.9 +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// The swift-tools-version declares the minimum version of Swift required to +// build this package. + +// snippet-start:[swift.sqs.basics.package] +import PackageDescription + +let package = Package( + name: "sqs-basics", + // Let Xcode know the minimum Apple platforms supported. + platforms: [ + .macOS(.v13), + .iOS(.v15) + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package( + url: "https://github.com/awslabs/aws-sdk-swift", + from: "1.0.0"), + .package( + url: "https://github.com/apple/swift-argument-parser.git", + branch: "main" + ) + ], + targets: [ + // Targets are the basic building blocks of a package, defining a module or a test suite. + // Targets can depend on other targets in this package and products + // from dependencies. + .executableTarget( + name: "sqs-basics", + dependencies: [ + .product(name: "AWSSQS", package: "aws-sdk-swift"), + .product(name: "ArgumentParser", package: "swift-argument-parser") + ], + path: "Sources") + + ] +) +// snippet-end:[swift.sqs.basics.package] diff --git a/swift/example_code/sqs/basics/Sources/entry.swift b/swift/example_code/sqs/basics/Sources/entry.swift new file mode 100644 index 00000000000..39fa21499ab --- /dev/null +++ b/swift/example_code/sqs/basics/Sources/entry.swift @@ -0,0 +1,75 @@ +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 +// +// An example demonstrating how to set up and use an Amazon Simple Notification +// Service client to list your available Amazon SQS queues. + +// snippet-start:[swift.sqs.basics] +import ArgumentParser +import AWSClientRuntime +import AWSSQS +import Foundation + +struct ExampleCommand: ParsableCommand { + @Option(help: "Name of the Amazon Region to use (default: us-east-1)") + var region = "us-east-1" + + static var configuration = CommandConfiguration( + commandName: "sqs-basics", + abstract: """ + This example shows how to list all of your available Amazon SQS queues. + """, + discussion: """ + """ + ) + + /// Called by ``main()`` to run the bulk of the example. + func runAsync() async throws { + // snippet-start:[swift.sqs.ListQueues] + let config = try await SQSClient.SQSClientConfiguration(region: region) + let sqsClient = SQSClient(config: config) + + var queues: [String] = [] + let outputPages = sqsClient.listQueuesPaginated( + input: ListQueuesInput() + ) + + // Each time a page of results arrives, process its contents. + + for try await output in outputPages { + guard let urls = output.queueUrls else { + print("No queues found.") + return + } + + // Iterate over the queue URLs listed on this page, adding them + // to the `queues` array. + + for queueUrl in urls { + queues.append(queueUrl) + } + } + // snippet-end:[swift.sqs.ListQueues] + + print("You have \(queues.count) queues:") + for queue in queues { + print(" \(queue)") + } + } +} + +/// The program's asynchronous entry point. +@main +struct Main { + static func main() async { + let args = Array(CommandLine.arguments.dropFirst()) + + do { + let command = try ExampleCommand.parse(args) + try await command.runAsync() + } catch { + ExampleCommand.exit(withError: error) + } + } +} +// snippet-end:[swift.sqs.basics]