ofermend commited on
Commit
b877458
1 Parent(s): b8958bb

added amplitude

Browse files
Files changed (3) hide show
  1. app.py +17 -57
  2. requirements.txt +2 -0
  3. utils.py +74 -0
app.py CHANGED
@@ -1,8 +1,5 @@
1
  from PIL import Image
2
  import sys
3
- import os
4
- import requests
5
- import json
6
  import uuid
7
 
8
  import streamlit as st
@@ -12,6 +9,7 @@ from streamlit_feedback import streamlit_feedback
12
  from vectara_agent.agent import AgentStatusType
13
 
14
  from agent import initialize_agent, get_agent_config
 
15
 
16
  initial_prompt = "How can I help you today?"
17
 
@@ -19,35 +17,6 @@ initial_prompt = "How can I help you today?"
19
  if 'device_id' not in st.session_state:
20
  st.session_state.device_id = str(uuid.uuid4())
21
 
22
- headers = {
23
- 'Content-Type': 'application/json',
24
- 'Accept': '*/*'
25
- }
26
- amp_api_key = os.getenv('AMPLITUDE_TOKEN')
27
-
28
- def thumbs_feedback(feedback, **kwargs):
29
- """
30
- Sends feedback to Amplitude Analytics
31
- """
32
- data = {
33
- "api_key": amp_api_key,
34
- "events": [{
35
- "device_id": st.session_state.device_id,
36
- "event_type": "provided_feedback",
37
- "event_properties": {
38
- "Space Name": kwargs.get("demo_name", "Unknown"),
39
- "query": kwargs.get("prompt", "No user input"),
40
- "response": kwargs.get("response", "No chat response"),
41
- "feedback": feedback["score"]
42
- }
43
- }]
44
- }
45
- response = requests.post('https://api2.amplitude.com/2/httpapi', headers=headers, data=json.dumps(data))
46
- if response.status_code != 200:
47
- print(f"Request failed with status code {response.status_code}. Response Text: {response.text}")
48
-
49
- st.session_state.feedback_key += 1
50
-
51
  if "feedback_key" not in st.session_state:
52
  st.session_state.feedback_key = 0
53
 
@@ -104,7 +73,7 @@ def launch_bot():
104
  reset()
105
  st.rerun()
106
 
