Skip to content

Commit c44c947

Browse files
committed
better manage conversation history
1 parent 7003f2d commit c44c947

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

Sources/Converse/ConverseRequestBuilder.swift

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,14 +97,21 @@ public struct ConverseRequestBuilder: Sendable {
9797
try withHistory(History(history))
9898
}
9999
public func withHistory(_ history: History) throws -> ConverseRequestBuilder {
100-
if let lastMessage = history.last {
100+
101+
if history.count > 0,
102+
let lastMessage = history.last
103+
{
101104
guard lastMessage.role == .assistant else {
102105
throw BedrockLibraryError.ConverseRequestBuilder("Last message in history must be from assistant.")
103106
}
104107
}
105-
if toolResult != nil {
108+
if history.count > 0,
109+
toolResult != nil
110+
{
106111
guard case .toolUse(_) = history.last?.content.last else {
107-
throw BedrockLibraryError.invalidPrompt("Tool result is defined but last message is not tool use.")
112+
throw BedrockLibraryError.ConverseRequestBuilder(
113+
"Tool result is defined but last message is not tool use."
114+
)
108115
}
109116
}
110117
var copy = self

Sources/Converse/History.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ public struct History: Codable, Sendable {
3030
self.messages = messages
3131
}
3232

33+
public init(_ slide: Slice<History>) {
34+
self.messages = Array(slide)
35+
}
36+
3337
public mutating func append(_ message: Message) {
3438
messages.append(message)
3539
}

0 commit comments

Comments
 (0)