Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,27 +1,43 @@
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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")
|
|
@@ -29,37 +45,114 @@ def get_current_time_in_timezone(timezone: str) -> str:
|
|
| 29 |
except Exception as e:
|
| 30 |
return f"Error fetching time for timezone '{timezone}': {str(e)}"
|
| 31 |
|
| 32 |
-
# Финальный инструмент
|
| 33 |
-
final_answer = FinalAnswerTool()
|
| 34 |
|
| 35 |
-
#
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 53 |
)
|
| 54 |
|
| 55 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
agent = CodeAgent(
|
| 57 |
model=model,
|
| 58 |
-
tools=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
max_steps=6,
|
| 60 |
verbosity_level=1,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
prompt_templates=prompt_templates,
|
| 62 |
)
|
| 63 |
|
| 64 |
-
#
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
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)
|
| 43 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
| 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"
|
| 64 |
+
response = requests.get(api_url, timeout=10)
|
| 65 |
+
response.raise_for_status()
|
| 66 |
+
data = response.json()
|
| 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"
|
| 92 |
+
response = requests.get(api_url, timeout=10)
|
| 93 |
+
response.raise_for_status()
|
| 94 |
+
joke_data = response.json()
|
| 95 |
+
|
| 96 |
+
if joke_data.get("error", False):
|
| 97 |
+
return f"Error: {joke_data.get('message', 'Could not get joke')}"
|
| 98 |
+
|
| 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=[
|
| 138 |
+
final_answer,
|
| 139 |
+
my_custom_tool,
|
| 140 |
+
get_current_time_in_timezone,
|
| 141 |
+
get_eur_exchange_rate,
|
| 142 |
+
get_simple_joke,
|
| 143 |
+
image_generation_tool,
|
| 144 |
+
],
|
| 145 |
max_steps=6,
|
| 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()
|