1616@preconcurrency import AWSBedrockRuntime
1717import Foundation
1818
19- public enum Role : String , Codable , Sendable {
20- case user
21- case assistant
19+ public struct Role : Codable , Sendable , Equatable {
20+ private enum RoleType : Codable , Sendable , Equatable {
21+ case user
22+ case assistant
23+ }
24+
25+ private let type : RoleType
2226
2327 public init ( from sdkConversationRole: BedrockRuntimeClientTypes . ConversationRole ) throws {
2428 switch sdkConversationRole {
25- case . user: self = . user
26- case . assistant: self = . assistant
29+ case . user: self . type = . user
30+ case . assistant: self . type = . assistant
2731 case . sdkUnknown( let unknownRole) :
2832 throw BedrockLibraryError . notImplemented (
2933 " Role \( unknownRole) is not implemented by BedrockRuntimeClientTypes "
@@ -32,9 +36,47 @@ public enum Role: String, Codable, Sendable {
3236 }
3337
3438 public func getSDKConversationRole( ) -> BedrockRuntimeClientTypes . ConversationRole {
35- switch self {
39+ switch self . type {
3640 case . user: return . user
3741 case . assistant: return . assistant
3842 }
3943 }
44+
45+ // custom encoding and decoding to handle string value with a "type" field
46+ /*
47+ "message":{
48+ "content":[
49+ {"text":"This is the textcompletion for: This is a test"}
50+ ],
51+ "role":"assistant"
52+ }},
53+ */
54+ public init ( from decoder: any Decoder ) throws {
55+ let container = try decoder. singleValueContainer ( )
56+ let role = try container. decode ( String . self)
57+ switch role {
58+ case " user " : self . type = . user
59+ case " assistant " : self . type = . assistant
60+ default :
61+ throw BedrockLibraryError . decodingError (
62+ " Role \( role) is not a valid role "
63+ )
64+ }
65+ }
66+ public func encode( to encoder: any Encoder ) throws {
67+ var container = encoder. singleValueContainer ( )
68+ switch self . type {
69+ case . user: try container. encode ( " user " )
70+ case . assistant: try container. encode ( " assistant " )
71+ }
72+ }
73+ /// Returns the type of the role as a string.
74+ public static func == ( lhs: Role , rhs: Role ) -> Bool {
75+ lhs. type == rhs. type
76+ }
77+ private init ( _ type: RoleType ) {
78+ self . type = type
79+ }
80+ public static let user = Role ( . user)
81+ public static let assistant = Role ( . assistant)
4082}
0 commit comments