四、使用langchain搭建RAG:金融问答机器人--构建web应用,问答链,带记忆功能

经过前面3节完成金融问答机器人基本流程,这章将使用Gradio构建web应用,同时加入memory令提示模板带有记忆的,使用LCEL构建问答链。

加载向量数据库

python 复制代码
from langchain.vectorstores import Chroma
from langchain_huggingface import HuggingFaceEmbeddings
import os

# 定义 Embeddings
embeddings = HuggingFaceEmbeddings(model_name="m3e-base")

# 向量数据库持久化路径
persist_directory = 'data_base/chroma'

# 加载数据库
vectordb = Chroma(
    persist_directory=persist_directory, 
    embedding_function=embeddings
)
retriever=vectordb.as_retriever()

加载LLM

python 复制代码
import os
os.environ["DASHSCOPE_API_KEY"] = 'sk-***'

from langchain_community.llms import Tongyi
llm = Tongyi()

创建memory

python 复制代码
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory(
    memory_key="chat_history",  # 与 prompt 的输入变量保持一致。
    return_messages=True  # 将以消息列表的形式返回聊天记录,而不是单个字符串
)

构建新的问答链,使用带有记忆的提示模板

python 复制代码
# 构建新的问答链,使用带有记忆的提示模板
from langchain.chains import ConversationalRetrievalChain
def chatqwen_chat(message, history):
     #构建对话问答链
     qa = ConversationalRetrievalChain.from_llm(
		llm,
		retriever=retriever,
		memory=memory,
		verbose=True,
	 )
     result = qa({"question": message})
     return result['answer']

定义gradio web app

python 复制代码
import gradio as gr
def launch_gradio():

    iface = gr.ChatInterface(
        fn=chatqwen_chat,
        title="金融RAG问答机器人",
        chatbot=gr.Chatbot(height=400),
    )
    iface.launch(share=True, server_name="0.0.0.0")

启动 Gradio 服务

python 复制代码
# 启动 Gradio 服务
launch_gradio()

测试

Gradio 服务启动成功后,可以使用浏览器f访问web应用: http://127.0.0.1:7861/

从上面第二个问题看出,有记忆到之前的问题。

下图是整个访问链条的LOG:

总结

使用Gradio构建web应用已完成,如果想独立部署项目,可以放到py文件中,然后使用下面代码启动

python 复制代码
if __name__ == "__main__": 
    # 启动 Gradio 服务
    launch_gradio()

启动脚本: python ***.py

如果是使用conda 虚拟环境则: **\envs\langchain_qwen\python **.py (带上虚拟环境的目录)

项目源代码: https://gitee.com/ailianshuo/finance-bot

相关推荐
沈管家AI数字员工2 分钟前
对话式数据分析实操:从自然语言到可视化图表的全流程
数据库·人工智能·ai·oracle·数据分析
威联通安全存储4 分钟前
TS-h1290FX 在模具制造设计与CAM场景的部署
python·制造
艾克斯观察14 分钟前
一条辞职帖,14小时7700万人看:全网到底在吵什么
人工智能·ai·x·世界末日·传播学
LayZhangStrive15 分钟前
LangChain4j-OpenAI - 结构化输出及优化
ai·prompt·agent·json_object·outputstruct·json_schema
liliangcsdn25 分钟前
IC计算-前向/远期收益计算和代码示例
开发语言·python·pandas
Darling噜啦啦32 分钟前
LLM 结构化输出进阶:withStructuredOutput 一行封装 Tool Call,从流式输出到 MySQL 落地
langchain·llm
2601_9623818637 分钟前
python安装好了如何设置环境变量
python·开发工具·环境变量·虚拟环境·ide配置
zhojiew1 小时前
让 Agent 安全地“借用别人的钥匙“:AgentCore 上用 Authentik 打通 OAuth 出站的一次实战
安全·ai·aws·agentcore
小柯南敲键盘1 小时前
跨马翻译:跨境电商图片翻译工具,批量处理视频字幕与抠图
python·音视频
Hali_Botebie1 小时前
PyTorch 内存布局,.view()要合并哪两个维度(比如 B 和 G),这两个维度在内存里就必须“紧挨着”。
人工智能·pytorch·python