Yescia commited on
Commit
4720161
Β·
verified Β·
1 Parent(s): 8681b54

Update app.py

Browse files

system comparison function added

Files changed (1) hide show
  1. app.py +64 -73
app.py CHANGED
@@ -4,22 +4,29 @@ import json
4
  from io import StringIO
5
  from datetime import datetime
6
  import requests
7
- import sseclient # for streaming response
8
 
9
- st.set_page_config(page_title="Solar Chat", page_icon="🌞")
10
- st.title("🌞 Chat with your own System Prompt")
11
 
12
- # --- User Input ---
13
  api_key = st.text_input("πŸ”‘ Upstage API Key (starts with 'up_')", type="password")
14
- system_prompt = st.text_area("🧠 System Prompt", "You are a helpful assistant.", height=100)
15
  user_input = st.text_input("πŸ’¬ Your Message", "")
16
 
17
- # --- Session state Reset ---
18
- if "messages" not in st.session_state or st.session_state.system_prompt != system_prompt:
19
- st.session_state.messages = [{"role": "system", "content": system_prompt}]
20
- st.session_state.system_prompt = system_prompt
21
 
22
- # --- Solar Pro API call function ---
 
 
 
 
 
 
 
 
 
 
23
  def solar_pro_chat(messages, api_key):
24
  url = "https://api.upstage.ai/v1/chat/completions"
