Download app.py from harryang/llm_rag: direct link, hf CLI and curl.
- Browser
- Download file 2.14 kB
-
https://huggingface.co/spaces/harryang/llm_rag/resolve/main/app.py
- Command line
-
hf download hf://spaces/harryang/llm_rag/app.py
-
curl -L -o app.py https://huggingface.co/spaces/harryang/llm_rag/resolve/main/app.py
2.14 kB
| import os | |
| import gradio as gr | |
| from langchain_community.document_loaders import PyPDFLoader | |
| from langchain_community.embeddings import HuggingFaceEmbeddings | |
| from langchain_community.vectorstores import FAISS | |
| from langchain.text_splitter import CharacterTextSplitter | |
| from langchain.chains import RetrievalQA | |
| from transformers import pipeline, AutoTokenizer, AutoModelForSeq2SeqLM | |
| from langchain_community.llms import HuggingFacePipeline | |
| # Load the Apple 10-K PDF | |
| loader = PyPDFLoader("apple_10k.pdf") | |
| docs = loader.load_and_split() | |
| splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=50) | |
| chunks = splitter.split_documents(docs[:10]) | |
| # Vector store | |
| embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2") | |
| db = FAISS.from_documents(chunks, embeddings) | |
| retriever = db.as_retriever() | |
| # Load LLM | |
| model_id = "google/flan-t5-large" | |
| token = os.getenv("HUGGINGFACEHUB_API_TOKEN") | |
| tokenizer = AutoTokenizer.from_pretrained(model_id, token=token) | |
| model = AutoModelForSeq2SeqLM.from_pretrained(model_id, device_map="auto", token=token) | |
| pipe = pipeline("text2text-generation", model=model, tokenizer=tokenizer, max_new_tokens=512) | |
| llm = HuggingFacePipeline(pipeline=pipe) | |
| # Build RAG pipeline | |
| qa = RetrievalQA.from_chain_type(llm=llm, retriever=db.as_retriever()) | |
| # === Prompt template (role-specific) === | |
| def finance_prompt(context, question): | |
| return f"""You are a professional financial analyst. Use the context below to answer the question clearly and concisely. | |
| Context: | |
| {context} | |
| Question: | |
| {question} | |
| Answer as a financial analyst:""" | |
| def rag_answer(user_input): | |
| docs = retriever.get_relevant_documents(user_input) | |
| context = "\n\n".join([doc.page_content for doc in docs]) | |
| prompt = finance_prompt(context, user_input) | |
| response = llm(prompt) | |
| return response | |
| gr.Interface( | |
| fn=rag_answer, | |
| inputs=gr.Textbox(lines=2, placeholder="Ask about Apple’s 10-K..."), | |
| outputs="text", | |
| title="📊 Financial Analyst Q&A (Apple 10-K RAG)", | |
| description="Ask anything based on Apple's official 10-K report. Uses financial prompt + document retrieval." | |
| ).launch() |