pantadeusz commited on
Commit
ee67144
·
1 Parent(s): f5adb6e

first rude chat

Browse files
Files changed (2) hide show
  1. app.py +177 -0
  2. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain_huggingface import HuggingFaceEndpoint
3
+ import streamlit as st
4
+ model_id="mistralai/Mistral-7B-Instruct-v0.3"
5
+ def get_llm_hf_inference(model_id=model_id, max_new_tokens=128, temperature=0.1):
6
+ """
7
+ Returns a language model for HuggingFace inference.
8
+
9
+ Parameters:
10
+ - model_id (str): The ID of the HuggingFace model repository.
11
+ - max_new_tokens (int): The maximum number of new tokens to generate.
12
+ - temperature (float): The temperature for sampling from the model.
13
+
14
+ Returns:
15
+ - llm (HuggingFaceEndpoint): The language model for HuggingFace inference.
16
+ """
17
+ llm = HuggingFaceEndpoint(
18
+ repo_id=model_id,
19
+ max_new_tokens=max_new_tokens,
20
+ temperature=temperature,
21
+ token = os.getenv("HF_TOKEN")
22
+ )
23
+ return llm
24
+
25
+ import streamlit as st
26
+
27
+ # Configure the Streamlit app
28
+ st.set_page_config(page_title="Tadeusz ChatBot", page_icon="🤖", layout="wide")
29
+ st.title("Personal (Free) HuggingFace ChatBot")
30
+ st.markdown("*This is a simple chatbot that uses the HuggingFace transformers library to generate responses to your text input. It uses the meta-llama/Meta-Llama-3.1-8B-Instruct.*")
31
+
32
+
33
+ # Initialize session state for avatars
34
+ if "avatars" not in st.session_state:
35
+ st.session_state.avatars = {'user': None, 'assistant': None}
36
+
37
+ # Initialize session state for user text input
38
+ if 'user_text' not in st.session_state:
39
+ st.session_state.user_text = None
40
+
41
+ # Initialize session state for model parameters
42
+ if "max_response_length" not in st.session_state:
43
+ st.session_state.max_response_length = 128
44
+
45
+ if "system_message" not in st.session_state:
46
+ st.session_state.system_message = "rude AI conversing with a human user"
47
+
48
+ if "starter_message" not in st.session_state:
49
+ st.session_state.starter_message = "What?"
50
+
51
+ # Sidebar for settings
52
+ with st.sidebar:
53
+ st.header("System Settings")
54
+
55
+ # AI Settings
56
+ st.session_state.system_message = st.text_input(
57
+ "System Message", value="rude AI conversing with a human user"
58
+ )
59
+ st.session_state.starter_message = st.text_area(
60
+ 'First AI Message', value="What"
61
+ )
62
+
63
+ # Model Settings
64
+ st.session_state.max_response_length = st.number_input(
65
+ "Max Response Length", value=128
66
+ )
67
+
68
+ # Avatar Selection
69
+ st.markdown("*Select Avatars:*")
70
+ col1, col2 = st.columns(2)
71
+ with col1:
72
+ st.session_state.avatars['assistant'] = st.selectbox(
73
+ "AI Avatar", options=["🤗", "💬", "🤖"], index=0
74
+ )
75
+ with col2:
76
+ st.session_state.avatars['user'] = st.selectbox(
77
+ "User Avatar", options=["👤", "👱", "👨🏾", "👩", "👧🏾"], index=0
78
+ )
79
+
80
+ # Reset Chat History
81
+ reset_history = st.button("Reset Chat History")
82
+
83
+ # Initialize or reset chat history
84
+ if "chat_history" not in st.session_state or reset_history:
85
+ st.session_state.chat_history = [{"role": "assistant", "content": st.session_state.starter_message}]
86
+
87
+ from langchain_core.prompts import PromptTemplate
88
+ from langchain_core.output_parsers import StrOutputParser
89
+
90
+ def get_response(system_message, chat_history, user_text,
91
+ eos_token_id=['User'], max_new_tokens=256, get_llm_hf_kws={}):
92
+ """
93
+ Generates a response from the chatbot model.
94
+
95
+ Args:
96
+ system_message (str): The system message for the conversation.
97
+ chat_history (list): The list of previous chat messages.
98
+ user_text (str): The user's input text.
99
+ model_id (str, optional): The ID of the HuggingFace model to use.
100
+ eos_token_id (list, optional): The list of end-of-sentence token IDs.
101
+ max_new_tokens (int, optional): The maximum number of new tokens to generate.
102
+ get_llm_hf_kws (dict, optional): Additional keyword arguments for the get_llm_hf function.
103
+
104
+ Returns:
105
+ tuple: A tuple containing the generated response and the updated chat history.
106
+ """
107
+ # Set up the model
108
+ hf = get_llm_hf_inference(max_new_tokens=max_new_tokens, temperature=0.1)
109
+
110
+ # Create the prompt template
111
+ prompt = PromptTemplate.from_template(
112
+ (
113
+ "[INST] {system_message}"
114
+ "\nCurrent Conversation:\n{chat_history}\n\n"
115
+ "\nUser: {user_text}.\n [/INST]"
116
+ "\nAI:"
117
+ )
118
+ )
119
+
120
+ # Make the chain and bind the prompt
121
+ chat = prompt | hf.bind(skip_prompt=True) | StrOutputParser(output_key='content')
122
+
123
+ # Generate the response
124
+ response = chat.invoke(
125
+ input=dict(system_message=system_message,
126
+ user_text=user_text,
127
+ chat_history=chat_history)
128
+ )
129
+ # Only keep the newly generated response
130
+ response = response.split("AI:")[-1]
131
+
132
+ # Update the chat history
133
+ chat_history.append({'role': 'user', 'content': user_text})
134
+ chat_history.append({'role': 'assistant', 'content': response})
135
+ return response, chat_history
136
+
137
+ # Container for chat messages
138
+ chat_interface = st.container(border=True)
139
+ with chat_interface:
140
+ output_container = st.container()
141
+ st.session_state.user_text = st.chat_input(placeholder="Enter your text here.")
142
+
143
+ # Display chat messages
144
+ with output_container:
145
+ # For every message in the history
146
+ for message in st.session_state.chat_history:
147
+ # Skip the system message
148
+ if message['role'] == 'system':
149
+ continue
150
+
151
+ # Display the chat message using the correct avatar
152
+ with st.chat_message(message['role'],
153
+ avatar=st.session_state['avatars'][message['role']]):
154
+ st.markdown(message['content'])
155
+
156
+ # When the user enter new text:
157
+ if st.session_state.user_text:
158
+
159
+ # Display the user's new message immediately
160
+ with st.chat_message("user",
161
+ avatar=st.session_state.avatars['user']):
162
+ st.markdown(st.session_state.user_text)
163
+
164
+ # Display a spinner status bar while waiting for the response
165
+ with st.chat_message("assistant",
166
+ avatar=st.session_state.avatars['assistant']):
167
+ with st.spinner("Thinking..."):
168
+
169
+ # Call the Inference API with the system_prompt, user text, and history
170
+ response, st.session_state.chat_history = get_response(
171
+ system_message=st.session_state.system_message,
172
+ user_text=st.session_state.user_text,
173
+ chat_history=st.session_state.chat_history,
174
+ max_new_tokens=st.session_state.max_response_length,
175
+ )
176
+ st.markdown(response)
177
+ # public-chat-interface
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers
2
+ huggingface_hub
3
+ streamlit
4
+ langchain_core
5
+ langchain_community
6
+ langchain_huggingface
7
+ langchain_text_splitters
8
+ accelerate
9
+ watchdog
10
+ tqdm