Find answers from the community

Updated 5 months ago

Hi all. Complete newbie here, spent the

At a glance
Hi all. Complete newbie here, spent the whole day looking for an answer, so I hope someone can help.

I've been able to create a chatbot, but now I want to be able to store the chat memory somewhere so that the user can continue their chat later in a different session.

As I understand it, LlamaIndex only keeps the memory within the same session. If so, what's the recommended method for saving the chat memory in a database and retrieving it later during another chat session?

Thank you!
L
f
10 comments
You can get the chat history from

Plain Text
chat_history = chat_engine.chat_history
chat_json = json.dumps([x.dict() for x in chat_history])

# restoring
from llama_index.llms import ChatMessage
chat_history = [ChatMessage.parse_raw(x) for x in json.loads(chat_json)]

# into chat engine
chat_engine = index.as_chat_engine(..., chat_history=chat_history)

# or directly into chat()
response = chat_engine.chat("hello", chat_history=chat_history)
Thanks @Logan M I'll give this a try.
Hi again. Ok so that works, but only during a single run of the script.

If I wanted the history to persist between running the script, what's the recommended approach? E.g. saving it to a database.

This is for a "chat with data" SaaS that will be used by different users, and each user will have its own chat sessions and chat history.

(Oh and I'm also new to Python!)

Thanks!
Went for a simple approach of saving to and restoring from a mysql db. Does this look right for restoring the chat history?
Attachment
image.png
Attachment
image.png
That looks right to me! Although you miiiight also need to restore additional_kwargs in the ChatMessage, in addition to role and content
Ah ok, thanks @Logan M ! What are the additional_kwargs for and where should I restore them? Sorry, still all new to this and can't find the documentation for it.
Additional kwargs are just extra info that openai (or other LLM providers) attach to messages (usually this is for function/tool calls)

You would restore it ideally in your loop above

Plain Text
for row in records:
  chat_history.append(
    ChatMessage(
      role=row[3],
      content=row[2],
      additional_kwargs=row[??]
    )
  )


Personally though, I would store an entire JSON of the chat message and restore from that directly

Plain Text
message_json = message.json()

[store in db]

for row in records:
  chat_history.append(
    ChatMessage.parse_raw(row[<json location>])
  )
Thanks @Logan M . That's really helpful!
Add a reply
Sign up and join the conversation on Discord