LLM漫谈(三)| 使用Chainlit和LangChain构建文档问答的LLM应用程序

本文主要是介绍LLM漫谈(三)| 使用Chainlit和LangChain构建文档问答的LLM应用程序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、Chainlit介绍

     Chainlit是一个开源Python包,旨在彻底改变构建和共享语言模型(LM)应用程序的方式。Chainlit可以创建用户界面(UI),类似于由OpenAI开发的ChatGPT用户界面,Chainlit可以开发类似streamlit的web界面。

1.1 Chainlit的主要特点

  • 可视化中间步骤:Chainlit可以可视化大语言模型管道中的每个步骤;
  • Chainlit与Python代码轻松集成,可以快速释放LM应用程序的潜力;
  • 快速响应的UI开发:使用Chainlit可以利用其直观的框架来设计和实现类似于ChatGPT的迷人UI。

1.2 Chainlit装饰器功能

on_message

      与框架的装饰器,用于对来自UI的消息作出反应。每次收到新消息时,都会调用装饰函数。

on_chat_start

       Decorator对用户websocket连接事件作出反应。

1.3 概念

User Session

      user_session是一个存储用户会话数据的字典,idenv键分别保持会话id和环境变量。用户会话其他数据存储在其他key中。

Streaming

Chainlit支持两种类型的流:

