|
| 1 | +import type { Message } from "@ai-sdk/react"; |
| 2 | +import "./Chat.css"; |
| 3 | +import { useAgentChat } from "agents/ai-react"; |
| 4 | +import { useAgent } from "agents/react"; |
| 5 | +import { useCallback, useEffect, useRef } from "react"; |
| 6 | + |
| 7 | +export default function Chat() { |
| 8 | + const messagesEndRef = useRef<HTMLDivElement>(null); |
| 9 | + |
| 10 | + const scrollToBottom = useCallback(() => { |
| 11 | + messagesEndRef.current?.scrollIntoView({ behavior: "smooth" }); |
| 12 | + }, []); |
| 13 | + |
| 14 | + // Scroll to bottom on mount |
| 15 | + useEffect(() => { |
| 16 | + scrollToBottom(); |
| 17 | + }, [scrollToBottom]); |
| 18 | + |
| 19 | + const agent = useAgent({ |
| 20 | + agent: "TestingAgent", |
| 21 | + name: "chat", |
| 22 | + }); |
| 23 | + |
| 24 | + const { messages, input, handleInputChange, handleSubmit } = useAgentChat({ |
| 25 | + agent, |
| 26 | + maxSteps: 5, |
| 27 | + }); |
| 28 | + |
| 29 | + // Scroll to bottom when messages change |
| 30 | + useEffect(() => { |
| 31 | + messages.length > 0 && scrollToBottom(); |
| 32 | + }, [messages, scrollToBottom]); |
| 33 | + |
| 34 | + return ( |
| 35 | + <div className="chat-wrapper"> |
| 36 | + <div className="chat-container"> |
| 37 | + <div className="messages-wrapper"> |
| 38 | + {messages?.map((m: Message) => ( |
| 39 | + <div key={m.id} className="message"> |
| 40 | + <strong>{`${m.role}: `}</strong> |
| 41 | + {m.parts?.map((part, i) => { |
| 42 | + switch (part.type) { |
| 43 | + case "text": |
| 44 | + return ( |
| 45 | + // biome-ignore lint/suspicious/noArrayIndexKey: vibes |
| 46 | + <div key={i} className="message-content"> |
| 47 | + {part.text} |
| 48 | + </div> |
| 49 | + ); |
| 50 | + default: |
| 51 | + return null; |
| 52 | + } |
| 53 | + })} |
| 54 | + <br /> |
| 55 | + </div> |
| 56 | + ))} |
| 57 | + <div ref={messagesEndRef} /> |
| 58 | + </div> |
| 59 | + |
| 60 | + <form onSubmit={handleSubmit}> |
| 61 | + <input |
| 62 | + className="chat-input" |
| 63 | + value={input} |
| 64 | + placeholder="Say something..." |
| 65 | + onChange={handleInputChange} |
| 66 | + /> |
| 67 | + </form> |
| 68 | + </div> |
| 69 | + </div> |
| 70 | + ); |
| 71 | +} |
0 commit comments