【RAG 项目实战 01】在 LangChain 中集成 Chainlit

【RAG 项目实战 01】在 LangChain 中集成 Chainlit


NLP Github 项目:


1、 环境安装

pip install chainlit

2、 创建  app.py 文件

from langchain.chat_models import ChatOpenAI
from langchain.prompts import ChatPromptTemplate
from langchain.schema import StrOutputParser
from langchain.schema.runnable import Runnable
from langchain.schema.runnable.config import RunnableConfig

import chainlit as cl


@cl.on_chat_start
async def on_chat_start():
	""" 监听会话开始事件 """
	image = cl.Image(url="https://qingsong-1257401904.cos.ap-nanjing.myqcloud.com/wecaht.png")

    # 发送一个图片
    await cl.Message(
        content="欢迎关注 **FasterAI**, 让每个人的 AI 学习之路走的更容易些!",
        elements=[image],
    ).send()

    model = ChatOpenAI(streaming=True)
    prompt = ChatPromptTemplate.from_messages(
        [
            (
                "system",
                "You're a very knowledgeable historian who provides accurate and eloquent answers to historical questions.",
            ),
            ("human", "{question}"),
        ]
    )
    runnable = prompt | model | StrOutputParser()
    cl.user_session.set("runnable", runnable)


@cl.on_message
async def on_message(message: cl.Message):
	""" 监听用户消息事件 """
    runnable = cl.user_session.get("runnable")  # type: Runnable

    msg = cl.Message(content="")

    async for chunk in runnable.astream(
        {"question": message.content},
        config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
    ):
        await msg.stream_token(chunk)

    await msg.send()

3、使用千帆模型替换ChatGPT

import os

from langchain_community.chat_models import QianfanChatEndpoint
from langchain.prompts import ChatPromptTemplate
from langchain.schema import StrOutputParser
from langchain.schema.runnable import Runnable
from langchain.schema.runnable.config import RunnableConfig

import chainlit as cl

# 配置百度千帆大模型(免费、无需FQ)
os.environ["QIANFAN_AK"] = "千帆模型 Token"
os.environ["QIANFAN_SK"] = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

model = QianfanChatEndpoint(
    streaming=True,
    model="ERNIE-Speed-8K",
)


@cl.on_chat_start
async def on_chat_start():
	""" 监听会话开始事件 """
	image = cl.Image(url="https://qingsong-1257401904.cos.ap-nanjing.myqcloud.com/wecaht.png")

    # 发送一个图片
    await cl.Message(
        content="欢迎关注 **FasterAI**, 让每个人的 AI 学习之路走的更容易些!",
        elements=[image],
    ).send()

    prompt = ChatPromptTemplate.from_messages(
        [
            (
                "system",
                "You're a very knowledgeable historian who provides accurate and eloquent answers to historical questions.",
            ),
            ("human", "{question}"),
        ]
    )
    runnable = prompt | model | StrOutputParser()
    cl.user_session.set("runnable", runnable)


@cl.on_message
async def on_message(message: cl.Message):
	""" 监听用户消息事件 """
    runnable = cl.user_session.get("runnable")  # type: Runnable

    msg = cl.Message(content="")

    async for chunk in runnable.astream(
            {"question": message.content},
            config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),
    ):
        await msg.stream_token(chunk)

    await msg.send()

4、启动程序

chainlit run app.py -w

5、访问 http://localhost:8000/

与大模型进行对话:

[!NOTE] 问题
未结合上下文进行多轮对话


【动手学 RAG】系列文章:

本文由mdnice多平台发布

posted @ 2024-11-20 16:16  青松^_^  阅读(3)  评论(0编辑  收藏  举报