ofermend commited on
Commit
ec17431
β€’
1 Parent(s): 92937db
Files changed (1) hide show
  1. app.py +42 -26
app.py CHANGED
@@ -13,6 +13,7 @@ from bs4 import BeautifulSoup
13
  from pydantic import Field, BaseModel
14
  from vectara_agent.agent import Agent, AgentStatusType
15
  from vectara_agent.tools import ToolsFactory
 
16
 
17
  initial_prompt = "How can I help you today?"
18
 
@@ -26,6 +27,7 @@ get_headers = {
26
  "Connection": "keep-alive",
27
  }
28
 
 
29
  def create_tools(cfg):
30
 
31
  class QueryHackerNews(BaseModel):
@@ -128,6 +130,18 @@ def create_tools(cfg):
128
  text = soup.get_text(" ", strip=True).replace('\n', ' ')
129
  return text
130
 
 
 
 
 
 
 
 
 
 
 
 
 
131
 
132
  return (
133
  tools_factory.get_tools(
@@ -137,6 +151,7 @@ def create_tools(cfg):
137
  get_ask_stories,
138
  get_story_details,
139
  get_story_text,
 
140
  ]
141
  ) +
142
  tools_factory.standard_tools() +
@@ -145,15 +160,9 @@ def create_tools(cfg):
145
  )
146
 
147
  def initialize_agent(_cfg):
148
- date = datetime.datetime.now().strftime("%Y-%m-%d")
149
- bot_instructions = f"""
150
- - You are a helpful assistant, answering user questions about content from hacker news.
151
- - Today's date is {date}.
152
  - Never discuss politics, and always respond politely.
153
- - Use tools when available instead of depending on your own knowledge.
154
- - If a tool provides citations, you can include them in your response to provide more context.
155
- - If a tool cannot respond properly, retry with a rephrased question or ask the user for more information.
156
- - Be very careful not to report results you are not confident about.
157
  """
158
 
159
  def update_func(status_type: AgentStatusType, msg: str):
@@ -168,13 +177,15 @@ def initialize_agent(_cfg):
168
  )
169
  return agent
170
 
 
 
 
171
  def launch_bot():
172
  def reset():
173
- cfg = st.session_state.cfg
174
  st.session_state.messages = [{"role": "assistant", "content": initial_prompt, "avatar": "πŸ¦–"}]
175
  st.session_state.thinking_message = "Agent at work..."
176
- st.session_state.agent = initialize_agent(cfg)
177
  st.session_state.log_messages = []
 
178
  st.session_state.show_logs = False
179
 
180
  st.set_page_config(page_title="Hacker News Bot", layout="wide")
@@ -186,7 +197,10 @@ def launch_bot():
186
  })
187
  st.session_state.cfg = cfg
188
  reset()
 
189
  cfg = st.session_state.cfg
 
 
190
 
191
  # left side content
192
  with st.sidebar:
@@ -195,13 +209,10 @@ def launch_bot():
195
  st.markdown("## Welcome to the hacker news assistant demo.\n\n\n")
196
 
197
  st.markdown("\n\n")
198
- bc1, bc2 = st.columns([1, 1])
199
  with bc1:
200
  if st.button('Start Over'):
201
  reset()
202
- with bc2:
203
- if st.button('Show Logs'):
204
- st.session_state.show_logs = not st.session_state.show_logs
205
 
206
  st.markdown("---")
207
  st.markdown(
@@ -211,10 +222,9 @@ def launch_bot():
211
  )
212
  st.markdown("---")
213
 
214
-
215
  if "messages" not in st.session_state.keys():
216
  reset()
217
-
218
  # Display chat messages
219
  for message in st.session_state.messages:
220
  with st.chat_message(message["role"], avatar=message["avatar"]):
@@ -223,28 +233,34 @@ def launch_bot():
223
  # User-provided prompt
224
  if prompt := st.chat_input():
225
  st.session_state.messages.append({"role": "user", "content": prompt, "avatar": 'πŸ§‘β€πŸ’»'})
 
 
 
226
  with st.chat_message("user", avatar='πŸ§‘β€πŸ’»'):
227
  print(f"Starting new question: {prompt}\n")
228
  st.write(prompt)
229
-
230
  # Generate a new response if last message is not from assistant
231
- if st.session_state.messages[-1]["role"] != "assistant":
232
  with st.chat_message("assistant", avatar='πŸ€–'):
233
  with st.spinner(st.session_state.thinking_message):
234
- res = st.session_state.agent.chat(prompt)
235
  res = res.replace('$', '\\$') # escape dollar sign for markdown
236
  message = {"role": "assistant", "content": res, "avatar": 'πŸ€–'}
237
  st.session_state.messages.append(message)
238
- st.rerun()
 
239
 
240
- # Display log messages in an expander
241
- if st.session_state.show_logs:
242
- with st.expander("Agent Log Messages", expanded=True):
 
243
  for msg in st.session_state.log_messages:
244
  st.write(msg)
