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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -33
app.py CHANGED
@@ -1,69 +1,113 @@
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, 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
 
89
  model = HfApiModel(
90
+ max_tokens=2096,
91
+ temperature=0.5,
92
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
93
+ custom_role_conversions=None,
94
  )
95
 
 
 
96
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
97
 
98
  with open("prompts.yaml", 'r') as stream:
99
  prompt_templates = yaml.safe_load(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
 
113
+ GradioUI(agent).launch()