mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-15 06:09:21 +03:00
17 KiB
17 KiB
In [ ]:
%pip install --upgrade --quiet langchain-google-cloud-sql-pg langchain-google-vertexaiIn [ ]:
# # Automatically restart kernel after installs so that your environment can access the new packages
# import IPython
# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)In [1]:
from google.colab import auth
auth.authenticate_user()In [ ]:
# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.
PROJECT_ID = "my-project-id" # @param {type:"string"}
# Set the project id
!gcloud config set project {PROJECT_ID}In [3]:
# enable Cloud SQL Admin API
!gcloud services enable sqladmin.googleapis.comIn [4]:
# @title Set Your Values Here { display-mode: "form" }
REGION = "us-central1" # @param {type: "string"}
INSTANCE = "my-postgresql-instance" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "message_store" # @param {type: "string"}In [5]:
from langchain_google_cloud_sql_pg import PostgresEngine
engine = PostgresEngine.from_instance(
project_id=PROJECT_ID, region=REGION, instance=INSTANCE, database=DATABASE
)In [ ]:
engine.init_chat_history_table(table_name=TABLE_NAME)In [10]:
from langchain_google_cloud_sql_pg import PostgresChatMessageHistory
history = PostgresChatMessageHistory.create_sync(
engine, session_id="test_session", table_name=TABLE_NAME
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")In [11]:
history.messagesOut [11]:
[HumanMessage(content='hi!'), AIMessage(content='whats up?')]
In [12]:
history.clear()In [13]:
# enable Vertex AI API
!gcloud services enable aiplatform.googleapis.comIn [14]:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_google_vertexai import ChatVertexAIIn [15]:
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
)
chain = prompt | ChatVertexAI(project=PROJECT_ID)In [16]:
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: PostgresChatMessageHistory.create_sync(
engine,
session_id=session_id,
table_name=TABLE_NAME,
),
input_messages_key="question",
history_messages_key="history",
)In [17]:
# This is where we configure the session id
config = {"configurable": {"session_id": "test_session"}}In [18]:
chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)Out [18]:
AIMessage(content=' Hello Bob, how can I help you today?')
In [19]:
chain_with_history.invoke({"question": "Whats my name"}, config=config)Out [19]:
AIMessage(content=' Your name is Bob.')