BairL commited on
Commit
220bb68
·
verified ·
1 Parent(s): dd706c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -47
app.py CHANGED
@@ -1,115 +1,131 @@
1
- import os
2
  import datetime
3
  import requests
4
  import pytz
5
  import yaml
6
-
7
- from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, load_tool, tool
8
  from tools.final_answer import FinalAnswerTool
9
- from Gradio_UI import GradioUI
10
 
11
- # ---------------------- Custom Tools ----------------------
12
 
 
13
  @tool
14
- def my_custom_tool(arg1: str, arg2: int) -> str:
15
- """A simple example tool that just echoes its inputs.
 
16
  Args:
17
- arg1: the first arguments
18
  arg2: the second argument
19
  """
20
- return f"Tool received arg1={arg1}, arg2={arg2}"
21
 
22
  @tool
23
  def get_current_time_in_timezone(timezone: str) -> str:
24
- """Fetches the current local time in a specified timezone.
25
  Args:
26
- timezone: e.g., 'America/New_York'
27
  """
28
  try:
 
29
  tz = pytz.timezone(timezone)
 
30
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
31
  return f"The current local time in {timezone} is: {local_time}"
32
  except Exception as e:
33
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
34
 
 
35
  @tool
36
  def get_eur_exchange_rate(currency_code: str) -> str:
37
- """Retrieves the current exchange rate from EUR to a given currency.
 
38
  Args:
39
- currency_code: 3-letter code, e.g. "usd", "gbp"
40
  """
 
41
  try:
 
42
  api_url = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.json"
43
  response = requests.get(api_url, timeout=10)
44
  response.raise_for_status()
 
45
  data = response.json()
46
-
 
47
  date = data.get("date", "Unknown date")
48
  exchange_rates = data.get("eur", {})
 
 
49
  if currency_code in exchange_rates:
50
  rate = exchange_rates[currency_code]
51
  return f"1 EUR = {rate} {currency_code.upper()} (as of {date})"
52
  else:
53
- return f"Currency code '{currency_code}' not found."
 
 
 
54
  except Exception as e:
55
- return f"Error fetching exchange rate: {str(e)}"
56
 
57
- @tool
58
  def get_simple_joke() -> str:
59
- """Fetches a random joke from JokeAPI."""
 
60
  try:
 
61
  api_url = "https://v2.jokeapi.dev/joke/any"
 
62
  response = requests.get(api_url, timeout=10)
63
  response.raise_for_status()
 
64
  joke_data = response.json()
65
-
66
  if joke_data.get("error", False):
67
  return f"Error: {joke_data.get('message', 'Could not get joke')}"
68
-
69
  if joke_data.get("type") == "single":
70
  return f"Here's a joke:\n\n{joke_data.get('joke', '')}"
71
  elif joke_data.get("type") == "twopart":
72
- return f"Here's a joke:\n\n{joke_data.get('setup', '')}\n{joke_data.get('delivery', '')}"
73
-
74
- return "Could not parse joke from API response."
 
 
 
75
  except Exception as e:
76
- return f"Error fetching joke: {str(e)}"
77
 
78
- # ---------------------- Model ----------------------
79
 
80
- # ВАЖНО: токен нужно добавить в Secrets как HF_TOKEN
81
- hf_token = os.environ.get("HF_TOKEN")
82
- if not hf_token:
83
- raise RuntimeError("❌ HF_TOKEN is not set in repository secrets!")
84
 
85
- model = HfApiModel(
86
- model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
87
- max_tokens=2048,
88
- temperature=0.5,
89
- api_key=hf_token, # <-- токен берется из Secrets
90
- )
91
 
92
- # ---------------------- Agent ----------------------
 
93
 
94
- final_answer = FinalAnswerTool()
 
 
 
 
 
95
 
96
- # Подгружаем промпты
97
- with open("prompts.yaml", "r") as stream:
98
- prompt_templates = yaml.safe_load(stream)
99
 
100
- # Импорт примера инструмента с Hugging Face Hub
101
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
102
 
 
 
 
103
  agent = CodeAgent(
104
  model=model,
105
- tools=[final_answer, my_custom_tool, get_current_time_in_timezone,
106
- get_eur_exchange_rate, get_simple_joke, image_generation_tool],
107
  max_steps=6,
108
  verbosity_level=1,
109
- prompt_templates=prompt_templates,
 
 
 
 
110
  )
111
 
112
- # ---------------------- UI ----------------------
113
 
114
- # Исправлено: убран подсчет last_input_token_count (он может быть None)
115
- GradioUI(agent).launch(share=True)
 
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
 
