Description
The current useChat hook supports onToolCall, which triggers when a tool starts running. However, there's no built-in way to detect when a tool finishes and returns a result.
Right now, to detect a finished tool result, I have to hack around it like this:
const seenToolIds = useRef<Set<string>>(new Set());
useEffect(() => {
if (!messages || messages.length === 0) return;
const lastMessage = messages[messages.length - 1];
if (messages.length <= initialMessages.length) return;
if (!lastMessage.parts) return;
lastMessage.parts.forEach((part: any) => {
if (
part.type === 'tool-invocation' &&
part.toolInvocation &&
part.toolInvocation.toolCallId &&
part.toolInvocation.state === 'result' &&
!seenToolIds.current.has(part.toolInvocation.toolCallId)
) {
seenToolIds.current.add(part.toolInvocation.toolCallId);
handleToolResult(part.toolInvocation);
}
});
}, [messages, initialMessages]);
This workaround works but is clunky and fragile. I'd love a native onToolResult callback that fires once when a tool call completes, just like onToolCall does when it starts.
Description
The current
useChathook supportsonToolCall, which triggers when a tool starts running. However, there's no built-in way to detect when a tool finishes and returns a result.Right now, to detect a finished tool result, I have to hack around it like this:
This workaround works but is clunky and fragile. I'd love a native
onToolResultcallback that fires once when a tool call completes, just likeonToolCalldoes when it starts.