MADtoBAD commited on
Commit
2305e0b
·
verified ·
1 Parent(s): 9c5afb3

Update app.py

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