107
- st.markdown("---")
108
  st.markdown(
109
  "## How this works?\n"
110
  "This app was built with [Vectara](https://vectara.com).\n\n"
@@ -146,33 +115,31 @@ def launch_bot():
146
  with st.chat_message("assistant", avatar='🤖'):
147
  with st.spinner(st.session_state.thinking_message):
148
  res = st.session_state.agent.chat(st.session_state.prompt)
149
- res = res.replace('$', '\\$') # escape dollar sign for markdown
150
  message = {"role": "assistant", "content": res, "avatar": '🤖'}
151
  st.session_state.messages.append(message)
152
  st.markdown(res)
153
 
154
- # Send query and response to Amplitude Analytics
155
- data = {
156
- "api_key": amp_api_key,
157
- "events": [{
158
- "device_id": st.session_state.device_id,
159
- "event_type": "submitted_query",
160
- "event_properties": {
161
- "Space Name": cfg['demo_name'],
162
- "query": st.session_state.messages[-2]["content"],
163
- "response": st.session_state.messages[-1]["content"]
164
- }
165
- }]
166
- }
167
- response = requests.post('https://api2.amplitude.com/2/httpapi', headers=headers, data=json.dumps(data))
168
- if response.status_code != 200:
169
- print(f"Request failed with status code {response.status_code}. Response Text: {response.text}")
170
 
171
  st.session_state.ex_prompt = None
172
  st.session_state.prompt = None
173
  st.session_state.first_turn = False
174
  st.rerun()
175
 
 
 
 
 
 
 
 
 
 
176
  log_placeholder = st.empty()
177
  with log_placeholder.container():
178
  if st.session_state.show_logs:
@@ -182,13 +149,6 @@ def launch_bot():
182
  else:
183
  if len(st.session_state.log_messages) > 0:
184
  st.button("Show Logs", on_click=toggle_logs)
185
-
186
- # Record user feedback
187
- if (st.session_state.messages[-1]["role"] == "assistant") & (st.session_state.messages[-1]["content"] != "How can I help you today?"):
188
- streamlit_feedback(feedback_type="thumbs", on_submit = thumbs_feedback, key = st.session_state.feedback_key,
189
- kwargs = {"prompt": st.session_state.messages[-2]["content"],
190
- "response": st.session_state.messages[-1]["content"],
191
- "demo_name": cfg["demo_name"]})
192
 
193
  sys.stdout.flush()
194
 
 
1
  from PIL import Image
2
  import sys
 
 
 
3
  import uuid
4
 
5
  import streamlit as st
 
9
  from vectara_agent.agent import AgentStatusType
10
 
11
  from agent import initialize_agent, get_agent_config
12
+ from utils import thumbs_feedback, escape_dollars_outside_latex, send_amplitude_data
13
 
14
  initial_prompt = "How can I help you today?"
15
 
 
17
  if 'device_id' not in st.session_state:
18
  st.session_state.device_id = str(uuid.uuid4())
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  if "feedback_key" not in st.session_state:
21
  st.session_state.feedback_key = 0
22
 
 
73
  reset()
74
  st.rerun()
75
 
76
+ st.divider()
77
  st.markdown(
78
  "## How this works?\n"
79
  "This app was built with [Vectara](https://vectara.com).\n\n"
 
115
  with st.chat_message("assistant", avatar='🤖'):
116
  with st.spinner(st.session_state.thinking_message):
117
  res = st.session_state.agent.chat(st.session_state.prompt)
118
+ res = escape_dollars_outside_latex(res)
119
  message = {"role": "assistant", "content": res, "avatar": '🤖'}
120
  st.session_state.messages.append(message)
121
  st.markdown(res)
122
 
123
+ send_amplitude_data(
124
+ user_query=st.session_state.messages[-2]["content"],
125
+ bot_response=st.session_state.messages[-1]["content"],
126
+ demo_name=cfg['demo_name']
127
+ )
 
 
 
 
 
 
 
 
 
 
 
128
 
129
  st.session_state.ex_prompt = None
130
  st.session_state.prompt = None
131
  st.session_state.first_turn = False
132
  st.rerun()
133
 
134
+ # Record user feedback
135
+ if (st.session_state.messages[-1]["role"] == "assistant") & (st.session_state.messages[-1]["content"] != "How can I help you today?"):
136
+ streamlit_feedback(
137
+ feedback_type="thumbs", on_submit = thumbs_feedback, key = st.session_state.feedback_key,
138
+ kwargs = {"user_query": st.session_state.messages[-2]["content"],
139
+ "bot_response": st.session_state.messages[-1]["content"],
140
+ "demo_name": cfg["demo_name"]}
141
+ )
142
+
143
  log_placeholder = st.empty()
144
  with log_placeholder.container():
145
  if st.session_state.show_logs:
 
149
  else:
150
  if len(st.session_state.log_messages) > 0:
151
  st.button("Show Logs", on_click=toggle_logs)
 
 
 
 
 
 
 
152
 
153
  sys.stdout.flush()
154
 
requirements.txt CHANGED
@@ -5,4 +5,6 @@ streamlit==1.32.2
5
  streamlit_pills==0.3.0
6
  streamlit_feedback==0.1.3
7
  uuid==1.30
 
 
8
  git+https://{GITHUB_TOKEN}@github.com/vectara/vectara-agent.git
 
5
  streamlit_pills==0.3.0
6
  streamlit_feedback==0.1.3
7
  uuid==1.30
8
+ langdetect==1.0.9
9
+ langcodes==3.4.0
10
  git+https://{GITHUB_TOKEN}@github.com/vectara/vectara-agent.git
utils.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import json
4
+ import re
5
+
6
+ import streamlit as st
7
+
8
+ from langdetect import detect_langs
9
+ from langcodes import Language
10
+
11
+ headers = {
12
+ 'Content-Type': 'application/json',
13
+ 'Accept': '*/*'
14
+ }
15
+
16
+ def identify_language(response):
17
+ lang_code = detect_langs(response)[0].lang
18
+ return Language.make(language=lang_code).display_name()
19
+
20
+ def thumbs_feedback(feedback, **kwargs):
21
+ """
22
+ Sends feedback to Amplitude Analytics
23
+ """
24
+ send_amplitude_data(
25
+ user_query=kwargs.get("user_query", "No user input"),
26
+ bot_response=kwargs.get("bot_response", "No bot response"),
27
+ demo_name=kwargs.get("demo_name", "Unknown"),
28
+ feedback=feedback['score'],
29
+ )
30
+ st.session_state.feedback_key += 1
31
+
32
+ def send_amplitude_data(user_query, bot_response, demo_name, feedback=None):
33
+ # Send query and response to Amplitude Analytics
34
+ data = {
35
+ "api_key": os.getenv('AMPLITUDE_TOKEN'),
36
+ "events": [{
37
+ "device_id": st.session_state.device_id,
38
+ "event_type": "submitted_query",
39
+ "event_properties": {
40
+ "Space Name": demo_name,
41
+ "Demo Type": "Agent",
42
+ "query": user_query,
43
+ "response": bot_response,
44
+ "Response Language": identify_language(bot_response)
45
+ }
46
+ }]
47
+ }
48
+ if feedback:
49
+ data["events"][0]["event_properties"]["feedback"] = feedback
50
+
51
+ response = requests.post('https://api2.amplitude.com/2/httpapi', headers=headers, data=json.dumps(data))
52
+ if response.status_code != 200:
53
+ print(f"Amplitude request failed with status code {response.status_code}. Response Text: {response.text}")
54
+
55
+ def escape_dollars_outside_latex(text):
56
+ # Define a regex pattern to find LaTeX equations (either single $ or double $$)
57
+ pattern = re.compile(r'(\$\$.*?\$\$|\$.*?\$)')
58
+ latex_matches = pattern.findall(text)
59
+
60
+ # Placeholder to temporarily store LaTeX equations
61
+ placeholders = {}
62
+ for i, match in enumerate(latex_matches):
63
+ placeholder = f'__LATEX_PLACEHOLDER_{i}__'
64
+ placeholders[placeholder] = match
65
+ text = text.replace(match, placeholder)
66
+
67
+ # Escape dollar signs in the rest of the text
68
+ text = text.replace('$', '\\$')
69
+
70
+ # Replace placeholders with the original LaTeX equations
71
+ for placeholder, original in placeholders.items():
72
+ text = text.replace(placeholder, original)
73
+ return text
74
+