Skip to content

Commit 0a88772

Browse files
sebstoCopilot
andauthored
Add basic support for agent runtime (#58)
* add basic support for agentruntime * Add retrieve example to the CI * Swift-format * Update Sources/BedrockService/BedrockService+AgentRuntime.swift Co-authored-by: Copilot <[email protected]> * Update Sources/BedrockService/RetrieveResult.swift Co-authored-by: Copilot <[email protected]> * provide a convenience wrapper around retrieveinput * add swift docc header * swift-format * move files to an agent runtime directory * rearrange files in different directory structure --------- Co-authored-by: Copilot <[email protected]>
1 parent e07b33d commit 0a88772

File tree

69 files changed

+519
-1
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

69 files changed

+519
-1
lines changed

.github/workflows/pull_request.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ jobs:
9191
# We pass the list of examples here, but we can't pass an array as argument
9292
# Instead, we pass a String with a valid JSON array.
9393
# The workaround is mentioned here https://github.com/orgs/community/discussions/11692
94-
examples: "[ 'api-key', 'converse', 'converse-stream', 'embeddings', 'openai', 'text_chat' ]"
94+
examples: "[ 'api-key', 'converse', 'converse-stream', 'embeddings', 'openai', 'retrieve', 'text_chat' ]"
9595

9696
swift-6-language-mode:
9797
name: Swift 6 Language Mode

Examples/retrieve/.gitignore

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
.DS_Store
2+
/.build
3+
/Packages
4+
xcuserdata/
5+
DerivedData/
6+
.swiftpm/configuration/registries.json
7+
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
8+
.netrc

Examples/retrieve/Package.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// swift-tools-version: 6.0
2+
// The swift-tools-version declares the minimum version of Swift required to build this package.
3+
4+
import PackageDescription
5+
6+
let package = Package(
7+
name: "Retrieve",
8+
platforms: [.macOS(.v15), .iOS(.v18), .tvOS(.v18)],
9+
products: [
10+
.executable(name: "Retrieve", targets: ["Retrieve"])
11+
],
12+
dependencies: [
13+
// for production use, uncomment the following line
14+
// .package(url: "https://github.com/build-on-aws/swift-bedrock-library.git", branch: "main"),
15+
16+
// for local development, use the following line
17+
.package(name: "swift-bedrock-library", path: "../.."),
18+
19+
.package(url: "https://github.com/apple/swift-log.git", from: "1.5.0"),
20+
],
21+
targets: [
22+
.executableTarget(
23+
name: "Retrieve",
24+
dependencies: [
25+
.product(name: "BedrockService", package: "swift-bedrock-library"),
26+
.product(name: "Logging", package: "swift-log"),
27+
]
28+
)
29+
]
30+
)
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift Bedrock Library open source project
4+
//
5+
// Copyright (c) 2025 Amazon.com, Inc. or its affiliates
6+
// and the Swift Bedrock Library project authors
7+
// Licensed under Apache License v2.0
8+
//
9+
// See LICENSE.txt for license information
10+
// See CONTRIBUTORS.txt for the list of Swift Bedrock Library project authors
11+
//
12+
// SPDX-License-Identifier: Apache-2.0
13+
//
14+
//===----------------------------------------------------------------------===//
15+
16+
import BedrockService
17+
import Logging
18+
19+
@main
20+
struct Main {
21+
static func main() async throws {
22+
do {
23+
try await Main.retrieve()
24+
} catch {
25+
print("Error:\n\(error)")
26+
}
27+
}
28+
29+
static func retrieve() async throws {
30+
var logger = Logger(label: "Retrieve")
31+
logger.logLevel = .debug
32+
33+
let bedrock = try await BedrockService(
34+
region: .uswest2,
35+
logger: logger
36+
// uncomment if you use SSO with AWS Identity Center
37+
// authentication: .sso
38+
)
39+
40+
let knowledgeBaseId = "EQ13XRVPLE"
41+
let query = "should I write open source or open-source"
42+
let numberOfResults = 3
43+
44+
print("Retrieving from knowledge base...")
45+
print("Knowledge Base ID: \(knowledgeBaseId)")
46+
print("Query: \(query)")
47+
print("Number of results: \(numberOfResults)")
48+
print()
49+
50+
let response = try await bedrock.retrieve(
51+
knowledgeBaseId: knowledgeBaseId,
52+
retrievalQuery: query,
53+
numberOfResults: numberOfResults
54+
)
55+
56+
print("Retrieved \(response.results?.count ?? 0) results:")
57+
58+
// Show best match using convenience function
59+
if let bestMatch = response.bestMatch() {
60+
print("\n--- Best Match (Score: \(bestMatch.score ?? 0)) ---")
61+
if let content = bestMatch.content?.text {
62+
print("Content: \(content)")
63+
}
64+
}
65+
66+
// Show all results using convenience property
67+
// if let results = response.results {
68+
// for (index, result) in results.enumerated() {
69+
// print("\n--- Result \(index + 1) ---")
70+
// if let content = result.content?.text {
71+
// print("Content: \(content)")
72+
// }
73+
// if let score = result.score {
74+
// print("Score: \(score)")
75+
// }
76+
// if let location = result.location?.s3Location {
77+
// print("Source: s3://\(location.uri ?? "unknown")")
78+
// }
79+
// }
80+
// }
81+
}
82+
}

Package.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ let package = Package(
2323
.product(name: "AWSClientRuntime", package: "aws-sdk-swift"),
2424
.product(name: "AWSBedrock", package: "aws-sdk-swift"),
2525
.product(name: "AWSBedrockRuntime", package: "aws-sdk-swift"),
26+
.product(name: "AWSBedrockAgentRuntime", package: "aws-sdk-swift"),
2627
.product(name: "AWSSSOOIDC", package: "aws-sdk-swift"),
2728
.product(name: "Smithy", package: "smithy-swift"),
2829
.product(name: "Logging", package: "swift-log"),

Sources/BedrockService/Protocols/BedrockConfigProtocol.swift renamed to Sources/BedrockService/BedrockConfigProtocol.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
//===----------------------------------------------------------------------===//
1515

1616
import AWSBedrock
17+
import AWSBedrockAgentRuntime
1718
import AWSBedrockRuntime
1819
import ClientRuntime
1920
import SmithyHTTPAuthAPI
@@ -38,3 +39,6 @@ extension BedrockClient.BedrockClientConfiguration: @retroactive @unchecked Send
3839
extension BedrockRuntimeClient.BedrockRuntimeClientConfiguration: @retroactive @unchecked Sendable,
3940
BedrockConfigProtocol
4041
{}
42+
extension BedrockAgentRuntimeClient.BedrockAgentRuntimeClientConfiguration: @retroactive @unchecked Sendable,
43+
BedrockConfigProtocol
44+
{}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift Bedrock Library open source project
4+
//
5+
// Copyright (c) 2025 Amazon.com, Inc. or its affiliates
6+
// and the Swift Bedrock Library project authors
7+
// Licensed under Apache License v2.0
8+
//
9+
// See LICENSE.txt for license information
10+
// See CONTRIBUTORS.txt for the list of Swift Bedrock Library project authors
11+
//
12+
// SPDX-License-Identifier: Apache-2.0
13+
//
14+
//===----------------------------------------------------------------------===//
15+
16+
@preconcurrency import AWSBedrockAgentRuntime
17+
import AWSClientRuntime
18+
19+
#if canImport(FoundationEssentials)
20+
import FoundationEssentials
21+
#else
22+
import Foundation
23+
#endif
24+
25+
/// Protocol for Amazon Bedrock Runtime Agent operations
26+
///
27+
/// This protocol allows writing mocks for unit tests and provides a clean interface
28+
/// for knowledge base retrieval operations.
29+
public protocol BedrockRuntimeAgentProtocol: Sendable {
30+
/// Retrieves information from a knowledge base
31+
/// - Parameter input: The retrieve input containing query and configuration
32+
/// - Returns: RetrieveOutput with the retrieved results
33+
/// - Throws: Error if the retrieval operation fails
34+
func retrieve(input: RetrieveInput) async throws -> RetrieveOutput
35+
}
36+
37+
extension BedrockAgentRuntimeClient: @retroactive @unchecked Sendable, BedrockRuntimeAgentProtocol {}
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift Bedrock Library open source project
4+
//
5+
// Copyright (c) 2025 Amazon.com, Inc. or its affiliates
6+
// and the Swift Bedrock Library project authors
7+
// Licensed under Apache License v2.0
8+
//
9+
// See LICENSE.txt for license information
10+
// See CONTRIBUTORS.txt for the list of Swift Bedrock Library project authors
11+
//
12+
// SPDX-License-Identifier: Apache-2.0
13+
//
14+
//===----------------------------------------------------------------------===//
15+
16+
@preconcurrency import AWSBedrockAgentRuntime
17+
import Logging
18+
19+
extension BedrockService {
20+
/// Creates a BedrockAgentRuntimeClient
21+
/// - Parameters:
22+
/// - region: The AWS region to configure the client for
23+
/// - authentication: The authentication type to use
24+
/// - logger: Logger instance
25+
/// - Returns: Configured BedrockAgentRuntimeProtocol instance
26+
/// - Throws: Error if client creation fails
27+
internal static func createBedrockAgentRuntimeClient(
28+
region: Region,
29+
authentication: BedrockAuthentication,
30+
logger: Logging.Logger
31+
) async throws -> BedrockAgentRuntimeClient {
32+
let config: BedrockAgentRuntimeClient.BedrockAgentRuntimeClientConfiguration = try await prepareConfig(
33+
initialConfig: BedrockAgentRuntimeClient.BedrockAgentRuntimeClientConfiguration(region: region.rawValue),
34+
authentication: authentication,
35+
logger: logger
36+
)
37+
return BedrockAgentRuntimeClient(config: config)
38+
}
39+
/// Retrieves information from a knowledge base for RAG applications
40+
///
41+
/// This method queries an Amazon Bedrock knowledge base to retrieve relevant information
42+
/// that can be used for Retrieval-Augmented Generation (RAG) applications.
43+
///
44+
/// - Parameters:
45+
/// - knowledgeBaseId: The unique identifier of the knowledge base to query
46+
/// - retrievalQuery: The query to search for in the knowledge base
47+
/// - numberOfResults: The number of results to return (optional, defaults to 3)
48+
/// - Returns: RetrieveResult containing the retrieved results with convenience methods
49+
/// - Throws: BedrockLibraryError or other errors from the underlying service
50+
public func retrieve(
51+
knowledgeBaseId: String,
52+
retrievalQuery: String,
53+
numberOfResults: Int = 3
54+
) async throws -> RetrieveResult {
55+
logger.trace(
56+
"Retrieving from knowledge base",
57+
metadata: [
58+
"knowledgeBaseId": .string(knowledgeBaseId),
59+
"numberOfResults": .stringConvertible(numberOfResults),
60+
]
61+
)
62+
63+
let request = RetrieveRequest(
64+
knowledgeBaseId: knowledgeBaseId,
65+
retrievalQuery: retrievalQuery,
66+
numberOfResults: numberOfResults
67+
)
68+
69+
do {
70+
let response = try await bedrockAgentRuntimeClient.retrieve(input: request.input)
71+
logger.trace("Successfully retrieved from knowledge base")
72+
return RetrieveResult(response)
73+
} catch {
74+
try handleCommonError(error, context: "retrieving from knowledge base")
75+
}
76+
}
77+
}

0 commit comments

Comments
 (0)