Skip to content

Commit ee96e85

Browse files
committed
fix(session): Automatically detect and remove dangling tool calls when resuming a conversation
1 parent e738d27 commit ee96e85

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,8 @@ public void loadFrom(Session session, SessionKey sessionKey) {
226226
// Load memory if managed
227227
if (statePersistence.memoryManaged()) {
228228
memory.loadFrom(session, sessionKey);
229+
// Clean up any pending tool calls from previous session
230+
cleanupPendingToolCalls();
229231
}
230232

231233
// Load toolkit activeGroups if managed
@@ -240,6 +242,31 @@ public void loadFrom(Session session, SessionKey sessionKey) {
240242
}
241243
}
242244

245+
/**
246+
* Clean up pending tool calls after session restoration.
247+
*
248+
* <p>When a session is restored, there may be incomplete tool calls from the previous
249+
* session. This method removes the last assistant message if it contains tool calls without
250+
* corresponding results, preventing IllegalStateException on the next user input.
251+
*/
252+
private void cleanupPendingToolCalls() {
253+
Set<String> pendingIds = getPendingToolUseIds();
254+
if (!pendingIds.isEmpty()) {
255+
// Find and remove the last assistant message with pending tool calls
256+
List<Msg> messages = memory.getMessages();
257+
for (int i = messages.size() - 1; i >= 0; i--) {
258+
Msg msg = messages.get(i);
259+
if (msg.getRole() == MsgRole.ASSISTANT) {
260+
memory.deleteMessage(i);
261+
log.warn(
262+
"Removed incomplete tool calls from restored session. Pending IDs: {}",
263+
pendingIds);
264+
break;
265+
}
266+
}
267+
}
268+
}
269+
243270
// ==================== Protected API ====================
244271

245272
@Override

0 commit comments

Comments
 (0)