Spaces:
Build error
Build error
Doux Thibault commited on
Commit ·
9a30a8c
1
Parent(s): 025e412
rag to streamlit + new pdf
Browse filesFiles changed (3)
- Modules/rag.py+28-17
- app.py+15-2
- data/pdf/F12_Strength&Conditioning_Program.pdfAdded+3
8 unmodified lines9101112131415161718192021222324256 unmodified lines3233343536373815 unmodified lines54555657585960616263646566676869707172737475767778791 unmodified line8182838485868 unmodified linesfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.document_loaders import WebBaseLoaderfrom langchain_community.vectorstores import Chroma, FAISSfrom langchain_mistralai import MistralAIEmbeddingsfrom langchain import hubfrom typing import Literalfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.pydantic_v1 import BaseModel, Fieldfrom langchain_mistralai import ChatMistralAIfrom langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddingsfrom langchain_community.tools import DuckDuckGoSearchRundef load_chunk_persist_pdf() -> Chroma:pdf_folder_path = "data/pdf_folder/"documents = []for file in os.listdir(pdf_folder_path):if file.endswith('.pdf'):6 unmodified linesvectorstore = Chroma.from_documents(documents=chunked_documents,embedding=MistralAIEmbeddings(),persist_directory="data/chroma_store/")vectorstore.persist()return vectorstore15 unmodified lines# LLM with function callllm = ChatMistralAI(model="mistral-large-latest", mistral_api_key=mistral_api_key, temperature=0)# structured_llm_router = llm.with_structured_output(RouteQuery, method="json_mode")# Promptsystem = """You are an expert at routing a user question to a vectorstore or web search.The vectorstore contains documents related to agents, prompt engineering, and adversarial attacks.Use the vectorstore for questions on these topics. For all else, use web-search."""route_prompt = ChatPromptTemplate.from_messages([("system", system),("human", "{question}"),])prompt = hub.pull("rlm/rag-prompt")from langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnablePassthroughdef format_docs(docs):return "\n\n".join(doc.page_content for doc in docs)rag_chain = ({"context": retriever | format_docs, "question": RunnablePassthrough()}| prompt1 unmodified line| StrOutputParser())print(rag_chain.invoke("Build a fitness program for me. Be precise in terms of exercises"))# print(rag_chain.invoke("I am a 45 years old woman and I have to loose weight for the summer. Provide me with a fitness program"))8 unmodified lines910111213141516171819202122232425262728293031326 unmodified lines3940414243444515 unmodified lines61626364656667686970717273747576777879808182838485868788891 unmodified line919293949596978 unmodified linesfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.document_loaders import WebBaseLoaderfrom langchain_community.vectorstores import Chroma, FAISSfrom langchain.chains.combine_documents import create_stuff_documents_chainfrom langchain_mistralai import MistralAIEmbeddingsfrom langchain import hubfrom langchain.chains import (create_history_aware_retriever,create_retrieval_chain,)from typing import Literalfrom langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholderfrom langchain_core.pydantic_v1 import BaseModel, Fieldfrom langchain_mistralai import ChatMistralAIfrom langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddingsfrom langchain_community.tools import DuckDuckGoSearchRunfrom pathlib import Pathdef load_chunk_persist_pdf() -> Chroma:pdf_folder_path = os.path.join(os.getcwd(),Path("data/pdf/"))documents = []for file in os.listdir(pdf_folder_path):if file.endswith('.pdf'):6 unmodified linesvectorstore = Chroma.from_documents(documents=chunked_documents,embedding=MistralAIEmbeddings(),persist_directory= os.path.join(os.getcwd(),Path("data/chroma_store/")))vectorstore.persist()return vectorstore15 unmodified lines# LLM with function callllm = ChatMistralAI(model="mistral-large-latest", mistral_api_key=mistral_api_key, temperature=0)prompt = ChatPromptTemplate.from_template("""You are a professional AI coach specialized in fitness, bodybuilding and nutrition.You must adapt to the user : if he is a beginner, use simple words. You are gentle and motivative.Use the following pieces of retrieved context to answer the question.If you don't know the answer, just say that you don't know, and to refer to a nutritionist or a doctor.Use three sentences maximum and keep the answer concise.Question: {question}Context: {context}Answer:""",)from langchain_core.output_parsers import StrOutputParserfrom langchain_core.runnables import RunnablePassthroughdef format_docs(docs):return "\n\n".join(doc.page_content for doc in docs)rag_chain = ({"context": retriever | format_docs, "question": RunnablePassthrough()}| prompt1 unmodified line| StrOutputParser())# print(rag_chain.invoke("Build a fitness program for me. Be precise in terms of exercises"))# print(rag_chain.invoke("I am a 45 years old woman and I have to loose weight for the summer. Provide me with a fitness program"))
5 unmodified lines67891011121329 unmodified lines43444546474849505 unmodified linesfrom dotenv import load_dotenvload_dotenv() # load .env api keysimport osmistral_api_key = os.getenv("MISTRAL_API_KEY")st.set_page_config(layout="wide", initial_sidebar_state="collapsed")# Create two columnscol1, col2 = st.columns(2)29 unmodified lineswith st.chat_message("assistant"):# Build answer from LLMresponse = llm.invoke(st.session_state.messages).contentst.session_state.messages.append({"role": "assistant", "content": response})st.markdown(response)5 unmodified lines678910111213141516171819202122232429 unmodified lines545556575859606162635 unmodified linesfrom dotenv import load_dotenvload_dotenv() # load .env api keysimport osfrom Modules.rag import rag_chainmistral_api_key = os.getenv("MISTRAL_API_KEY")def format_messages(messages):formatted_messages = ""for message in messages:role = message["role"]content = message["content"]formatted_messages += f"{role}: {content}\n"return formatted_messagesst.set_page_config(layout="wide", initial_sidebar_state="collapsed")# Create two columnscol1, col2 = st.columns(2)29 unmodified lineswith st.chat_message("assistant"):# Build answer from LLMresponse = rag_chain.invoke(instruction)print(type(response))st.session_state.messages.append({"role": "assistant", "content": response})st.markdown(response)
123version https://git-lfs.github.com/spec/v1oid sha256:8b6d7c1c04d0a98433e00e4a3ce1586311164a3ac50fc0e14a8fffb65ca7356bsize 17579128Modules/rag.py+28-17
app.py+15-2
data/pdf/F12_Strength&Conditioning_Program.pdfAdded+3