Frontend - handle data from the agent API using useChat from ai-sdk

Step 1: Import useChat

The useChat hook from @ai-sdk/react provides an easy way to manage chat interactions with an AI backend. It helps handle messages, inputs, and API communication.

import { useChat } from "@ai-sdk/react";

Step 2: Configure useChat

To initialize the chat functionality, set up useChat with the required parameters. These include the API endpoint and a body containing user-related data (e.g., name, age, and API keys).

    const {
        messages,
        input,
        setInput,
        handleInputChange,
        handleSubmit,
        isLoading: chatEndpointIsLoading,
        setMessages,
    } = useChat({
        api: endpoint,
        body: { name, age, pvtKey, openKey, oobeKey, personality },
        onResponse(response: Response) {
            let d_ata = response.headers.get('X-OOBE-Data') ?? '';
            if (d_ata) {
                try {
                    d_ata = atob(d_ata); // Decode base64 encoded data
                } catch (e) {
                    console.error("Failed to decode data:", e);
                }
            }

            chunkData(d_ata);
            if (d_ata) {
                try {
                    const parsedData = JSON.parse(d_ata);
                    setSourcesForMessages(prev => [...prev, parsedData]);
                } catch (error) {
                    console.error("Failed to parse JSON:", error);
                }
            }

            response.clone().text().then((data) => {
                const conv = JSON.stringify(data)
                const sources = JSON.parse(conv);

                setMessages((prevMessages) => [
                    ...prevMessages,
                    {
                        id: prevMessages.length.toString(),
                        content: sources,
                        role: "assistant",
                    },
                ]);
            })
        },
    });

Step 3: Sending a Message

The sendMessage function handles form submission, preventing duplicate submissions while the API request is in progress.

async function sendMessage(e: FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!chatEndpointIsLoading) {
        handleSubmit(e);
    }
}

Last updated