Spaces:
Sleeping
Sleeping
Update app.py
Browse files255 unmodified lines2562572582592602612627 unmodified lines270271272273274275276277278255 unmodified linesst.markdown("Go to this [google colab link](https://colab.research.google.com/drive/1eCpk9HUoCKZb--tiNyQSHFW2ojoaA35m) to get started")if selected_app == "4) Create Chatbot":requirements = '''7 unmodified linesst.write("requirements.txt")st.code(requirements, language='python')app = '''APP.PY'''st.write("app.py")st.code(app, language='python')255 unmodified lines2562572582592602612622637 unmodified lines271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521255 unmodified linesst.markdown("Go to this [google colab link](https://colab.research.google.com/drive/1eCpk9HUoCKZb--tiNyQSHFW2ojoaA35m) to get started")if selected_app == "4) Create Chatbot":num_domains = st.number_input("Number sentences per Q/A pair", value=2, step=1, min_value=1, max_value=3)requirements = '''7 unmodified linesst.write("requirements.txt")st.code(requirements, language='python')app = """import osimport streamlit as stfrom datasets import load_datasetimport chromadbimport stringfrom openai import OpenAIimport numpy as npimport pandas as pdfrom scipy.spatial.distance import cosinefrom typing import Dict, Listdef merge_dataframes(dataframes):# Concatenate the list of dataframescombined_dataframe = pd.concat(dataframes, ignore_index=True)# Ensure that the resulting dataframe only contains the columns "context", "questions", "answers"combined_dataframe = combined_dataframe[['context', 'questions', 'answers']]return combined_dataframedef call_chatgpt(prompt: str, directions: str) -> str:'''Uses the OpenAI API to generate an AI response to a prompt.Args:prompt: A string representing the prompt to send to the OpenAI API.Returns:A string representing the AI's generated response.'''# Use the OpenAI API to generate a response based on the input prompt.client = OpenAI(api_key = os.environ["OPENAI_API_KEY"])completion = client.chat.completions.create(model="gpt-3.5-turbo-0125",messages=[{"role": "system", "content": directions},{"role": "user", "content": prompt}])# Extract the text from the first (and only) choice in the response output.ans = completion.choices[0].message.content# Return the generated AI response.return ansdef openai_text_embedding(prompt: str) -> str:return openai.Embedding.create(input=prompt, model="text-embedding-ada-002")["data"][0]["embedding"]def calculate_sts_openai_score(sentence1: str, sentence2: str) -> float:# Compute sentence embeddingsembedding1 = openai_text_embedding(sentence1) # Flatten the embedding arrayembedding2 = openai_text_embedding(sentence2) # Flatten the embedding array# Convert to arrayembedding1 = np.asarray(embedding1)embedding2 = np.asarray(embedding2)# Calculate cosine similarity between the embeddingssimilarity_score = 1 - cosine(embedding1, embedding2)return similarity_scoredef add_dist_score_column(dataframe: pd.DataFrame, sentence: str,) -> pd.DataFrame:dataframe["stsopenai"] = dataframe["questions"].apply(lambda x: calculate_sts_openai_score(str(x), sentence))sorted_dataframe = dataframe.sort_values(by="stsopenai", ascending=False)return sorted_dataframe.iloc[:5, :]def convert_to_list_of_dict(df: pd.DataFrame) -> List[Dict[str, str]]:'''Reads in a pandas DataFrame and produces a list of dictionaries with two keys each, 'question' and 'answer.'Args:df: A pandas DataFrame with columns named 'questions' and 'answers'.Returns:A list of dictionaries, with each dictionary containing a 'question' and 'answer' key-value pair.'''# Initialize an empty list to store the dictionariesresult = []# Loop through each row of the DataFramefor index, row in df.iterrows():# Create a dictionary with the current question and answerqa_dict_quest = {"role": "user", "content": row["questions"]}qa_dict_ans = {"role": "assistant", "content": row["answers"]}# Add the dictionary to the result listresult.append(qa_dict_quest)result.append(qa_dict_ans)# Return the list of dictionariesreturn resultst.sidebar.markdown(f'''This is a chatbot to help you learn more about {organization_name}''')domain = st.sidebar.selectbox(f"Select a topic", {domains})special_threshold = 0.3n_results = 3clear_button = st.sidebar.button("Clear Conversation", key="clear")if clear_button:st.session_state.messages = []st.session_state.curr_domain = ""######### Load the dataset from a provided source.######initial_input = f"Tell me about {organization_name}"# Initialize a new client for ChromeDB.client = chromadb.Client()# Generate a random number between 1 billion and 10 billion.random_number: int = np.random.randint(low=1e9, high=1e10)# Generate a random string consisting of 10 uppercase letters and digits.random_string: str = "".join(np.random.choice(list(string.ascii_uppercase + string.digits), size=10))# Combine the random number and random string into one identifier.combined_string: str = f"{random_number}{random_string}"# Create a new collection in ChromeDB with the combined string as its name.collection = client.create_collection(combined_string)st.title(f"{organization_name} Chatbot")# Initialize chat historyif "messages" not in st.session_state:st.session_state.messages = []if "curr_domain" not in st.session_state:st.session_state.curr_domain = ""######### init_messages dict (one key per domain)############### chatbot_instructions dict (one key per domain)####### Embed and store the first N supports for this demowith st.spinner("Loading, please be patient with us ... 🙏"):L = len(dataset["train"]["questions"])collection.add(ids=[str(i) for i in range(0, L)], # IDs are just stringsdocuments=dataset["train"]["questions"], # Enter questions heremetadatas=[{"type": "support"} for _ in range(0, L)],)if st.session_state.curr_domain != domain:st.session_state.messages = []init_message = init_messages[domain]st.session_state.messages.append({"role": "assistant", "content": init_message})st.session_state.curr_domain = domain# Display chat messages from history on app rerunfor message in st.session_state.messages:with st.chat_message(message["role"]):st.markdown(message["content"])# React to user inputif prompt := st.chat_input(f"Tell me about {organization_name"):# Display user message in chat message containerst.chat_message("user").markdown(prompt)# Add user message to chat historyst.session_state.messages.append({"role": "user", "content": prompt})question = promptresults = collection.query(query_texts=question, n_results=n_results)idx = results["ids"][0]idx = [int(i) for i in idx]ref = pd.DataFrame({"idx": idx,"questions": [dataset["train"]["questions"][i] for i in idx],"answers": [dataset["train"]["answers"][i] for i in idx],"distances": results["distances"][0],})# special_threshold = st.sidebar.slider('How old are you?', 0, 0.6, 0.1) # 0.3# special_threshold = 0.3filtered_ref = ref[ref["distances"] < special_threshold]if filtered_ref.shape[0] > 0:# st.success("There are highly relevant information in our database.")ref_from_db_search = filtered_ref["answers"].str.cat(sep=" ")final_ref = filtered_refelse:# st.warning(# "The database may not have relevant information to help your question so please be aware of hallucinations."# )ref_from_db_search = ref["answers"].str.cat(sep=" ")final_ref = refengineered_prompt = f'''Based on the context: {ref_from_db_search},answer the user question: {question}.'''directions = chatbot_instructions[domain]answer = call_chatgpt(engineered_prompt, directions)response = answer# Display assistant response in chat message containerwith st.chat_message("assistant"):st.markdown(response)with st.expander("See reference:"):st.table(final_ref)# Add assistant response to chat historyst.session_state.messages.append({"role": "assistant", "content": response})"""st.write("app.py")st.code(app, language='python')
app.py+247-4