Nyanfa commited on
Commit
a3b9bb4
·
verified ·
1 Parent(s): 9748e7c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -45
app.py CHANGED
@@ -1,18 +1,19 @@
1
- import cohere
2
  import streamlit as st
3
  from streamlit.components.v1 import html
4
  from streamlit_extras.stylable_container import stylable_container
5
  import re
6
  import urllib.parse
7
 
8
- st.title("Cohere Chat UI")
9
 
10
  if "api_key" not in st.session_state:
11
  api_key = st.text_input("Enter your API Key", type="password")
12
  if api_key:
13
  if api_key.isascii():
14
  st.session_state.api_key = api_key
15
- client = cohere.Client(api_key=api_key)
 
16
  st.rerun()
17
  else:
18
  st.warning("Please enter your API key correctly.")
@@ -21,7 +22,8 @@ if "api_key" not in st.session_state:
21
  st.warning("Please enter your API key to use the app. You can obtain your API key from here: https://dashboard.cohere.com/api-keys")
22
  st.stop()
23
  else:
24
- client = cohere.Client(api_key=st.session_state.api_key)
 
25
 
26
  if "messages" not in st.session_state:
27
  st.session_state.messages = []
@@ -29,21 +31,16 @@ if "messages" not in st.session_state:
29
  def get_ai_response(prompt, chat_history):
30
  st.session_state.is_streaming = True
31
  st.session_state.response = ""
 
 
 
32
 
33
- with st.chat_message("ai", avatar=st.session_state.assistant_avatar):
34
- penalty_kwargs = {
35
- "frequency_penalty" if penalty_type == "Frequency Penalty" else "presence_penalty": penalty_value
36
- }
37
-
38
- stream = client.chat_stream(
39
- message=prompt,
40
- model=model,
41
- preamble=preamble,
42
  chat_history=chat_history,
43
  temperature=temperature,
44
- k=k,
45
- p=p,
46
- **penalty_kwargs
47
  )
48
 
49
  placeholder = st.empty()
@@ -64,9 +61,9 @@ def get_ai_response(prompt, chat_history):
64
 
65
  shown_message = ""
66
 
67
- for event in stream:
68
- if event.event_type == "text-generation":
69
- content = event.text
70
  st.session_state.response += content
71
  shown_message += content.replace("\n", " \n")\
72
  .replace("<", "\\<")\
@@ -90,12 +87,11 @@ inline_pattern = r"`([^`\n]+?)`"
90
 
91
  def display_messages():
92
  for i, message in enumerate(st.session_state.messages):
93
- name = "user" if message["role"] == "USER" else "ai"
94
- avatar = st.session_state.user_avatar if message["role"] == "USER" else st.session_state.assistant_avatar
95
  with st.chat_message(name, avatar=avatar):
96
- shown_message = message["text"].replace("\n", " \n")\
97
- .replace("<", "\\<")\
98
- .replace(">", "\\>")
99
  if "```" in shown_message:
100
  # Replace " \n" with "\n" within code blocks
101
  shown_message = re.sub(code_block_pattern, normalize_code_block, shown_message, flags=re.DOTALL)
@@ -113,7 +109,7 @@ def display_messages():
113
  del st.session_state.messages[i]
114
  st.rerun()
115
  with col3:
116
- text_to_copy = message["text"]
117
  # Encode the string to escape
118
  text_to_copy_escaped = urllib.parse.quote(text_to_copy)
119
 
@@ -141,11 +137,11 @@ def display_messages():
141
 
142
  if "edit_index" in st.session_state and st.session_state.edit_index == i:
143
  with st.form(key=f"edit_form_{i}_{len(st.session_state.messages)}"):
144
- new_content = st.text_area("Edit message", height=200, value=st.session_state.messages[i]["text"])
145
  col1, col2 = st.columns([1, 1])
146
  with col1:
147
  if st.form_submit_button("Save"):
148
- st.session_state.messages[i]["text"] = new_content
149
  del st.session_state.edit_index
150
  st.rerun()
151
  with col2:
@@ -163,12 +159,12 @@ with st.sidebar:
163
  # Copy Conversation History button
164
  log_text = ""
165
  for message in st.session_state.messages:
166
- if message["role"] == "USER":
167
  log_text += "<USER>\n"
168
- log_text += message["text"] + "\n\n"
169
  else:
170
  log_text += "<ASSISTANT>\n"
171
- log_text += message["text"] + "\n\n"
172
  log_text = log_text.rstrip("\n")
173
 
174
  # Encode the string to escape
@@ -202,13 +198,10 @@ with st.sidebar:
202
 
203
  st.header("Advanced Settings")
204
  model = st.selectbox("Model", options=["command-r-plus", "command-r"], index=0)
