-
Notifications
You must be signed in to change notification settings - Fork 81
feat: Adding PGChatMessageHistory #203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dishaprakash
wants to merge
10
commits into
langchain-ai:main
Choose a base branch
from
dishaprakash:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
56f76e4
feat: Add PGChatMessageHistory
dishaprakash a4846f3
Add incorrect schema test
dishaprakash eddc6ef
Merge pull request #1 from dishaprakash/chat-message
dishaprakash f62eaab
Merge branch 'langchain-ai:main' into main
dishaprakash 0d78b87
chore(docs): Add documentation for PGChatMessageHistory
dishaprakash cb896c7
Merge pull request #2 from dishaprakash/chat-message
dishaprakash d713aa8
Update test_imports.py
dishaprakash 7e80b4f
fix test
dishaprakash 68741c8
review changes
dishaprakash c4c036f
Merge branch 'main' into main
averikitsch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,314 @@ | ||
{ | ||
"cells": [ | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"# PGChatMessageHistory\n", | ||
"\n", | ||
"`PGChatMessageHistory` is a an implementation of the the LangChain ChatMessageHistory abstraction using `postgres` as the backend.\n" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": { | ||
"id": "IR54BmgvdHT_" | ||
}, | ||
"source": [ | ||
"## Install\n", | ||
"\n", | ||
"Install the `langchain-postgres` package." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"colab": { | ||
"base_uri": "https://localhost:8080/", | ||
"height": 1000 | ||
}, | ||
"id": "0ZITIDE160OD", | ||
"outputId": "e184bc0d-6541-4e0a-82d2-1e216db00a2d", | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"%pip install --upgrade --quiet langchain-postgres" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": { | ||
"id": "QuQigs4UoFQ2" | ||
}, | ||
"source": [ | ||
"## Create an engine\n", | ||
"\n", | ||
"The first step is to create a `PGEngine` instance, which does the following:\n", | ||
"\n", | ||
"1. Allows you to create tables for storing documents and embeddings.\n", | ||
"2. Maintains a connection pool that manages connections to the database. This allows sharing of the connection pool and helps to reduce latency for database calls." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"from langchain_postgres import PGEngine\n", | ||
"\n", | ||
"# See docker command above to launch a Postgres instance with pgvector enabled.\n", | ||
"# Replace these values with your own configuration.\n", | ||
"POSTGRES_USER = \"langchain\"\n", | ||
"POSTGRES_PASSWORD = \"langchain\"\n", | ||
"POSTGRES_HOST = \"localhost\"\n", | ||
"POSTGRES_PORT = \"6024\"\n", | ||
"POSTGRES_DB = \"langchain\"\n", | ||
"\n", | ||
"CONNECTION_STRING = (\n", | ||
" f\"postgresql+asyncpg://{POSTGRES_USER}:{POSTGRES_PASSWORD}@{POSTGRES_HOST}\"\n", | ||
" f\":{POSTGRES_PORT}/{POSTGRES_DB}\"\n", | ||
")\n", | ||
"\n", | ||
"pg_engine = PGEngine.from_connection_string(url=CONNECTION_STRING)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"To use psycopg3 driver, set your connection string to `postgresql+psycopg://`" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": { | ||
"id": "D9Xs2qhm6X56" | ||
}, | ||
"source": [ | ||
"### Initialize a table\n", | ||
"The `PGChatMessageHistory` class requires a database table with a specific schema in order to store the chat message history.\n", | ||
"\n", | ||
"The `PGEngine` engine has a helper method `init_chat_history_table()` that can be used to create a table with the proper schema for you." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"TABLE_NAME = \"chat_history\"\n", | ||
"\n", | ||
"pg_engine.init_chat_history_table(table_name=TABLE_NAME)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"### PGChatMessageHistory\n", | ||
"\n", | ||
"To initialize the `PGChatMessageHistory` class you need to provide only 3 things:\n", | ||
"\n", | ||
"1. `engine` - An instance of a `PGEngine` engine.\n", | ||
"1. `session_id` - A unique identifier string that specifies an id for the session.\n", | ||
"1. `table_name` : The name of the table within the PG database to store the chat message history.\n", | ||
"1. `schema_name` : The name of the database schema containing the chat message history table." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"id": "z-AZyzAQ7bsf", | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"from langchain_postgres import PGChatMessageHistory\n", | ||
"\n", | ||
"history = PGChatMessageHistory.create_sync(\n", | ||
" pg_engine,\n", | ||
" session_id=\"test_session\",\n", | ||
" table_name=TABLE_NAME,\n", | ||
" # schema_name=SCHEMA_NAME,\n", | ||
")\n", | ||
"history.add_user_message(\"hi!\")\n", | ||
"history.add_ai_message(\"whats up?\")" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"history.messages" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"#### Cleaning up\n", | ||
"When the history of a specific session is obsolete and can be deleted, it can be done the following way.\n", | ||
"\n", | ||
"**Note:** Once deleted, the data is no longer stored in Postgres and is gone forever." | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"history.clear()" | ||
] | ||
}, | ||
{ | ||
"cell_type": "markdown", | ||
"metadata": {}, | ||
"source": [ | ||
"## Chaining\n", | ||
"\n", | ||
"We can easily combine this message history class with [LCEL Runnables](https://python.langchain.com/docs/concepts/lcel/) such as `RunnableWithMessageHistory`.\n", | ||
"\n", | ||
"To create an agent or chain, you will need a model. This example will use one of [Google's Vertex AI chat models](https://python.langchain.com/docs/integrations/chat/google_vertex_ai_palm)\n" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"# enable Vertex AI API\n", | ||
"!gcloud services enable aiplatform.googleapis.com" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": {}, | ||
"outputs": [], | ||
"source": [ | ||
"from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n", | ||
"from langchain_core.runnables.history import RunnableWithMessageHistory\n", | ||
"from langchain_google_vertexai import ChatVertexAI" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"## Please update the project id\n", | ||
"GOOGLE_CLOUD_PROJECT_ID = \"\"\n", | ||
"\n", | ||
"prompt = ChatPromptTemplate.from_messages(\n", | ||
" [\n", | ||
" (\"system\", \"You are a helpful assistant.\"),\n", | ||
" MessagesPlaceholder(variable_name=\"history\"),\n", | ||
" (\"human\", \"{question}\"),\n", | ||
" ]\n", | ||
")\n", | ||
"\n", | ||
"chain = prompt | ChatVertexAI(\n", | ||
" project=GOOGLE_CLOUD_PROJECT_ID, model_name=\"gemini-2.0-flash-exp\"\n", | ||
")" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"chain_with_history = RunnableWithMessageHistory(\n", | ||
" chain,\n", | ||
" lambda session_id: PGChatMessageHistory.create_sync(\n", | ||
" pg_engine,\n", | ||
" session_id=session_id,\n", | ||
" table_name=TABLE_NAME,\n", | ||
" # schema_name=SCHEMA_NAME,\n", | ||
" ),\n", | ||
" input_messages_key=\"question\",\n", | ||
" history_messages_key=\"history\",\n", | ||
")" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"# This is where we configure the session id\n", | ||
"config = {\"configurable\": {\"session_id\": \"test_session\"}}" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"chain_with_history.invoke({\"question\": \"Hi! I'm bob\"}, config=config)" | ||
] | ||
}, | ||
{ | ||
"cell_type": "code", | ||
"execution_count": null, | ||
"metadata": { | ||
"tags": [] | ||
}, | ||
"outputs": [], | ||
"source": [ | ||
"chain_with_history.invoke({\"question\": \"Whats my name\"}, config=config)" | ||
] | ||
} | ||
], | ||
"metadata": { | ||
"colab": { | ||
"provenance": [], | ||
"toc_visible": true | ||
}, | ||
"kernelspec": { | ||
"display_name": "Python 3 (ipykernel)", | ||
"language": "python", | ||
"name": "python3" | ||
}, | ||
"language_info": { | ||
"codemirror_mode": { | ||
"name": "ipython", | ||
"version": 3 | ||
}, | ||
"file_extension": ".py", | ||
"mimetype": "text/x-python", | ||
"name": "python", | ||
"nbconvert_exporter": "python", | ||
"pygments_lexer": "ipython3", | ||
"version": "3.11.4" | ||
} | ||
}, | ||
"nbformat": 4, | ||
"nbformat_minor": 4 | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.