useChat Hook
The useChat
hook provides access to Kapa's chat functionality, conversation
state, and actions to interact with the chatbot.
Usage
import { useChat } from "@kapaai/react-sdk";
function ChatComponent() {
const {
conversation,
submitQuery,
isGeneratingAnswer,
resetConversation,
stopGeneration,
addFeedback,
} = useChat();
// Use the hook values and functions to build your UI
// ...
}
Return values
The useChat
hook returns an object with the following properties:
Property | Type | Description |
---|---|---|
isGeneratingAnswer | boolean | true when an answer is being streamed. |
isPreparingAnswer | boolean | true when the SDK is connecting to the backend. |
error | string | null | Error message or null if no error occurred. |
conversation | Conversation | Current conversation history with all Q&A pairs. |
threadId | string | null | Current conversation thread ID or null if no conversation started. |
submitQuery | (query: string) => void | Function to submit a new question to the AI. |
resetConversation | () => void | Function to clear the conversation history. |
stopGeneration | () => void | Function to abort the current generation. |
addFeedback | (questionAnswerId: string, reaction: Reaction, comment?: FeedbackComment) => void | Function to send feedback for a specific Q&A pair. |
Conversation object
The conversation
property returned by useChat
contains the complete chat
history. It's an array-like object with additional helper methods for accessing
question-answer pairs.
// Access a specific QA pair by ID
const specificQA = conversation.getById("qa-123");
// Get the most recent QA pair
const latestQA = conversation.getLatest();
Each QA pair contains the question, answer, sources, feedback state, and other metadata. For full details on the conversation object structure and methods, see the Conversation documentation.
Examples
Basic chat interface
import React, { useState } from "react";
import { useChat } from "@kapaai/react-sdk";
function ChatInterface() {
const [inputValue, setInputValue] = useState("");
const { conversation, submitQuery, isGeneratingAnswer, stopGeneration } =
useChat();
const handleSubmit = (e) => {
e.preventDefault();
if (inputValue.trim()) {
submitQuery(inputValue);
setInputValue("");
}
};
return (
<div className="chat-container">
<div className="messages">
{conversation.map((qa) => (
<div key={qa.id || `temp-${qa.question}`}>
<div className="user-message">{qa.question}</div>
<div className="ai-message">
{qa.answer || (isGeneratingAnswer ? "Typing..." : "")}
</div>
</div>
))}
</div>
<form onSubmit={handleSubmit}>
<input
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Ask a question..."
disabled={isGeneratingAnswer}
/>
{isGeneratingAnswer ? (
<button type="button" onClick={stopGeneration}>
Stop
</button>
) : (
<button type="submit">Send</button>
)}
</form>
</div>
);
}