Xata
Xata is a serverless data platform, based on
PostgreSQL
andElasticsearch
. It provides a Python SDK for interacting with your database, and a UI for managing your data. With theXataChatMessageHistory
class, you can use Xata databases for longer-term persistence of chat sessions.
This notebook covers:
- A simple example showing what
XataChatMessageHistory
does. - A more complex example using a REACT agent that answer questions based on a knowledge based or documentation (stored in Xata as a vector store) and also having a long-term searchable history of its past messages (stored in Xata as a memory store)
Setup
Create a database
In the Xata UI create a new database. You can name it whatever you want, in this notepad we'll use langchain
. The Langchain integration can auto-create the table used for storying the memory, and this is what we'll use in this example. If you want to pre-create the table, ensure it has the right schema and set create_table
to False
when creating the class. Pre-creating the table saves one round-trip to the database during each session initialization.
Let's first install our dependencies:
%pip install --upgrade --quiet xata langchain-openai langchain langchain-community
Next, we need to get the environment variables for Xata. You can create a new API key by visiting your account settings. To find the database URL, go to the Settings page of the database that you have created. The database URL should look something like this: https://demo-uni3q8.eu-west-1.xata.sh/db/langchain
.
import getpass
api_key = getpass.getpass("Xata API key: ")
db_url = input("Xata database URL (copy it from your DB settings):")
Create a simple memory store
To test the memory store functionality in isolation, let's use the following code snippet:
from langchain_community.chat_message_histories import XataChatMessageHistory
history = XataChatMessageHistory(
session_id="session-1", api_key=api_key, db_url=db_url, table_name="memory"
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")
The above code creates a session with the ID session-1
and stores two messages in it. After running the above, if you visit the Xata UI, you should see a table named memory
and the two messages added to it.
You can retrieve the message history for a particular session with the following code:
history.messages