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

相关推荐
IT猿手41 分钟前
2025最新群智能优化算法:山羊优化算法(Goat Optimization Algorithm, GOA)求解23个经典函数测试集,MATLAB
人工智能·python·算法·数学建模·matlab·智能优化算法
萧鼎2 小时前
深入解析 Umi-OCR:高效的免费开源 OCR 文字识别工具
python·ocr·umi-ocr
梦丶晓羽5 小时前
自然语言处理:文本分类
人工智能·python·自然语言处理·文本分类·朴素贝叶斯·逻辑斯谛回归
苏格拉真没有底6 小时前
python实现mqtt消息转Tcp消息
网络·python·tcp/ip
一尘之中6 小时前
从青铜巨人到硅基生命:机器人文明的意识觉醒之路--三千年人类想象与科技突破的双螺旋演进)
人工智能·科技·机器人
天才测试猿6 小时前
功能测试详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
vortex56 小时前
在Kali中使用虚拟环境安装python工具的最佳实践:以 pwncat 为例
linux·python·网络安全·渗透测试·pip·kali
十年一梦实验室7 小时前
机器人驱控一体平台简介
机器人
AntBlack7 小时前
Python 打包笔记 : 你别说 ,PyStand 确实简单易上手
后端·python·创业
狠活科技7 小时前
国内免费使用 Claude 3.7 Sonnt,GPT-4o,DeepSeek-R1联网极速响应
ai·chatgpt·oneapi