|
| 1 | +from langchain_community.llms import Ollama |
| 2 | +from langchain_community.document_loaders import PyPDFLoader |
| 3 | +from langchain_community.embeddings import OllamaEmbeddings |
| 4 | +from langchain_community.vectorstores import FAISS |
| 5 | +from langchain_core.prompts import ChatPromptTemplate |
| 6 | +from langchain_text_splitters import RecursiveCharacterTextSplitter |
| 7 | +from langchain.chains.combine_documents import create_stuff_documents_chain |
| 8 | +from langchain.chains import create_retrieval_chain |
| 9 | + |
| 10 | +def create_RAG_model(input_file, llm): |
| 11 | + # Create the LLM (Large Language Model) |
| 12 | + llm = Ollama(model="dolphin-phi") |
| 13 | + # Define model used to embed the info |
| 14 | + embeddings = OllamaEmbeddings(model="nomic-embed-text") |
| 15 | + # Load the PDF |
| 16 | + loader = PyPDFLoader(input_file) |
| 17 | + doc = loader.load() |
| 18 | + # Split the text and embed it into the vector DB |
| 19 | + text_splitter = RecursiveCharacterTextSplitter() |
| 20 | + split = text_splitter.split_documents(doc) |
| 21 | + vector_store = FAISS.from_documents(split, embeddings) |
| 22 | + |
| 23 | + |
| 24 | + # Prompt generation: Giving the LLM character and purpose |
| 25 | + prompt = ChatPromptTemplate.from_template( |
| 26 | + """ |
| 27 | + Answer the following questions only based on the given context |
| 28 | + |
| 29 | + <context> |
| 30 | + {context} |
| 31 | + </context> |
| 32 | + |
| 33 | + Question: {input} |
| 34 | + """ |
| 35 | + ) |
| 36 | + # Linking the LLM, vector DB and the prompt |
| 37 | + docs_chain = create_stuff_documents_chain(llm, prompt) |
| 38 | + retriever = vector_store.as_retriever() |
| 39 | + retrieval_chain = create_retrieval_chain(retriever, docs_chain) |
| 40 | + return retrieval_chain |
| 41 | + |
| 42 | +# Using the retrieval chain |
| 43 | +# Example: |
| 44 | + |
| 45 | +''' |
| 46 | +chain = create_RAG_model("your_file_here.pdf", "mistral") |
| 47 | +output = chain.invoke({"input":"What is the purpose of RAG?"}) |
| 48 | +print(output["answer"]) |
| 49 | +''' |
| 50 | + |
0 commit comments