zaephaer23 commited on
Commit
ef07385
1 Parent(s): 00fdf8b

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +145 -0
app.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Simple Chatbot
2
+ @author: Nigel Gebodh
3
+ @email: nigel.gebodh@gmail.com
4
+ """
5
+
6
+ import streamlit as st
7
+ from openai import OpenAI
8
+ import os
9
+ import sys
10
+ from dotenv import load_dotenv, dotenv_values
11
+ load_dotenv()
12
+
13
+ # initialize the client
14
+ client = OpenAI(
15
+ base_url="https://api-inference.huggingface.co/v1",
16
+ api_key = os.environ.get('HUGGINGFACEHUB_API_TOKEN')#"hf_xxx" # Replace with your token
17
+ )
18
+
19
+ #Create supported models
20
+ model_links ={
21
+ "Mistral":"mistralai/Mistral-7B-Instruct-v0.2",
22
+ "Gemma-7B":"google/gemma-7b-it",
23
+ "Zephyr-7B-β":"HuggingFaceH4/zephyr-7b-beta",
24
+ "Mesolitica":"mesolitica/malaysian-llama2-7b-32k-instructions",
25
+
26
+ }
27
+
28
+ #Pull info about the model to display
29
+ model_info ={
30
+ "Mistral":
31
+ {'description':"""The Mistral model is a **Large Language Model (LLM)** that's able to have question and answer interactions.\n \
32
+ \nIt was created by the [**Mistral AI**](https://mistral.ai/news/announcing-mistral-7b/) team as has over **7 billion parameters.** \n""",
33
+ 'logo':'https://mistral.ai/images/logo_hubc88c4ece131b91c7cb753f40e9e1cc5_2589_256x0_resize_q97_h2_lanczos_3.webp'},
34
+ "Gemma-7B":
35
+ {'description':"""The Gemma model is a **Large Language Model (LLM)** that's able to have question and answer interactions.\n \
36
+ \nIt was created by the [**Google's AI Team**](https://blog.google/technology/developers/gemma-open-models/) team as has over **7 billion parameters.** \n""",
37
+ 'logo':'https://pbs.twimg.com/media/GG3sJg7X0AEaNIq.jpg'},
38
+ "Gemma-2B":
39
+ {'description':"""The Gemma model is a **Large Language Model (LLM)** that's able to have question and answer interactions.\n \
40
+ \nIt was created by the [**Google's AI Team**](https://blog.google/technology/developers/gemma-open-models/) team as has over **2 billion parameters.** \n""",
41
+ 'logo':'https://pbs.twimg.com/media/GG3sJg7X0AEaNIq.jpg'},
42
+ "Llama-2":
43
+ {'description':"""Llama 2 is a collection of pretrained and fine-tuned generative text models ranging in scale from 7 billion to 70 billion parameters.\n \
44
+ \nFrom Huggingface: \n\
45
+ [Llama-2](https://huggingface.co/meta-llama/Llama-2-7b)\
46
+ is an auto-regressive language model that uses an optimized transformer architecture. The tuned versions use supervised fine-tuning (SFT) and reinforcement learning with human feedback (RLHF) to align to human preferences for helpfulness and safety. \n""",},
47
+ "Command-R":
48
+ {'description':"""Command-R is a **Large Language Model (LLM)** with open weights optimized for a variety of use cases including reasoning, summarization, and question answering. Command-R has the capability for multilingual generation evaluated in 10 languages and highly performant RAG capabilities.\n \
49
+ \nFrom Huggingface: \n\
50
+ [Command-R](https://huggingface.co/CohereForAI/c4ai-command-r-v01)\
51
+ is a research release of a 35 billion parameter highly performant generative model. \n""",},
52
+ "Zephyr-7B-β":
53
+ {'description':"""The Zephyr model is a **Large Language Model (LLM)** that's able to have question and answer interactions.\n \
54
+ \nFrom Huggingface: \n\
55
+ Zephyr is a series of language models that are trained to act as helpful assistants. \
56
+ [Zephyr-7B-β](https://huggingface.co/HuggingFaceH4/zephyr-7b-beta)\
57
+ is the second model in the series, and is a fine-tuned version of mistralai/Mistral-7B-v0.1 \
58
+ that was trained on on a mix of publicly available, synthetic datasets using Direct Preference Optimization (DPO)\n""",
59
+ 'logo':'https://huggingface.co/HuggingFaceH4/zephyr-7b-alpha/resolve/main/thumbnail.png'},
60
+ "Mesolitica":
61
+ {'description':"""GPT-2 is a transformers model pretrained on a very large corpus of English data in a self-supervised fashion. This means it was pretrained on the raw texts only, with no humans labelling them in any way.\n \
62
+ \nFrom Huggingface: \n\
63
+ This is the smallest version of [GPT-2](https://huggingface.co/openai-community/gpt2)\
64
+ with 124M parameters. \n""",},
65
+ }
66
+
67
+ def reset_conversation():
68
+ '''
69
+ Resets Conversation
70
+ '''
71
+ st.session_state.conversation = []
72
+ st.session_state.messages = []
73
+ return None
74
+
75
+ # Define the available models
76
+ models =[key for key in model_links.keys()]
77
+
78
+ # Create the sidebar with the dropdown for model selection
79
+ selected_model = st.sidebar.selectbox("Select Model", models)
80
+
81
+ #Create a temperature slider
82
+ temp_values = st.sidebar.slider('Select a temperature value', 0.0, 1.0, (0.5))
83
+
84
+ #Add reset button to clear conversation
85
+ st.sidebar.button('Reset Chat', on_click=reset_conversation) #Reset button
86
+
87
+ # Create model description
88
+ st.sidebar.write(f"You're now chatting with **{selected_model}**")
89
+ st.sidebar.markdown(model_info[selected_model]['description'])
90
+ #st.sidebar.image(model_info[selected_model]['logo'])
91
+ st.sidebar.markdown("*Generated content may be inaccurate or false.*")
92
+ #st.sidebar.markdown("\nLearn how to build this chatbot [here](https://ngebodh.github.io/projects/2024-03-05/).")
93
+ #st.sidebar.markdown("\nRun into issues? Try the [back-up](https://huggingface.co/spaces/ngebodh/SimpleChatbot-Backup).")
94
+
95
+ if "prev_option" not in st.session_state:
96
+ st.session_state.prev_option = selected_model
97
+
98
+ if st.session_state.prev_option != selected_model:
99
+ st.session_state.messages = []
100
+ # st.write(f"Changed to {selected_model}")
101
+ st.session_state.prev_option = selected_model
102
+ reset_conversation()
103
+
104
+ #Pull in the model we want to use
105
+ repo_id = model_links[selected_model]
106
+
107
+ st.subheader(f'AI - {selected_model}')
108
+ # st.title(f'ChatBot Using {selected_model}')
109
+
110
+ # Set a default model
111
+ if selected_model not in st.session_state:
112
+ st.session_state[selected_model] = model_links[selected_model]
113
+
114
+ # Initialize chat history
115
+ if "messages" not in st.session_state:
116
+ st.session_state.messages = []
117
+
118
+
119
+ # Display chat messages from history on app rerun
120
+ for message in st.session_state.messages:
121
+ with st.chat_message(message["role"]):
122
+ st.markdown(message["content"])
123
+
124
+ # Accept user input
125
+ if prompt := st.chat_input(f"Hi I'm {selected_model}, ask me a question"):
126
+ # Display user message in chat message container
127
+ with st.chat_message("user"):
128
+ st.markdown(prompt)
129
+ # Add user message to chat history
130
+ st.session_state.messages.append({"role": "user", "content": prompt})
131
+
132
+ # Display assistant response in chat message container
133
+ with st.chat_message("assistant"):
134
+ stream = client.chat.completions.create(
135
+ model=model_links[selected_model],
136
+ messages=[
137
+ {"role": m["role"], "content": m["content"]}
138
+ for m in st.session_state.messages
139
+ ],
140
+ temperature=temp_values,#0.5,
141
+ stream=True,
142
+ max_tokens=3000,
143
+ )
144
+ response = st.write_stream(stream)
145
+ st.session_state.messages.append({"role": "assistant", "content": response})