205
- preamble = st.text_area("Preamble", height=200)
206
  temperature = st.slider("Temperature", min_value=0.0, max_value=1.0, value=0.3, step=0.1)
207
- k = st.slider("Top-K", min_value=0, max_value=500, value=0, step=1)
208
- p = st.slider("Top-P", min_value=0.01, max_value=0.99, value=0.75, step=0.01)
209
- penalty_type = st.selectbox("Penalty Type", options=["Frequency Penalty", "Presence Penalty"])
210
- penalty_value = st.slider("Penalty Value", min_value=0.0, max_value=1.0, value=0.0, step=0.1)
211
-
212
  st.header("Restore History")
213
  history_input = st.text_area("Paste conversation history:", height=200)
214
  if st.button("Restore History"):
@@ -219,13 +212,13 @@ with st.sidebar:
219
  for message in messages:
220
  if message.strip() in ["<USER>", "<ASSISTANT>"]:
221
  if role and text:
222
- st.session_state.messages.append({"role": role, "text": text.strip()})
223
  text = ""
224
- role = "USER" if message.strip() == "<USER>" else "CHATBOT"
225
  else:
226
  text += message
227
  if role and text:
228
- st.session_state.messages.append({"role": role, "text": text.strip()})
229
  st.rerun()
230
 
231
  st.header("Clear History")
@@ -238,7 +231,7 @@ with st.sidebar:
238
  if st.button("Update API Key"):
239
  if new_api_key and new_api_key.isascii():
240
  st.session_state.api_key = new_api_key
241
- client = cohere.Client(api_key=new_api_key)
242
  st.success("API Key updated successfully!")
243
  else:
244
  st.warning("Please enter a valid API Key.")
@@ -267,7 +260,7 @@ with st.sidebar:
267
 
268
  # After Stop generating
269
  if st.session_state.get("is_streaming"):
270
- st.session_state.messages.append({"role": "CHATBOT", "text": st.session_state.response})
271
  st.session_state.is_streaming = False
272
  if "retry_flag" in st.session_state and st.session_state.retry_flag:
273
  st.session_state.retry_flag = False
@@ -311,10 +304,10 @@ display_messages()
311
  # After Retry
312
  if st.session_state.get("retry_flag"):
313
  if len(st.session_state.messages) > 0:
314
- prompt = st.session_state.messages[-1]["text"]
315
  messages = st.session_state.messages[:-1].copy()
316
  response = get_ai_response(prompt, messages)
317
- st.session_state.messages.append({"role": "CHATBOT", "text": response})
318
  st.session_state.retry_flag = False
319
  st.rerun()
320
  else:
@@ -330,9 +323,9 @@ if prompt := st.chat_input("Enter your message here..."):
330
  with st.chat_message("user", avatar=st.session_state.user_avatar):
331
  st.write(shown_message)
332
 
333
- st.session_state.messages.append({"role": "USER", "text": prompt})
334
 
335
  response = get_ai_response(prompt, chat_history)
336
 
337
- st.session_state.messages.append({"role": "CHATBOT", "text": response})
338
  st.rerun()
 
1
+ import openai
2
  import streamlit as st
3
  from streamlit.components.v1 import html
4
  from streamlit_extras.stylable_container import stylable_container
5
  import re
6
  import urllib.parse
7
 
8
+ st.title("Nvidia Chat UI")
9
 
10
  if "api_key" not in st.session_state:
11
  api_key = st.text_input("Enter your API Key", type="password")
12
  if api_key:
13
  if api_key.isascii():
14
  st.session_state.api_key = api_key
15
+ client = openai.OpenAI(base_url = "https://integrate.api.nvidia.com/v1",
16
+ api_key=api_key)
17
  st.rerun()
18
  else:
19
  st.warning("Please enter your API key correctly.")
 
22
  st.warning("Please enter your API key to use the app. You can obtain your API key from here: https://dashboard.cohere.com/api-keys")
23
  st.stop()
24
  else:
25
+ client = openai.OpenAI(base_url = "https://integrate.api.nvidia.com/v1",
26
+ api_key=st.session_state.api_key)
27
 
28
  if "messages" not in st.session_state:
29
  st.session_state.messages = []
 
31
  def get_ai_response(prompt, chat_history):
32
  st.session_state.is_streaming = True
33
  st.session_state.response = ""
34
+
35
+ chat_history.insert({"role": "system", "content": system_prompt})
36
+ chat_history.append({"role": "user", "content": prompt})
37
 
38
+ with st.chat_message("assistant", avatar=st.session_state.assistant_avatar):
39
+ stream = client.chat.completions.create(
40
+ model="nvidia/nemotron-4-340b-instruct",
 
 
 
 
 
 
41
  chat_history=chat_history,
42
  temperature=temperature,
43
+ top_p=top_p,
 
 
44
  )
45
 
46
  placeholder = st.empty()
 
