Skip to content

Commit 6f4d063

Browse files
lgrammeljrandolf
andauthored
fix (ai/react): cache addToolResult in useChat (#4492)
Co-authored-by: Randolf J <[email protected]>
1 parent 3a58a2e commit 6f4d063

File tree

2 files changed

+37
-35
lines changed

2 files changed

+37
-35
lines changed

.changeset/plenty-dogs-warn.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@ai-sdk/react': patch
3+
---
4+
5+
fix (ai/react): cache addToolResult in useChat

packages/react/src/use-chat.ts

+32-35
Original file line numberDiff line numberDiff line change
@@ -541,41 +541,38 @@ By default, it's set to 1, which means that only a single LLM call is made.
541541
setInput(e.target.value);
542542
};
543543

544-
const addToolResult = ({
545-
toolCallId,
546-
result,
547-
}: {
548-
toolCallId: string;
549-
result: any;
550-
}) => {
551-
const updatedMessages = messagesRef.current.map((message, index, arr) =>
552-
// update the tool calls in the last assistant message:
553-
index === arr.length - 1 &&
554-
message.role === 'assistant' &&
555-
message.toolInvocations
556-
? {
557-
...message,
558-
toolInvocations: message.toolInvocations.map(toolInvocation =>
559-
toolInvocation.toolCallId === toolCallId
560-
? {
561-
...toolInvocation,
562-
result,
563-
state: 'result' as const,
564-
}
565-
: toolInvocation,
566-
),
567-
}
568-
: message,
569-
);
570-
571-
mutate(updatedMessages, false);
572-
573-
// auto-submit when all tool calls in the last assistant message have results:
574-
const lastMessage = updatedMessages[updatedMessages.length - 1];
575-
if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
576-
triggerRequest({ messages: updatedMessages });
577-
}
578-
};
544+
const addToolResult = useCallback(
545+
({ toolCallId, result }: { toolCallId: string; result: any }) => {
546+
const updatedMessages = messagesRef.current.map((message, index, arr) =>
547+
// update the tool calls in the last assistant message:
548+
index === arr.length - 1 &&
549+
message.role === 'assistant' &&
550+
message.toolInvocations
551+
? {
552+
...message,
553+
toolInvocations: message.toolInvocations.map(toolInvocation =>
554+
toolInvocation.toolCallId === toolCallId
555+
? {
556+
...toolInvocation,
557+
result,
558+
state: 'result' as const,
559+
}
560+
: toolInvocation,
561+
),
562+
}
563+
: message,
564+
);
565+
566+
mutate(updatedMessages, false);
567+
568+
// auto-submit when all tool calls in the last assistant message have results:
569+
const lastMessage = updatedMessages[updatedMessages.length - 1];
570+
if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
571+
triggerRequest({ messages: updatedMessages });
572+
}
573+
},
574+
[mutate, triggerRequest],
575+
);
579576

580577
return {
581578
messages: messages || [],

0 commit comments

Comments
 (0)