Skip to main content

Conversation object

The Conversation object is an array-like collection of question-answer pairs with additional utility methods. It's returned by the useChat hook to provide access to the current conversation state.

note

The Conversation object is read-only from your application's perspective. Use the methods from the useChat hook to modify the conversation.

Methods

The Conversation object extends the standard JavaScript Array and adds these utility methods:

getById(id: string)

Retrieves a specific QA pair by its ID.

Parameters:

  • id (string): The unique identifier of the QA pair

Returns:

  • QA pair object or undefined if not found

Example:

const specificQA = conversation.getById("qa-123");
if (specificQA) {
displaySpecificAnswer(specificQA);
}

getLatest()

Gets the most recent QA pair in the conversation.

Parameters: none

Returns: the most recent QA pair or undefined if the conversation is empty

Example:

const latest = conversation.getLatest();
if (latest) {
scrollToLatestAnswer();
}

Usage examples

Rendering a conversation thread

function ChatThread() {
const { conversation } = useChat();

return (
<div className="chat-thread">
{conversation.map((qa, index) => (
<div key={qa.id || `temp-${index}`} className="message-pair">
<div className="user-message">{qa.question}</div>
<div className="ai-message">
{qa.answer || <span className="loading">...</span>}

{qa.sources.length > 0 && (
<div className="sources">
<h4>Sources:</h4>
<ul>
{qa.sources.map(source => (
<li key={source.source_url}>
<a href={source.source_url} target="_blank" rel="noopener">
{source.title}
</a>
</li>
))}
</ul>
</div>
)}
</div>
</div>
))}
</div>
);
}

Working with the latest QA pair

function LatestAnswer() {
const { conversation, isGeneratingAnswer } = useChat();
const latestQA = conversation.getLatest();

if (!latestQA) return <p>No conversation yet. Ask a question to start!</p>;

return (
<div>
<h3>Latest question:</h3>
<p>{latestQA.question}</p>

<h3>Answer:</h3>
{isGeneratingAnswer ? (
<p>Generating answer...</p>
) : (
<p>{latestQA.answer || "No answer yet."}</p>
)}
</div>
);
}