Superbrida commited on
Commit
c907a28
·
verified ·
1 Parent(s): 5cd96ae

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -72
app.py CHANGED
@@ -1,88 +1,32 @@
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
- from transformers import pipeline
9
- from geopy.distance import geodesic
10
 
11
- # Strumento per la traduzione
12
  @tool
13
- def translate_text(text: str, target_lang: str) -> str:
14
- """A tool that translates text into the specified language.
15
  Args:
16
- text: The text to translate.
17
- target_lang: The target language code (e.g., 'en', 'fr', 'de').
18
  """
19
- try:
20
- translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-{target_lang}")
21
- translated_text = translator(text)[0]['translation_text']
22
- return translated_text
23
- except Exception as e:
24
- return f"Error in translation: {str(e)}"
25
-
26
- # Strumento per calcolare la distanza tra due coordinate GPS
27
- @tool
28
- def calculate_distance(coord1: str, coord2: str) -> str:
29
- """A tool that calculates the distance between two GPS coordinates.
30
- Args:
31
- coord1: The first coordinate in 'lat,lon' format.
32
- coord2: The second coordinate in 'lat,lon' format.
33
- """
34
- try:
35
- lat1, lon1 = map(float, coord1.split(','))
36
- lat2, lon2 = map(float, coord2.split(','))
37
- distance_km = geodesic((lat1, lon1), (lat2, lon2)).kilometers
38
- return f"The distance between {coord1} and {coord2} is {distance_km:.2f} km."
39
- except Exception as e:
40
- return f"Error calculating distance: {str(e)}"
41
-
42
- # Strumento per analisi del sentimento
43
- @tool
44
- def analyze_sentiment(text: str) -> str:
45
- """A tool that analyzes the sentiment of a given text.
46
- Args:
47
- text: The text to analyze.
48
- """
49
- try:
50
- sentiment_analyzer = pipeline("sentiment-analysis")
51
- result = sentiment_analyzer(text)[0]
52
- return f"Sentiment: {result['label']} (Confidence: {result['score']:.2f})"
53
- except Exception as e:
54
- return f"Error in sentiment analysis: {str(e)}"
55
-
56
- # Strumento per generare testo creativo
57
- @tool
58
- def generate_creative_text(prompt: str) -> str:
59
- """A tool that generates creative text based on a given prompt.
60
- Args:
61
- prompt: The input prompt for text generation.
62
- """
63
- try:
64
- generator = pipeline("text-generation", model="gpt2")
65
- response = generator(prompt, max_length=100, num_return_sequences=1)
66
- return response[0]['generated_text']
67
- except Exception as e:
68
- return f"Error in text generation: {str(e)}"
69
 
70
- # Strumento per ottenere il meteo attuale
71
  @tool
72
- def get_weather(city: str) -> str:
73
- """A tool that fetches the current weather for a specified city.
74
  Args:
75
- city: The city name.
76
  """
77
  try:
78
- api_key = "YOUR_OPENWEATHER_API_KEY"
79
- url = f"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}&units=metric"
80
- response = requests.get(url).json()
81
- weather = response['weather'][0]['description']
82
- temp = response['main']['temp']
83
- return f"Current weather in {city}: {weather}, {temp}°C."
84
  except Exception as e:
85
- return f"Error fetching weather: {str(e)}"
86
 
87
  final_answer = FinalAnswerTool()
88
 
@@ -100,13 +44,13 @@ with open("prompts.yaml", 'r') as stream:
100
 
101
  agent = CodeAgent(
102
  model=model,
103
- tools=[final_answer, translate_text, calculate_distance, analyze_sentiment, generate_creative_text, get_weather],
104
  max_steps=6,
105
  verbosity_level=1,
106
  grammar=None,
107
  planning_interval=None,
108
- name="AdvancedCodeAgent",
109
- description="An enhanced AI agent with additional capabilities.",
110
  prompt_templates=prompt_templates
111
  )
112
 
 
1
  from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
2
  import datetime
 
3
  import pytz
4
  import yaml
5
  from tools.final_answer import FinalAnswerTool
6
  from Gradio_UI import GradioUI
 
 
7
 
8
+ # Strumento personalizzato per restituire un messaggio di saluto
9
  @tool
10
+ def greet_user(name: str) -> str:
11
+ """A tool that returns a greeting message.
12
  Args:
13
+ name: The name of the user.
 
14
  """
15
+ return f"Hello, {name}! How can I assist you today?"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ # Strumento per ottenere l'ora corrente in un fuso orario specifico
18
  @tool
19
+ def get_current_time_in_timezone(timezone: str) -> str:
20
+ """A tool that fetches the current local time in a specified timezone.
21
  Args:
22
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
23
  """
24
  try:
25
+ tz = pytz.timezone(timezone)
26
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
27
+ return f"The current local time in {timezone} is: {local_time}"
 
 
 
28
  except Exception as e:
29
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
30
 
31
  final_answer = FinalAnswerTool()
32
 
 
44
 
45
  agent = CodeAgent(
46
  model=model,
47
+ tools=[final_answer, greet_user, get_current_time_in_timezone],
48
  max_steps=6,
49
  verbosity_level=1,
50
  grammar=None,
51
  planning_interval=None,
52
+ name=None,
53
+ description=None,
54
  prompt_templates=prompt_templates
55
  )
56