Spaces:
Sleeping
Sleeping
Alberto Carmona
commited on
Commit
·
3e9f4d2
1
Parent(s):
2ca40cc
Refactor get_news function to use web_search for fetching articles and add logging for better traceability
Browse files
tools.py
CHANGED
@@ -9,8 +9,7 @@ from llms import llm_openai
|
|
9 |
|
10 |
|
11 |
last_news = []
|
12 |
-
|
13 |
-
|
14 |
def get_news(topics: List[str]) -> List[Dict]:
|
15 |
"""
|
16 |
Fetches news articles related to the specified topics using the NewsAPI, analyzes their sentiment and named entities, and returns a list of processed news items.
|
@@ -31,34 +30,22 @@ def get_news(topics: List[str]) -> List[Dict]:
|
|
31 |
None. All exceptions are caught and returned as error messages in the result.
|
32 |
"""
|
33 |
global last_news
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
sentiment = analyze_sentiment(summary)
|
51 |
-
entities = recognize_entities(summary)
|
52 |
-
last_news.append({
|
53 |
-
"index": idx,
|
54 |
-
"title": article.get("title", "No title"),
|
55 |
-
"summary": summary,
|
56 |
-
"sentiment": sentiment,
|
57 |
-
"entities": entities
|
58 |
-
})
|
59 |
-
return last_news
|
60 |
-
except requests.RequestException as e:
|
61 |
-
return [{"error": f"Failed to fetch news: {str(e)}"}]
|
62 |
|
63 |
|
64 |
|
@@ -126,6 +113,7 @@ def generate_implications(article_index: int) -> str:
|
|
126 |
str: A message containing the implications for the specified article, or an error message if the index is invalid.
|
127 |
"""
|
128 |
global last_news
|
|
|
129 |
if not (1 <= article_index <= len(last_news)):
|
130 |
return "Invalid article index."
|
131 |
article = last_news[article_index - 1]
|
@@ -137,6 +125,7 @@ def generate_implications(article_index: int) -> str:
|
|
137 |
)
|
138 |
except Exception as e:
|
139 |
return f"Error generating implications: {str(e)}"
|
|
|
140 |
return f"Implications for article {article_index}: {result.message.content}"
|
141 |
|
142 |
|
@@ -152,6 +141,7 @@ def web_search(query: str) -> List[Dict]:
|
|
152 |
"""
|
153 |
client = TavilyClient(os.environ.get("TAVILY_API_KEY"))
|
154 |
response = client.search(query)
|
|
|
155 |
return response['results'] if 'results' in response else []
|
156 |
|
157 |
|
@@ -187,6 +177,7 @@ def get_lead_up_events(article_index: int) -> str:
|
|
187 |
str: A formatted string summarizing the lead-up events or background information for the article's topic.
|
188 |
"""
|
189 |
global last_news
|
|
|
190 |
if not (1 <= article_index <= len(last_news)):
|
191 |
return "Invalid article index."
|
192 |
article = last_news[article_index - 1]
|
@@ -211,8 +202,26 @@ def get_lead_up_events(article_index: int) -> str:
|
|
211 |
)
|
212 |
except Exception as e:
|
213 |
return f"Error generating background information: {str(e)}"
|
|
|
214 |
return f"Background information for article {article_index}: {result.message.content}"
|
215 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
216 |
|
217 |
def get_social_media_opinions(article_index: int) -> str:
|
218 |
"""
|
@@ -228,27 +237,24 @@ def get_social_media_opinions(article_index: int) -> str:
|
|
228 |
str: A summary string indicating the categorized number of positive and negative opinions about the event.
|
229 |
"""
|
230 |
global last_news
|
|
|
231 |
if not (1 <= article_index <= len(last_news)):
|
232 |
return "Invalid article index."
|
233 |
article = last_news[article_index - 1]
|
234 |
title = article["title"]
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
return "high"
|
252 |
-
positive_level = categorize(positive_count)
|
253 |
-
negative_level = categorize(negative_count)
|
254 |
-
return f"There are a {positive_level} number of positive opinions and a {negative_level} number of negative opinions about this event."
|
|
|
9 |
|
10 |
|
11 |
last_news = []
|
12 |
+
|
|
|
13 |
def get_news(topics: List[str]) -> List[Dict]:
|
14 |
"""
|
15 |
Fetches news articles related to the specified topics using the NewsAPI, analyzes their sentiment and named entities, and returns a list of processed news items.
|
|
|
30 |
None. All exceptions are caught and returned as error messages in the result.
|
31 |
"""
|
32 |
global last_news
|
33 |
+
print(f"Fetching news for topics: {topics}")
|
34 |
+
|
35 |
+
last_news.clear() # Clear previous news to avoid duplication
|
36 |
+
for topic in topics:
|
37 |
+
search_results = web_search(f'Find the latest news related to: {topic}')
|
38 |
+
if search_results:
|
39 |
+
for res in search_results:
|
40 |
+
last_news.append({
|
41 |
+
"index": len(last_news) + 1,
|
42 |
+
"title": res.get("title", "No title available"),
|
43 |
+
"summary": res.get("content", "No summary available"),
|
44 |
+
# "sentiment": analyze_sentiment(res.get("snippet", "")),
|
45 |
+
# "entities": recognize_entities(res.get("snippet", ""))
|
46 |
+
})
|
47 |
+
print(f"Found {len(last_news)} articles.")
|
48 |
+
return last_news
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
|
50 |
|
51 |
|
|
|
113 |
str: A message containing the implications for the specified article, or an error message if the index is invalid.
|
114 |
"""
|
115 |
global last_news
|
116 |
+
print(f"Generating implications for article index: {article_index}")
|
117 |
if not (1 <= article_index <= len(last_news)):
|
118 |
return "Invalid article index."
|
119 |
article = last_news[article_index - 1]
|
|
|
125 |
)
|
126 |
except Exception as e:
|
127 |
return f"Error generating implications: {str(e)}"
|
128 |
+
print(f"Generated implications: {result.message.content}")
|
129 |
return f"Implications for article {article_index}: {result.message.content}"
|
130 |
|
131 |
|
|
|
141 |
"""
|
142 |
client = TavilyClient(os.environ.get("TAVILY_API_KEY"))
|
143 |
response = client.search(query)
|
144 |
+
print(f"Web search results for query '{query}': {response}")
|
145 |
return response['results'] if 'results' in response else []
|
146 |
|
147 |
|
|
|
177 |
str: A formatted string summarizing the lead-up events or background information for the article's topic.
|
178 |
"""
|
179 |
global last_news
|
180 |
+
print(f"Getting lead-up events for article index: {article_index}")
|
181 |
if not (1 <= article_index <= len(last_news)):
|
182 |
return "Invalid article index."
|
183 |
article = last_news[article_index - 1]
|
|
|
202 |
)
|
203 |
except Exception as e:
|
204 |
return f"Error generating background information: {str(e)}"
|
205 |
+
print(f"Generated background information: {result.message.content}")
|
206 |
return f"Background information for article {article_index}: {result.message.content}"
|
207 |
|
208 |
+
def call_llm(prompt: str) -> str:
|
209 |
+
"""
|
210 |
+
Calls the LLM with a given prompt and returns the response.
|
211 |
+
|
212 |
+
Args:
|
213 |
+
prompt: The input prompt to send to the LLM.
|
214 |
+
|
215 |
+
Returns:
|
216 |
+
str: The response from the LLM.
|
217 |
+
"""
|
218 |
+
try:
|
219 |
+
result = llm_openai.chat(
|
220 |
+
messages=[ChatMessage(role="user", content=prompt)]
|
221 |
+
)
|
222 |
+
return result.message.content
|
223 |
+
except Exception as e:
|
224 |
+
return f"Error calling LLM: {str(e)}"
|
225 |
|
226 |
def get_social_media_opinions(article_index: int) -> str:
|
227 |
"""
|
|
|
237 |
str: A summary string indicating the categorized number of positive and negative opinions about the event.
|
238 |
"""
|
239 |
global last_news
|
240 |
+
print(f"Getting social media opinions for article index: {article_index}")
|
241 |
if not (1 <= article_index <= len(last_news)):
|
242 |
return "Invalid article index."
|
243 |
article = last_news[article_index - 1]
|
244 |
title = article["title"]
|
245 |
+
|
246 |
+
pos_posts = web_search(f'What are the positive social media reactions related to: {title}?')
|
247 |
+
neg_posts = web_search(f'What are the negative social media reactions related to: {title}?')
|
248 |
+
|
249 |
+
# haz un resumen con el llm de los posts positivos
|
250 |
+
pos_summary = call_llm('Make a summary of the following social media posts: ' + str(pos_posts))
|
251 |
+
neg_summary = call_llm('Make a summary of the following social media posts: ' + str(neg_posts))
|
252 |
+
|
253 |
+
print(f"Positive summary: {pos_summary}")
|
254 |
+
print(f"Negative summary: {neg_summary}")
|
255 |
+
|
256 |
+
return f"""
|
257 |
+
Social Media Opinions for Article {article_index}:
|
258 |
+
Positive Summary: {pos_summary}
|
259 |
+
Negative Summary: {neg_summary}
|
260 |
+
"""
|
|
|
|
|
|
|
|