MADtoBAD commited on
Commit
9c5afb3
·
verified ·
1 Parent(s): 36dc97d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +86 -60
app.py CHANGED
@@ -1,33 +1,27 @@
1
- from smolagents import CodeAgent, DuckDuckGoSearchTool, tool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
 
 
 
 
 
6
  from Gradio_UI import GradioUI
7
 
8
- # Создаем свой собственный инструмент для финального ответа
 
9
  @tool
10
- def final_answer(answer: str) -> str:
11
- """Provide the final answer to the user. Use this when you have the answer to the user's question.
12
 
13
  Args:
14
- answer: The final answer to present to the user
 
 
 
15
  """
16
- return answer
17
-
18
- # Инструменты (tools), используемые агентом:
19
- # - web_search: поиск в интернете через DuckDuckGo
20
- # - get_weather: получение текущей погоды для города
21
- # - get_weather_detailed: подробный прогноз погоды
22
- # - convert_fahrenheit_to_celsius: конвертация температуры
23
- # - get_current_time_in_timezone: время в указанном часовом поясе
24
- # - calculate_math: вычисление математических выражений
25
- # - suggest_weather_sources: рекомендации источников погоды
26
- # - final_answer: инструмент для финального ответа
27
-
28
- @tool
29
- def web_search(query: str) -> str:
30
- """Search the web for information using DuckDuckGo."""
31
  try:
32
  search_tool = DuckDuckGoSearchTool()
33
  results = search_tool(query)
@@ -39,17 +33,26 @@ def web_search(query: str) -> str:
39
 
40
  @tool
41
  def get_weather(city: str) -> str:
42
- """Get current weather for a city using reliable weather services."""
 
 
 
 
 
 
 
43
  try:
 
44
  url = f"https://wttr.in/{city}?format=%C+%t+%h+%w&m&lang=ru"
45
  response = requests.get(url, timeout=10)
46
 
47
  if response.status_code == 200 and response.text.strip():
48
  data = response.text.strip()
 
49
  if '°F' in data:
50
  data = data.replace('°F', '°C')
51
  return f"Погода в {city}:\n{data}"
52
-
53
  url2 = f"https://wttr.in/{city}?format=%C+%t+%h+%w+%P&m&lang=ru"
54
  response2 = requests.get(url2, timeout=10)
55
 
@@ -66,14 +69,24 @@ def get_weather(city: str) -> str:
66
 
67
  @tool
68
  def get_weather_detailed(city: str) -> str:
69
- """Get detailed weather forecast for a city."""
 
 
 
 
 
 
 
70
  try:
 
71
  url = f"https://wttr.in/{city}?m&lang=ru"
72
  response = requests.get(url, timeout=10)
73
 
74
  if response.status_code == 200:
 
75
  lines = response.text.split('\n')
76
- short_forecast = '\n'.join(lines[:8])
 
77
  short_forecast = short_forecast.replace('°F', '°C')
78
  return f"Подробный прогноз для {city}:\n{short_forecast}"
79
  else:
@@ -84,7 +97,14 @@ def get_weather_detailed(city: str) -> str:
84
 
85
  @tool
86
  def convert_fahrenheit_to_celsius(f_temp: float) -> str:
87
- """Convert Fahrenheit temperature to Celsius."""
 
 
 
 
 
 
 
88
  try:
89
  c_temp = (f_temp - 32) * 5/9
90
  return f"{f_temp}°F = {c_temp:.1f}°C"
@@ -93,18 +113,32 @@ def convert_fahrenheit_to_celsius(f_temp: float) -> str:
93
 
94
  @tool
95
  def get_current_time_in_timezone(timezone: str) -> str:
96
- """Get current local time in specified timezone."""
 
 
 
 
 
 
 
97
  try:
98
  tz = pytz.timezone(timezone)
99
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
100
  return f"Текущее время в {timezone}: {local_time}"
101
  except Exception as e:
102
  return f"Ошибка получения времени для часового пояса '{timezone}': {str(e)}"
103
-
104
  @tool
105
  def calculate_math(expression: str) -> str:
106
- """Calculate mathematical expressions safely."""
 
 
 
 
 
 
 
