【RAG 项目实战 05】重构:封装代码

【RAG 项目实战 05】重构:封装代码


NLP Github 项目:


  • 新增 common.py
  • 改造 llm_util.py
  • 新增 chain_util.py
  • 新增 msg_util.py
  • 改造 app.py

新增 common.py

python 复制代码
# @Author:青松
# 公众号:FasterAI
# Python, version 3.10.14
# Pytorch, version 2.3.0
# Chainlit, version 1.1.301


class Constants:
    MODEL_NAME = {
        'QianFan': 'QianFan'
    }

改造 llm_util.py

python 复制代码
# @Author:青松
# 公众号:FasterAI
# Python, version 3.10.14
# Pytorch, version 2.3.0
# Chainlit, version 1.1.301

from common import Constants
from langchain_community.chat_models import QianfanChatEndpoint

# 加载环境变量
from dotenv import load_dotenv

load_dotenv()


def get_llm(model_name):
    llm = None

    try:
        if model_name == Constants.MODEL_NAME['QianFan']:
            llm = QianfanChatEndpoint(
                streaming=True,
                model="ERNIE-Speed-8K",
            )
    except:
        llm = get_default_llm()
    finally:
        if llm is None:
            llm = get_default_llm()
        return llm


def get_default_llm():
    default_llm = QianfanChatEndpoint(
        streaming=True,
        model="ERNIE-Speed-8K",
    )

    return default_llm

新增 chain_util.py

python 复制代码
# @Author:青松
# 公众号:FasterAI
# Python, version 3.10.14
# Pytorch, version 2.3.0
# Chainlit, version 1.1.301

from langchain.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import MessagesPlaceholder
from langchain_core.runnables import RunnablePassthrough
from langchain_core.vectorstores import VectorStore


def get_chat_chain(llm):
    # 提示模板中添加 chat_history
    prompt = ChatPromptTemplate.from_messages(
        [
            (
                "system",
                "你是一个中国古诗词专家,能准确的一字不差的背诵很多古诗词,请用你最大的能力来回答用户的问题。",
            ),
            MessagesPlaceholder("chat_history"),
            ("human", "{question}"),
        ]
    )
    
    chat_chain = prompt | llm | StrOutputParser()
    
    return chat_chain

新增 msg_util.py

python 复制代码
# @Author:青松
# 公众号:FasterAI
# Python, version 3.10.14
# Pytorch, version 2.3.0
# Chainlit, version 1.1.301

import chainlit as cl
from langchain_core.chat_history import BaseChatMessageHistory
from langchain_core.runnables import RunnableConfig
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_community.chat_message_histories import ChatMessageHistory

# 存储对话历史
store = {}


def get_session_history(session_id: str) -> BaseChatMessageHistory:
    if session_id not in store:
        store[session_id] = ChatMessageHistory()
    return store[session_id]


async def send_welcome_msg():
    # todo: 添加 FasterAI 知识星球图片以及 FastAI 知识库地址
    image = cl.Image(url="https://qingsong-1257401904.cos.ap-nanjing.myqcloud.com/wecaht.png")

    # 发送一个图片
    await cl.Message(
        content="**青松** 邀你关注 **FasterAI**, 让每个人的 AI 学习之路走的更容易些!立刻扫码开启 AI 学习、面试快车道 **(^_^)** ",
        elements=[image],
    ).send()


async def response_with_history_by_astream(message: cl.Message, chain, session_id):
    # 用 RunnableWithMessageHistory 包装 Chain 添加对话历史能力
    runnable_with_history = RunnableWithMessageHistory(
        chain,
        get_session_history,
        input_messages_key="question",
        history_messages_key="chat_history",
    )

    msg = cl.Message(content="")

    # 配置中使用 session_id 进行大模型交互
    async for chunk in runnable_with_history.astream(
            {"question": message.content},
            config=RunnableConfig(configurable={"session_id": session_id},
                                  callbacks=[cl.LangchainCallbackHandler()])
    ):
        await msg.stream_token(chunk)

    await msg.send()

改造 app.py

python 复制代码
# @Author:青松
# 公众号:FasterAI
# Python, version 3.10.14
# Pytorch, version 2.3.0
# Chainlit, version 1.1.301

import chainlit as cl

from common import Constants
import chain_util
import llm_util
import msg_util

# 获取大模型实例
llm = llm_util.get_llm(Constants.MODEL_NAME['QianFan'])


@cl.password_auth_callback
def auth_callback(username: str, password: str):
    """ 持久化客户端聊天历史代码,不需要请删除 """
    if (username, password) == ("admin", "admin"):
        return cl.User(
            identifier="admin", metadata={"role": "admin", "provider": "credentials"}
        )
    else:
        return None


@cl.on_chat_start
async def on_chat_start():
    """ 监听会话开始事件 """

    # 添加 session_id
    cl.user_session.set('session_id', 'abc2')

    # 发送欢迎信息
    await msg_util.send_welcome_msg()

    # 初始化链
    init_chains()


@cl.on_message
async def on_message(message: cl.Message):
    """ 监听用户消息事件 """

    # 获得对话链
    chat_chain = cl.user_session.get("chat_chain")

    # 获取当前的 session_id
    session_id = cl.user_session.get("session_id")

    # 使用对话历史通过 astream 的方式响应用户消息
    await msg_util.response_with_history_by_astream(message, chat_chain, session_id)


def init_chains():
    """ 初始化系统中的链 """

    # 对话链
    chat_chain = chain_util.get_chat_chain(llm)
    cl.user_session.set("chat_chain", chat_chain)

【动手学 RAG】系列文章:

相关推荐
Easy_API5 小时前
2.8万亿参数,编程反超GPT-6 Astra:Kimi K3.1 Pro把开源模型推到了哪一步
大数据·人工智能·gpt·深度学习
GlobalInfo5 小时前
2026年机器人多指灵巧手市场分析报告——涵盖行业调查、趋势分析与发展前景
大数据·人工智能·microsoft·微服务·机器人
紧跟先前的步伐6 小时前
Go AI Agent 实战 24|工具系统工程化收尾与阶段验收
人工智能·ai·golang·1024程序员节
释厄6236 小时前
AI学习层更新与跨体转移律——人类社会同构·不缺理解缺 U
人工智能·学习
老金带你玩AI7 小时前
集万家所长,一键复制的Agent.md!
人工智能
ZhuoAIStage7 小时前
舞台工艺多专业审图提速:用 AI 智能体编排 A+B+C+G 四段读图流水线
人工智能·自动化·工作流编排·舞台工艺·审图智能体
小奶包他干奶奶7 小时前
AI学习——1、机器学习概念
人工智能·机器学习
展讯快报8 小时前
悬浮提词器免费App评估报告:说得AI的免费策略与可用性分析
人工智能
Yuzhiyuxia8 小时前
【AI Agent面试系列】AI Agent记忆机制知识点1
人工智能·面试·职场和发展
2601_965448878 小时前
AI视频制作:做系列历史人物视频音色不搭,AI 音色克隆的方法实测
人工智能·音视频