245
- if st.button('Close Logs'):
246
- st.session_state.show_logs = False
247
- st.rerun()
 
248
 
249
  sys.stdout.flush()
250
 
 
13
  from pydantic import Field, BaseModel
14
  from vectara_agent.agent import Agent, AgentStatusType
15
  from vectara_agent.tools import ToolsFactory
16
+ from vectara_agent.tools_catalog import summarize_text
17
 
18
  initial_prompt = "How can I help you today?"
19
 
 
27
  "Connection": "keep-alive",
28
  }
29
 
30
+
31
  def create_tools(cfg):
32
 
33
  class QueryHackerNews(BaseModel):
 
130
  text = soup.get_text(" ", strip=True).replace('\n', ' ')
131
  return text
132
 
133
+ def whats_new(
134
+ n_stories: int = Field(default=10, description="The number of new stories to return.")
135
+ ) -> list[str]:
136
+ """
137
+ Provides a succint summary of what is new in the hackernews community
138
+ by summarizing the content and comments of top stories.
139
+ Returns a string with the summary.
140
+ """
141
+ stories = get_top_stories(n_stories)
142
+ texts = [get_story_text(story_id) for story_id in stories[:n_stories]]
143
+ all_stories = '---------\n\n'.join(texts)
144
+ return summarize_text(all_stories)
145
 
146
  return (
147
  tools_factory.get_tools(
 
151
  get_ask_stories,
152
  get_story_details,
153
  get_story_text,
154
+ whats_new
155
  ]
156
  ) +
157
  tools_factory.standard_tools() +
 
160
  )
161
 
162
  def initialize_agent(_cfg):
163
+ bot_instructions = """
164
+ - You are a helpful assistant, with expertise in answering user questions about Hacker News stories and comments.
 
 
165
  - Never discuss politics, and always respond politely.
 
 
 
 
166
  """
167
 
168
  def update_func(status_type: AgentStatusType, msg: str):
 
177
  )
178
  return agent
179
 
180
+ def toggle_logs():
181
+ st.session_state.show_logs = not st.session_state.show_logs
182
+
183
  def launch_bot():
184
  def reset():
 
185
  st.session_state.messages = [{"role": "assistant", "content": initial_prompt, "avatar": "πŸ¦–"}]
186
  st.session_state.thinking_message = "Agent at work..."
 
187
  st.session_state.log_messages = []
188
+ st.session_state.prompt = None
189
  st.session_state.show_logs = False
190
 
191
  st.set_page_config(page_title="Hacker News Bot", layout="wide")
 
197
  })
198
  st.session_state.cfg = cfg
199
  reset()
200
+
201
  cfg = st.session_state.cfg
202
+ if 'agent' not in st.session_state:
203
+ st.session_state.agent = initialize_agent(cfg)
204
 
205
  # left side content
206
  with st.sidebar:
 
209
  st.markdown("## Welcome to the hacker news assistant demo.\n\n\n")
210
 
211
  st.markdown("\n\n")
212
+ bc1, _ = st.columns([1, 1])
213
  with bc1:
214
  if st.button('Start Over'):
215
  reset()
 
 
 
216
 
217
  st.markdown("---")
218
  st.markdown(
 
222
  )
223
  st.markdown("---")
224
 
 
225
  if "messages" not in st.session_state.keys():
226
  reset()
227
+
228
  # Display chat messages
229
  for message in st.session_state.messages:
230
  with st.chat_message(message["role"], avatar=message["avatar"]):
 
233
  # User-provided prompt
234
  if prompt := st.chat_input():
235
  st.session_state.messages.append({"role": "user", "content": prompt, "avatar": 'πŸ§‘β€πŸ’»'})
236
+ st.session_state.prompt = prompt # Save the prompt in session state
237
+ st.session_state.log_messages = []
238
+ st.session_state.show_logs = False
239
  with st.chat_message("user", avatar='πŸ§‘β€πŸ’»'):
240
  print(f"Starting new question: {prompt}\n")
241
  st.write(prompt)
242
+
243
  # Generate a new response if last message is not from assistant
244
+ if st.session_state.prompt:
245
  with st.chat_message("assistant", avatar='πŸ€–'):
246
  with st.spinner(st.session_state.thinking_message):
247
+ res = st.session_state.agent.chat(st.session_state.prompt)
248
  res = res.replace('$', '\\$') # escape dollar sign for markdown
249
  message = {"role": "assistant", "content": res, "avatar": 'πŸ€–'}
250
  st.session_state.messages.append(message)
251
+ st.markdown(res)
252
+ st.session_state.prompt = None
253
 
254
+ log_placeholder = st.empty()
255
+ with log_placeholder.container():
256
+ if st.session_state.show_logs:
257
+ st.button("Hide Logs", on_click=toggle_logs)
258
  for msg in st.session_state.log_messages:
259
  st.write(msg)
260
+ else:
261
+ if len(st.session_state.log_messages) > 0:
262
+ st.button("Show Logs", on_click=toggle_logs)
263
+
264
 
265
  sys.stdout.flush()
266