文档 AWS SDK 示例 GitHub 存储库中还有更多 S AWS DK 示例
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用适用于 Swift 的软件开发工具包的亚马逊 Bedrock
以下代码示例向您展示了如何使用带有 Amazon Bedrock Runtime 的 Swift AWS 开发工具包来执行操作和实现常见场景。
每个示例都包含一个指向完整源代码的链接,您可以从中找到有关如何在上下文中设置和运行代码的说明。
Amazon Nova
以下代码示例展示了如何使用 Bedrock 的 Converse API 向 Amazon Nova 发送短信。
- 适用于 Swift 的 SDK
-
注意
还有更多相关信息 GitHub。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 使用 Bedrock 的 Converse API 向 Amazon Nova 发送文本消息。
// An example demonstrating how to use the Conversation API to send // a text message to Amazon Nova. import AWSBedrockRuntime func converse(_ textPrompt: String) async throws -> String { // Create a Bedrock Runtime client in the AWS Region you want to use. let config = try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration( region: "us-east-1" ) let client = BedrockRuntimeClient(config: config) // Set the model ID. let modelId = "amazon.nova-micro-v1:0" // Start a conversation with the user message. let message = BedrockRuntimeClientTypes.Message( content: [.text(textPrompt)], role: .user ) // Optionally use inference parameters let inferenceConfig = BedrockRuntimeClientTypes.InferenceConfiguration( maxTokens: 512, stopSequences: ["END"], temperature: 0.5, topp: 0.9 ) // Create the ConverseInput to send to the model let input = ConverseInput( inferenceConfig: inferenceConfig, messages: [message], modelId: modelId) // Send the ConverseInput to the model let response = try await client.converse(input: input) // Extract and return the response text. if case let .message(msg) = response.output { if case let .text(textResponse) = msg.content![0] { return textResponse } else { return "No text response found in message content" } } else { return "No message found in converse output" } }
-
有关 API 详细信息,请参阅 AWS SDK for Swift API 参考中的 Converse
。
-
以下代码示例展示了如何使用 Bedrock 的 Converse API 向 Amazon Nova 发送短信并实时处理响应流。
- 适用于 Swift 的 SDK
-
注意
还有更多相关信息 GitHub。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 使用 Bedrock 的 Converse API 向 Amazon Nova 发送文本消息并实时处理回复流。
// An example demonstrating how to use the Conversation API to send a text message // to Amazon Nova and print the response stream import AWSBedrockRuntime func printConverseStream(_ textPrompt: String) async throws { // Create a Bedrock Runtime client in the AWS Region you want to use. let config = try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration( region: "us-east-1" ) let client = BedrockRuntimeClient(config: config) // Set the model ID. let modelId = "amazon.nova-lite-v1:0" // Start a conversation with the user message. let message = BedrockRuntimeClientTypes.Message( content: [.text(textPrompt)], role: .user ) // Optionally use inference parameters. let inferenceConfig = BedrockRuntimeClientTypes.InferenceConfiguration( maxTokens: 512, stopSequences: ["END"], temperature: 0.5, topp: 0.9 ) // Create the ConverseStreamInput to send to the model. let input = ConverseStreamInput( inferenceConfig: inferenceConfig, messages: [message], modelId: modelId) // Send the ConverseStreamInput to the model. let response = try await client.converseStream(input: input) // Extract the streaming response. guard let stream = response.stream else { print("No stream available") return } // Extract and print the streamed response text in real-time. for try await event in stream { switch event { case .messagestart(_): print("\nNova Lite:") case .contentblockdelta(let deltaEvent): if case .text(let text) = deltaEvent.delta { print(text, terminator: "") } default: break } } }
-
如需了解 API 的详细信息,请参阅适用ConverseStream
于 S wift 的AWS SDK API 参考。
-
Amazon Nova Reel
以下代码示例演示了如何使用 Amazon Nova Reel 根据文本提示生成视频。
- 适用于 Swift 的 SDK
-
注意
还有更多相关信息 GitHub。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 使用 Amazon Nova Reel 根据文本提示生成视频。
// This example demonstrates how to use Amazon Nova Reel to generate a video from a text prompt. // It shows how to: // - Set up the Amazon Bedrock runtime client // - Configure a text-to-video request // - Submit an asynchronous job for video generation // - Poll for job completion status // - Access the generated video from S3 import AWSBedrockRuntime import Foundation import Smithy func startTextToVideoGenerationJob( bedrockRuntimeClient: BedrockRuntimeClient, prompt: String, outputS3Uri: String ) async throws -> String? { // Specify the model ID for text-to-video generation let modelId = "amazon.nova-reel-v1:0" // Configure the video generation request with additional parameters let modelInputSource: [String: Any] = [ "taskType": "TEXT_VIDEO", "textToVideoParams": [ "text": "\(prompt)" ], "videoGenerationConfig": [ "durationSeconds": 6, "fps": 24, "dimension": "1280x720", ], ] let modelInput = try Document.make(from: modelInputSource) let input = StartAsyncInvokeInput( modelId: modelId, modelInput: modelInput, outputDataConfig: .s3outputdataconfig( BedrockRuntimeClientTypes.AsyncInvokeS3OutputDataConfig( s3Uri: outputS3Uri ) ) ) // Invoke the model asynchronously let output = try await bedrockRuntimeClient.startAsyncInvoke(input: input) return output.invocationArn } func queryJobStatus( bedrockRuntimeClient: BedrockRuntimeClient, invocationArn: String? ) async throws -> GetAsyncInvokeOutput { try await bedrockRuntimeClient.getAsyncInvoke( input: GetAsyncInvokeInput(invocationArn: invocationArn)) } func main() async throws { // Create a Bedrock Runtime client let config = try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration( region: "us-east-1" ) let client = BedrockRuntimeClient(config: config) // Specify the S3 location for the output video let bucket = "s3://REPLACE-WITH-YOUR-S3-BUCKET-NAM" print("Submitting video generation job...") let invocationArn = try await startTextToVideoGenerationJob( bedrockRuntimeClient: client, prompt: "A pomegranate juice in a railway station", outputS3Uri: bucket ) print("Job started with invocation ARN: \(String(describing:invocationArn))") // Poll for job completion var status: BedrockRuntimeClientTypes.AsyncInvokeStatus? var isReady = false var hasFailed = false while !isReady && !hasFailed { print("\nPolling job status...") status = try await queryJobStatus( bedrockRuntimeClient: client, invocationArn: invocationArn ).status switch status { case .completed: isReady = true print("Video is ready\nCheck S3 bucket: \(bucket)") case .failed: hasFailed = true print("Something went wrong") case .inProgress: print("Job is in progress...") try await Task.sleep(nanoseconds: 15 * 1_000_000_000) // 15 seconds default: isReady = true } } } do { try await main() } catch { print("An error occurred: \(error)") }
-
有关 API 详细信息,请参阅《AWS SDK for Swift API 参考》中的以下主题。
-
Anthropic Claude
以下代码示例展示了如何使用 Bedrock 的 Converse API 向 Anthropic Claude 发送短信。
- 适用于 Swift 的 SDK
-
注意
还有更多相关信息 GitHub。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 使用 Bedrock 的 Converse API 向 Anthropic Claude 发送文本消息。
// An example demonstrating how to use the Conversation API to send // a text message to Anthropic Claude. import AWSBedrockRuntime func converse(_ textPrompt: String) async throws -> String { // Create a Bedrock Runtime client in the AWS Region you want to use. let config = try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration( region: "us-east-1" ) let client = BedrockRuntimeClient(config: config) // Set the model ID. let modelId = "anthropic.claude-3-haiku-20240307-v1:0" // Start a conversation with the user message. let message = BedrockRuntimeClientTypes.Message( content: [.text(textPrompt)], role: .user ) // Optionally use inference parameters let inferenceConfig = BedrockRuntimeClientTypes.InferenceConfiguration( maxTokens: 512, stopSequences: ["END"], temperature: 0.5, topp: 0.9 ) // Create the ConverseInput to send to the model let input = ConverseInput( inferenceConfig: inferenceConfig, messages: [message], modelId: modelId) // Send the ConverseInput to the model let response = try await client.converse(input: input) // Extract and return the response text. if case let .message(msg) = response.output { if case let .text(textResponse) = msg.content![0] { return textResponse } else { return "No text response found in message content" } } else { return "No message found in converse output" } }
-
有关 API 详细信息,请参阅 AWS SDK for Swift API 参考中的 Converse
。
-
以下代码示例展示了如何使用 Bedrock 的 Converse API 向 Anthropic Claude 发送短信并实时处理响应流。
- 适用于 Swift 的 SDK
-
注意
还有更多相关信息 GitHub。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 使用 Bedrock 的 Converse API 向 Anthropic Claude 发送文本消息并实时处理响应流。
// An example demonstrating how to use the Conversation API to send a text message // to Anthropic Claude and print the response stream import AWSBedrockRuntime func printConverseStream(_ textPrompt: String) async throws { // Create a Bedrock Runtime client in the AWS Region you want to use. let config = try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration( region: "us-east-1" ) let client = BedrockRuntimeClient(config: config) // Set the model ID. let modelId = "anthropic.claude-3-haiku-20240307-v1:0" // Start a conversation with the user message. let message = BedrockRuntimeClientTypes.Message( content: [.text(textPrompt)], role: .user ) // Optionally use inference parameters. let inferenceConfig = BedrockRuntimeClientTypes.InferenceConfiguration( maxTokens: 512, stopSequences: ["END"], temperature: 0.5, topp: 0.9 ) // Create the ConverseStreamInput to send to the model. let input = ConverseStreamInput( inferenceConfig: inferenceConfig, messages: [message], modelId: modelId) // Send the ConverseStreamInput to the model. let response = try await client.converseStream(input: input) // Extract the streaming response. guard let stream = response.stream else { print("No stream available") return } // Extract and print the streamed response text in real-time. for try await event in stream { switch event { case .messagestart(_): print("\nAnthropic Claude:") case .contentblockdelta(let deltaEvent): if case .text(let text) = deltaEvent.delta { print(text, terminator: "") } default: break } } }
-
如需了解 API 的详细信息,请参阅适用ConverseStream
于 S wift 的AWS SDK API 参考。
-
Meta Llama
以下代码示例展示了如何使用 Bedrock 的 Converse API 向 Meta Llama 发送短信。
- 适用于 Swift 的 SDK
-
注意
还有更多相关信息 GitHub。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 使用 Bedrock 的 Converse API 向 Meta Llama 发送文本消息。
// An example demonstrating how to use the Conversation API to send // a text message to Meta Llama. import AWSBedrockRuntime func converse(_ textPrompt: String) async throws -> String { // Create a Bedrock Runtime client in the AWS Region you want to use. let config = try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration( region: "us-east-1" ) let client = BedrockRuntimeClient(config: config) // Set the model ID. let modelId = "meta.llama3-8b-instruct-v1:0" // Start a conversation with the user message. let message = BedrockRuntimeClientTypes.Message( content: [.text(textPrompt)], role: .user ) // Optionally use inference parameters let inferenceConfig = BedrockRuntimeClientTypes.InferenceConfiguration( maxTokens: 512, stopSequences: ["END"], temperature: 0.5, topp: 0.9 ) // Create the ConverseInput to send to the model let input = ConverseInput( inferenceConfig: inferenceConfig, messages: [message], modelId: modelId) // Send the ConverseInput to the model let response = try await client.converse(input: input) // Extract and return the response text. if case let .message(msg) = response.output { if case let .text(textResponse) = msg.content![0] { return textResponse } else { return "No text response found in message content" } } else { return "No message found in converse output" } }
-
有关 API 详细信息,请参阅 AWS SDK for Swift API 参考中的 Converse
。
-
以下代码示例展示了如何使用 Bedrock 的 Converse API 向 Meta Llama 发送短信并实时处理响应流。
- 适用于 Swift 的 SDK
-
注意
还有更多相关信息 GitHub。在 AWS 代码示例存储库
中查找完整示例,了解如何进行设置和运行。 使用 Bedrock 的 Converse API 向 Meta Llama 发送文本消息并实时处理响应流。
// An example demonstrating how to use the Conversation API to send a text message // to Meta Llama and print the response stream. import AWSBedrockRuntime func printConverseStream(_ textPrompt: String) async throws { // Create a Bedrock Runtime client in the AWS Region you want to use. let config = try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration( region: "us-east-1" ) let client = BedrockRuntimeClient(config: config) // Set the model ID. let modelId = "meta.llama3-8b-instruct-v1:0" // Start a conversation with the user message. let message = BedrockRuntimeClientTypes.Message( content: [.text(textPrompt)], role: .user ) // Optionally use inference parameters. let inferenceConfig = BedrockRuntimeClientTypes.InferenceConfiguration( maxTokens: 512, stopSequences: ["END"], temperature: 0.5, topp: 0.9 ) // Create the ConverseStreamInput to send to the model. let input = ConverseStreamInput( inferenceConfig: inferenceConfig, messages: [message], modelId: modelId) // Send the ConverseStreamInput to the model. let response = try await client.converseStream(input: input) // Extract the streaming response. guard let stream = response.stream else { print("No stream available") return } // Extract and print the streamed response text in real-time. for try await event in stream { switch event { case .messagestart(_): print("\nMeta Llama:") case .contentblockdelta(let deltaEvent): if case .text(let text) = deltaEvent.delta { print(text, terminator: "") } default: break } } }
-
如需了解 API 的详细信息,请参阅适用ConverseStream
于 S wift 的AWS SDK API 参考。
-