Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,131 +1,65 @@
|
|
| 1 |
-
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
@tool
|
| 12 |
-
def my_custom_tool(arg1:str, arg2:int)-> str:
|
| 13 |
-
|
| 14 |
-
"
|
| 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 |
-
"""
|
| 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 |
-
#
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
|
|
|
| 104 |
model = HfApiModel(
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
|
|
|
| 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,
|
| 121 |
max_steps=6,
|
| 122 |
verbosity_level=1,
|
| 123 |
-
|
| 124 |
-
planning_interval=None,
|
| 125 |
-
name=None,
|
| 126 |
-
description=None,
|
| 127 |
-
prompt_templates=prompt_templates
|
| 128 |
)
|
| 129 |
|
| 130 |
-
|
| 131 |
-
GradioUI(agent).launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
import datetime
|
|
|
|
| 3 |
import pytz
|
| 4 |
import yaml
|
|
|
|
| 5 |
|
| 6 |
+
from smolagents import CodeAgent, load_tool, tool, HfApiModel
|
| 7 |
+
from tools.final_answer import FinalAnswerTool
|
| 8 |
from Gradio_UI import GradioUI
|
| 9 |
|
| 10 |
+
# Загружаем секрет из переменных окружения
|
| 11 |
+
HF_TOKEN = os.environ.get("HF_API_TOKEN")
|
| 12 |
+
if HF_TOKEN is None:
|
| 13 |
+
raise RuntimeError("HF_API_TOKEN is not set. Please set it in Space secrets.")
|
| 14 |
+
|
| 15 |
+
# Определяем инструменты
|
| 16 |
+
|
| 17 |
@tool
|
| 18 |
+
def my_custom_tool(arg1: str, arg2: int) -> str:
|
| 19 |
+
"""Инструмент-пример, пока ничего не делает"""
|
| 20 |
+
return f"Custom tool executed with arg1={arg1}, arg2={arg2}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
@tool
|
| 23 |
def get_current_time_in_timezone(timezone: str) -> str:
|
| 24 |
+
"""Получает текущее локальное время в указанном часовом поясе."""
|
|
|
|
|
|
|
|
|
|
| 25 |
try:
|
|
|
|
| 26 |
tz = pytz.timezone(timezone)
|
|
|
|
| 27 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 28 |
return f"The current local time in {timezone} is: {local_time}"
|
| 29 |
except Exception as e:
|
| 30 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 31 |
|
| 32 |
+
# Финальный инструмент
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
final_answer = FinalAnswerTool()
|
| 34 |
|
| 35 |
+
# Загружаем инструмент генерации изображений из Hub
|
| 36 |
+
image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
|
| 37 |
+
|
| 38 |
+
# Загружаем шаблоны промптов, если есть
|
| 39 |
+
prompt_templates = {}
|
| 40 |
+
try:
|
| 41 |
+
with open("prompts.yaml", "r") as stream:
|
| 42 |
+
prompt_templates = yaml.safe_load(stream)
|
| 43 |
+
except FileNotFoundError:
|
| 44 |
+
pass
|
| 45 |
|
| 46 |
+
# Конфигурация модели с использованием секретного токена
|
| 47 |
model = HfApiModel(
|
| 48 |
+
model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
|
| 49 |
+
api_key=HF_TOKEN,
|
| 50 |
+
max_tokens=2096,
|
| 51 |
+
temperature=0.5,
|
| 52 |
+
custom_role_conversions=None,
|
| 53 |
)
|
| 54 |
|
| 55 |
+
# Создаём агент с инструментами
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
agent = CodeAgent(
|
| 57 |
model=model,
|
| 58 |
+
tools=[final_answer, my_custom_tool, get_current_time_in_timezone, image_generation_tool],
|
| 59 |
max_steps=6,
|
| 60 |
verbosity_level=1,
|
| 61 |
+
prompt_templates=prompt_templates,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
)
|
| 63 |
|
| 64 |
+
# Запуск интерфейса
|
| 65 |
+
GradioUI(agent).launch()
|