Spaces:
Runtime error
Runtime error
Update app.py
Browse files1 unmodified line2345677 unmodified lines151617181920216 unmodified lines2829303132333422 unmodified lines5758596061626364656624 unmodified lines91929394959697989910010110210310410510610710810911020 unmodified lines1311321331341351361371381391401411421431444 unmodified lines1491501511521531541551561571581591601611621631641655 unmodified lines1711721731741751761772 unmodified lines18018118218318418518618718818918 unmodified lines20820921021121221321421521621721821922017 unmodified lines2382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712723 unmodified lines2762772782792802812821 unmodified lineimport randomimport timefrom langchain.chat_models import ChatOpenAIfrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain.vectorstores import Pinecone7 unmodified lines#OPENAI_API_KEY = ""OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")OPENAI_TEMP = 0PINECONE_KEY = os.environ.get("PINECONE_KEY", "")PINECONE_ENV = os.environ.get("PINECONE_ENV", "asia-northeast1-gcp")6 unmodified linesTOP_K_MAX = 25BUTTON_MIN_WIDTH = 180STATUS_NOK = "404-MODEL UNREADY-critical"STATUS_OK = "200-MODEL LOADED-9cf"22 unmodified lines[openai.com](https://platform.openai.com/account/api-keys) and then **{KEY_INIT}**"TAB_1 = "3GPP Chatbot"FAVICON = './icon.svg'webui_title = """# OpenAI Chatbot Based on Vector Database## Example of 3GPP24 unmodified lines#llm = OpenAI(temperature=OPENAI_TEMP, model_name="gpt-3.5-turbo-0301")llm = ChatOpenAI(temperature = OPENAI_TEMP,openai_api_key = api_key)chain = load_qa_chain(llm, chain_type="stuff")db = Pinecone.from_existing_index(index_name = db_index,embedding = embeddings)return api_key, MODEL_DONE, chain, db, Noneelse:return None,MODEL_NULL,None,None,Noneexcept Exception as e:print(e)return None,MODEL_NULL,None,None,Nonedef get_chat_history(inputs) -> str:20 unmodified linesdef user(user_message, history):return "", history+[[user_message, None]]def bot(box_message, ref_message, chain, db, top_k):# bot_message = random.choice(["Yes", "No"])# 0 is user question, 1 is bot responsequestion = box_message[-1][0]history = box_message[:-1]if (not chain) or (not db):box_message[-1][1] = MODEL_WARNINGreturn box_message, "", ""4 unmodified linesdetails = f"Q: {question}\nR: {ref_message}"docs = doc_similarity(ref_message, db, top_k)delta_top_k = top_k - len(docs)if delta_top_k > 0:docs = doc_similarity(ref_message, db, top_k+delta_top_k)all_output = chain({"input_documents": docs,"question": question,"chat_history": get_chat_history(history)})bot_message = all_output['output_text']5 unmodified lines#print(source)box_message[-1][1] = bot_messagereturn box_message, "", [[details, source]]#----------------------------------------------------------------------------------------------------------#----------------------------------------------------------------------------------------------------------2 unmodified linestitle = TAB_1,theme = "Base",css = """.bigbox {min-height:200px;}""") as demo:llm_chain = gr.State()vector_db = gr.State()gr.Markdown(webui_title)gr.HTML(dup_link)18 unmodified lineswith gr.Row():with gr.Column(scale=10):chatbot = gr.Chatbot(elem_classes="bigbox")with gr.Row():with gr.Column(scale=10):query = gr.Textbox(label="Question:",lines=2)ref = gr.Textbox(label="Reference(optional):")with gr.Column(scale=1, min_width=BUTTON_MIN_WIDTH):clear = gr.Button(KEY_CLEAR)submit = gr.Button(KEY_SUBMIT,variant="primary")17 unmodified lineslines=1,interactive=True,type='email')with gr.Row():db_api_textbox = gr.Textbox(label = "Pinecone API Key",# show_label = False,value = PINECONE_KEY,placeholder = "Paste Your Pinecone API Key (xx-xx-xx-xx-xx) and Hit ENTER",lines=1,interactive=True,type='password')with gr.Row():db_env_textbox = gr.Textbox(label = "Pinecone Environment",# show_label = False,value = PINECONE_ENV,placeholder = "Paste Your Pinecone Environment (xx-xx-xx) and Hit ENTER",lines=1,interactive=True,type='email')db_index_textbox = gr.Textbox(label = "Pinecone Index",# show_label = False,value = PINECONE_INDEX,placeholder = "Paste Your Pinecone Index (xxxx) and Hit ENTER",lines=1,interactive=True,type='email')init_input = [llm_api_textbox, emb_textbox, db_api_textbox, db_env_textbox, db_index_textbox]init_output = [llm_api_textbox, model_statusbox, llm_chain, vector_db, chatbot]llm_api_textbox.submit(init_model, init_input, init_output)init.click(init_model, init_input, init_output)3 unmodified lines[query, chatbot],queue=False).then(bot,[chatbot, ref, llm_chain, vector_db, top_k],[chatbot, ref, detail_panel])1 unmodified line234567897 unmodified lines171819202122236 unmodified lines3031323334353622 unmodified lines5960616263646566676869707172737475767724 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114220 unmodified lines1631641651661671681691701711721731741751761771784 unmodified lines1831841851861871881891901911921931941951961971981992002012022032042052062072082092102112125 unmodified lines2182192202212222232242 unmodified lines22722822923023123223323423523623718 unmodified lines25625725825926026126226326426526626726826927027127227327427527627727827928028117 unmodified lines2993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363 unmodified lines3403413423433443453463473481 unmodified lineimport randomimport timefrom langchain import PromptTemplatefrom langchain.llms import OpenAIfrom langchain.chat_models import ChatOpenAIfrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain.vectorstores import Pinecone7 unmodified lines#OPENAI_API_KEY = ""OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")OPENAI_TEMP = 1PINECONE_KEY = os.environ.get("PINECONE_KEY", "")PINECONE_ENV = os.environ.get("PINECONE_ENV", "asia-northeast1-gcp")6 unmodified linesTOP_K_MAX = 25BUTTON_MIN_WIDTH = 205STATUS_NOK = "404-MODEL UNREADY-critical"STATUS_OK = "200-MODEL LOADED-9cf"22 unmodified lines[openai.com](https://platform.openai.com/account/api-keys) and then **{KEY_INIT}**"TAB_1 = "Chatbot"FAVICON = './icon.svg'LLM_LIST = ["gpt-3.5-turbo", "text-davinci-003"]DOC_1 = '3GPP'DOC_2 = 'HTTP2'DOC_SUPPORTED = [DOC_1, DOC_2]DOC_DEFAULT = [DOC_1]webui_title = """# OpenAI Chatbot Based on Vector Database## Example of 3GPP24 unmodified lines#llm = OpenAI(temperature=OPENAI_TEMP, model_name="gpt-3.5-turbo-0301")llm_dict = {}for llm_name in LLM_LIST:if llm_name == "gpt-3.5-turbo":llm_dict[llm_name] = ChatOpenAI(model_name=llm_name,temperature = OPENAI_TEMP,openai_api_key = api_key)else:llm_dict[llm_name] = OpenAI(model_name=llm_name,temperature = OPENAI_TEMP,openai_api_key = api_key)'''ChatOpenAI(model_name="gpt-3.5-turbo",temperature = OPENAI_TEMP,openai_api_key = api_key)chain_1 = load_qa_chain(llm, chain_type="stuff")#LLMChain(llm=llm, prompt=condense_question_prompt)chain_2 = LLMChain(llm = llm,prompt = PromptTemplate(template='{question}',input_variables=['question']),output_key = 'output_text')'''db = Pinecone.from_existing_index(index_name = db_index,embedding = embeddings)return api_key, MODEL_DONE, llm_dict, None, db, Noneelse:return None,MODEL_NULL,None,None,None,Noneexcept Exception as e:print(e)return None,MODEL_NULL,None,None,None,Nonedef get_chat_history(inputs) -> str:20 unmodified linesdef user(user_message, history):return "", history+[[user_message, None]]def bot(box_message, ref_message,llm_dropdown, llm_dict, doc_list,db, top_k):# bot_message = random.choice(["Yes", "No"])# 0 is user question, 1 is bot responsequestion = box_message[-1][0]history = box_message[:-1]if (not llm_dict) or (not doc_check) or (not db):box_message[-1][1] = MODEL_WARNINGreturn box_message, "", ""4 unmodified linesdetails = f"Q: {question}\nR: {ref_message}"llm = llm_dict[llm_dropdown]print(llm)print(doc_list)if DOC_1 in doc_list:chain = load_qa_chain(llm, chain_type="stuff")docs = doc_similarity(ref_message, db, top_k)delta_top_k = top_k - len(docs)if delta_top_k > 0:docs = doc_similarity(ref_message, db, top_k+delta_top_k)else:chain = LLMChain(llm = llm,prompt = PromptTemplate(template='{question}',input_variables=['question']),output_key = 'output_text')docs = []all_output = chain({"input_documents": docs,"question": question,"chat_history": get_chat_history(history)})bot_message = all_output['output_text']5 unmodified lines#print(source)box_message[-1][1] = bot_messagereturn box_message, "", [[details, bot_message + source]]#----------------------------------------------------------------------------------------------------------#----------------------------------------------------------------------------------------------------------2 unmodified linestitle = TAB_1,theme = "Base",css = """.bigbox {min-height:250px;}""") as demo:llm = gr.State()chain_2 = gr.State() # not inusevector_db = gr.State()gr.Markdown(webui_title)gr.HTML(dup_link)18 unmodified lineswith gr.Row():with gr.Column(scale=10):chatbot = gr.Chatbot(elem_classes="bigbox")#with gr.Column(scale=1):with gr.Column(scale=1, min_width=BUTTON_MIN_WIDTH):doc_check = gr.CheckboxGroup(choices = DOC_SUPPORTED,value = DOC_DEFAULT,label = "Reference Docs",interactive=True)llm_dropdown = gr.Dropdown(LLM_LIST,value=LLM_LIST[0],multiselect=False,interactive=True,label="LLM Selection",)with gr.Row():with gr.Column(scale=10):query = gr.Textbox(label="Question:",lines=2)ref = gr.Textbox(label="Reference(optional):")with gr.Column(scale=1, min_width=BUTTON_MIN_WIDTH):clear = gr.Button(KEY_CLEAR)submit = gr.Button(KEY_SUBMIT,variant="primary")17 unmodified lineslines=1,interactive=True,type='email')with gr.Accordion("Pinecone Database for "+DOC_1):with gr.Row():db_api_textbox = gr.Textbox(label = "Pinecone API Key",# show_label = False,value = PINECONE_KEY,placeholder = "Paste Your Pinecone API Key (xx-xx-xx-xx-xx) and Hit ENTER",lines=1,interactive=True,type='password')with gr.Row():db_env_textbox = gr.Textbox(label = "Pinecone Environment",# show_label = False,value = PINECONE_ENV,placeholder = "Paste Your Pinecone Environment (xx-xx-xx) and Hit ENTER",lines=1,interactive=True,type='email')db_index_textbox = gr.Textbox(label = "Pinecone Index",# show_label = False,value = PINECONE_INDEX,placeholder = "Paste Your Pinecone Index (xxxx) and Hit ENTER",lines=1,interactive=True,type='email')init_input = [llm_api_textbox, emb_textbox, db_api_textbox, db_env_textbox, db_index_textbox]init_output = [llm_api_textbox, model_statusbox,llm, chain_2,vector_db, chatbot]llm_api_textbox.submit(init_model, init_input, init_output)init.click(init_model, init_input, init_output)3 unmodified lines[query, chatbot],queue=False).then(bot,[chatbot, ref,llm_dropdown, llm, doc_check,vector_db, top_k],[chatbot, ref, detail_panel])
app.py+116-50