fprogr commited on
Commit
5f2831a
·
verified ·
1 Parent(s): 9a8c112

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -22
app.py CHANGED
@@ -1,23 +1,95 @@
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_cutom_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.
@@ -25,33 +97,30 @@ def get_current_time_in_timezone(timezone: str) -> str:
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
  model = HfApiModel(
39
- max_tokens=2096,
40
- temperature=0.5,
41
- model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',# it is possible that this model may be overloaded
42
- custom_role_conversions=None,
43
  )
44
 
45
-
46
- # Import tool from Hub
47
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
48
 
49
  with open("prompts.yaml", 'r') as stream:
50
  prompt_templates = yaml.safe_load(stream)
51
-
 
52
  agent = CodeAgent(
53
  model=model,
54
- tools=[final_answer], ## add your tools here (don't remove final answer)
55
  max_steps=6,
56
  verbosity_level=1,
57
  grammar=None,
@@ -61,5 +130,4 @@ agent = CodeAgent(
61
  prompt_templates=prompt_templates
62
  )
63
 
64
-
65
- GradioUI(agent).launch()
 
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
  from Gradio_UI import GradioUI
8
 
9
+ # Search Tool using DuckDuckGo
10
+ search_tool = DuckDuckGoSearchTool()
11
+
12
+ # Text Summarization Tool
13
+ @tool
14
+ def summarize_text(text: str) -> str:
15
+ """Summarizes a given text into a concise version.
16
+ Args:
17
+ text: The text to be summarized.
18
+ """
19
+ try:
20
+ api_url = "https://api-inference.huggingface.co/models/facebook/bart-large-cnn"
21
+ headers = {"Authorization": "Bearer YOUR_HUGGINGFACE_API_KEY"}
22
+ response = requests.post(api_url, headers=headers, json={"inputs": text})
23
+ summary = response.json()[0]['summary_text']
24
+ return summary
25
+ except Exception as e:
26
+ return f"Error in summarization: {str(e)}"
27
+
28
+ # Weather Information Tool
29
+ @tool
30
+ def get_weather(city: str) -> str:
31
+ """Fetches current weather information for a given city.
32
+ Args:
33
+ city: Name of the city.
34
+ """
35
+ try:
36
+ api_key = "YOUR_OPENWEATHERMAP_API_KEY"
37
+ url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
38
+ response = requests.get(url).json()
39
+ temp = response["main"]["temp"]
40
+ weather_desc = response["weather"][0]["description"]
41
+ return f"The current temperature in {city} is {temp}°C with {weather_desc}."
42
+ except Exception as e:
43
+ return f"Error fetching weather data: {str(e)}"
44
+
45
+ # Currency Conversion Tool
46
+ @tool
47
+ def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
48
+ """Converts currency based on real-time exchange rates.
49
+ Args:
50
+ amount: The amount to be converted.
51
+ from_currency: The source currency (e.g., 'USD').
52
+ to_currency: The target currency (e.g., 'EUR').
53
+ """
54
+ try:
55
+ api_url = f"https://api.exchangerate-api.com/v4/latest/{from_currency}"
56
+ response = requests.get(api_url).json()
57
+ rate = response["rates"].get(to_currency, None)
58
+ if rate:
59
+ converted_amount = amount * rate
60
+ return f"{amount} {from_currency} is approximately {converted_amount:.2f} {to_currency}."
61
+ else:
62
+ return f"Conversion rate for {to_currency} not found."
63
+ except Exception as e:
64
+ return f"Error in currency conversion: {str(e)}"
65
+
66
+ # Fun Fact Generator Tool
67
  @tool
68
+ def get_fun_fact() -> str:
69
+ """Fetches a random fun fact."""
70
+ try:
71
+ response = requests.get("https://uselessfacts.jsph.pl/random.json?language=en").json()
72
+ return response["text"]
73
+ except Exception as e:
74
+ return f"Error fetching fun fact: {str(e)}"
75
+
76
+ # Text Sentiment Analyzer
77
+ @tool
78
+ def analyze_sentiment(text: str) -> str:
79
+ """Analyzes the sentiment of a given text (positive, neutral, or negative).
80
  Args:
81
+ text: The text to be analyzed.
 
82
  """
83
+ try:
84
+ api_url = "https://api-inference.huggingface.co/models/cardiffnlp/twitter-roberta-base-sentiment"
85
+ headers = {"Authorization": "Bearer YOUR_HUGGINGFACE_API_KEY"}
86
+ response = requests.post(api_url, headers=headers, json={"inputs": text})
87
+ sentiment = response.json()[0][0]['label']
88
+ return f"The sentiment of the given text is: {sentiment}"
89
+ except Exception as e:
90
+ return f"Error in sentiment analysis: {str(e)}"
91
 
92
+ # Time Zone Tool
93
  @tool
94
  def get_current_time_in_timezone(timezone: str) -> str:
95
  """A tool that fetches the current local time in a specified timezone.
 
97
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
98
  """
99
  try:
 
100
  tz = pytz.timezone(timezone)
 
101
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
102
  return f"The current local time in {timezone} is: {local_time}"
103
  except Exception as e:
104
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
105
 
 
106
  final_answer = FinalAnswerTool()
107
  model = HfApiModel(
108
+ max_tokens=2096,
109
+ temperature=0.5,
110
+ model_id='https://wxknx1kg971u7k1n.us-east-1.aws.endpoints.huggingface.cloud',
111
+ custom_role_conversions=None,
112
  )
113
 
114
+ # Import tool from Hugging Face Hub
 
115
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
116
 
117
  with open("prompts.yaml", 'r') as stream:
118
  prompt_templates = yaml.safe_load(stream)
119
+
120
+ # Define Agent with All Tools
121
  agent = CodeAgent(
122
  model=model,
123
+ tools=[final_answer, search_tool, image_generation_tool, summarize_text, get_weather, convert_currency, get_fun_fact, analyze_sentiment, get_current_time_in_timezone],
124
  max_steps=6,
125
  verbosity_level=1,
126
  grammar=None,
 
130
  prompt_templates=prompt_templates
131
  )
132
 
133
+ GradioUI(agent).launch()