#ai sdk useChat, multiple chat histories

1 messages · Page 1 of 1 (latest)

pseudo plinth
#

How can i save and load multiple chat histories using the useChat? And keep track of multiple conversations at once

lime lakeBOT
#

Hi @pseudo plinth. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To save and load multiple chat histories using the useChat hook in a Next.js application, you can follow these steps:

  1. Modify the useChat hook to handle multiple conversations: You need to manage the state for multiple chat histories. This can be done by maintaining an object where each key represents a unique conversation ID and the value is the chat history for that conversation.

  2. Save chat histories: You can save chat histories to a backend or local storage. For simplicity, I'll show how to save them to local storage.

  3. Load chat histories: When a user selects a conversation, you can load the corresponding chat history from local storage.

Here is an example implementation:

Step 1: Modify the useChat Hook

First, create a custom hook to manage multiple chat histories:

import { useState } from 'react';
import { useChat as useSingleChat } from 'ai/react';

export function useChat() {
  const [conversations, setConversations] = useState({});
  const [currentConversationId, setCurrentConversationId] = useState(null);

  const { messages, input, handleInputChange, handleSubmit } = useSingleChat({
    onMessage: (message) => {
      setConversations((prev) => {
        const updatedConversation = [...(prev[currentConversationId] || []), message];
        localStorage.setItem(currentConversationId, JSON.stringify(updatedConversation));
        return { ...prev, [currentConversationId]: updatedConversation };
      });
    },
  });

  const loadConversation = (conversationId) => {
    const savedMessages = JSON.parse(localStorage.getItem(conversationId)) || [];
    setConversations((prev) => ({ ...prev, [conversationId]: savedMessages }));
    setCurrentConversationId(conversationId);
  };
#

return {
conversations,
currentConversationId,
messages: conversations[currentConversationId] || [],
input,
handleInputChange,
handleSubmit,
loadConversation,
};
}


### Step 2: Use the Custom Hook in Your Component

Now, use this custom hook in your component to manage multiple chat histories:

```javascript
'use client';
import { useChat } from './path/to/custom/useChat';
import { useState } from 'react';

export default function Chat() {
  const { conversations, currentConversationId, messages, input, handleInputChange, handleSubmit, loadConversation } = useChat();
  const [newConversationId, setNewConversationId] = useState('');

  const handleNewConversation = () => {
    loadConversation(newConversationId);
    setNewConversationId('');
  };

  return (
    <div>
      <div>
        <input
          value={newConversationId}
          onChange={(e) => setNewConversationId(e.target.value)}
          placeholder="Enter conversation ID"
        />
        <button onClick={handleNewConversation}>Load Conversation</button>
      </div>
      <div>
        {messages.map((m) => (
          <div key={m.id}>
            {m.role === 'user' ? 'User: ' : 'AI: '}
            {m.content}
          </div>
        ))}
        <form onSubmit={handleSubmit}>
          <input
            value={input}
            placeholder="Say something..."
            onChange={handleInputChange}
          />
        </form>
      </div>
    </div>
  );
}

Explanation

  • Custom Hook (useChat): This hook manages multiple conversations by storing them in an object. Each conversation is identified by a unique ID.
  • Saving Messages: When a new message is received, it is saved to local

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: