BairL commited on
Commit
b4b6b2f
·
verified ·
1 Parent(s): fbf9b96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -61
app.py CHANGED
@@ -3,40 +3,31 @@ import datetime
3
  import requests
4
  import pytz
5
  import yaml
 
6
  from smolagents import CodeAgent, HfApiModel, load_tool, tool
7
  from tools.final_answer import FinalAnswerTool
8
  from Gradio_UI import GradioUI
9
 
 
 
 
10
 
11
- # -------------------------
12
- # Пример кастомного инструмента
13
- # -------------------------
14
  @tool
15
  def my_custom_tool(arg1: str, arg2: int) -> str:
16
- """A tool that does nothing yet.
17
-
18
  Args:
19
- arg1: the first argument
20
- arg2: the second argument
21
-
22
- Returns:
23
- A placeholder string message.
24
  """
25
- return "What magic will you build ?"
26
-
27
 
28
- # -------------------------
29
- # Текущее время в таймзоне
30
- # -------------------------
31
  @tool
32
  def get_current_time_in_timezone(timezone: str) -> str:
33
- """Fetches the current local time in a specified timezone.
34
-
35
  Args:
36
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
37
-
38
- Returns:
39
- A string with the current local time in the given timezone.
40
  """
41
  try:
42
  tz = pytz.timezone(timezone)
@@ -45,19 +36,12 @@ def get_current_time_in_timezone(timezone: str) -> str:
45
  except Exception as e:
46
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
47
 
48
-
49
- # -------------------------
50
- # Курс EUR
51
- # -------------------------
52
  @tool
53
  def get_eur_exchange_rate(currency_code: str) -> str:
54
- """Retrieves the current exchange rate from EUR to a given currency.
55
-
56
  Args:
57
  currency_code: The 3-letter currency code in lowercase (e.g., "usd", "gbp", "jpy").
58
-
59
- Returns:
60
- The exchange rate as a string.
61
  """
62
  try:
63
  api_url = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.json"
@@ -67,25 +51,18 @@ def get_eur_exchange_rate(currency_code: str) -> str:
67
 
68
  date = data.get("date", "Unknown date")
69
  exchange_rates = data.get("eur", {})
70
-
71
  if currency_code in exchange_rates:
72
  rate = exchange_rates[currency_code]
73
  return f"1 EUR = {rate} {currency_code.upper()} (as of {date})"
74
  else:
75
- return f"Currency code '{currency_code}' not found in the exchange rate data."
76
  except Exception as e:
77
- return f"Error fetching exchange rate: {str(e)}"
78
-
79
 
80
- # -------------------------
81
- # Шутка
82
- # -------------------------
83
  @tool
84
  def get_simple_joke() -> str:
85
- """Fetches a random joke from JokeAPI with minimal filtering.
86
-
87
- Returns:
88
- A string with the joke or an error message.
89
  """
90
  try:
91
  api_url = "https://v2.jokeapi.dev/joke/any"
@@ -99,39 +76,35 @@ def get_simple_joke() -> str:
99
  if joke_data.get("type") == "single":
100
  return f"Here's a joke:\n\n{joke_data.get('joke', '')}"
101
  elif joke_data.get("type") == "twopart":
102
- setup = joke_data.get("setup", "")
103
- delivery = joke_data.get("delivery", "")
104
- return f"Here's a joke:\n\n{setup}\n{delivery}"
105
 
106
  return "Could not parse joke from API response"
107
  except Exception as e:
108
  return f"Error: {str(e)}"
109
 
110
 
111
- # -------------------------
112
- # Настройка агента
113
- # -------------------------
114
- final_answer = FinalAnswerTool()
115
 
116
- # ✅ Токен теперь берём из Hugging Face Secrets
117
- hf_token = os.environ.get("HF_API_TOKEN")
118
- if not hf_token:
119
- raise ValueError("HF_API_TOKEN is not set. Please add it in Hugging Face Secrets.")
120
 
121
  model = HfApiModel(
122
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
123
  max_tokens=2096,
124
  temperature=0.5,
125
- api_key=hf_token, # <--- ключ теперь из секрета
126
  )
127
 
128
- # Инструмент для генерации картинок
129
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
130
 
131
- # Загружаем шаблоны промптов
132
  with open("prompts.yaml", "r") as stream:
133
  prompt_templates = yaml.safe_load(stream)
