useChat doesn't automatically invoke client tools? #784
Unanswered
puehringer
asked this question in
Q&A
Replies: 2 comments 1 reply
|
Running into the same, did you ever figure this out? |
0 replies
|
@dbridges Yeah I figured this out, although I'm not sure if it's the accepted answer: with a custom backend, useChat does not automatically execute client-side tools. You have to do it yourself in onFinish: const chat = useChat({
// ...
onFinish: async (message) => {
// Find tool calls that the server returned but haven't been executed yet
const pendingToolCalls = message.parts.flatMap((p) =>
p.type === 'tool-call' && p.state === 'input-complete' && p.output === undefined ? [p] : []
);
await Promise.all(
pendingToolCalls.map(async (part) => {
const tool = tools.find((t) => t.name === part.name);
if (!tool?.execute) return;
try {
const args = typeof part.arguments === 'string' ? JSON.parse(part.arguments) : part.arguments;
const output = await tool.execute(args);
await chat.addToolResult({ toolCallId: part.id, tool: part.name, output, state: 'output-available' });
} catch (e) {
await chat.addToolResult({ toolCallId: part.id, tool: part.name, output: null, state: 'output-error' });
}
})
);
},
});Once you call addToolResult, it automatically sends the result back to the server which triggers the next assistant turn, completing the agentic loop. Let me know if it works for you, or if you have a better idea on how to solve this. |
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
From the docs I got the impression that any client tool should automatically invoke when using useChat, but I can't seem to get it working. I have an existing setup with pydantic-ai and their ag-ui adapter, but for this simple example I'm using an inline stream taken from https://dojo.ag-ui.com/pydantic-ai/feature/agentic_chat. I would expect that the changeBackground tool is called, but it isn't. At the end, it's simply stuck at
input-completeand nothing else happens.Anything I'm missing here?
Demo: https://codesandbox.io/p/sandbox/99p776
All reactions