Spaces:
Build error
Build error
Download app.py from sara4dev/rag-iblog-qa: direct link, hf CLI and curl.
- Browser
- Download file 1.77 kB
-
https://huggingface.co/spaces/sara4dev/rag-iblog-qa/resolve/main/app.py
- Command line
-
hf download hf://spaces/sara4dev/rag-iblog-qa/app.py
-
curl -L -o app.py https://huggingface.co/spaces/sara4dev/rag-iblog-qa/resolve/main/app.py
1.77 kB
| from langchain.chat_models import ChatOpenAI | |
| from langchain.embeddings.openai import OpenAIEmbeddings | |
| from langchain.chains import ConversationalRetrievalChain | |
| from langchain.memory import ConversationSummaryMemory | |
| from langchain.vectorstores import FAISS | |
| import gradio as gr | |
| import logging | |
| logging.basicConfig(level=logging.INFO) | |
| ## setup LLM | |
| llm = ChatOpenAI() | |
| ## load vector db | |
| embeddings = OpenAIEmbeddings() | |
| db = FAISS.load_local("faiss_index", embeddings) | |
| ## Setup the Q&A chain that stitches LLM, similar results from the vectordb & the prompt template | |
| memory = ConversationSummaryMemory(llm=llm,memory_key="chat_history",return_messages=True, output_key="answer") | |
| retriever = db.as_retriever(search_type="mmr", search_kwargs={'k': 4, 'fetch_k': 5, 'lambda_mult': 0.25}) | |
| llm_chain = ConversationalRetrievalChain.from_llm(llm, retriever=retriever, memory=memory, | |
| verbose=False, return_source_documents=True) | |
| def blogbot(question, history=None): | |
| # log what questions are asked | |
| logging.info('question: ' + question) | |
| ## do the prompt against the Q&A chain & display the result | |
| result = llm_chain(question) | |
| source_urls = list(set(doc.metadata["source"] for doc in result["source_documents"])) | |
| answer = f"<strong>Answer:</strong><br><br>{result['answer']}<br><br><strong>Sources:</strong><br>" | |
| answer += "<br>".join(f'<a href="{url}" target="_blank">{url}</a>' for url in source_urls) | |
| return answer | |
| gr.ChatInterface(fn=blogbot,chatbot=gr.Chatbot(height=600), | |
| examples=["Is the author biased?", "What his opinion on US?", "what is his investment stratergy?"], | |
| cache_examples=True, | |
| title="Lisa - Sara's Assistant").queue().launch(share=False) |