25
  headers = {
@@ -30,84 +37,59 @@ def solar_pro_chat(messages, api_key):
30
  payload = {
31
  "model": "solar-pro",
32
  "messages": messages,
33
- "stream": True # SSE 방식 ν™œμ„±ν™”
34
  }
35
 
36
  try:
37
  response = requests.post(url, headers=headers, json=payload, stream=True)
38
- response.raise_for_status() # HTTP μ—λŸ¬ λ°œμƒ μ‹œ μ˜ˆμ™Έ λ°œμƒ
39
-
40
  client = sseclient.SSEClient(response)
41
- full_reply = ""
42
-
43
  for event in client.events():
44
  if event.data == "[DONE]":
45
  break
46
  try:
47
  content = json.loads(event.data)["choices"][0]["delta"].get("content", "")
48
- full_reply += content
49
  yield content
50
  except Exception as e:
51
- st.error("⚠️ 응닡 처리 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. 둜그λ₯Ό ν™•μΈν•˜μ„Έμš”.")
52
  print(f"[SSE νŒŒμ‹± 였λ₯˜] {e}")
53
  continue
54
-
55
  except requests.exceptions.RequestException as e:
56
- st.error("❌ API 호좜 쀑 λ¬Έμ œκ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€. API ν‚€λ₯Ό ν™•μΈν•˜κ±°λ‚˜ λ„€νŠΈμ›Œν¬ μƒνƒœλ₯Ό μ κ²€ν•΄μ£Όμ„Έμš”.")
57
  print(f"[API μš”μ²­ 였λ₯˜] {e}")
58
  return
59
 
60
- # SSE streaming
61
- response = requests.post(url, headers=headers, json=payload, stream=True)
62
- client = sseclient.SSEClient(response)
63
- full_reply = ""
64
- for event in client.events():
65
- if event.data == "[DONE]":
66
- break
67
- try:
68
- content = eval(event.data)["choices"][0]["delta"].get("content", "")
69
- full_reply += content
70
- yield content
71
- except Exception:
72
- continue
73
- return full_reply
74
 
75
- # --- Send Messages ---
76
- if st.button("Send") and api_key and user_input:
77
- st.session_state.messages.append({"role": "user", "content": user_input})
78
- with st.spinner("Generating response..."):
79
- response_text = ""
80
- response_area = st.empty()
81
- for chunk in solar_pro_chat(st.session_state.messages, api_key):
82
- response_text += chunk
83
- response_area.markdown(f"**πŸ€– Bot:** {response_text}")
84
- st.session_state.messages.append({"role": "assistant", "content": response_text})
85
 
86
- # --- Chat history in bubbles ---
87
- def render_message(role, content):
88
- if role == "user":
89
- st.markdown(f"""
90
- <div style='background-color:#DCF8C6; padding:10px 15px; border-radius:10px; margin:5px 0; text-align:right;'>
91
- <b>You:</b> {content}
92
- </div>
93
- """, unsafe_allow_html=True)
94
- elif role == "assistant":
95
- st.markdown(f"""
96
- <div style='background-color:#F1F0F0; padding:10px 15px; border-radius:10px; margin:5px 0; text-align:left;'>
97
- <b>Bot:</b> {content}
98
- </div>
99
- """, unsafe_allow_html=True)
100
 
101
- st.markdown("### πŸ—‚οΈ Chat History")
102
- for msg in st.session_state.messages:
103
- if msg["role"] != "system":
104
- render_message(msg["role"], msg["content"])
 
 
 
 
 
105
 
106
- # --- CSV Download Function ---
107
- def generate_csv():
108
- rows = []
109
- rows.append({"role": "system", "content": st.session_state.system_prompt})
110
- for msg in st.session_state.messages:
111
  if msg["role"] != "system":
112
  rows.append(msg)
113
  df = pd.DataFrame(rows)
@@ -116,11 +98,20 @@ def generate_csv():
116
  return output.getvalue()
117
 
118
  now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
119
- filename = f"solar_chat_{now}.csv"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
- st.download_button(
122
- label="⬇️ Download Chat History as CSV",
123
- data=generate_csv(),
124
- file_name=filename,
125
- mime="text/csv",
126
- )
 
4
  from io import StringIO
5
  from datetime import datetime
6
  import requests
7
+ import sseclient
8
 
9
+ st.set_page_config(page_title="Solar Prompt Comparator", page_icon="🌞")
10
+ st.title("🌞 System Prompt Comparison Chat")
11
 
12
+ # --- Input UI ---
13
  api_key = st.text_input("πŸ”‘ Upstage API Key (starts with 'up_')", type="password")
 
14
  user_input = st.text_input("πŸ’¬ Your Message", "")
15
 
16
+ st.markdown("### 🧠 Custom System Prompt")
17
+ custom_prompt = st.text_area("μ‚¬μš©μž μ •μ˜ μ‹œμŠ€ν…œ ν”„λ‘¬ν”„νŠΈ", "You are a helpful assistant.", height=100)
 
 
18
 
19
+ # --- Default prompt μ„€μ • ---
20
+ default_prompt = "You are a helpful assistant."
21
+
22
+ # --- μ„Έμ…˜ μ΄ˆκΈ°ν™” ---
23
+ if "default_messages" not in st.session_state:
24
+ st.session_state.default_messages = [{"role": "system", "content": default_prompt}]
25
+ if "custom_messages" not in st.session_state or st.session_state.custom_prompt != custom_prompt:
26
+ st.session_state.custom_messages = [{"role": "system", "content": custom_prompt}]
27
+ st.session_state.custom_prompt = custom_prompt
28
+
29
+ # --- Solar Pro API 호좜 ν•¨μˆ˜ ---
30
  def solar_pro_chat(messages, api_key):
31
  url = "https://api.upstage.ai/v1/chat/completions"
32
  headers = {
 
37
  payload = {
38
  "model": "solar-pro",
39
  "messages": messages,
40
+ "stream": True
41
  }
42
 
43
  try:
44
  response = requests.post(url, headers=headers, json=payload, stream=True)
45
+ response.raise_for_status()
 
46
  client = sseclient.SSEClient(response)
 
 
47
  for event in client.events():
48
  if event.data == "[DONE]":
49
  break
50
  try:
51
  content = json.loads(event.data)["choices"][0]["delta"].get("content", "")
 
52
  yield content
53
  except Exception as e:
54
+ st.error("⚠️ 응닡 처리 쀑 였λ₯˜κ°€ λ°œμƒν–ˆμŠ΅λ‹ˆλ‹€.")
55
  print(f"[SSE νŒŒμ‹± 였λ₯˜] {e}")
56
  continue
 
57
  except requests.exceptions.RequestException as e:
58
+ st.error("❌ API 호좜 μ‹€νŒ¨: API ν‚€ λ˜λŠ” λ„€νŠΈμ›Œν¬ μƒνƒœ 확인")
59
  print(f"[API μš”μ²­ 였λ₯˜] {e}")
60
  return
61
 
62
+ # --- λΉ„κ΅μš© 응닡 처리 ---
63
+ if st.button("πŸš€ Compare Responses") and api_key and user_input:
64
+ st.session_state.default_messages.append({"role": "user", "content": user_input})
65
+ st.session_state.custom_messages.append({"role": "user", "content": user_input})
 
 
 
 
 
 
 
 
 
 
66
 
67
+ col1, col2 = st.columns(2)
 
 
 
 
 
 
 
 
 
68
 
69
+ with col1:
70
+ st.subheader("πŸ”Ή Default Prompt")
71
+ default_response = ""
72
+ default_area = st.empty()
73
+ with st.spinner("Default 응닡 생성 쀑..."):
74
+ for chunk in solar_pro_chat(st.session_state.default_messages, api_key):
75
+ default_response += chunk
76
+ default_area.markdown(f"**πŸ€– Bot:** {default_response}")
77
+ st.session_state.default_messages.append({"role": "assistant", "content": default_response})
 
 
 
 
 
78
 
79
+ with col2:
80
+ st.subheader("πŸ”Έ Custom Prompt")
81
+ custom_response = ""
82
+ custom_area = st.empty()
83
+ with st.spinner("Custom 응닡 생성 쀑..."):
84
+ for chunk in solar_pro_chat(st.session_state.custom_messages, api_key):
85
+ custom_response += chunk
86
+ custom_area.markdown(f"**πŸ€– Bot:** {custom_response}")
87
+ st.session_state.custom_messages.append({"role": "assistant", "content": custom_response})
88
 
89
+ # --- μ±„νŒ… νžˆμŠ€ν† λ¦¬ λ‹€μš΄λ‘œλ“œ ---
90
+ def generate_csv(messages, prompt_label):
91
+ rows = [{"role": "system", "content": prompt_label}]
92
+ for msg in messages:
 
93
  if msg["role"] != "system":
94
  rows.append(msg)
95
  df = pd.DataFrame(rows)
 
98
  return output.getvalue()
99
 
100
  now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
101
+ st.markdown("### ⬇️ Download Chat Histories")
102
+ col1, col2 = st.columns(2)
103
+ with col1:
104
+ st.download_button(
105
+ label="Download Default Chat",
106
+ data=generate_csv(st.session_state.default_messages, default_prompt),
107
+ file_name=f"default_chat_{now}.csv",
108
+ mime="text/csv",
109
+ )
110
+ with col2:
111
+ st.download_button(
112
+ label="Download Custom Chat",
113
+ data=generate_csv(st.session_state.custom_messages, custom_prompt),
114
+ file_name=f"custom_chat_{now}.csv",
115
+ mime="text/csv",
116
+ )
117