import os from langchain.chains import RetrievalQA from langchain.llms import OpenAI from langchain.document_loaders import PyPDFLoader from langchain.indexes import VectorstoreIndexCreator from langchain.text_splitter import CharacterTextSplitter from langchain.embeddings import OpenAIEmbeddings from langchain.vectorstores import Chroma import gradio as gr import tempfile #定义查询函数qa def qa(file, openaikey, query, chain_type, k): os.environ["OPENAI_API_KEY"] = openaikey # load document 加载PDF文件 loader = PyPDFLoader(file.name) documents = loader.load() # split the documents into chunks 将PDF文件分割成小块 text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0) texts = text_splitter.split_documents(documents) # select which embeddings we want to use 使用 OpenAI 的embeddings模型为每个文本块创建一个向量嵌入 embeddings = OpenAIEmbeddings() # create the vectorestore to use as the index 创建一个向量存储VectorStore,用于后续的搜索。 db = Chroma.from_documents(texts, embeddings) # expose this index in a retriever interface 使用这个向量存储VectorStore创建一个检索器retriever retriever = db.as_retriever( search_type="similarity", search_kwargs={"k": k}) # create a chain to answer questions 然后使用这个检索器和 OpenAI 的模型创建一个问答链来回答问题。 qa = RetrievalQA.from_chain_type( llm=OpenAI(), chain_type=chain_type, retriever=retriever, return_source_documents=True) result = qa({"query": query}) print(result['result']) return result["result"] iface = gr.Interface( fn=qa, inputs=[ gr.inputs.File(label="上传PDF"), gr.inputs.Textbox(label="OpenAI API Key"), gr.inputs.Textbox(label="你的问题"), #longchain的文档documents分析功能的不同类型,具体见https://python.langchain.com.cn/docs/modules/chains/document/的解释 gr.inputs.Dropdown(choices=['stuff', 'map_reduce', "refine", "map_rerank"], label="Chain type"), gr.inputs.Slider(minimum=1, maximum=5, default=2, label="Number of relevant chunks"), ], outputs="text", title="你可以问我关于你上传的PDF文件的任何信息!", description="1) 上传一个PDF文件. 2)输入你的OpenAI API key.这将产生费用 3) 输入问题然后点击运行." ) iface.launch()