Importing the Hook

import { useChat } from "polyfire-js/hooks";

Using the useChat hook

function useChat(): { messages: Message[], sendMessage: (message: string) => void, loading: boolean };

useChat doesn't take any parameter returns three elements: messages, sendMessage and loading

messages contains a list of Message defined as:

type Message = {
    id: string | null; // The current question/answer will be null. An id will be set to it at the end of the generation
    chat_id: string;
    is_user_message: boolean;
    content: string;
    created_at: string | null; // The current question/answer will be null. The date will be set at the end of the generation

To send a new message, use the sendMessage function.

function sendMessage(message: string): void;

The message will be added to messages and the answer from the LLM will be updated token by token until the answer have been fully generated.

During the generation, loading will be set to true, allowing you to disable the send button.


usePolyfire needs to be called for useChat to be initialized.

loading is also set to true during the usePolyfire initialization.

:warning: Using sendMessage when loading is true will throw an error

Example Usage

The How to make a clone of ChatGPT app could be simplified with this hook:

function App() {
    const {
        auth: { login, status },
    } = usePolyfire();
    const { messages, sendMessage, loading } = useChat();

    return (
            {status === "unauthenticated" ? (
                <button onClick={() => login("github")}>Login with Github</button>
            ) : status === "authenticated" ? (
                    messages={messages?.slice().reverse() || []}
            ) : (