fdaudens HF staff commited on
Commit
f387a3a
·
verified ·
1 Parent(s): ae7a494

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -44
app.py CHANGED
@@ -1,69 +1,122 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
- import datetime
3
- import requests
4
- import pytz
5
- import yaml
6
  from tools.final_answer import FinalAnswerTool
7
-
8
  from Gradio_UI import GradioUI
 
 
 
 
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
  Args:
16
- arg1: the first argument
17
- arg2: the second argument
 
 
 
18
  """
19
- return "What magic will you build ?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
 
24
  Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
 
26
  """
27
- try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
33
- except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
-
36
-
37
- final_answer = FinalAnswerTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
 
41
 
 
42
  model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
  )
48
 
 
49
 
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
-
53
- with open("prompts.yaml", 'r') as stream:
54
- prompt_templates = yaml.safe_load(stream)
55
-
56
  agent = CodeAgent(
57
  model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
  max_steps=6,
60
  verbosity_level=1,
61
  grammar=None,
62
  planning_interval=None,
63
- name=None,
64
- description=None,
65
  prompt_templates=prompt_templates
66
  )
67
 
68
-
69
- GradioUI(agent).launch()
 
 
1
+ from smolagents import CodeAgent, HfApiModel, tool
 
 
 
 
2
  from tools.final_answer import FinalAnswerTool
 
3
  from Gradio_UI import GradioUI
4
+ import requests
5
+ import yaml
6
+ import os
7
+ from typing import Dict, List, Optional
8
 
 
9
  @tool
10
+ def fetch_news(topic: str, num_results: int = 5) -> List[Dict]:
11
+ """Fetches recent news articles about any topic using Serper.dev.
12
+
13
  Args:
14
+ topic: The topic to search for news about
15
+ num_results: Number of news articles to retrieve (default: 5)
16
+
17
+ Returns:
18
+ List of dictionaries containing article information
19
  """
20
+ try:
21
+ api_key = os.environ.get("SERPER_API_KEY")
22
+ if not api_key:
23
+ return "Error: SERPER_API_KEY not found in environment variables"
24
+
25
+ url = f"https://google.serper.dev/news"
26
+ headers = {
27
+ "X-API-KEY": api_key
28
+ }
29
+ params = {
30
+ "q": topic,
31
+ "gl": "us",
32
+ "hl": "en"
33
+ }
34
+
35
+ response = requests.get(url, headers=headers, params=params)
36
+ response.raise_for_status()
37
+
38
+ results = response.json()
39
+
40
+ if "news" not in results:
41
+ return []
42
+
43
+ articles = []
44
+ for article in results["news"][:num_results]:
45
+ articles.append({
46
+ 'title': article.get('title', 'No title'),
47
+ 'source': article.get('source', 'Unknown source'),
48
+ 'date': article.get('date', 'No date'),
49
+ 'link': article.get('link', 'No link'),
50
+ 'snippet': article.get('snippet', 'No preview available')
51
+ })
52
+
53
+ return articles
54
+
55
+ except Exception as e:
56
+ return f"Error: {str(e)}"
57
 
58
  @tool
59
+ def summarize_news(articles: List[Dict]) -> str:
60
+ """Creates a summary of the news articles followed by a list of sources.
61
+
62
  Args:
63
+ articles: List of article dictionaries containing title, source, date, link, and snippet
64
+
65
+ Returns:
66
+ A string containing a summary followed by article references
67
  """
68
+ if not articles or not isinstance(articles, list):
69
+ return "No articles to summarize"
70
+
71
+ # Collect all snippets for the overall summary
72
+ all_snippets = [article['snippet'] for article in articles if article.get('snippet')]
73
+
74
+ # Create a high-level summary from snippets
75
+ summary = "📰 Summary:\n"
76
+ summary += "Latest news covers " + ", ".join(set(article['source'] for article in articles)) + ". "
77
+ summary += "Key points: " + ". ".join(all_snippets[:2]) + "\n\n"
78
+
79
+ # List individual articles
80
+ summary += "🔍 Articles:\n"
81
+ for idx, article in enumerate(articles, 1):
82
+ title = article['title']
83
+ link = article['link']
84
+ date = article['date']
85
+ snippet = article['snippet'][:100] + "..." if len(article['snippet']) > 100 else article['snippet']
86
+
87
+ summary += f"{idx}. **{title}**\n"
88
+ summary += f" {snippet}\n"
89
+ summary += f" [Read more]({link}) ({date})\n\n"
90
+
91
+ return summary
92
 
93
+ # Load prompt templates
94
+ with open("prompts.yaml", 'r') as stream:
95
+ prompt_templates = yaml.safe_load(stream)
96
 
97
+ # Initialize the model
98
  model = HfApiModel(
99
+ max_tokens=2096,
100
+ temperature=0.5,
101
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
102
+ custom_role_conversions=None,
103
  )
104
 
105
+ final_answer = FinalAnswerTool()
106
 
107
+ # Create the agent with all tools
 
 
 
 
 
108
  agent = CodeAgent(
109
  model=model,
110
+ tools=[fetch_news, summarize_news, final_answer],
111
  max_steps=6,
112
  verbosity_level=1,
113
  grammar=None,
114
  planning_interval=None,
115
+ name="News Agent",
116
+ description="An agent that fetches and summarizes news about any topic",
117
  prompt_templates=prompt_templates
118
  )
119
 
120
+ # Launch the Gradio interface
121
+ if __name__ == "__main__":
122
+ GradioUI(agent).launch()