'use client'; import { useChat } from '@ai-sdk/react'; import ChatInput from '@component/chat-input'; import { DefaultChatTransport, lastAssistantMessageIsCompleteWithToolCalls, } from 'ai'; import { StreamingToolCallsMessage } from '../api/use-chat-streaming-tool-calls/route'; export default function Chat() { const { messages, status, sendMessage, addToolResult } = useChat({ transport: new DefaultChatTransport({ api: '/api/use-chat-streaming-tool-calls', }), sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls, // run client-side tools that are automatically executed: async onToolCall({ toolCall }) { if (toolCall.toolName === 'showWeatherInformation') { // display tool. add tool result that informs the llm that the tool was executed. addToolResult({ tool: 'showWeatherInformation', toolCallId: toolCall.toolCallId, output: 'Weather information was shown to the user.', }); } }, }); // used to only render the role when it changes: let lastRole: string | undefined = undefined; return (
{messages?.map(m => { const isNewRole = m.role !== lastRole; lastRole = m.role; return (
{isNewRole && {`${m.role}: `}} {m.parts.map(part => { if (part.type === 'text') { return part.text; } if (part.type === 'tool-showWeatherInformation') { return (

{part.input?.city ?? ''}

{part.input?.weather && {part.input.weather}} {part.input?.temperature && ( {part.input.temperature} °C )}
{part.input?.typicalWeather && (
{part.input.typicalWeather}
)}
); } })}
); })} sendMessage({ text })} />
); }