medoed-8 commited on
Commit
e34c4ab
·
verified ·
1 Parent(s): fad238d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +38 -41
app.py CHANGED
@@ -1,7 +1,6 @@
1
  from smolagents import CodeAgent, DuckDuckGoSearchTool, load_tool, tool
2
- from smolagents.models import LiteLLMModel # или другой подходящий класс
3
  import datetime
4
- import requests
5
  import pytz
6
  import yaml
7
  from tools.final_answer import FinalAnswerTool
@@ -9,17 +8,13 @@ from Gradio_UI import GradioUI
9
 
10
  # ==================== ИНСТРУМЕНТЫ ====================
11
 
12
- # 1. Инструмент для поиска в интернете
13
  search_tool = DuckDuckGoSearchTool()
14
 
15
- # 2. Инструмент для времени (уже есть)
16
  @tool
17
  def get_current_time_in_timezone(timezone: str) -> str:
18
- """Получает текущее время в указанном часовом поясе.
19
-
20
- Args:
21
- timezone: Часовой пояс (например, 'Europe/Moscow', 'America/New_York')
22
- """
23
  try:
24
  tz = pytz.timezone(timezone)
25
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
@@ -27,56 +22,58 @@ def get_current_time_in_timezone(timezone: str) -> str:
27
  except Exception as e:
28
  return f"Ошибка: неправильный часовой пояс '{timezone}'"
29
 
30
- # 3. Ваш собственный инструмент (пример)
31
  @tool
32
- def get_exchange_rate(currency: str) -> str:
33
- """Получает примерный курс валюты к рублю.
34
-
35
- Args:
36
- currency: Код валюты (USD, EUR, GBP)
37
- """
38
- rates = {
39
- "USD": 90.5,
40
- "EUR": 98.2,
41
- "GBP": 115.7
42
- }
43
-
44
- if currency.upper() in rates:
45
- return f"Примерный курс {currency}: {rates[currency.upper()]} руб."
46
- else:
47
- return f"Курс для {currency} не найден. Доступно: USD, EUR, GBP"
48
 
49
- # ==================== СОЗДАНИЕ АГЕНТА ====================
50
 
51
  final_answer = FinalAnswerTool()
52
 
53
- # Модель LLM
54
- model = InferenceClientModel(
 
 
55
  max_tokens=2096,
56
- temperature=0.5,
57
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',
58
- custom_role_conversions=None,
59
  )
60
 
61
- # Загрузка инструмента генерации изображений
62
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
 
 
 
 
 
 
 
 
 
 
63
 
64
- # Загрузка промпта
65
  with open("prompts.yaml", 'r') as stream:
66
  prompt_templates = yaml.safe_load(stream)
67
-
68
- # СОЗДАНИЕ АГЕНТА со всеми инструментами
 
69
  agent = CodeAgent(
70
  model=model,
71
  tools=[
72
- final_answer, # ОБЯЗАТЕЛЬНО оставить!
73
  search_tool,
74
  get_current_time_in_timezone,
75
- get_exchange_rate,
76
  image_generation_tool
77
  ],
78
- max_steps=6, # Максимум шагов цикла
79
- verbosity_level=2, # 2 = показывать мысли и действия
80
  prompt_templates=prompt_templates
81
  )
82
 
 
1
  from smolagents import CodeAgent, DuckDuckGoSearchTool, load_tool, tool
2
+ from smolagents.models import LiteLLMModel # ← ПРАВИЛЬНЫЙ ИМПОРТ
3
  import datetime
 
4
  import pytz
5
  import yaml
6
  from tools.final_answer import FinalAnswerTool
 
8
 
9
  # ==================== ИНСТРУМЕНТЫ ====================
10
 
11
+ # 1. Поиск в интернете
12
  search_tool = DuckDuckGoSearchTool()
13
 
14
+ # 2. Время в часовом поясе
15
  @tool
16
  def get_current_time_in_timezone(timezone: str) -> str:
17
+ """Получает текущее время в указанном часовом поясе."""
 
 
 
 
18
  try:
19
  tz = pytz.timezone(timezone)
20
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
 
22
  except Exception as e:
23
  return f"Ошибка: неправильный часовой пояс '{timezone}'"
24
 
25
+ # 3. Простой калькулятор
26
  @tool
27
+ def calculator(expression: str) -> str:
28
+ """Вычисляет математическое выражение."""
29
+ try:
30
+ # Внимание: eval опасен! Только для демонстрации
31
+ result = eval(expression)
32
+ return f"Результат: {result}"
33
+ except Exception as e:
34
+ return f"Ошибка вычисления: {str(e)}"
 
 
 
 
 
 
 
 
35
 
36
+ # ==================== СОЗДАНИЕ МОДЕЛИ ====================
37
 
38
  final_answer = FinalAnswerTool()
39
 
40
+ # ИСПРАВЛЕНИЕ: Используем LiteLLMModel
41
+ model = LiteLLMModel(
42
+ model="huggingface/Qwen/Qwen2.5-Coder-32B-Instruct",
43
+ api_base="https://api-inference.huggingface.co/models",
44
  max_tokens=2096,
45
+ temperature=0.5
 
 
46
  )
47
 
48
+ # ==================== ЗАГРУЗКА ИНСТРУМЕНТОВ ====================
49
+
50
+ # Генерация изображений
51
+ try:
52
+ image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
53
+ except:
54
+ @tool
55
+ def image_generation_tool(prompt: str) -> str:
56
+ """Генерация изображений (заглушка)."""
57
+ return f"Изображение '{prompt}' временно недоступно"
58
+
59
+ # ==================== ЗАГРУЗКА ПРОМПТА ====================
60
 
 
61
  with open("prompts.yaml", 'r') as stream:
62
  prompt_templates = yaml.safe_load(stream)
63
+
64
+ # ==================== СОЗДАНИЕ АГЕНТА ====================
65
+
66
  agent = CodeAgent(
67
  model=model,
68
  tools=[
69
+ final_answer,
70
  search_tool,
71
  get_current_time_in_timezone,
72
+ calculator,
73
  image_generation_tool
74
  ],
75
+ max_steps=6,
76
+ verbosity_level=2,
77
  prompt_templates=prompt_templates
78
  )
79