Spaces:
Runtime error
Runtime error
Zwea Htet commited on
Commit ·
13c5bb4
1
Parent(s): 19f4fce
updated code for llamaCustom
Browse filesFiles changed (5)
3 unmodified lines4567891011121317 unmodified lines3132333435363738393 unmodified linesfrom dotenv import load_dotenvfrom langchain.chains import LLMChainfrom langchain.chat_models import ChatOpenAIfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.prompts import PromptTemplatefrom langchain.vectorstores import FAISSload_dotenv()embeddings = OpenAIEmbeddings()17 unmodified linesif os.path.exists(path=path):return FAISS.load_local(folder_path=path, embeddings=embeddings)else:faiss = FAISS.from_texts("./assets/updated_calregs.txt", embedding=embeddings)faiss.save_local(path)return faiss3 unmodified lines456789101112131415161717 unmodified lines353637383940413 unmodified linesfrom dotenv import load_dotenvfrom langchain.chains import LLMChainfrom langchain.chat_models import ChatOpenAIfrom langchain.document_loaders import PyPDFLoaderfrom langchain.embeddings.openai import OpenAIEmbeddingsfrom langchain.prompts import PromptTemplatefrom langchain.vectorstores import FAISSloader = PyPDFLoader("./assets/pdf/CADWReg.pdf")pages = loader.load_and_split()load_dotenv()embeddings = OpenAIEmbeddings()17 unmodified linesif os.path.exists(path=path):return FAISS.load_local(folder_path=path, embeddings=embeddings)else:faiss = FAISS.from_documents(pages, embeddings)faiss.save_local(path)return faiss
5 unmodified lines678910111213144 unmodified lines1920212223242526272829302 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939423 unmodified lines1181191201211221235 unmodified linesimport numpy as npimport openaiimport pandas as pdfrom dotenv import load_dotenvfrom huggingface_hub import HfFileSystemfrom langchain.llms.base import LLMfrom llama_index import (Document,GPTVectorStoreIndex,4 unmodified linesStorageContext,load_index_from_storage,)from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline# from utils.customLLM import CustomLLMload_dotenv()# openai.api_key = os.getenv("OPENAI_API_KEY")fs = HfFileSystem()# define prompt helper2 unmodified lines# set number of output tokensNUM_OUTPUT = 525# set maximum chunk overlapCHUNK_OVERLAP_RATION = 0.2prompt_helper = PromptHelper(context_window=CONTEXT_WINDOW,num_output=NUM_OUTPUT,chunk_overlap_ratio=CHUNK_OVERLAP_RATION,)llm_model_name = "bigscience/bloom-560m"tokenizer = AutoTokenizer.from_pretrained(llm_model_name)model = AutoModelForCausalLM.from_pretrained(llm_model_name, config="T5Config")model_pipeline = pipeline(model=model,tokenizer=tokenizer,task="text-generation",# device=0, # GPU device number# max_length=512,do_sample=True,top_p=0.95,top_k=50,temperature=0.7,)class CustomLLM(LLM):pipeline = model_pipelinedef _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:prompt_length = len(prompt)response = self.pipeline(prompt, max_new_tokens=525)[0]["generated_text"]# only return newly generated tokensreturn response[prompt_length:]@propertydef _identifying_params(self) -> Mapping[str, Any]:return {"name_of_model": self.model_name}@propertydef _llm_type(self) -> str:return "custom"class LlamaCustom:# define llmllm_predictor = LLMPredictor(llm=CustomLLM())service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor, prompt_helper=prompt_helper)def __init__(self, name: str) -> None:self.vector_index = self.initialize_index(index_name=name)def initialize_index(self, index_name):file_path = f"./vectorStores/{index_name}"if os.path.exists(path=file_path):# rebuild storage contextstorage_context = StorageContext.from_defaults(persist_dir=file_path)23 unmodified linesdef get_response(self, query_str):print("query_str: ", query_str)query_engine = self.vector_index.as_query_engine()response = query_engine.query(query_str)return str(response)5 unmodified lines678910111213144 unmodified lines19202122232425262728293031323334352 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815923 unmodified lines1831841851861871881891901911925 unmodified linesimport numpy as npimport openaiimport pandas as pdimport streamlit as stfrom dotenv import load_dotenvfrom huggingface_hub import HfFileSystem, Repositoryfrom llama_index import (Document,GPTVectorStoreIndex,4 unmodified linesStorageContext,load_index_from_storage,)from llama_index.llms import CompletionResponse, CustomLLM, LLMMetadata# from langchain.llms.base import LLMfrom llama_index.prompts import Promptfrom transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, pipeline# from utils.customLLM import CustomLLMload_dotenv()# openai.api_key = os.getenv("OPENAI_API_KEY")fs = HfFileSystem()# define prompt helper2 unmodified lines# set number of output tokensNUM_OUTPUT = 525# set maximum chunk overlapCHUNK_OVERLAP_RATIO = 0.2prompt_helper = PromptHelper(context_window=CONTEXT_WINDOW,num_output=NUM_OUTPUT,chunk_overlap_ratio=CHUNK_OVERLAP_RATIO,)text_qa_template_str = ("Context information is below.\n""---------------------\n""{context_str}\n""---------------------\n""Using both the context information and also using your own knowledge, ""answer the question: {query_str}\n""If the question is relevant, you can answer by providing the name of the chapter, the article and the title to the answer. In addition, you can add the page number of the document when you found the answer.\n""If the context isn't helpful, you can also answer the question on your own.\n")text_qa_template = Prompt(text_qa_template_str)refine_template_str = ("The original question is as follows: {query_str}\n""We have provided an existing answer: {existing_answer}\n""We have the opportunity to refine the existing answer ""(only if needed) with some more context below.\n""------------\n""{context_msg}\n""------------\n""Using both the new context and your own knowledege, update or repeat the existing answer.\n")refine_template = Prompt(refine_template_str)@st.cache_resourcedef load_model(mode_name: str):# llm_model_name = "bigscience/bloom-560m"tokenizer = AutoTokenizer.from_pretrained(mode_name)model = AutoModelForCausalLM.from_pretrained(mode_name, config="T5Config")pipe = pipeline(task="text-generation",model=model,tokenizer=tokenizer,# device=0, # GPU device number# max_length=512,do_sample=True,top_p=0.95,top_k=50,temperature=0.7,)return pipeclass OurLLM(CustomLLM):def __init__(self, model_name: str, model_pipeline):self.model_name = model_nameself.pipeline = model_pipeline@propertydef metadata(self) -> LLMMetadata:"""Get LLM metadata."""return LLMMetadata(context_window=CONTEXT_WINDOW,num_output=NUM_OUTPUT,model_name=self.model_name,)def complete(self, prompt: str, **kwargs: Any) -> CompletionResponse:prompt_length = len(prompt)response = self.pipeline(prompt, max_new_tokens=NUM_OUTPUT)[0]["generated_text"]# only return newly generated tokenstext = response[prompt_length:]return CompletionResponse(text=text)def stream_complete(self, prompt: str, **kwargs: Any) -> CompletionResponse:raise NotImplementedError()# def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:# prompt_length = len(prompt)# response = self.pipeline(prompt, max_new_tokens=525)[0]["generated_text"]# # only return newly generated tokens# return response[prompt_length:]# @property# def _identifying_params(self) -> Mapping[str, Any]:# return {"name_of_model": self.model_name}# @property# def _llm_type(self) -> str:# return "custom"@st.cache_resourceclass LlamaCustom:# define llm# llm_predictor = LLMPredictor(llm=OurLLM())# service_context = ServiceContext.from_defaults(# llm_predictor=llm_predictor, prompt_helper=prompt_helper# )def __init__(self, model_name: str) -> None:pipe = load_model(mode_name=model_name)llm = OurLLM(model_name=model_name, model_pipeline=pipe)self.service_context = ServiceContext.from_defaults(llm=llm, prompt_helper=prompt_helper)self.vector_index = self.initialize_index(model_name=model_name)def initialize_index(self, model_name: str):index_name = model_name.split("/")[-1]file_path = f"./vectorStores/{index_name}"if os.path.exists(path=file_path):# rebuild storage contextstorage_context = StorageContext.from_defaults(persist_dir=file_path)23 unmodified linesdef get_response(self, query_str):print("query_str: ", query_str)# query_engine = self.vector_index.as_query_engine()query_engine = self.vector_index.as_query_engine(text_qa_template=text_qa_template, refine_template=refine_template)response = query_engine.query(query_str)print("metadata: ", response.metadata)return str(response)
16 unmodified lines1718192021222316 unmodified linesst.info("Enter your openai key to access the chatbot.")else:option = st.selectbox(label="Select your model:", options=("gpt-3.5-turbo", "gpt-4"), index=0)with st.spinner(f"Initializing {option} ..."):16 unmodified lines1718192021222316 unmodified linesst.info("Enter your openai key to access the chatbot.")else:option = st.selectbox(label="Select your model:", options=("gpt-3.5-turbo", "gpt-4"))with st.spinner(f"Initializing {option} ..."):
12345678910115 unmodified lines17181920212223import osimport timeimport openaiimport streamlit as stfrom models.llamaCustom import LlamaCustomfrom utils.chatbox import *st.set_page_config(page_title="Llama", page_icon="🦙")5 unmodified linesif "openai_api_key" not in st.session_state:st.info("Enter your openai key to access the chatbot.")else:with st.spinner("Initializing vector index"):model = LlamaCustom(name="llamaCustom")chatbox("llama_custom", model)123456789105 unmodified lines1617181920212223242526import osimport openaiimport streamlit as stfrom models.llamaCustom import LlamaCustomfrom utils.chatbox import chatboxst.set_page_config(page_title="Llama", page_icon="🦙")5 unmodified linesif "openai_api_key" not in st.session_state:st.info("Enter your openai key to access the chatbot.")else:option = st.selectbox(label="Select your model:", options=("bigscience/bloom-560m",))with st.spinner("Initializing vector index"):model = LlamaCustom(model_name=option)chatbox("llama_custom", model)
39 unmodified lines4041424344454639 unmodified lines{"model_name": model_name, "role": "assistant", "content": full_response})# @st.cache_datadef chatbox(model_name: str, model: None):# Display chat messages from history on app rerunfor message in st.session_state.messages:39 unmodified lines40414243444539 unmodified lines{"model_name": model_name, "role": "assistant", "content": full_response})def chatbox(model_name: str, model: None):# Display chat messages from history on app rerunfor message in st.session_state.messages:
models/langOpen.py+5-3
models/llamaCustom.py+108-39
pages/langchain_demo.py+1-1
pages/llama_custom_demo.py+6-3
utils/chatbox.py-1