134
 
 
135
  agent = CodeAgent(
136
  model=model,
137
  tools=[
@@ -146,13 +119,10 @@ agent = CodeAgent(
146
  verbosity_level=1,
147
  grammar=None,
148
  planning_interval=None,
149
- name="MyAgent",
150
- description="An agent with custom tools (time, jokes, exchange rate, images).",
151
  prompt_templates=prompt_templates,
152
  )
153
 
154
- # -------------------------
155
- # Запуск Gradio UI
156
- # -------------------------
157
- if __name__ == "__main__":
158
- GradioUI(agent).launch()
 
3
  import requests
4
  import pytz
5
  import yaml
6
+
7
  from smolagents import CodeAgent, HfApiModel, load_tool, tool
8
  from tools.final_answer import FinalAnswerTool
9
  from Gradio_UI import GradioUI
10
 
11
+ # ---------------------------
12
+ # Custom tools
13
+ # ---------------------------
14
 
 
 
 
15
  @tool
16
  def my_custom_tool(arg1: str, arg2: int) -> str:
17
+ """
18
+ A tool that demonstrates how to define custom functions.
19
  Args:
20
+ arg1: The first argument as a string.
21
+ arg2: The second argument as an integer.
 
 
 
22
  """
23
+ return f"You passed arg1={arg1} and arg2={arg2}. Imagine some real magic here!"
 
24
 
 
 
 
25
  @tool
26
  def get_current_time_in_timezone(timezone: str) -> str:
27
+ """
28
+ A tool that fetches the current local time in a specified timezone.
29
  Args:
30
  timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
 
31
  """
32
  try:
33
  tz = pytz.timezone(timezone)
 
36
  except Exception as e:
37
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
38
 
 
 
 
 
39
  @tool
40
  def get_eur_exchange_rate(currency_code: str) -> str:
41
+ """
42
+ A tool that retrieves the current exchange rate from EUR to a given currency.
43
  Args:
44
  currency_code: The 3-letter currency code in lowercase (e.g., "usd", "gbp", "jpy").
 
 
 
45
  """
46
  try:
47
  api_url = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.json"
 
51
 
52
  date = data.get("date", "Unknown date")
53
  exchange_rates = data.get("eur", {})
 
54
  if currency_code in exchange_rates:
55
  rate = exchange_rates[currency_code]
56
  return f"1 EUR = {rate} {currency_code.upper()} (as of {date})"
57
  else:
58
+ return f"Currency code '{currency_code}' not found."
59
  except Exception as e:
60
+ return f"Error fetching exchange rate data: {str(e)}"
 
61
 
 
 
 
62
  @tool
63
  def get_simple_joke() -> str:
64
+ """
65
+ A tool that fetches a random joke from JokeAPI with minimal filtering.
 
 
66
  """
67
  try:
68
  api_url = "https://v2.jokeapi.dev/joke/any"
 
76
  if joke_data.get("type") == "single":
77
  return f"Here's a joke:\n\n{joke_data.get('joke', '')}"
78
  elif joke_data.get("type") == "twopart":
79
+ return f"Here's a joke:\n\n{joke_data.get('setup', '')}\n{joke_data.get('delivery', '')}"
 
 
80
 
81
  return "Could not parse joke from API response"
82
  except Exception as e:
83
  return f"Error: {str(e)}"
84
 
85
 
86
+ # ---------------------------
87
+ # Setup model and agent
88
+ # ---------------------------
 
89
 
90
+ # ✅ Токен берется автоматически из Secrets (HF_TOKEN), его не надо писать в коде!
91
+ final_answer = FinalAnswerTool()
 
 
92
 
93
  model = HfApiModel(
94
  model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
95
  max_tokens=2096,
96
  temperature=0.5,
97
+ custom_role_conversions=None,
98
  )
99
 
100
+ # Load external tool from Hub
101
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
102
 
103
+ # Load prompts
104
  with open("prompts.yaml", "r") as stream:
105
  prompt_templates = yaml.safe_load(stream)
106
 
107
+ # Build agent
108
  agent = CodeAgent(
109
  model=model,
110
  tools=[
 
119
  verbosity_level=1,
120
  grammar=None,
121
  planning_interval=None,
 
 
122
  prompt_templates=prompt_templates,
123
  )
124
 
125
+ # ---------------------------
126
+ # Launch Gradio UI
127
+ # ---------------------------
128
+ GradioUI(agent).launch()