四、使用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

相关推荐
前端双越老师1 分钟前
使用 langChain.js 实现 RAG 知识库语义搜索
人工智能·langchain·node.js
今天炼丹了吗22 分钟前
RTDETR融合[WACV 2025]SEM-Net中的模块
python·深度学习·机器学习
Damon小智29 分钟前
玩转ClaudeCode:ClaudeCode安装教程(Windows+Linux+MacOS)
windows·ai·mac·wsl·claude code·vibe code
这里有鱼汤1 小时前
一篇文章让你彻底搞懂量化中RSI指标,附实战策略+附源码,建议收藏
python
IIIIIII_II1 小时前
【视频格式转换】.264格式转为mp4格式
python·视频·格式转换
都叫我大帅哥1 小时前
LangChain的TXT文档加载:从入门到实战的终极指南
python·langchain
蹦蹦跳跳真可爱5891 小时前
Python----NLP自然语言处理(中文分词器--jieba分词器)
开发语言·人工智能·python·自然语言处理·中文分词
蹦蹦跳跳真可爱5891 小时前
Python----OpenCV(图像分割——彩色图像分割,GrabCut算法分割图像)
开发语言·图像处理·人工智能·python·opencv·计算机视觉
吃手机用谁付的款2 小时前
基于hadoop的竞赛网站日志数据分析与可视化(下)
大数据·hadoop·python·信息可视化·数据分析
Kyln.Wu2 小时前
【python实用小脚本-139】Python 在线图片批量下载器:requests+PIL 一键保存网络图像
数据库·python·php