Spaces:
Build error
Build error
Update app.py
Browse files1234512 unmodified lines1819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import gradio as grfrom langchain.chains.question_answering import load_qa_chainfrom langchain_community.document_loaders import TextLoader, PyPDFLoader, DirectoryLoaderfrom langchain_community.vectorstores import Chromafrom langchain_core.callbacks import CallbackManager, StreamingStdOutCallbackHandler12 unmodified linespdf_dir = 'docs'for filename in os.listdir(pdf_dir):if filename.endswith('.pdf'):pdf_file = open(os.path.join(pdf_dir, filename), 'rb')pdf_reader = PyPDF2.PdfReader(pdf_file)context = ''for i in range(len(pdf_reader.pages)):page = pdf_reader.pages[i]context+= page.extract_text()if context:# Split Textstext_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)texts = text_splitter.split_text(context)def invoke(question):# Check if the API key is availableif google_api_key is None:response = 'No GOOGLE_API_KEY!'elif not context:response = 'No PDF file!'else:# Chroma Embeddingsembeddings = GoogleGenerativeAIEmbeddings(api_key=google_api_key, model="models/embedding-001")vector_index = Chroma.from_texts(texts, embeddings).as_retriever(search_kwargs={"k": 100})# Get Relevant Documentsdocs = vector_index.get_relevant_documents(question)# Define Prompt Templateprompt_template = """Answer the question as detailed as possible from the provided context,make sure to provide all the details, if the answer is not inprovided context just say, "Answer is not available in the context",don't provide the wrong answer\n\nContext:\n {context}?\nQuestion: \n{question}\nAnswer:"""# Create Promptprompt = PromptTemplate(template=prompt_template, input_variables=['context', 'question'])callback_manager = CallbackManager([StreamingStdOutCallbackHandler()])llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.3, api_key=google_api_key, callback_manager=callback_manager,)# rag_chain = (# {"context": vector_index, "question": RunnablePassthrough()}# | prompt# | llm# | StrOutputParser()# )# response = rag_chain.invoke(question)# Load QA Chainmodel = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.3, api_key=google_api_key, callback_manager=callback_manager,)chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)# Get Responseresponse = chain({"input_documents": docs, "question": question}, return_only_outputs=True)return response['output_text']description = """Gradio UI using the Gemini Pro model for RAG."""12345612 unmodified lines1920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import gradio as grfrom langchain.chains import create_retrieval_chainfrom langchain.chains.combine_documents import create_stuff_documents_chainfrom langchain_community.document_loaders import TextLoader, PyPDFLoader, DirectoryLoaderfrom langchain_community.vectorstores import Chromafrom langchain_core.callbacks import CallbackManager, StreamingStdOutCallbackHandler12 unmodified linespdf_dir = 'docs'for filename in os.listdir(pdf_dir):if filename.endswith('.pdf'):pdf_file = open(os.path.join(pdf_dir, filename), 'rb')pdf_reader = PyPDF2.PdfReader(pdf_file)context = ''for i in range(len(pdf_reader.pages)):page = pdf_reader.pages[i]context+= page.extract_text()if context:# 分割文本# 使用 RecursiveCharacterTextSplitter 將長文本分割成多個較小的文本塊,方便後續處理。text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)texts = text_splitter.split_text(context)# Chroma 嵌入# 使用 GoogleGenerativeAIEmbeddings 創建嵌入模型,用于将文本转换为向量表示。# "models/embedding-001" 是 Google 提供的嵌入模型名称。embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001", google_api_key=GOOGLE_API_KEY)# 使用 Chroma 創建检索器,用于根据文本的向量表示进行相似性检索。# Chroma.from_texts() 将文本列表转换为向量表示并存储在 Chroma 中。# as_retriever() 将 Chroma 转换为检索器,用于根据查询向量检索最相似的文本。# search_kwargs={"k": 1} 设置检索结果数量为 1,即只返回最相似的文本。retriever = Chroma.from_texts(texts, embeddings).as_retriever(search_kwargs={"k": 1})# Create Promptprompt = PromptTemplate(template=prompt_template, input_variables=['context', 'question'])# Create llmllm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.1, api_key=google_api_key, callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]))if docs:system_prompt = (# "You are an assistant for question-answering tasks. "# "Use the following pieces of retrieved context to answer "# "the question. If you don't know the answer, say that you "# "don't know. Keep the answer concise.""您是一位問答助手。使用以下提供的內容來回答問題。如果您不知道答案,請說您不知道。""請盡可能簡潔地回答,""\n\n""{context}")# 創建一個聊天提示模板,用于将用户问题和系统提示结合起��。prompt = ChatPromptTemplate.from_messages([("system", system_prompt), # 定义系统提示部分,例如告知模型角色或提供一些背景信息。("human", "{input}"), # 定义用户输入部分,{input} 表示用户输入的具体问题。])question_answer_chain = create_stuff_documents_chain(llm, prompt) # LangChain的工具函数,用于创建问答链,它将LLM和提示模板结合在一起。rag_chain = create_retrieval_chain(retriever, question_answer_chain) # 创建检索增强生成(RAG)链,将检索器与问答链结合起来。retriever用于根据问题检索相关文本。response = rag_chain.invoke({"input": question})["answer"] # 使用RAG链处理用户输入的问题question。else:response = 'No context!'return responsedescription = """Gradio UI using the Gemini Pro model for RAG."""
app.py+50-55