引言
Google Cloud El Carro Oracle 提供了一种在 Kubernetes 中运行 Oracle 数据库的方法,作为一个便携的、开源的、社区驱动的容器编排系统。本指南将向您展示如何使用 El Carro 的 Langchain 集成来存储聊天消息历史,特别是通过 ElCarroChatMessageHistory 类。无论您的 Oracle 数据库在哪里运行,这种集成都可以工作。
主要内容
🦜🔗 库安装
首先,需要安装 langchain-google-el-carro 包来获取该集成。
%pip install --upgrade --quiet langchain-google-el-carro langchain-google-vertexai langchain
🔐 身份验证
使用 Google Cloud 项目中的 IAM 用户进行身份验证。
对于 Colab,请使用以下命令:
# from google.colab import auth
# auth.authenticate_user()
☁ 设置您的 Google Cloud 项目
确保设置 Google Cloud 项目以利用其中的资源:
PROJECT_ID = "my-project-id" # @param {type:"string"}
!gcloud config set project {PROJECT_ID}
基础用法
设置 Oracle 数据库连接
填写以下变量以连接到您的 Oracle 数据库:
HOST = "127.0.0.1" # @param {type: "string"}
PORT = 3307 # @param {type: "integer"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "message_store" # @param {type: "string"}
USER = "my-user" # @param {type: "string"}
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
初始化 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?")
查看已存储的消息:
history.messages
清理历史记录
删除不再需要的会话历史:
history.clear()
🔗 链接
结合使用 Vertex AI 聊天模型:
# enable 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"}}
chain_with_history.invoke({"question": "Hi! I'm Bob"}, config=config)
chain_with_history.invoke({"question": "What's my name"}, config=config)
常见问题和解决方案
-
访问 Oracle 数据库的网络问题:在某些地区可能需要考虑使用 API 代理服务来提高访问稳定性。
-
潜在的配置问题:确保所有必需的 Google Cloud API 已启用,尤其是 Vertex AI。
总结和进一步学习资源
Google El Carro 为 Oracle 数据库提供了一种强大的 Kubernetes 集成方式,通过 Langchain 集成,可以轻松实现与 AI 驱动的聊天历史存储的交互。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---