ofermend commited on
Commit
89f1436
β€’
1 Parent(s): e821217
Files changed (1) hide show
  1. app.py +36 -30
app.py CHANGED
@@ -55,17 +55,16 @@ def create_tools(cfg):
55
  query_tool = tools_factory.create_rag_tool(
56
  tool_name = "justice_harvard_query",
57
  tool_description = """
58
- Given a user query, returns a response (str) based on the content of the Justice Harvard lecture transcripts.
59
- It can answer questions about the justice, morality, politics and related topics,
60
  based on transcripts of recordings from the Justice Harvard class that includes a lot of content on these topics.
61
  When using the tool it's best to ask simple short questions. You can break complex questions into sub-queries.
62
  """,
63
  tool_args_schema = JusticeHarvardArgs,
64
- tool_filter_template = '',
65
  reranker = "multilingual_reranker_v1", rerank_k = 100,
66
- n_sentences_before = 2, n_sentences_after = 2, lambda_val = 0.01,
67
  summary_num_results = 10,
68
  vectara_summarizer = 'vectara-summary-ext-24-05-med-omni',
 
69
  )
70
 
71
  return (tools_factory.get_tools(
@@ -79,15 +78,15 @@ def create_tools(cfg):
79
  )
80
 
81
  def initialize_agent(_cfg):
82
- date = datetime.datetime.now().strftime("%Y-%m-%d")
83
  bot_instructions = f"""
84
  - You are a helpful teacher assistant, with expertise in education in various teaching styles.
85
- - Today's date is {date}.
 
 
 
 
86
  - Response in a concise and clear manner, and provide the most relevant information to the student.
87
- - Use tools when available instead of depending on your own knowledge.
88
- - Always use the rephrase tool at the end in order to ensure it fits the student's age of {_cfg.student_age},
89
- the {_cfg.style} teaching style and the {_cfg.language} language
90
- - Always use any guardrails tools to ensure your responses are polite and do not discuss politices.
91
  """
92
 
93
  def update_func(status_type: AgentStatusType, msg: str):
@@ -96,12 +95,15 @@ def initialize_agent(_cfg):
96
 
97
  agent = Agent(
98
  tools=create_tools(_cfg),
99
- topic="An educator with expertise in philosophy",
100
  custom_instructions=bot_instructions,
101
  update_func=update_func
102
  )
103
  return agent
104
 
 
 
 
105
  def launch_bot():
106
  def reset():
107
  cfg = st.session_state.cfg
@@ -109,6 +111,7 @@ def launch_bot():
109
  st.session_state.thinking_message = "Agent at work..."
110
  st.session_state.agent = initialize_agent(cfg)
111
  st.session_state.log_messages = []
 
112
  st.session_state.show_logs = False
113
 
114
  st.set_page_config(page_title="Justice Harvard Teaching Assistant", layout="wide")
@@ -150,7 +153,7 @@ def launch_bot():
150
 
151
  st.markdown("\n")
152
  cfg.student_age = st.number_input(
153
- 'Student age:', min_value=13, value=cfg.student_age,
154
  step=1, format='%i'
155
  )
156
  if st.session_state.student_age != cfg.student_age:
@@ -158,13 +161,10 @@ def launch_bot():
158
  reset()
159
 
160
  st.markdown("\n\n")
161
- bc1, bc2 = st.columns([1, 1])
162
  with bc1:
163
  if st.button('Start Over'):
164
  reset()
165
- with bc2:
166
- if st.button('Show Logs'):
167
- st.session_state.show_logs = not st.session_state.show_logs
168
 
169
  st.markdown("---")
170
  st.markdown(
@@ -177,7 +177,7 @@ def launch_bot():
177
 
178
  if "messages" not in st.session_state.keys():
179
  reset()
180
-
181
  # Display chat messages
182
  for message in st.session_state.messages:
183
  with st.chat_message(message["role"], avatar=message["avatar"]):
@@ -186,27 +186,33 @@ def launch_bot():
186
  # User-provided prompt
187
  if prompt := st.chat_input():
188
  st.session_state.messages.append({"role": "user", "content": prompt, "avatar": 'πŸ§‘β€πŸ’»'})
 
 
 
189
  with st.chat_message("user", avatar='πŸ§‘β€πŸ’»'):
190
  print(f"Starting new question: {prompt}\n")
191
  st.write(prompt)
192
-
193
- if st.session_state.messages[-1]["role"] != "assistant":
 
194
  with st.chat_message("assistant", avatar='πŸ€–'):
195
  with st.spinner(st.session_state.thinking_message):
196
- res = st.session_state.agent.chat(prompt)
197
- cleaned = re.sub(r'\[\d+\]', '', res).replace('$', '\\$')
198
- message = {"role": "assistant", "content": cleaned, "avatar": 'πŸ€–'}
199
  st.session_state.messages.append(message)
200
- st.rerun()
201
-
202
- # Display log messages in an expander
203
- if st.session_state.show_logs:
204
- with st.expander("Agent Log Messages", expanded=True):
 
 
205
  for msg in st.session_state.log_messages:
206
  st.write(msg)
207
- if st.button('Close Logs'):
208
- st.session_state.show_logs = False
209
- st.rerun()
210
 
211
  sys.stdout.flush()
212
 
 
55
  query_tool = tools_factory.create_rag_tool(
56
  tool_name = "justice_harvard_query",
57
  tool_description = """
58
+ Answer questions about the justice, morality, politics and related topics,
 
59
  based on transcripts of recordings from the Justice Harvard class that includes a lot of content on these topics.
60
  When using the tool it's best to ask simple short questions. You can break complex questions into sub-queries.
61
  """,
62
  tool_args_schema = JusticeHarvardArgs,
 
63
  reranker = "multilingual_reranker_v1", rerank_k = 100,
64
+ n_sentences_before = 2, n_sentences_after = 2, lambda_val = 0.005,
65
  summary_num_results = 10,
66
  vectara_summarizer = 'vectara-summary-ext-24-05-med-omni',
67
+ include_citations = True,
68
  )
69
 
70
  return (tools_factory.get_tools(
 
78
  )
79
 
80
  def initialize_agent(_cfg):
 
81
  bot_instructions = f"""
82
  - You are a helpful teacher assistant, with expertise in education in various teaching styles.
83
+ - Obtain information using tools to answer the user's query.
84
+ - If the tool cannot provide information relevant to the user's query, tell the user that you are unable to provide an answer.
85
+ - If the tool can provide relevant information, use the adjust_response_to_student tool
86
+ to rephrase the response to ensure it fits the student's age of {_cfg.student_age},
87
+ the {_cfg.style} teaching style and the {_cfg.language} language.
88
  - Response in a concise and clear manner, and provide the most relevant information to the student.
89
+ - Never discuss politics, and always respond politely.
 
 
 
90
  """
91
 
92
  def update_func(status_type: AgentStatusType, msg: str):
 
95
 
96
  agent = Agent(
97
  tools=create_tools(_cfg),
98
+ topic="justice, morality, politics, and philosophy",
99
  custom_instructions=bot_instructions,
100
  update_func=update_func
101
  )
102
  return agent
103
 
104
+ def toggle_logs():
105
+ st.session_state.show_logs = not st.session_state.show_logs
106
+
107
  def launch_bot():
108
  def reset():
109
  cfg = st.session_state.cfg
 
111
  st.session_state.thinking_message = "Agent at work..."
112
  st.session_state.agent = initialize_agent(cfg)
113
  st.session_state.log_messages = []
114
+ st.session_state.prompt = None
115
  st.session_state.show_logs = False
116
 
117
  st.set_page_config(page_title="Justice Harvard Teaching Assistant", layout="wide")
 
153
 
154
  st.markdown("\n")
155
  cfg.student_age = st.number_input(
156
+ 'Student age:', min_value=13, max_value=99, value=cfg.student_age,
157
  step=1, format='%i'
158
  )
159
  if st.session_state.student_age != cfg.student_age:
 
161
  reset()
162
 
163
  st.markdown("\n\n")
164
+ bc1, _ = st.columns([1, 1])
165
  with bc1:
166
  if st.button('Start Over'):
167
  reset()
 
 
 
168
 
169
  st.markdown("---")
170
  st.markdown(
 
177
 
178
  if "messages" not in st.session_state.keys():
179
  reset()
180
+
181
  # Display chat messages
182
  for message in st.session_state.messages:
183
  with st.chat_message(message["role"], avatar=message["avatar"]):
 
186
  # User-provided prompt
187
  if prompt := st.chat_input():
188
  st.session_state.messages.append({"role": "user", "content": prompt, "avatar": 'πŸ§‘β€πŸ’»'})
189
+ st.session_state.prompt = prompt # Save the prompt in session state
190
+ st.session_state.log_messages = []
191
+ st.session_state.show_logs = False
192
  with st.chat_message("user", avatar='πŸ§‘β€πŸ’»'):
193
  print(f"Starting new question: {prompt}\n")
194
  st.write(prompt)
195
+
196
+ # Generate a new response if last message is not from assistant
197
+ if st.session_state.prompt:
198
  with st.chat_message("assistant", avatar='πŸ€–'):
199
  with st.spinner(st.session_state.thinking_message):
200
+ res = st.session_state.agent.chat(st.session_state.prompt)
201
+ res = res.replace('$', '\\$') # escape dollar sign for markdown
202
+ message = {"role": "assistant", "content": res, "avatar": 'πŸ€–'}
203
  st.session_state.messages.append(message)
204
+ st.markdown(res)
205
+ st.session_state.prompt = None
206
+
207
+ log_placeholder = st.empty()
208
+ with log_placeholder.container():
209
+ if st.session_state.show_logs:
210
+ st.button("Hide Logs", on_click=toggle_logs)
211
  for msg in st.session_state.log_messages:
212
  st.write(msg)
213
+ else:
214
+ if len(st.session_state.log_messages) > 0:
215
+ st.button("Show Logs", on_click=toggle_logs)
216
 
217
  sys.stdout.flush()
218