Skip to content

Swift: Add example of Bedrock's ListFoundationModels function #7365

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .doc_gen/metadata/bedrock_metadata.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,14 @@ bedrock_Hello:
- description:
snippet_tags:
- bedrock.example_code.hello_bedrock.complete
Swift:
versions:
- sdk_version: 1
github: swift/example_code/bedrock
excerpts:
- description:
snippet_tags:
- swift.bedrock.hello
services:
bedrock: {ListFoundationModels}

Expand Down Expand Up @@ -135,5 +143,14 @@ bedrock_ListFoundationModels:
- description: List the available Bedrock foundation models.
snippet_tags:
- Bedrock.dotnetv3.BedrockActions.ListFoundationModels
Swift:
versions:
- sdk_version: 1
github: swift/example_code/bedrock
excerpts:
- description:
snippet_tags:
- swift.bedrock.import
- swift.bedrock.ListFoundationModels
services:
bedrock: {ListFoundationModels}
40 changes: 40 additions & 0 deletions swift/example_code/bedrock/ListFoundationModels/Package.swift
Original file line number Diff line number Diff line change
@@ -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: "ListFoundationModels",
// 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: "ListFoundationModels",
dependencies: [
.product(name: "AWSBedrock", package: "aws-sdk-swift"),
.product(name: "ArgumentParser", package: "swift-argument-parser")
],
path: "Sources")

]
)
148 changes: 148 additions & 0 deletions swift/example_code/bedrock/ListFoundationModels/Sources/entry.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//
// An example demonstrating how to fetch a list of foundation models available
// using Amazon Bedrock.

// snippet-start:[swift.bedrock.hello]
import ArgumentParser
import AWSClientRuntime
import Foundation

// snippet-start:[swift.bedrock.import]
import AWSBedrock
// snippet-end:[swift.bedrock.import]

struct ExampleCommand: ParsableCommand {
static var configuration = CommandConfiguration(
commandName: "ListFoundationModels",
abstract: """
This example demonstrates how to retrieve a list of the available
foundation models from Amazon Bedrock.
""",
discussion: """
"""
)

/// Construct a string listing the specified modalities.
///
/// - Parameter modalities: An array of the modalities to list.
///
/// - Returns: A string with a human-readable list of modalities.
func buildModalityList(modalities: [BedrockClientTypes.ModelModality]?) -> String {
var first = true
var str = ""

if modalities == nil {
return "<none>"
}

for modality in modalities! {
if !first {
str += ", "
}
first = false
str += modality.rawValue
}

return str
}

/// Construct a string listing the specified customizations.
///
/// - Parameter customizations: An array of the customizations to list.
///
/// - Returns: A string listing the customizations.
func buildCustomizationList(customizations: [BedrockClientTypes.ModelCustomization]?) -> String {
var first = true
var str = ""

if customizations == nil {
return "<none>"
}

for customization in customizations! {
if !first {
str += ", "
}
first = false
str += customization.rawValue
}

return str
}

/// Construct a string listing the specified inferences.
///
/// - Parameter inferences: An array of inferences to list.
///
/// - Returns: A string listing the specified inferences.
func buildInferenceList(inferences: [BedrockClientTypes.InferenceType]?) -> String {
var first = true
var str = ""

if inferences == nil {
return "<none>"
}

for inference in inferences! {
if !first {
str += ", "
}
first = false
str += inference.rawValue
}

return str
}

/// Called by ``main()`` to run the bulk of the example.
func runAsync() async throws {
// snippet-start:[swift.bedrock.ListFoundationModels]
// Always use the Region "us-east-1" to have access to the most models.
let config = try await BedrockClient.BedrockClientConfiguration(region: "us-east-1")
let bedrockClient = BedrockClient(config: config)

let output = try await bedrockClient.listFoundationModels(
input: ListFoundationModelsInput()
)

guard let summaries = output.modelSummaries else {
print("No models returned.")
return
}

// Output a list of the models with their details.
for summary in summaries {
print("==========================================")
print(" Model ID: \(summary.modelId ?? "<unknown>")")
print("------------------------------------------")
print(" Name: \(summary.modelName ?? "<unknown>")")
print(" Provider: \(summary.providerName ?? "<unknown>")")
print(" Input modalities: \(buildModalityList(modalities: summary.inputModalities))")
print(" Output modalities: \(buildModalityList(modalities: summary.outputModalities))")
print(" Supported customizations: \(buildCustomizationList(customizations: summary.customizationsSupported ))")
print(" Supported inference types: \(buildInferenceList(inferences: summary.inferenceTypesSupported))")
print("------------------------------------------\n")
}
// snippet-end:[swift.bedrock.ListFoundationModels]

print("\(summaries.count) models available.")
}
}

/// 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.bedrock.hello]
98 changes: 98 additions & 0 deletions swift/example_code/bedrock/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
# Amazon Bedrock code examples for the SDK for Swift

## Overview

Shows how to use the AWS SDK for Swift to work with Amazon Bedrock.

<!--custom.overview.start-->
<!--custom.overview.end-->

_Amazon Bedrock enables you to build and scale generative AI applications with foundation models._

## ⚠ 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).

<!--custom.important.start-->
<!--custom.important.end-->

## Code examples

### Prerequisites

For prerequisites, see the [README](../../README.md#Prerequisites) in the `swift` folder.


<!--custom.prerequisites.start-->
<!--custom.prerequisites.end-->

### Get started

- [Hello Amazon Bedrock](ListFoundationModels/Sources/entry.swift#L7) (`ListFoundationModels`)


### Single actions

Code excerpts that show you how to call individual service functions.

- [ListFoundationModels](ListFoundationModels/Sources/entry.swift#L101)


<!--custom.examples.start-->
<!--custom.examples.end-->

## 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.

<!--custom.instructions.start-->
<!--custom.instructions.end-->

#### Hello Amazon Bedrock

This example shows you how to get started using Amazon Bedrock.



### 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.



<!--custom.tests.start-->
<!--custom.tests.end-->

## Additional resources

- [Amazon Bedrock User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)
- [Amazon Bedrock API Reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/welcome.html)
- [SDK for Swift Amazon Bedrock reference](https://sdk.amazonaws.com/swift/api/awsbedrock/latest/documentation/awsbedrock)

<!--custom.resources.start-->
<!--custom.resources.end-->

---

Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
Loading