翻篇收录说明
翻篇网页快照

Chatbot Tool Usage | AI SDK

https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-tool-usage

最近抓取:2026-12-04 03:04:03(北京时间)

最近内容变化:2026-11-30 23:41:55(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Learn how to use tools with the useChat hook.

正文摘录

AI SDK UIMenuChatbot Tool UsageCopy for LLMView MarkdownAsk AI about this pageWith useChat and streamText, you can use tools in your chatbot application. The AI SDK supports three tool execution patterns in this context: Automatically executed server-side tools Automatically executed client-side tools Tools that require user interaction, such as confirmation dialogs The flow is as follows: The user enters a message in the chat UI. The message is sent to the API route. In your server-side route, the language model generates tool calls during the streamText call. All tool calls are forwarded to the client. Server-side tools are executed using their execute method and their results are forwarded to the client. Client-side tools that should be automatically executed are handled with the onToolCall callback. You must call addToolOutput to provide the tool result. Client-side tools that require user interactions can be displayed in the UI. The tool calls and results are available as tool invocation parts in the parts property of the last assistant message. When the user interaction is done, addToolOutput can be used to add the tool result to the chat. The chat can be configured to automatically submit when all tool results are available using sendAutomaticallyWhen. This triggers another iteration of this flow. The tool calls and tool executions are integrated into the assistant message as typed tool parts. A tool part is at first a tool call, and then it becomes a tool result when the tool is executed. The tool result contains all information about the tool call as well as the result of the tool execution. Tool result submission can be configured using the sendAutomaticallyWhen option. You can use the lastAssistantMessageIsCompleteWithToolCalls helper to automatically submit when all tool results are available. This simplifies the client-side code while still allowing full control when needed. Example In this example, we'll use three tools: getWeatherInformation: An automatically executed server-side tool that returns the weather in a given city. askForConfirmation: A user-interaction client-side tool that asks the user for confirmation. getLocation: An automatically executed client-side tool that returns a random city. API route GatewayProviderCustomClaude Sonnet 5.5app/api/chat/route.tsimport { convertToModelMessages, createUIMessageStreamResponse, streamText, toUIMessageStream, UIMessage, } from 'ai'; import { z } from 'zod'; // Allow streaming responses up to 30 seconds export const maxDuration = 30; export async function POST(req: Request) { const { messages }: { messages: UIMessage[] } = await req.json(); const result = streamText({ model: "anthropic/claude-sonnet-5.5", messages: await convertToModelMessages(messages), tools: { // server-side tool with execute function: getWeatherInformation: { description: 'show the weather in a given city to the user', inputSchema: z.object({ city: z.string() }), execute: async ({}: { city: string }) => { const weatherOptions = ['sunny', 'cloudy', 'rainy', 'snowy', 'windy']; return weatherOptions[ Math.floor(Math.random() * weatherOptions.length) ]; }, }, // client-side tool that starts user interaction: askForConfirmation: { description: 'Ask the user for confirmation.', inputSchema: z.object({ message: z.string().describe('The message to ask for confirmation.'), }), }, // client-side tool that is automatically executed on the client: getLocation: { description: 'Get the user location. Always ask for confirmation before using this tool.', inputSchema: z.object({}), }, }, }); return createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }), }); } Client-side page The client-side page uses the useChat hook to create a chatbot application with real-time message streaming. Tool calls are displayed in the chat UI as typed tool parts. Please make sure to render the messages using the parts property of the message. There are three things worth mentioning: The onToolCall callback is used to handle client-side tools that should be automatically executed. In this example, the getLocation tool is a client-side tool that returns a random city. You call addToolOutput to provide the result (without await to avoid potential deadlocks). Always check if (toolCall.dynamic) first in your onToolCall handler. Without this check, TypeScript will throw an error like: Type 'string' is not assignable to type '"toolName1" | "toolName2"' when you try to use toolCall.toolName in addToolOutput. The sendAutomaticallyWhen option with lastAssistantMessageIsCompleteWithToolCalls helper automatically submits when all tool results are available. The parts array of assistant messages contains tool parts with typed names like tool-askForConfirmation. The client-side tool askForConfirmation is displayed in the UI. It asks the user for confirmation and displays the result once the user confirms or denies the execution. The result is added to the chat using addToolOutput with the tool parameter for type safety. Typed tool parts also include the approval-requested, approval-responded, and output-denied states. Include these states when handling part.state exhaustively, even when a tool does not require approval. See Tool execution approval for a complete approval UI. app/page.tsx'use client'; import { useChat } from '@ai-sdk/react'; import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls, } from 'ai'; import { useState } from 'react'; export default function Chat() { const { messages, sendMessage, addToolOutput } = useChat({ transport: new DefaultChatTransport({ api: '/api/chat', }), sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls, // run client-side tools that are automatically executed: async onToolCall({ toolCall }) { // Check if it's a dynamic tool first for proper type narrowing if (toolCall.dynamic) { return; } if (toolCall.toolName === 'getLocation') { const cities = ['New York', 'Los Angeles', 'Chicago', 'San Francisco']; // No await - avoids potential deadlocks addToolOutput({ tool: 'getLocation', toolCallId: toolCall.toolCallId, output: cities[Math.floor(Math.random() * cities.length)], }); } }, }); const [input, setInput] = useState(''); return ( <> {messages?.map(message => ( <div key={message.id}> <strong>{`${message.role}: `}</strong> {message.parts.map(part => { switch (part.type) { // render text parts as simple text: case 'text': return part.text; // for tool parts, use the typed tool part names: case 'tool-askForConfirmation': { const callId = part.toolCallId; switch (part.state) { case 'input-streaming': return ( <div key={callId}>Loading confirmation request...</div> ); case 'input-available': return ( <div key={callId}> {part.input.message} <div> <button onClick={() => addToolOutput({ tool: 'askForConfirmation', toolCallId: callId, output: 'Yes, confirmed.', }) } > Yes </button> <button onClick={() => addToolOutput({ tool: 'askForConfirmation', toolCallId: callId, output: 'No, denied', }) } > No </button> </div> </div> ); case 'approval-requested': return <div key={callId}>Approval requested.</div>; case 'approval-responded': return <div key={callId}>Approval response received.</div>; case 'output-available': return ( <div key={callId}>Confirmation result: {part.output}</div> ); case 'output-error': return <div key={callId}>Error: {part.errorText}</div>; case 'output-denied': return <div key={callId}>Tool call denied.</div>; } break; } case 'tool-getLocation': { const callId = part.toolCallId; switch (part.state) { case 'input-streaming': return ( <div key={callId}>Preparing location request...</div> ); case 'input-available': return <div key={callId}>Getting location...</div>; case 'approval-requested': return <div key={callId}>Approval requested.</div>; case 'approval-responded': return <div key={callId}>Approval response received.</div>; case 'output-available': return <div key={callId}>Location: {part.output}</div>; case 'output-error': return ( <div key={callId}> Error getting location: {part.errorText} </div> ); case 'output-denied': return <div key={callId}>Location request denied.</div>; } break; } case 'tool-getWeatherInformation': { const callId = part.toolCallId; switch (part.state) { // example of pre-rendering streaming tool inputs: case 'input-streaming': return ( <pre key={callId}>{JSON.stringify(part, null, 2)}</pre> ); case 'input-available': return ( <div key={callId}> Getting weather information for {part.input.city}... </div> ); case 'approval-requested': return <div key={callId}>Approval requested.</div>; case 'approval-responded': return <div key={callId}>Approval response received.</div>; case 'output-available': return ( <div key={callId}> Weather in {part.input.city}: {part.output} </div> ); case 'output-error': return ( <div key={callId}> Error getting weather for {part.input.city}:{' '} {part.errorText} </div> ); case 'output-denied': return <div key={callId}>Weather request denied.</div>; } break; } } })} <br /> </div> ))} <form onSubmit={e => { e.preventDefault(); if (input.trim()) { sendMessage({ text: input }); setInput(''); } }} > <input value={input} onChange={e => setInput(e.target.value)} /> </form> </> ); } Error handling Sometimes an error may occur during client-side tool execution. Use the addToolOutput method with a state of output-error and errorText value instead of output to record the error. app/page.tsx'use client'; import { useChat } from '@ai-sdk/react'; import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls, } from 'ai'; import { useState } from 'react'; export default function Chat() { const { messages, sendMessage, addToolOutput } = useChat({ transport: new DefaultChatTransport({ api: '/api/chat', }), sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls, // run client-side tools that are automatically executed: async onToolCall({ toolCall }) { // Check if it's a dynamic tool first for proper type narrowing if (toolCall.dynamic) { return; } if (to