Spaces:
Build error
Build error
Download app.py from lindachao/GeminiRAGapi: direct link, hf CLI and curl.
- Browser
- Download file 4.39 kB
-
https://huggingface.co/spaces/lindachao/GeminiRAGapi/resolve/main/app.py
- Command line
-
hf download hf://spaces/lindachao/GeminiRAGapi/app.py
-
curl -L -o app.py https://huggingface.co/spaces/lindachao/GeminiRAGapi/resolve/main/app.py
4.39 kB
| import gradio as gr | |
| from langchain.chains import create_retrieval_chain | |
| from langchain.chains.combine_documents import create_stuff_documents_chain | |
| from langchain_community.document_loaders import TextLoader, PyPDFLoader, DirectoryLoader | |
| from langchain_community.vectorstores import Chroma | |
| from langchain_core.callbacks import CallbackManager, StreamingStdOutCallbackHandler | |
| from langchain_core.prompts import ChatPromptTemplate | |
| from langchain_core.output_parsers import StrOutputParser | |
| from langchain.text_splitter import RecursiveCharacterTextSplitter | |
| from langchain.schema.runnable import RunnablePassthrough | |
| from langchain_google_genai import GoogleGenerativeAIEmbeddings, ChatGoogleGenerativeAI | |
| import PyPDF2 | |
| import os | |
| import io | |
| # Retrieve API key from environment variable | |
| GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") | |
| pdf_dir = 'docs' | |
| context = '' | |
| 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) | |
| 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": 30}) | |
| # Create llm | |
| # callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]) | |
| llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash", temperature=0.1, google_api_key=GOOGLE_API_KEY) #callback_manager=callback_manager | |
| def invoke(question): | |
| if context: | |
| 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" | |
| "{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 response | |
| description = """Gradio UI using the Gemini Pro model for RAG.""" | |
| gr.close_all() | |
| demo = gr.Interface(fn = invoke, | |
| inputs = [gr.Textbox(label = "Question", lines = 1)], | |
| outputs = [gr.Textbox(label = "Response", lines = 1)], | |
| title = "Generative AI - Gemini", | |
| description = description) | |
| demo.launch() |