Langchain+LLM+Streamlit构建QA机器人

本文介绍了一个使用LLM(语言模型)和相关工具如文档加载器、文本分块器、嵌入向量存储等,实现上传文件内容分析、查询并生成类似问题答案的过程。通过Chroma矢量数据库进行相似性搜索,提供基于文本的智能对话功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

步聚如下:

文档加载器:它用于将数据加载为文档。
文档转换器:它将文档分成更小的块。
嵌入:它将块转换为向量表示,即嵌入。
嵌入向量存储:用于将上述块向量存储在矢量数据库中。
检索器:它用于检索一组向量,这些向量以嵌入在相同Latent空间中的向量的形式与查询最相似。
生成Prompt
LLM 检索

代码如下:

import streamlit as st 
from langchain.llms import LlamaCpp
from langchain.embeddings import LlamaCppEmbeddings
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from langchain.document_loaders import TextLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import Chroma


# Customize the layout
st.set_page_config(page_title="DOCAI", page_icon=" ", layout="wide", )     
st.markdown(f"""
            <style>
            .stApp {{background-image: url("https://images.unsplash.com/photo-1509537257950-20f875b03669?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=1469&q=80"); 
                     background-attachment: fixed;
                     background-size: cover}}
         </style>
         """, unsafe_allow_html=True)

# function for writing uploaded file in temp
def write_text_file(content, file_path):
    try:
        with open(file_path, 'w') as file:
            file.write(content)
        return True
    except Exception as e:
        print(f"Error occurred while writing the file: {e}")
        return False

# set prompt template
prompt_template = """Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.
{context}
Question: {question}
Answer:"""
prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])

# initialize hte LLM & Embeddings
llm = LlamaCpp(model_path="./models/llama-7b.ggmlv3.q4_0.bin")
embeddings = LlamaCppEmbeddings(model_path="models/llama-7b.ggmlv3.q4_0.bin")
llm_chain = LLMChain(llm=llm, prompt=prompt)

st.title("  Document Conversation  ")
uploaded_file = st.file_uploader("Upload an article", type="txt")

if uploaded_file is not None:
    content = uploaded_file.read().decode('utf-8')
    # st.write(content)
    file_path = "temp/file.txt"
    write_text_file(content, file_path)   
 
    loader = TextLoader(file_path)
    docs = loader.load()    
    text_splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=0)
    texts = text_splitter.split_documents(docs)
    db = Chroma.from_documents(texts, embeddings)    
    st.success("File Loaded Successfully!!")
 
    # Query through LLM    
    question = st.text_input("Ask something from the file", placeholder="Find something similar to: ....this.... in the text?", disabled=not uploaded_file,)    
    if question:
        similar_doc = db.similarity_search(question, k=1)
        context = similar_doc[0].page_content
        query_llm = LLMChain(llm=llm, prompt=prompt)
        response = query_llm.run({"context": context, "question": question})        
        st.write(response)
### 关于 LangChainLLM 的实战案例 LangChain 提供了一个强大的框架用于开发基于大型语言模型的应用程序。通过该平台,开发者能够更高效地创建复杂的对话系统和其他文本处理工具。 #### 使用 LangChain 构建 LLM 驱动应用程序的基础流程 新手教程介绍了如何开始使用 LangChain 来简化与预训练的语言模型之间的交互过程[^2]。这不仅限于简单的 API 调用;还包括了提示工程——即设计有效的输入指令以获取理想的响应结果。为了便于重复利用成功的提示语句,LangChain 还引入了提示模板的概念,允许用户保存并重用经过验证的工作配置。 #### 实际操作指南:编写代码示例 对于想要深入了解具体实现细节的人来说,官方文档提供了一系列详细的实例说明。例如,在表达式语言部分有一个专门针对代码编写的章节[^3],其中包含了完整的 Python 代码片段,展示了怎样运用 LangChain 表达式来执行特定的任务,如自动生成函数定义或解析编程问题。 ```python from langchain import PromptTemplate, LLMChain from langchain.llms import OpenAI # 创建一个带有变量插槽的PromptTemplate对象 template = "你是一个擅长{language}编程的大师,请解释什么是{concept}" prompt = PromptTemplate(input_variables=["language", "concept"], template=template) # 初始化OpenAI LLMllm_chain = LLMChain(prompt=prompt, llm=OpenAI()) # 执行查询 response = llm_chain.run({"language": "Python", "concept": "列表推导"}) print(response) ``` 这段代码演示了如何设置一个包含动态参数的提示模板,并通过调用 `run` 方法传入具体的值来进行个性化提问。此方法非常适合用来探索不同领域内的知识点或是解决实际遇到的技术难题。 #### Chain 模块的作用及其重要性 值得注意的是,LangChain 中的核心概念之一就是 Chains(链条),它负责连接各个独立的功能单元形成一条逻辑清晰的操作流水线[^4]。这种结构化的设计使得整个系统的扩展性和灵活性大大增强,同时也降低了维护成本。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值