generated from amazon-archives/__template_MIT-0
-
Notifications
You must be signed in to change notification settings - Fork 2
[auth] Add support for Bedrock API Keys #30
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
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
8179f69
add support for Bedrock API Key
sebsto 8358b4e
add documentation for authentication
sebsto 64a07b5
add a test on AWS_BEARER_TOKEN_BEDROCK
sebsto c312031
add example
sebsto 3d76d6b
swift-format
sebsto 835cb2e
add license header
sebsto File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| .DS_Store | ||
| /.build | ||
| /Packages | ||
| xcuserdata/ | ||
| DerivedData/ | ||
| .swiftpm/configuration/registries.json | ||
| .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata | ||
| .netrc |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| // swift-tools-version: 6.0 | ||
| // The swift-tools-version declares the minimum version of Swift required to build this package. | ||
|
|
||
| import PackageDescription | ||
|
|
||
| let package = Package( | ||
| name: "APIKey", | ||
| platforms: [.macOS(.v15), .iOS(.v18), .tvOS(.v18)], | ||
| products: [ | ||
| .executable(name: "APIKey", targets: ["APIKey"]) | ||
| ], | ||
| dependencies: [ | ||
| // for production use, uncomment the following line | ||
| // .package(url: "https://github.com/build-on-aws/swift-bedrock-library.git", branch: "main"), | ||
|
|
||
| // for local development, use the following line | ||
| .package(name: "swift-bedrock-library", path: "../.."), | ||
|
|
||
| .package(url: "https://github.com/apple/swift-log.git", from: "1.6.0"), | ||
| ], | ||
| 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: "APIKey", | ||
| dependencies: [ | ||
| .product(name: "BedrockService", package: "swift-bedrock-library"), | ||
| .product(name: "Logging", package: "swift-log"), | ||
| ] | ||
| ) | ||
| ] | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift Bedrock Library open source project | ||
| // | ||
| // Copyright (c) 2025 Amazon.com, Inc. or its affiliates | ||
| // and the Swift Bedrock Library project authors | ||
| // Licensed under Apache License v2.0 | ||
| // | ||
| // See LICENSE.txt for license information | ||
| // See CONTRIBUTORS.txt for the list of Swift Bedrock Library project authors | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| // You can create short-lived or long-term API keys in the AWS Management Console. | ||
| // see documentation : https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-generate.html | ||
| // link to the console : https://console.aws.amazon.com/bedrock/home#/api-keys?tab=short-term | ||
| let myApiKey = "bedrock-api-key-YmVkcm9jay ... (redacted for brevity) .... b249MQ==" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| //===----------------------------------------------------------------------===// | ||
| // | ||
| // This source file is part of the Swift Bedrock Library open source project | ||
| // | ||
| // Copyright (c) 2025 Amazon.com, Inc. or its affiliates | ||
| // and the Swift Bedrock Library project authors | ||
| // Licensed under Apache License v2.0 | ||
| // | ||
| // See LICENSE.txt for license information | ||
| // See CONTRIBUTORS.txt for the list of Swift Bedrock Library project authors | ||
| // | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| // | ||
| //===----------------------------------------------------------------------===// | ||
|
|
||
| import BedrockService | ||
| import Logging | ||
|
|
||
| @main | ||
| struct Main { | ||
| static func main() async throws { | ||
| do { | ||
| try await Main.converse() | ||
| } catch { | ||
| print("Error:\n\(error)") | ||
| } | ||
| } | ||
| static func converse() async throws { | ||
| var logger = Logger(label: "APIKey") | ||
| logger.logLevel = .debug | ||
|
|
||
| // generate an API Key in the AWS Management Console | ||
| // see https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-generate.html | ||
| let bedrock = try await BedrockService( | ||
| region: .useast1, | ||
| logger: logger, | ||
| authentication: .apiKey(key: myApiKey) // define your API Key in APIKey.swift | ||
| ) | ||
|
|
||
| // select a model that supports the converse modality | ||
| // models must be enabled in your AWS account | ||
| let model: BedrockModel = .nova_lite | ||
|
|
||
| guard model.hasConverseModality() else { | ||
| throw MyError.incorrectModality("\(model.name) does not support converse") | ||
| } | ||
|
|
||
| // create a request | ||
| let builder = try ConverseRequestBuilder(with: model) | ||
| .withPrompt("What is an API key?") | ||
|
|
||
| // send the request | ||
| let reply = try await bedrock.converse(with: builder) | ||
|
|
||
| print("Assistant: \(reply)") | ||
| } | ||
|
|
||
| enum MyError: Error { | ||
| case incorrectModality(String) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -20,6 +20,13 @@ import AwsCommonRuntimeKit | |||||||||||
| import Foundation | ||||||||||||
| import Logging | ||||||||||||
|
|
||||||||||||
| // for setenv and unsetenv functions | ||||||||||||
| #if os(Linux) | ||||||||||||
| import Glibc | ||||||||||||
| #else | ||||||||||||
| import Darwin.C | ||||||||||||
| #endif | ||||||||||||
|
|
||||||||||||
| public struct BedrockService: Sendable { | ||||||||||||
| package let region: Region | ||||||||||||
| package let logger: Logging.Logger | ||||||||||||
|
|
@@ -106,21 +113,18 @@ public struct BedrockService: Sendable { | |||||||||||
| /// - authentication: The authentication type to use | ||||||||||||
| /// - Returns: Configured BedrockClientProtocol instance | ||||||||||||
| /// - Throws: Error if client creation fails | ||||||||||||
| static private func createBedrockClient( | ||||||||||||
| internal static func createBedrockClient( | ||||||||||||
| region: Region, | ||||||||||||
| authentication: BedrockAuthentication, | ||||||||||||
| logger: Logging.Logger | ||||||||||||
| ) async throws | ||||||||||||
| -> BedrockClientProtocol | ||||||||||||
| -> BedrockClient | ||||||||||||
| { | ||||||||||||
| let config = try await BedrockClient.BedrockClientConfiguration( | ||||||||||||
| region: region.rawValue | ||||||||||||
| ) | ||||||||||||
| if let awsCredentialIdentityResolver = try? await authentication.getAWSCredentialIdentityResolver( | ||||||||||||
| let config: BedrockClient.BedrockClientConfiguration = try await prepareConfig( | ||||||||||||
| region: region, | ||||||||||||
| authentication: authentication, | ||||||||||||
| logger: logger | ||||||||||||
| ) { | ||||||||||||
| config.awsCredentialIdentityResolver = awsCredentialIdentityResolver | ||||||||||||
| } | ||||||||||||
| ) | ||||||||||||
| return BedrockClient(config: config) | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
|
|
@@ -130,24 +134,56 @@ public struct BedrockService: Sendable { | |||||||||||
| /// - authentication: The authentication type to use | ||||||||||||
| /// - Returns: Configured BedrockRuntimeClientProtocol instance | ||||||||||||
| /// - Throws: Error if client creation fails | ||||||||||||
| static private func createBedrockRuntimeClient( | ||||||||||||
| internal static func createBedrockRuntimeClient( | ||||||||||||
| region: Region, | ||||||||||||
| authentication: BedrockAuthentication, | ||||||||||||
| logger: Logging.Logger | ||||||||||||
| ) | ||||||||||||
| async throws | ||||||||||||
| -> BedrockRuntimeClientProtocol | ||||||||||||
| -> BedrockRuntimeClient | ||||||||||||
| { | ||||||||||||
| let config = | ||||||||||||
| try await BedrockRuntimeClient.BedrockRuntimeClientConfiguration( | ||||||||||||
| region: region.rawValue | ||||||||||||
| ) | ||||||||||||
| let config: BedrockRuntimeClient.BedrockRuntimeClientConfiguration = try await prepareConfig( | ||||||||||||
| region: region, | ||||||||||||
| authentication: authentication, | ||||||||||||
| logger: logger | ||||||||||||
| ) | ||||||||||||
| return BedrockRuntimeClient(config: config) | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| /// Generic function to create client configuration and avoid duplication code. | ||||||||||||
| internal static func prepareConfig<C: BedrockConfigProtocol>( | ||||||||||||
| region: Region, | ||||||||||||
| authentication: BedrockAuthentication, | ||||||||||||
| logger: Logging.Logger | ||||||||||||
| ) async throws -> C { | ||||||||||||
| var config: C = try await .init() | ||||||||||||
|
|
||||||||||||
| config.region = region.rawValue | ||||||||||||
|
|
||||||||||||
| // support profile, SSO, web identity and static authentication | ||||||||||||
| if let awsCredentialIdentityResolver = try? await authentication.getAWSCredentialIdentityResolver( | ||||||||||||
| logger: logger | ||||||||||||
| ) { | ||||||||||||
| config.awsCredentialIdentityResolver = awsCredentialIdentityResolver | ||||||||||||
| } | ||||||||||||
| return BedrockRuntimeClient(config: config) | ||||||||||||
|
|
||||||||||||
| // support API keys | ||||||||||||
| if case .apiKey(let key) = authentication { | ||||||||||||
| config.httpClientConfiguration.defaultHeaders.add( | ||||||||||||
| name: "Authorization", | ||||||||||||
| value: "Bearer \(key)" | ||||||||||||
| ) | ||||||||||||
| logger.trace("Using API Key for authentication") | ||||||||||||
| } else { | ||||||||||||
| logger.trace("Using AWS credentials for authentication") | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| //We uncheck AWS_BEARER_TOKEN_BEDROCK to avoid conflict with future AWS SDK version | ||||||||||||
| //see https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started-api-keys.html | ||||||||||||
| //FIXME: there is a risk of side effect here - what other ways we have to ignore this variable ? | ||||||||||||
| unsetenv("AWS_BEARER_TOKEN_BEDROCK") | ||||||||||||
|
||||||||||||
| unsetenv("AWS_BEARER_TOKEN_BEDROCK") | |
| // Temporarily remove AWS_BEARER_TOKEN_BEDROCK from the environment for this configuration | |
| var environment = ProcessInfo.processInfo.environment | |
| environment["AWS_BEARER_TOKEN_BEDROCK"] = nil | |
| // Pass the modified environment to the relevant configuration or process if needed |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[nitpick] The
prepareConfigfunction bundles initialization, credential resolver setup, API-key header injection, and environment cleanup. Consider splitting these responsibilities into focused helper methods or adding detailed comments to clarify each step and improve readability and testability.