Skip to content

Commit 7f6dcd8

Browse files
authored
Swift: Add example of Bedrock's ListFoundationModels function (#7365)
* Add example for Bedrock's ListFoundationModels
1 parent de1d84f commit 7f6dcd8

File tree

4 files changed

+303
-0
lines changed

4 files changed

+303
-0
lines changed

.doc_gen/metadata/bedrock_metadata.yaml

+17
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,14 @@ bedrock_Hello:
3838
- description:
3939
snippet_tags:
4040
- bedrock.example_code.hello_bedrock.complete
41+
Swift:
42+
versions:
43+
- sdk_version: 1
44+
github: swift/example_code/bedrock
45+
excerpts:
46+
- description:
47+
snippet_tags:
48+
- swift.bedrock.hello
4149
services:
4250
bedrock: {ListFoundationModels}
4351

@@ -135,5 +143,14 @@ bedrock_ListFoundationModels:
135143
- description: List the available Bedrock foundation models.
136144
snippet_tags:
137145
- Bedrock.dotnetv3.BedrockActions.ListFoundationModels
146+
Swift:
147+
versions:
148+
- sdk_version: 1
149+
github: swift/example_code/bedrock
150+
excerpts:
151+
- description:
152+
snippet_tags:
153+
- swift.bedrock.import
154+
- swift.bedrock.ListFoundationModels
138155
services:
139156
bedrock: {ListFoundationModels}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// swift-tools-version: 5.9
2+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
// SPDX-License-Identifier: Apache-2.0
4+
//
5+
// The swift-tools-version declares the minimum version of Swift required to
6+
// build this package.
7+
8+
import PackageDescription
9+
10+
let package = Package(
11+
name: "ListFoundationModels",
12+
// Let Xcode know the minimum Apple platforms supported.
13+
platforms: [
14+
.macOS(.v13),
15+
.iOS(.v15)
16+
],
17+
dependencies: [
18+
// Dependencies declare other packages that this package depends on.
19+
.package(
20+
url: "https://github.com/awslabs/aws-sdk-swift",
21+
from: "1.0.0"),
22+
.package(
23+
url: "https://github.com/apple/swift-argument-parser.git",
24+
branch: "main"
25+
)
26+
],
27+
targets: [
28+
// Targets are the basic building blocks of a package, defining a module or a test suite.
29+
// Targets can depend on other targets in this package and products
30+
// from dependencies.
31+
.executableTarget(
32+
name: "ListFoundationModels",
33+
dependencies: [
34+
.product(name: "AWSBedrock", package: "aws-sdk-swift"),
35+
.product(name: "ArgumentParser", package: "swift-argument-parser")
36+
],
37+
path: "Sources")
38+
39+
]
40+
)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
// SPDX-License-Identifier: Apache-2.0
3+
//
4+
// An example demonstrating how to fetch a list of foundation models available
5+
// using Amazon Bedrock.
6+
7+
// snippet-start:[swift.bedrock.hello]
8+
import ArgumentParser
9+
import AWSClientRuntime
10+
import Foundation
11+
12+
// snippet-start:[swift.bedrock.import]
13+
import AWSBedrock
14+
// snippet-end:[swift.bedrock.import]
15+
16+
struct ExampleCommand: ParsableCommand {
17+
static var configuration = CommandConfiguration(
18+
commandName: "ListFoundationModels",
19+
abstract: """
20+
This example demonstrates how to retrieve a list of the available
21+
foundation models from Amazon Bedrock.
22+
""",
23+
discussion: """
24+
"""
25+
)
26+
27+
/// Construct a string listing the specified modalities.
28+
///
29+
/// - Parameter modalities: An array of the modalities to list.
30+
///
31+
/// - Returns: A string with a human-readable list of modalities.
32+
func buildModalityList(modalities: [BedrockClientTypes.ModelModality]?) -> String {
33+
var first = true
34+
var str = ""
35+
36+
if modalities == nil {
37+
return "<none>"
38+
}
39+
40+
for modality in modalities! {
41+
if !first {
42+
str += ", "
43+
}
44+
first = false
45+
str += modality.rawValue
46+
}
47+
48+
return str
49+
}
50+
51+
/// Construct a string listing the specified customizations.
52+
///
53+
/// - Parameter customizations: An array of the customizations to list.
54+
///
55+
/// - Returns: A string listing the customizations.
56+
func buildCustomizationList(customizations: [BedrockClientTypes.ModelCustomization]?) -> String {
57+
var first = true
58+
var str = ""
59+
60+
if customizations == nil {
61+
return "<none>"
62+
}
63+
64+
for customization in customizations! {
65+
if !first {
66+
str += ", "
67+
}
68+
first = false
69+
str += customization.rawValue
70+
}
71+
72+
return str
73+
}
74+
75+
/// Construct a string listing the specified inferences.
76+
///
77+
/// - Parameter inferences: An array of inferences to list.
78+
///
79+
/// - Returns: A string listing the specified inferences.
80+
func buildInferenceList(inferences: [BedrockClientTypes.InferenceType]?) -> String {
81+
var first = true
82+
var str = ""
83+
84+
if inferences == nil {
85+
return "<none>"
86+
}
87+
88+
for inference in inferences! {
89+
if !first {
90+
str += ", "
91+
}
92+
first = false
93+
str += inference.rawValue
94+
}
95+
96+
return str
97+
}
98+
99+
/// Called by ``main()`` to run the bulk of the example.
100+
func runAsync() async throws {
101+
// snippet-start:[swift.bedrock.ListFoundationModels]
102+
// Always use the Region "us-east-1" to have access to the most models.
103+
let config = try await BedrockClient.BedrockClientConfiguration(region: "us-east-1")
104+
let bedrockClient = BedrockClient(config: config)
105+
106+
let output = try await bedrockClient.listFoundationModels(
107+
input: ListFoundationModelsInput()
108+
)
109+
110+
guard let summaries = output.modelSummaries else {
111+
print("No models returned.")
112+
return
113+
}
114+
115+
// Output a list of the models with their details.
116+
for summary in summaries {
117+
print("==========================================")
118+
print(" Model ID: \(summary.modelId ?? "<unknown>")")
119+
print("------------------------------------------")
120+
print(" Name: \(summary.modelName ?? "<unknown>")")
121+
print(" Provider: \(summary.providerName ?? "<unknown>")")
122+
print(" Input modalities: \(buildModalityList(modalities: summary.inputModalities))")
123+
print(" Output modalities: \(buildModalityList(modalities: summary.outputModalities))")
124+
print(" Supported customizations: \(buildCustomizationList(customizations: summary.customizationsSupported ))")
125+
print(" Supported inference types: \(buildInferenceList(inferences: summary.inferenceTypesSupported))")
126+
print("------------------------------------------\n")
127+
}
128+
// snippet-end:[swift.bedrock.ListFoundationModels]
129+
130+
print("\(summaries.count) models available.")
131+
}
132+
}
133+
134+
/// The program's asynchronous entry point.
135+
@main
136+
struct Main {
137+
static func main() async {
138+
let args = Array(CommandLine.arguments.dropFirst())
139+
140+
do {
141+
let command = try ExampleCommand.parse(args)
142+
try await command.runAsync()
143+
} catch {
144+
ExampleCommand.exit(withError: error)
145+
}
146+
}
147+
}
148+
// snippet-end:[swift.bedrock.hello]

