|
| 1 | +# |
| 2 | +# This one is to be used in Notebooks |
| 3 | +# |
| 4 | + |
| 5 | +# for pdf post processing |
| 6 | +import re |
| 7 | + |
| 8 | +import cohere |
| 9 | +# modified to load from Pdf |
| 10 | +from langchain.document_loaders import PyPDFLoader |
| 11 | +from langchain.text_splitter import RecursiveCharacterTextSplitter |
| 12 | + |
| 13 | +# two possible vector store |
| 14 | +from langchain.vectorstores import Chroma |
| 15 | +from langchain.vectorstores import FAISS |
| 16 | + |
| 17 | +from langchain.schema.runnable import RunnablePassthrough |
| 18 | + |
| 19 | +# removed OpenAI, using Cohere embeddings |
| 20 | +from langchain.embeddings import CohereEmbeddings |
| 21 | +from langchain.embeddings import HuggingFaceEmbeddings |
| 22 | + |
| 23 | +from langchain import hub |
| 24 | + |
| 25 | +import oci |
| 26 | + |
| 27 | +from langchain.llms import Cohere |
| 28 | +from langchain_community.llms.oci_generative_ai import OCIGenAI |
| 29 | +from oci.generative_ai_inference import generative_ai_inference_client |
| 30 | + |
| 31 | +# oci_llm is in a local file |
| 32 | +from oci_llm import OCIGenAILLM |
| 33 | + |
| 34 | +# config for the RAG |
| 35 | +from config_rag import ( |
| 36 | + BOOK_LIST, |
| 37 | + CHUNK_SIZE, |
| 38 | + CHUNK_OVERLAP, |
| 39 | + VECTOR_STORE_NAME, |
| 40 | + MAX_TOKENS, |
| 41 | + ENDPOINT, |
| 42 | + EMBED_TYPE, |
| 43 | + MAX_DOCS_RETRIEVED, |
| 44 | + TEMPERATURE, |
| 45 | + EMBED_HF_MODEL_NAME, |
| 46 | + TIMEOUT, |
| 47 | + LLM_TYPE, |
| 48 | +) |
| 49 | + |
| 50 | +# private configs |
| 51 | +CONFIG_PROFILE = "DEFAULT" |
| 52 | +COMPARTMENT_OCID = "ocid1.compartment.oc1..aaaaaaaajdyhd7dqnix2avhlckbhhkkcl3cujzyuz6jzyzonadca3i66pqjq" |
| 53 | +oci_config = oci.config.from_file("~/.oci/config", CONFIG_PROFILE) |
| 54 | +COHERE_API_KEY = oci_config['security_token_file'] |
| 55 | +DEBUG = True |
| 56 | + |
| 57 | + |
| 58 | +# |
| 59 | +# def load_oci_config() |
| 60 | +# |
| 61 | +def load_oci_config(): |
| 62 | + # read OCI config to connect to OCI with API key |
| 63 | + oci_config = oci.config.from_file("~/.oci/config", CONFIG_PROFILE) |
| 64 | + |
| 65 | + # check the config to access to api keys |
| 66 | + if DEBUG: |
| 67 | + print(oci_config) |
| 68 | + |
| 69 | + return oci_config |
| 70 | + |
| 71 | + |
| 72 | +# |
| 73 | +# do some post processing on text |
| 74 | +# |
| 75 | +def post_process(splits): |
| 76 | + for split in splits: |
| 77 | + split.page_content = split.page_content.replace("\n", " ") |
| 78 | + split.page_content = re.sub("[^a-zA-Z0-9 \n\.]", " ", split.page_content) |
| 79 | + # remove duplicate blank |
| 80 | + split.page_content = " ".join(split.page_content.split()) |
| 81 | + |
| 82 | + return splits |
| 83 | + |
| 84 | + |
| 85 | +# |
| 86 | +# def: Initialize_rag_chain |
| 87 | +# |
| 88 | +def initialize_rag_chain(): |
| 89 | + # Initialize RAG |
| 90 | + |
| 91 | + # Loading a list of pdf documents |
| 92 | + all_pages = [] |
| 93 | + |
| 94 | + # modified to load a list of pdf |
| 95 | + for book in BOOK_LIST: |
| 96 | + print(f"Loading book: {book}...") |
| 97 | + loader = PyPDFLoader(book) |
| 98 | + |
| 99 | + # loader split in pages |
| 100 | + pages = loader.load() |
| 101 | + print(f"Loaded {len(pages)} pages...") |
| 102 | + |
| 103 | + all_pages.extend(pages) |
| 104 | + |
| 105 | + print("PDF document loaded!") |
| 106 | + |
| 107 | + # This split in chunks |
| 108 | + # try with smaller chuncks |
| 109 | + text_splitter = RecursiveCharacterTextSplitter( |
| 110 | + chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP |
| 111 | + ) |
| 112 | + |
| 113 | + splits = text_splitter.split_documents(all_pages) |
| 114 | + |
| 115 | + print(f"We have splitted the pdf in {len(splits)} splits...") |
| 116 | + |
| 117 | + # some post processing |
| 118 | + splits = post_process(splits) |
| 119 | + |
| 120 | + print("Initializing vector store...") |
| 121 | + |
| 122 | + if EMBED_TYPE == "COHERE": |
| 123 | + print("Loading Cohere Embeddings Model...") |
| 124 | + embed_model = CohereEmbeddings(cohere_api_key=COHERE_API_KEY) |
| 125 | + if EMBED_TYPE == "LOCAL": |
| 126 | + print(f"Loading HF Embeddings Model: {EMBED_HF_MODEL_NAME}") |
| 127 | + |
| 128 | + model_kwargs = {"device": "cpu"} |
| 129 | + # changed to True for BAAI, to use cosine similarity |
| 130 | + encode_kwargs = {"normalize_embeddings": True} |
| 131 | + |
| 132 | + embed_model = HuggingFaceEmbeddings( |
| 133 | + model_name=EMBED_HF_MODEL_NAME, |
| 134 | + model_kwargs=model_kwargs, |
| 135 | + encode_kwargs=encode_kwargs, |
| 136 | + ) |
| 137 | + |
| 138 | + # using Chroma as Vector store |
| 139 | + print(f"Indexing: using {VECTOR_STORE_NAME} as Vector Store...") |
| 140 | + |
| 141 | + if VECTOR_STORE_NAME == "CHROME": |
| 142 | + vectorstore = Chroma.from_documents(documents=splits, embedding=embed_model) |
| 143 | + if VECTOR_STORE_NAME == "FAISS": |
| 144 | + vectorstore = FAISS.from_documents(documents=splits, embedding=embed_model) |
| 145 | + |
| 146 | + # increased num. of docs to 5 (default to 4) |
| 147 | + retriever = vectorstore.as_retriever(search_kwargs={"k": MAX_DOCS_RETRIEVED}) |
| 148 | + |
| 149 | + # Build the class for OCI GenAI |
| 150 | + |
| 151 | + # Only needed for OCI LLM |
| 152 | + print(f"Using {LLM_TYPE} llm...") |
| 153 | + |
| 154 | + if LLM_TYPE == "OCI": |
| 155 | + |
| 156 | + llm = OCIGenAI( |
| 157 | + service_endpoint="https://inference.generativeai.us-chicago-1.oci.oraclecloud.com", |
| 158 | + compartment_id="ocid1.compartment.oc1..aaaaaaaajdyhd7dqnix2avhlckbhhkkcl3cujzyuz6jzyzonadca3i66pqjq", |
| 159 | + model_kwargs={"max_tokens": 1000}, |
| 160 | + auth_type='SECURITY_TOKEN', |
| 161 | + ) |
| 162 | + if LLM_TYPE == "COHERE": |
| 163 | + llm = cohere.Client(COHERE_API_KEY) |
| 164 | + response = llm.generate( |
| 165 | + prompt="Please explain to me how LLMs work", |
| 166 | + ) |
| 167 | + print(response) |
| 168 | + return llm |
| 169 | + |
| 170 | + # for now hard coded... |
| 171 | + rag_prompt = hub.pull("rlm/rag-prompt") |
| 172 | + |
| 173 | + print("Building rag_chain...") |
| 174 | + rag_chain = ( |
| 175 | + {"context": retriever, "question": RunnablePassthrough()} | rag_prompt | llm |
| 176 | + ) |
| 177 | + |
| 178 | + print("Init RAG complete...") |
| 179 | + return rag_chain |
| 180 | + |
| 181 | + |
| 182 | +# |
| 183 | +# def: get_answer from LLM |
| 184 | +# |
| 185 | +def get_answer(rag_chain, question): |
| 186 | + response = rag_chain.invoke(question) |
| 187 | + |
| 188 | + print(f"Question: {question}") |
| 189 | + print("The response:") |
| 190 | + print(response) |
| 191 | + print() |
| 192 | + |
| 193 | + return response |
0 commit comments