107
  try:
 
108
  allowed_chars = set('0123456789+-*/.() ')
109
  if all(c in allowed_chars for c in expression):
110
  result = eval(expression)
@@ -116,7 +150,14 @@ def calculate_math(expression: str) -> str:
116
 
117
  @tool
118
  def suggest_weather_sources(city: str) -> str:
119
- """Suggest reliable weather sources for a city."""
 
 
 
 
 
 
 
120
  sources = [
121
  f"Gismeteo: https://www.gismeteo.ru/weather-{city.lower()}-4368/",
122
  f"Yandex.Погода: https://yandex.ru/pogoda/{city.lower()}",
@@ -126,36 +167,21 @@ def suggest_weather_sources(city: str) -> str:
126
 
127
  return f"Надежные источники погоды для {city}:\n" + "\n".join(sources)
128
 
129
- # Используем локальную модель вместо HfApiModel
130
- try:
131
- from transformers import AutoModelForCausalLM, AutoTokenizer
132
- from smolagents import TransformersModel
133
-
134
- model = TransformersModel(
135
- model_id='Qwen/Qwen2.5-Coder-1.5B', # Используем меньшую модель для совместимости
136
- max_tokens=2096,
137
- temperature=0.5
138
- )
139
- except ImportError:
140
- # Если transformers не установлен, используем простую модель
141
- from smolagents import LiteLLMModel
142
- model = LiteLLMModel(
143
- model_id='gpt-3.5-turbo',
144
- max_tokens=2096,
145
- temperature=0.5
146
- )
147
 
148
- # Загружаем промпты, если файл существует, иначе создаем базовый шаблон
149
- try:
150
- with open("prompts.yaml", 'r') as stream:
151
- prompt_templates = yaml.safe_load(stream)
152
- except FileNotFoundError:
153
- prompt_templates = {
154
- "final_answer": {
155
- "pre_messages": "Based on my research: ",
156
- "post_messages": ""
157
- }
158
- }
 
 
159
 
160
  if "final_answer" not in prompt_templates:
161
  prompt_templates["final_answer"] = {
@@ -167,7 +193,7 @@ agent = CodeAgent(
167
  model=model,
168
  tools=[final_answer, web_search, get_weather, get_weather_detailed, convert_fahrenheit_to_celsius, get_current_time_in_timezone, calculate_math, suggest_weather_sources],
169
  max_steps=8,
170
- verbosity_level=0,
171
  grammar=None,
172
  planning_interval=None,
173
  name=None,
@@ -175,4 +201,4 @@ agent = CodeAgent(
175
  prompt_templates=prompt_templates
176
  )
177
 
178
- GradioUI(agent).launch()
 
1
+ from smolagents import CodeAgent, HfApiModel, load_tool, tool, DuckDuckGoSearchTool
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
+ import base64
7
+ import os
8
+ import io
9
+ from PIL import Image
10
+ from tools.final_answer import FinalAnswerTool
11
  from Gradio_UI import GradioUI
12
 
13
+ # 1. функции-инструменты
14
+
15
  @tool
16
+ def web_search(query: str) -> str:
17
+ """Search the web for information using DuckDuckGo.
18
 
19
  Args:
20
+ query: The search query to look up
21
+
22
+ Returns:
23
+ Search results from DuckDuckGo
24
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  try:
26
  search_tool = DuckDuckGoSearchTool()
27
  results = search_tool(query)
 
33
 
34
  @tool
35
  def get_weather(city: str) -> str:
36
+ """Get current weather for a city using reliable weather services.
37
+
38
+ Args:
39
+ city: The name of the city to get weather for (e.g., 'Moscow', 'London')
40
+
41
+ Returns:
42
+ Current weather information in Celsius
43
+ """
44
  try:
45
+
46
  url = f"https://wttr.in/{city}?format=%C+%t+%h+%w&m&lang=ru"
47
  response = requests.get(url, timeout=10)
48
 
49
  if response.status_code == 200 and response.text.strip():
50
  data = response.text.strip()
51
+
52
  if '°F' in data:
53
  data = data.replace('°F', '°C')
54
  return f"Погода в {city}:\n{data}"
55
+
56
  url2 = f"https://wttr.in/{city}?format=%C+%t+%h+%w+%P&m&lang=ru"
57
  response2 = requests.get(url2, timeout=10)
58
 
 
69
 
70
  @tool
71
  def get_weather_detailed(city: str) -> str:
72
+ """Get detailed weather forecast for a city.
73
+
74
+ Args:
75
+ city: The name of the city
76
+
77
+ Returns:
78
+ Detailed weather information in Celsius
79
+ """
80
  try:
81
+
82
  url = f"https://wttr.in/{city}?m&lang=ru"
83
  response = requests.get(url, timeout=10)
84
 
85
  if response.status_code == 200:
86
+
87
  lines = response.text.split('\n')
88
+ short_forecast = '\n'.join(lines[:8]) # Первые 8 строк
89
+
90
  short_forecast = short_forecast.replace('°F', '°C')
91
  return f"Подробный прогноз для {city}:\n{short_forecast}"
92
  else:
 
97
 
98
  @tool
99
  def convert_fahrenheit_to_celsius(f_temp: float) -> str:
100
+ """Convert Fahrenheit temperature to Celsius.
101
+
102
+ Args:
103
+ f_temp: Temperature in Fahrenheit
104
+
105
+ Returns:
106
+ Temperature in Celsius
107
+ """
108
  try:
109
  c_temp = (f_temp - 32) * 5/9
110
  return f"{f_temp}°F = {c_temp:.1f}°C"
 
113
 
114
  @tool
115
  def get_current_time_in_timezone(timezone: str) -> str:
116
+ """Get current local time in specified timezone.
117
+
118
+ Args:
119
+ timezone: A valid timezone (e.g., 'America/New_York', 'Europe/Moscow')
120
+
121
+ Returns:
122
+ Current time in the specified timezone
123
+ """
124
  try:
125
  tz = pytz.timezone(timezone)
126
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
127
  return f"Текущее время в {timezone}: {local_time}"
128
  except Exception as e:
129
  return f"Ошибка получения времени для часового пояса '{timezone}': {str(e)}"
 
130
  @tool
131
  def calculate_math(expression: str) -> str:
132
+ """Calculate mathematical expressions safely.
133
+
134
+ Args:
135
+ expression: A mathematical expression (e.g., '2+2', '5*3/2')
136
+
137
+ Returns:
138
+ Result of the calculation
139
+ """
140
  try:
141
+
142
  allowed_chars = set('0123456789+-*/.() ')
143
  if all(c in allowed_chars for c in expression):
144
  result = eval(expression)
 
150
 
151
  @tool
152
  def suggest_weather_sources(city: str) -> str:
153
+ """Suggest reliable weather sources for a city.
154
+
155
+ Args:
156
+ city: The name of the city
157
+
158
+ Returns:
159
+ List of reliable weather sources
160
+ """
161
  sources = [
162
  f"Gismeteo: https://www.gismeteo.ru/weather-{city.lower()}-4368/",
163
  f"Yandex.Погода: https://yandex.ru/pogoda/{city.lower()}",
 
167
 
168
  return f"Надежные источники погоды для {city}:\n" + "\n".join(sources)
169
 
170
+ # 2. остальные объекты
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
+ final_answer = FinalAnswerTool()
173
+
174
+ model = HfApiModel(
175
+ max_tokens=2096,
176
+ temperature=0.5,
177
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
178
+ custom_role_conversions=None,
179
+ )
180
+
181
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
182
+
183
+ with open("prompts.yaml", 'r') as stream:
184
+ prompt_templates = yaml.safe_load(stream)
185
 
186
  if "final_answer" not in prompt_templates:
187
  prompt_templates["final_answer"] = {
 
193
  model=model,
194
  tools=[final_answer, web_search, get_weather, get_weather_detailed, convert_fahrenheit_to_celsius, get_current_time_in_timezone, calculate_math, suggest_weather_sources],
195
  max_steps=8,
196
+ verbosity_level=1,
197
  grammar=None,
198
  planning_interval=None,
199
  name=None,
 
201
  prompt_templates=prompt_templates
202
  )
203
 
204
+ GradioUI(agent).launch()