swift/example_code/bedrock/README.md

+98
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
# Amazon Bedrock code examples for the SDK for Swift
2+
3+
## Overview
4+
5+
Shows how to use the AWS SDK for Swift to work with Amazon Bedrock.
6+
7+
<!--custom.overview.start-->
8+
<!--custom.overview.end-->
9+
10+
_Amazon Bedrock enables you to build and scale generative AI applications with foundation models._
11+
12+
## ⚠ Important
13+
14+
* 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/).
15+
* Running the tests might result in charges to your AWS account.
16+
* 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).
17+
* 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).
18+
19+
<!--custom.important.start-->
20+
<!--custom.important.end-->
21+
22+
## Code examples
23+
24+
### Prerequisites
25+
26+
For prerequisites, see the [README](../../README.md#Prerequisites) in the `swift` folder.
27+
28+
29+
<!--custom.prerequisites.start-->
30+
<!--custom.prerequisites.end-->
31+
32+
### Get started
33+
34+
- [Hello Amazon Bedrock](ListFoundationModels/Sources/entry.swift#L7) (`ListFoundationModels`)
35+
36+
37+
### Single actions
38+
39+
Code excerpts that show you how to call individual service functions.
40+
41+
- [ListFoundationModels](ListFoundationModels/Sources/entry.swift#L101)
42+
43+
44+
<!--custom.examples.start-->
45+
<!--custom.examples.end-->
46+
47+
## Run the examples
48+
49+
### Instructions
50+
51+
To build any of these examples from a terminal window, navigate into its
52+
directory, then use the following command:
53+
54+
```
55+
$ swift build
56+
```
57+
58+
To build one of these examples in Xcode, navigate to the example's directory
59+
(such as the `ListUsers` directory, to build that example). Then type `xed.`
60+
to open the example directory in Xcode. You can then use standard Xcode build
61+
and run commands.
62+
63+
<!--custom.instructions.start-->
64+
<!--custom.instructions.end-->
65+
66+
#### Hello Amazon Bedrock
67+
68+
This example shows you how to get started using Amazon Bedrock.
69+
70+
71+
72+
### Tests
73+
74+
⚠ Running tests might result in charges to your AWS account.
75+
76+
77+
To find instructions for running these tests, see the [README](../../README.md#Tests)
78+
in the `swift` folder.
79+
80+
81+
82+
<!--custom.tests.start-->
83+
<!--custom.tests.end-->
84+
85+
## Additional resources
86+
87+
- [Amazon Bedrock User Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)
88+
- [Amazon Bedrock API Reference](https://docs.aws.amazon.com/bedrock/latest/APIReference/welcome.html)
89+
- [SDK for Swift Amazon Bedrock reference](https://sdk.amazonaws.com/swift/api/awsbedrock/latest/documentation/awsbedrock)
90+
91+
<!--custom.resources.start-->
92+
<!--custom.resources.end-->
93+
94+
---
95+
96+
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
97+
98+
SPDX-License-Identifier: Apache-2.0

0 commit comments

Comments
 (0)