8
+ from Gradio_UI import GradioUI
9
 
10
+ # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
  @tool
12
+ def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
+ #Keep this format for the description / args / args description but feel free to modify the tool
14
+ """A tool that does nothing yet
15
  Args:
16
+ arg1: the first argument
17
  arg2: the second argument
18
  """
19
+ return "What magic will you build ?"
20
 
21
  @tool
22
  def get_current_time_in_timezone(timezone: str) -> str:
23
+ """A tool that fetches the current local time in a specified timezone.
24
  Args:
25
+ timezone: A string representing a valid timezone (e.g., 'America/New_York').
26
  """
27
  try:
28
+ # Create timezone object
29
  tz = pytz.timezone(timezone)
30
+ # Get current time in that timezone
31
  local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
  return f"The current local time in {timezone} is: {local_time}"
33
  except Exception as e:
34
  return f"Error fetching time for timezone '{timezone}': {str(e)}"
35
 
36
+
37
  @tool
38
  def get_eur_exchange_rate(currency_code: str) -> str:
39
+ """A tool that retrieves the current exchange rate from EUR to a given currency
40
+
41
  Args:
42
+ currency_code: The 3-letter currency code in lowercase (e.g., "usd", "gbp", "jpy")
43
  """
44
+
45
  try:
46
+ # Fetch the EUR exchange rates from the API
47
  api_url = "https://cdn.jsdelivr.net/npm/@fawazahmed0/currency-api@latest/v1/currencies/eur.json"
48
  response = requests.get(api_url, timeout=10)
49
  response.raise_for_status()
50
+
51
  data = response.json()
52
+
53
+ # Extract date and exchange rates
54
  date = data.get("date", "Unknown date")
55
  exchange_rates = data.get("eur", {})
56
+
57
+ # Get the specific exchange rate
58
  if currency_code in exchange_rates:
59
  rate = exchange_rates[currency_code]
60
  return f"1 EUR = {rate} {currency_code.upper()} (as of {date})"
61
  else:
62
+ return f"Currency code '{currency_code}' not found in the exchange rate data. Please check the currency code format."
63
+
64
+ except requests.RequestException as e:
65
+ return f"Error fetching exchange rate data: {str(e)}"
66
  except Exception as e:
67
+ return f"Error: {str(e)}"
68
 
69
+ @tool
70
  def get_simple_joke() -> str:
71
+ """A tool that fetches a random joke from JokeAPI with minimal filtering"""
72
+
73
  try:
74
+ # Simple request to JokeAPI
75
  api_url = "https://v2.jokeapi.dev/joke/any"
76
+
77
  response = requests.get(api_url, timeout=10)
78
  response.raise_for_status()
79
+
80
  joke_data = response.json()
81
+
82
  if joke_data.get("error", False):
83
  return f"Error: {joke_data.get('message', 'Could not get joke')}"
84
+
85
  if joke_data.get("type") == "single":
86
  return f"Here's a joke:\n\n{joke_data.get('joke', '')}"
87
  elif joke_data.get("type") == "twopart":
88
+ setup = joke_data.get("setup", "")
89
+ delivery = joke_data.get("delivery", "")
90
+ return f"Here's a joke:\n\n{setup}\n{delivery}"
91
+
92
+ return "Could not parse joke from API response"
93
+
94
  except Exception as e:
95
+ return f"Error: {str(e)}"
96
 
 
97
 
 
 
 
 
98
 
99
+ final_answer = FinalAnswerTool()
 
 
 
 
 
100
 
101
+ # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
102
+ # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
103
 
104
+ model = HfApiModel(
105
+ max_tokens=2096,
106
+ temperature=0.5,
107
+ model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
108
+ custom_role_conversions=None,
109
+ )
110
 
 
 
 
111
 
112
+ # Import tool from Hub
113
  image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
114
 
115
+ with open("prompts.yaml", 'r') as stream:
116
+ prompt_templates = yaml.safe_load(stream)
117
+
118
  agent = CodeAgent(
119
  model=model,
120
+ tools=[final_answer, my_custom_tool, get_current_time_in_timezone, get_eur_exchange_rate, get_simple_joke], ## add your tools here (don't remove final answer)
 
121
  max_steps=6,
122
  verbosity_level=1,
123
+ grammar=None,
124
+ planning_interval=None,
125
+ name=None,
126
+ description=None,
127
+ prompt_templates=prompt_templates
128
  )
129
 
 
130
 
131
+ GradioUI(agent).launch()