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

相关推荐
overmind1 小时前
oeasy Python 115 列表弹栈用pop删除指定索引
开发语言·python
Ray Liang1 小时前
吊打OpenClaw!国产AI助理MindX开源:Token消耗砍至10%,还能养出专属数字分身
ai·智能体·ai助手·openclaw
hnxaoli2 小时前
win10程序(十六)通达信参数清洗器
开发语言·python·小程序·股票·炒股
电饭叔2 小时前
文本为 “ok”、前景色为白色、背景色为红色,且点击后触发 processOK 回调函数的 tkinter 按钮
开发语言·python
沙漏AI机器人3 小时前
2026年春晚舞台上宇树、银河、松延等机器人的表演给你留下了哪些印象?
机器人
雷电法拉珑3 小时前
财务数据批量采集
linux·前端·python
Nightwish53 小时前
一、读《彼得·林奇的成功投资》-随记-摘要
金融
shangjian0074 小时前
Python基础-With关键字
python
logocode_li4 小时前
跑通第一个LLM应用:调用DeepSeek模型
ai·llm·sdk·deepseek
KG_LLM图谱增强大模型4 小时前
给具身智能装上图谱大模型大脑,7B小模型超越72B大模型!层次化知识图谱让复杂机器人规划能力暴增17%,能耗大幅降低
人工智能·机器人·知识图谱