SaraM2727 commited on
Commit
c4c003b
·
verified ·
1 Parent(s): d15dc03

Create app1.py

Browse files
Files changed (1) hide show
  1. app1.py +159 -0
app1.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Tool: Fetch current time in a given timezone
10
+ @tool
11
+ def get_current_time_in_timezone(timezone: str) -> str:
12
+ """
13
+ Fetches the current local time in a specified timezone.
14
+
15
+ Args:
16
+ timezone (str): The timezone string (e.g., 'America/New_York').
17
+
18
+ Returns:
19
+ str: The current local time in the specified timezone.
20
+ """
21
+ try:
22
+ tz = pytz.timezone(timezone)
23
+ local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
24
+ return f"The current local time in {timezone} is: {local_time}"
25
+ except Exception as e:
26
+ return f"Error fetching time for timezone '{timezone}': {str(e)}"
27
+
28
+ # Tool: Fetch real-time weather for a given location
29
+ @tool
30
+ def get_weather(city: str) -> str:
31
+ """
32
+ Fetches the current weather for a given city.
33
+
34
+ Args:
35
+ city (str): The name of the city.
36
+
37
+ Returns:
38
+ str: Weather description and temperature.
39
+ """
40
+ api_url = f"https://wttr.in/{city}?format=%C+%t"
41
+ response = requests.get(api_url)
42
+ if response.status_code == 200:
43
+ return response.text
44
+ return "Unable to retrieve weather information."
45
+
46
+ # Tool: Fetch currency exchange rate
47
+ @tool
48
+ def get_exchange_rate(base_currency: str, target_currency: str) -> str:
49
+ """
50
+ Fetches the exchange rate between two currencies.
51
+
52
+ Args:
53
+ base_currency (str): The currency to convert from.
54
+ target_currency (str): The currency to convert to.
55
+
56
+ Returns:
57
+ str: Exchange rate information.
58
+ """
59
+ url = f"https://api.exchangerate-api.com/v4/latest/{base_currency}"
60
+ response = requests.get(url)
61
+ if response.status_code == 200:
62
+ data = response.json()
63
+ rate = data['rates'].get(target_currency, "N/A")
64
+ return f"1 {base_currency} = {rate} {target_currency}"
65
+ return "Exchange rate information not available."
66
+
67
+ # Tool: Fetch Wikipedia summary
68
+ @tool
69
+ def get_wikipedia_summary(query: str) -> str:
70
+ """
71
+ Fetches a short summary from Wikipedia.
72
+
73
+ Args:
74
+ query (str): The topic to search on Wikipedia.
75
+
76
+ Returns:
77
+ str: Summary of the topic.
78
+ """
79
+ url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{query}"
80
+ response = requests.get(url)
81
+ if response.status_code == 200:
82
+ return response.json().get("extract", "No summary available.")
83
+ return "Wikipedia summary not found."
84
+
85
+ # Tool: Fetch latest news headlines
86
+ @tool
87
+ def get_latest_news() -> str:
88
+ """
89
+ Fetches the latest news headlines.
90
+
91
+ Returns:
92
+ str: Top 5 latest news headlines.
93
+ """
94
+ url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=YOUR_NEWSAPI_KEY"
95
+ response = requests.get(url)
96
+ if response.status_code == 200:
97
+ articles = response.json().get("articles", [])[:5]
98
+ return "\n".join([f"{i+1}. {article['title']}" for i, article in enumerate(articles)])
99
+ return "Unable to retrieve news."
100
+
101
+ # Tool: Fetch stock price for a given company symbol
102
+ @tool
103
+ def get_stock_price(symbol: str) -> str:
104
+ """
105
+ Fetches the latest stock price for a given company symbol.
106
+
107
+ Args:
108
+ symbol (str): The stock ticker symbol.
109
+
110
+ Returns:
111
+ str: The latest stock price.
112
+ """
113
+ url = f"https://finnhub.io/api/v1/quote?symbol={symbol}&token=YOUR_FINNHUB_API_KEY"
114
+ response = requests.get(url)
115
+ if response.status_code == 200:
116
+ data = response.json()
117
+ return f"Stock price of {symbol}: ${data.get('c', 'N/A')}"
118
+ return "Stock information not available."
119
+
120
+ final_answer = FinalAnswerTool()
121
+
122
+ # Hugging Face model setup
123
+ model = HfApiModel(
124
+ max_tokens=2096,
125
+ temperature=0.5,
126
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
127
+ custom_role_conversions=None,
128
+ )
129
+
130
+ # Load image generation tool from Hugging Face
131
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
132
+
133
+ with open("prompts.yaml", 'r') as stream:
134
+ prompt_templates = yaml.safe_load(stream)
135
+
136
+ # Creating the AI agent
137
+ agent = CodeAgent(
138
+ model=model,
139
+ tools=[
140
+ final_answer,
141
+ get_current_time_in_timezone,
142
+ get_weather,
143
+ get_exchange_rate,
144
+ get_wikipedia_summary,
145
+ get_latest_news,
146
+ get_stock_price,
147
+ image_generation_tool,
148
+ ],
149
+ max_steps=6,
150
+ verbosity_level=1,
151
+ grammar=None,
152
+ planning_interval=None,
153
+ name=None,
154
+ description=None,
155
+ prompt_templates=prompt_templates
156
+ )
157
+
158
+ # Launch Gradio UI for interaction
159
+ GradioUI(agent).launch()