用 Google El Carro 和 Langchain 轻松管理 Oracle 聊天记录
引言
在 Kubernetes 上运行 Oracle 数据库?Google Cloud 的 El Carro 提供了一种无供应商锁定的方法来管理 Oracle 数据库,同时支持强大的声明式 API 和实时操作监控。这篇文章将介绍如何通过 El Carro 与 Langchain 的集成,使用 ElCarroChatMessageHistory
类存储聊天消息历史。
主要内容
环境准备
在开始之前,请确保完成以下步骤:
- 如果想使用 El Carro 运行 Oracle 数据库,请参阅 Getting Started。
- 安装必要的库:
%pip install --upgrade --quiet langchain-google-el-carro langchain-google-vertexai langchain
Colab 用户需重启内核:
# import IPython
# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)
认证与项目设置
在 Google Cloud 上进行身份验证并设置项目:
# from google.colab import auth
# auth.authenticate_user()
PROJECT_ID = "your-project-id"
!gcloud config set project {PROJECT_ID}
Oracle 数据库连接设置
填写 Oracle 数据库连接信息:
HOST = "127.0.0.1"
PORT = 3307
DATABASE = "my-database"
TABLE_NAME = "message_store"
USER = "my-user"
PASSWORD = input("Please provide a password to be used for the database user: ")
使用 ElCarroEngine 创建连接池
from langchain_google_el_carro import ElCarroEngine
elcarro_engine = ElCarroEngine.from_instance(
db_host=HOST,
db_port=PORT,
db_name=DATABASE,
db_user=USER,
db_password=PASSWORD,
)
初始化聊天历史表
elcarro_engine.init_chat_history_table(table_name=TABLE_NAME)
管理聊天消息历史
使用 ElCarroChatMessageHistory
管理聊天记录:
from langchain_google_el_carro import ElCarroChatMessageHistory
history = ElCarroChatMessageHistory(
elcarro_engine=elcarro_engine, session_id="test_session", table_name=TABLE_NAME
)
history.add_user_message("hi!")
history.add_ai_message("whats up?")
print(history.messages)
清除聊天记录:
history.clear()
与 Vertex AI 集成
启用 Vertex AI API 以使用 Google 的 Vertex AI 模型:
!gcloud services enable aiplatform.googleapis.com
创建包含历史记录的链:
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_google_vertexai import ChatVertexAI
prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a helpful assistant."),
MessagesPlaceholder(variable_name="history"),
("human", "{question}"),
]
)
chain = prompt | ChatVertexAI(project=PROJECT_ID)
chain_with_history = RunnableWithMessageHistory(
chain,
lambda session_id: ElCarroChatMessageHistory(
elcarro_engine,
session_id=session_id,
table_name=TABLE_NAME,
),
input_messages_key="question",
history_messages_key="history",
)
config = {"configurable": {"session_id": "test_session"}}
chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
chain_with_history.invoke({"question": "Whats my name"}, config=config)
常见问题和解决方案
网络访问问题
由于某些地区的网络限制,开发者可以考虑使用API代理服务提高访问稳定性。
数据库连接失败
- 确保数据库端口和主机名正确。
- 检查用户凭证是否有效。
总结和进一步学习资源
Google Cloud 的 El Carro 提供了强大的工具集成,简化了 Oracle 数据库的管理和扩展。在此基础上,您可以轻松构建 AI 支持的体验。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—