61
 
62
  shown_message = ""
63
 
64
+ for chunk in stream:
65
+ if chunk.choices[0].delta.content is not None:
66
+ content = chunk.choices[0].delta.content
67
  st.session_state.response += content
68
  shown_message += content.replace("\n", " \n")\
69
  .replace("<", "\\<")\
 
87
 
88
  def display_messages():
89
  for i, message in enumerate(st.session_state.messages):
90
+ avatar = st.session_state.user_avatar if message["role"] == "user" else st.session_state.assistant_avatar
 
91
  with st.chat_message(name, avatar=avatar):
92
+ shown_message = message["content"].replace("\n", " \n")\
93
+ .replace("<", "\\<")\
94
+ .replace(">", "\\>")
95
  if "```" in shown_message:
96
  # Replace " \n" with "\n" within code blocks
97
  shown_message = re.sub(code_block_pattern, normalize_code_block, shown_message, flags=re.DOTALL)
 
109
  del st.session_state.messages[i]
110
  st.rerun()
111
  with col3:
112
+ text_to_copy = message["content"]
113
  # Encode the string to escape
114
  text_to_copy_escaped = urllib.parse.quote(text_to_copy)
115
 
 
137
 
138
  if "edit_index" in st.session_state and st.session_state.edit_index == i:
139
  with st.form(key=f"edit_form_{i}_{len(st.session_state.messages)}"):
140
+ new_content = st.text_area("Edit message", height=200, value=st.session_state.messages[i]["content"])
141
  col1, col2 = st.columns([1, 1])
142
  with col1:
143
  if st.form_submit_button("Save"):
144
+ st.session_state.messages[i]["content"] = new_content
145
  del st.session_state.edit_index
146
  st.rerun()
147
  with col2:
 
159
  # Copy Conversation History button
160
  log_text = ""
161
  for message in st.session_state.messages:
162
+ if message["role"] == "user":
163
  log_text += "<USER>\n"
164
+ log_text += message["content"] + "\n\n"
165
  else:
166
  log_text += "<ASSISTANT>\n"
167
+ log_text += message["content"] + "\n\n"
168
  log_text = log_text.rstrip("\n")
169
 
170
  # Encode the string to escape
 
198
 
199
  st.header("Advanced Settings")
200
  model = st.selectbox("Model", options=["command-r-plus", "command-r"], index=0)
201
+ system_prompt = st.text_area("System Prompt", height=200)
202
  temperature = st.slider("Temperature", min_value=0.0, max_value=1.0, value=0.3, step=0.1)
203
+ top_p = st.slider("Top-P", min_value=0.01, max_value=0.99, value=0.75, step=0.01)
204
+
 
 
 
205
  st.header("Restore History")
206
  history_input = st.text_area("Paste conversation history:", height=200)
207
  if st.button("Restore History"):
 
212
  for message in messages:
213
  if message.strip() in ["<USER>", "<ASSISTANT>"]:
214
  if role and text:
215
+ st.session_state.messages.append({"role": role, "content": text.strip()})
216
  text = ""
217
+ role = "user" if message.strip() == "<USER>" else "assistant"
218
  else:
219
  text += message
220
  if role and text:
221
+ st.session_state.messages.append({"role": role, "content": text.strip()})
222
  st.rerun()
223
 
224
  st.header("Clear History")
 
231
  if st.button("Update API Key"):
232
  if new_api_key and new_api_key.isascii():
233
  st.session_state.api_key = new_api_key
234
+ client = openai.OpenAI(api_key=new_api_key)
235
  st.success("API Key updated successfully!")
236
  else:
237
  st.warning("Please enter a valid API Key.")
 
260
 
261
  # After Stop generating
262
  if st.session_state.get("is_streaming"):
263
+ st.session_state.messages.append({"role": "assistant", "content": st.session_state.response})
264
  st.session_state.is_streaming = False
265
  if "retry_flag" in st.session_state and st.session_state.retry_flag:
266
  st.session_state.retry_flag = False
 
304
  # After Retry
305
  if st.session_state.get("retry_flag"):
306
  if len(st.session_state.messages) > 0:
307
+ prompt = st.session_state.messages[-1]["content"]
308
  messages = st.session_state.messages[:-1].copy()
309
  response = get_ai_response(prompt, messages)
310
+ st.session_state.messages.append({"role": "assistant", "content": response})
311
  st.session_state.retry_flag = False
312
  st.rerun()
313
  else:
 
323
  with st.chat_message("user", avatar=st.session_state.user_avatar):
324
  st.write(shown_message)
325
 
326
+ st.session_state.messages.append({"role": "user", "content": prompt})
327
 
328
  response = get_ai_response(prompt, chat_history)
329
 
330
+ st.session_state.messages.append({"role": "assistant", "content": response})
331
  st.rerun()