Python Streaming(https://docs.chainlit.io/concepts/streaming/python)

Langchain Streaming(https://docs.chainlit.io/concepts/streaming/langchain)

二、实施步骤

1.开始上传PDF格式文件,确保其正确提交;

2.随后,使用PyPDF2从上传的PDF文档中提取文本内容;

3.利用OpenAIEmbeddings将提取的文本内容转换为矢量化嵌入;

4.将这些矢量化嵌入保存在指定的向量库中,比如Chromadb;

5.当用户查询时,通过应用OpenAIEmbeddings将查询转换为相应的矢量嵌入,将查询的语义结构对齐到矢量化域中;

6.调用查询的矢量化嵌入有效地检索上下文相关的文档和文档上下文的相关元数据;

7.将检索到的相关文档及其附带的元数据传递给LLM,从而生成响应。

三、代码实施

3.1 安装所需的包

pip install -qU langchain openai tiktoken pyPDF2 chainlitconda install -c conda-forge chromadb

3.2 代码实施

#import required librariesfrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.vectorstores  import Chromafrom langchain.chains import RetrievalQAWithSourcesChainfrom langchain.chat_models import ChatOpenAIfrom langchain.prompts.chat import (ChatPromptTemplate,                                    SystemMessagePromptTemplate,                                    HumanMessagePromptTemplate)#import chainlit as climport PyPDF2from io import BytesIOfrom getpass import getpass#import osfrom configparser import ConfigParserenv_config =  ConfigParser()# Retrieve the openai key from the environmental variablesdef read_config(parser: ConfigParser, location: str) -> None:    assert parser.read(location), f"Could not read config {location}"#CONFIG_FILE = os.path.join("./env", "env.conf")read_config(env_config, CONFIG_FILE)api_key = env_config.get("openai", "api_key").strip()#os.environ["OPENAI_API_KEY"] = api_key# Chunking the texttext_splitter = RecursiveCharacterTextSplitter(chunk_size=1000,chunk_overlap=100)##system templatesystem_template = """Use the following pieces of context to answer the user's question.If you don't know the answer, just say that you don't know, don't try to make up an answer.ALWAYS return a "SOURCES" part in your answer.The "SOURCES" part should be a reference to the source of the document from which you got your answer.Begin!----------------{summaries}"""messages = [SystemMessagePromptTemplate.from_template(system_template),HumanMessagePromptTemplate.from_template("{question}"),]prompt = ChatPromptTemplate.from_messages(messages)chain_type_kwargs = {"prompt": prompt}#Decorator to react to the user websocket connection event. @cl.on_chat_startasync def init():    files = None    # Wait for the user to upload a PDF file    while files is None:        files = await cl.AskFileMessage(            content="Please upload a PDF file to begin!",            accept=["application/pdf"],        ).send()    file = files[0]    msg = cl.Message(content=f"Processing `{file.name}`...")    await msg.send()    # Read the PDF file    pdf_stream = BytesIO(file.content)    pdf = PyPDF2.PdfReader(pdf_stream)    pdf_text = ""    for page in pdf.pages:        pdf_text += page.extract_text()    # Split the text into chunks    texts = text_splitter.split_text(pdf_text)    # Create metadata for each chunk    metadatas = [{"source": f"{i}-pl"} for i in range(len(texts))]    # Create a Chroma vector store    embeddings = OpenAIEmbeddings(openai_api_key=os.getenv("OPENAI_API_KEY"))    docsearch = await cl.make_async(Chroma.from_texts)(        texts, embeddings, metadatas=metadatas    )    # Create a chain that uses the Chroma vector store    chain = RetrievalQAWithSourcesChain.from_chain_type(        ChatOpenAI(temperature=0,                    openai_api_key=os.environ["OPENAI_API_KEY"]),        chain_type="stuff",        retriever=docsearch.as_retriever(),    )    # Save the metadata and texts in the user session    cl.user_session.set("metadatas", metadatas)    cl.user_session.set("texts", texts)    # Let the user know that the system is ready    msg.content = f"`{file.name}` processed. You can now ask questions!"    await msg.update()    cl.user_session.set("chain", chain)# react to messages coming from the UI@cl.on_messageasync def process_response(res):    chain = cl.user_session.get("chain")  # type: RetrievalQAWithSourcesChain    cb = cl.AsyncLangchainCallbackHandler(        stream_final_answer=True, answer_prefix_tokens=["FINAL", "ANSWER"])    cb.answer_reached = True    res = await chain.acall(res, callbacks=[cb])    print(f"response: {res}")    answer = res["answer"]    sources = res["sources"].strip()    source_elements = []    # Get the metadata and texts from the user session    metadatas = cl.user_session.get("metadatas")    all_sources = [m["source"] for m in metadatas]    texts = cl.user_session.get("texts")    if sources:        found_sources = []        # Add the sources to the message        for source in sources.split(","):            source_name = source.strip().replace(".", "")            # Get the index of the source            try:                index = all_sources.index(source_name)            except ValueError:                continue            text = texts[index]            found_sources.append(source_name)            # Create the text element referenced in the message            source_elements.append(cl.Text(content=text, name=source_name))        if found_sources:            answer += f"\nSources: {', '.join(found_sources)}"        else:            answer += "\nNo sources found"    if cb.has_streamed_final_answer:        cb.final_stream.elements = source_elements        await cb.final_stream.update()    else:        await cl.Message(content=answer, elements=source_elements).send()

3.3 运行应用程序

chainlit run <name of the python script>

3.4 Chainlit UI

点击返回的页码,详细说明所引用的文档内容。

我们也可以更改设置。

参考文献:

[1] https://medium.aiplanet.com/building-llm-application-for-document-question-answering-using-chainlit-d15d10469069

这篇关于LLM漫谈(三)| 使用Chainlit和LangChain构建文档问答的LLM应用程序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/605137

相关文章

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

C#下Newtonsoft.Json的具体使用

《C#下Newtonsoft.Json的具体使用》Newtonsoft.Json是一个非常流行的C#JSON序列化和反序列化库,它可以方便地将C#对象转换为JSON格式,或者将JSON数据解析为C#对... 目录安装 Newtonsoft.json基本用法1. 序列化 C# 对象为 JSON2. 反序列化

RabbitMQ 延时队列插件安装与使用示例详解(基于 Delayed Message Plugin)

《RabbitMQ延时队列插件安装与使用示例详解(基于DelayedMessagePlugin)》本文详解RabbitMQ通过安装rabbitmq_delayed_message_exchan... 目录 一、什么是 RabbitMQ 延时队列? 二、安装前准备✅ RabbitMQ 环境要求 三、安装延时队

Python ORM神器之SQLAlchemy基本使用完全指南

《PythonORM神器之SQLAlchemy基本使用完全指南》SQLAlchemy是Python主流ORM框架,通过对象化方式简化数据库操作,支持多数据库,提供引擎、会话、模型等核心组件,实现事务... 目录一、什么是SQLAlchemy?二、安装SQLAlchemy三、核心概念1. Engine(引擎)

Java Stream 并行流简介、使用与注意事项小结

《JavaStream并行流简介、使用与注意事项小结》Java8并行流基于StreamAPI,利用多核CPU提升计算密集型任务效率,但需注意线程安全、顺序不确定及线程池管理,可通过自定义线程池与C... 目录1. 并行流简介​特点:​2. 并行流的简单使用​示例:并行流的基本使用​3. 配合自定义线程池​示

Python自动化处理PDF文档的操作完整指南

《Python自动化处理PDF文档的操作完整指南》在办公自动化中,PDF文档处理是一项常见需求,本文将介绍如何使用Python实现PDF文档的自动化处理,感兴趣的小伙伴可以跟随小编一起学习一下... 目录使用pymupdf读写PDF文件基本概念安装pymupdf提取文本内容提取图像添加水印使用pdfplum

GO语言中函数命名返回值的使用

《GO语言中函数命名返回值的使用》在Go语言中,函数可以为其返回值指定名称,这被称为命名返回值或命名返回参数,这种特性可以使代码更清晰,特别是在返回多个值时,感兴趣的可以了解一下... 目录基本语法函数命名返回特点代码示例命名特点基本语法func functionName(parameters) (nam

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

使用shardingsphere实现mysql数据库分片方式

《使用shardingsphere实现mysql数据库分片方式》本文介绍如何使用ShardingSphere-JDBC在SpringBoot中实现MySQL水平分库,涵盖分片策略、路由算法及零侵入配置... 目录一、ShardingSphere 简介1.1 对比1.2 核心概念1.3 Sharding-Sp

Java 正则表达式的使用实战案例

《Java正则表达式的使用实战案例》本文详细介绍了Java正则表达式的使用方法,涵盖语法细节、核心类方法、高级特性及实战案例,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录一、正则表达式语法详解1. 基础字符匹配2. 字符类([]定义)3. 量词(控制匹配次数)4. 边