|
| 1 | +import { useChat } from "@ai-sdk/react"; |
| 2 | +import type { ClientSideToolResult } from "@voltagent/core"; |
| 3 | +import { |
| 4 | + type ChatOnToolCallCallback, |
| 5 | + DefaultChatTransport, |
| 6 | + type UIMessage, |
| 7 | + lastAssistantMessageIsCompleteWithToolCalls, |
| 8 | +} from "ai"; |
| 9 | +import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; |
| 10 | + |
| 11 | +function ChatMessageView({ m }: { m: UIMessage }) { |
| 12 | + const renderContent = (content: any) => { |
| 13 | + if (typeof content === "string") return content; |
| 14 | + if (Array.isArray(content)) { |
| 15 | + // Collect text from parts like { type: 'text', text: '...' } or strings |
| 16 | + const textParts: string[] = []; |
| 17 | + for (const part of content) { |
| 18 | + if (typeof part === "string") { |
| 19 | + textParts.push(part); |
| 20 | + } else if (part && typeof part === "object") { |
| 21 | + if (typeof (part as any).text === "string") { |
| 22 | + textParts.push((part as any).text); |
| 23 | + } else if (typeof (part as any).content === "string") { |
| 24 | + textParts.push((part as any).content); |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + if (textParts.length > 0) return textParts.join(""); |
| 29 | + // Fallback: show structured content for non-text parts (e.g., tool calls) |
| 30 | + return <pre style={{ whiteSpace: "pre-wrap" }}>{JSON.stringify(content, null, 2)}</pre>; |
| 31 | + } |
| 32 | + // Unknown shape fallback |
| 33 | + return <pre style={{ whiteSpace: "pre-wrap" }}>{JSON.stringify(content, null, 2)}</pre>; |
| 34 | + }; |
| 35 | + |
| 36 | + return ( |
| 37 | + <div |
| 38 | + style={{ |
| 39 | + padding: "8px 12px", |
| 40 | + borderRadius: 8, |
| 41 | + background: m.role === "assistant" ? "#f4f6ff" : "#f6f6f6", |
| 42 | + marginBottom: 8, |
| 43 | + }} |
| 44 | + > |
| 45 | + <div style={{ fontSize: 12, color: "#666", marginBottom: 4 }}>{m.role}</div> |
| 46 | + <div>{renderContent(m.content || m.parts)}</div> |
| 47 | + </div> |
| 48 | + ); |
| 49 | +} |
| 50 | +const agentId = "ai-agent"; |
| 51 | +const port = "3141"; |
| 52 | + |
| 53 | +export default function App() { |
| 54 | + const [input, setInput] = useState(""); |
| 55 | + const inputRef = useRef<HTMLInputElement | null>(null); |
| 56 | + const [userId] = useState("user-123"); |
| 57 | + const [conversationId] = useState("test-conversation-10"); |
| 58 | + const [result, setResult] = useState<ClientSideToolResult | null>(null); |
| 59 | + |
| 60 | + const handleToolCall = useCallback<ChatOnToolCallCallback>(async ({ toolCall }) => { |
| 61 | + if (toolCall.toolName === "getLocation") { |
| 62 | + navigator.geolocation.getCurrentPosition( |
| 63 | + (position) => { |
| 64 | + setResult({ |
| 65 | + tool: "getLocation", |
| 66 | + toolCallId: toolCall.toolCallId, |
| 67 | + output: { |
| 68 | + latitude: position.coords.latitude, |
| 69 | + longitude: position.coords.longitude, |
| 70 | + accuracy: position.coords.accuracy, |
| 71 | + }, |
| 72 | + }); |
| 73 | + }, |
| 74 | + (error) => { |
| 75 | + setResult({ |
| 76 | + state: "output-error", |
| 77 | + tool: "getLocation", |
| 78 | + toolCallId: toolCall.toolCallId, |
| 79 | + errorText: error.message, |
| 80 | + }); |
| 81 | + }, |
| 82 | + ); |
| 83 | + } |
| 84 | + }, []); |
| 85 | + |
| 86 | + const { messages, sendMessage, addToolResult } = useChat({ |
| 87 | + transport: new DefaultChatTransport({ |
| 88 | + api: `http://localhost:${port}/agents/${agentId}/chat`, |
| 89 | + prepareSendMessagesRequest({ messages }) { |
| 90 | + const input = [messages[messages.length - 1]]; |
| 91 | + return { |
| 92 | + body: { |
| 93 | + input, |
| 94 | + options: { |
| 95 | + userId, |
| 96 | + conversationId, |
| 97 | + temperature: 0.7, |
| 98 | + maxSteps: 10, |
| 99 | + }, |
| 100 | + }, |
| 101 | + }; |
| 102 | + }, |
| 103 | + }), |
| 104 | + onToolCall: handleToolCall, |
| 105 | + onFinish: () => { |
| 106 | + console.log("Message completed"); |
| 107 | + }, |
| 108 | + onError: (error) => { |
| 109 | + console.error("Chat error:", error); |
| 110 | + }, |
| 111 | + sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithToolCalls, |
| 112 | + }); |
| 113 | + |
| 114 | + useEffect(() => { |
| 115 | + if (!result) return; |
| 116 | + console.log("Adding tool result:", result); |
| 117 | + addToolResult(result); |
| 118 | + }, [result, addToolResult]); |
| 119 | + |
| 120 | + // use local state for input control |
| 121 | + const value = input; |
| 122 | + return ( |
| 123 | + <div |
| 124 | + style={{ |
| 125 | + fontFamily: "Inter, ui-sans-serif, system-ui", |
| 126 | + maxWidth: 720, |
| 127 | + margin: "40px auto", |
| 128 | + padding: 16, |
| 129 | + }} |
| 130 | + > |
| 131 | + <h1>VoltAgent + AI SDK useChat</h1> |
| 132 | + <p style={{ color: "#444" }}> |
| 133 | + This example streams UI messages from VoltAgent's SSE endpoint that is compatible with the |
| 134 | + AI SDK's useChat hook. |
| 135 | + </p> |
| 136 | + |
| 137 | + <div> |
| 138 | + {messages.map((m) => ( |
| 139 | + <ChatMessageView key={m.id} m={m as UIMessage} /> |
| 140 | + ))} |
| 141 | + </div> |
| 142 | + |
| 143 | + <form |
| 144 | + onSubmit={(e) => { |
| 145 | + e.preventDefault(); |
| 146 | + const text = value?.trim(); |
| 147 | + if (text) { |
| 148 | + // AI SDK's sendMessage expects a UIMessage-like object in this version |
| 149 | + sendMessage({ role: "user", content: text } as any); |
| 150 | + setInput(""); |
| 151 | + } |
| 152 | + // focus input afterwards |
| 153 | + requestAnimationFrame(() => inputRef.current?.focus()); |
| 154 | + }} |
| 155 | + style={{ display: "flex", gap: 8, marginTop: 16 }} |
| 156 | + > |
| 157 | + <input |
| 158 | + ref={inputRef} |
| 159 | + name="input" |
| 160 | + value={value} |
| 161 | + onChange={(e) => { |
| 162 | + setInput(e.target.value); |
| 163 | + }} |
| 164 | + placeholder="Type a message..." |
| 165 | + style={{ flex: 1, padding: "10px 12px", borderRadius: 8, border: "1px solid #ddd" }} |
| 166 | + /> |
| 167 | + <button type="submit" disabled={!value?.trim()}> |
| 168 | + Send |
| 169 | + </button> |
| 170 | + </form> |
| 171 | + </div> |
| 172 | + ); |
| 173 | +} |
0 commit comments