Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,123 +1,64 @@
|
|
| 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 |
-
from openai import OpenAI
|
| 8 |
import gradio as gr
|
| 9 |
-
import os
|
| 10 |
-
from huggingface_hub import login
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
client = OpenAI(api_key=api_key)
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
if not hf_token:
|
| 21 |
-
print("HF_TOKEN not set. Attempting to log in via huggingface-cli...")
|
| 22 |
-
try:
|
| 23 |
-
login() # Prompts for token if not already logged in
|
| 24 |
-
except Exception as e:
|
| 25 |
-
raise ValueError(f"Failed to authenticate with Hugging Face: {str(e)}. Please run `huggingface-cli login` or set HF_TOKEN environment variable.")
|
| 26 |
-
else:
|
| 27 |
-
login(token=hf_token)
|
| 28 |
-
|
| 29 |
-
# Tool to get current time in a specified timezone
|
| 30 |
-
@tool
|
| 31 |
-
def get_current_time_in_timezone(timezone: str) -> str:
|
| 32 |
-
"""A tool that fetches the current local time in a specified timezone.
|
| 33 |
-
Args:
|
| 34 |
-
timezone: A string representing a valid timezone (e.g., 'America/New_York').
|
| 35 |
-
"""
|
| 36 |
try:
|
| 37 |
tz = pytz.timezone(timezone)
|
| 38 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 39 |
-
return f"
|
| 40 |
except Exception as e:
|
| 41 |
-
return f"Error
|
| 42 |
|
| 43 |
-
#
|
| 44 |
-
|
| 45 |
-
def
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
Returns:
|
| 51 |
-
A string indicating whether the timezone and time are valid, with details.
|
| 52 |
-
"""
|
| 53 |
-
try:
|
| 54 |
-
if timezone not in pytz.all_timezones:
|
| 55 |
-
return f"Verification failed: '{timezone}' is not a valid timezone."
|
| 56 |
-
if "The current local time" not in time_output or timezone not in time_output:
|
| 57 |
-
return "Verification failed: Invalid time output format."
|
| 58 |
-
time_str = time_output.split("is: ")[-1].strip()
|
| 59 |
-
try:
|
| 60 |
-
parsed_time = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")
|
| 61 |
-
except ValueError:
|
| 62 |
-
return "Verification failed: Time format is incorrect (expected 'YYYY-MM-DD HH:MM:SS')."
|
| 63 |
-
try:
|
| 64 |
-
response = requests.get(f"http://worldtimeapi.org/api/timezone/{timezone}", timeout=5)
|
| 65 |
-
response.raise_for_status()
|
| 66 |
-
api_data = response.json()
|
| 67 |
-
api_time = datetime.datetime.fromisoformat(api_data["datetime"].replace("Z", "+00:00"))
|
| 68 |
-
api_time = api_time.astimezone(pytz.timezone(timezone))
|
| 69 |
-
api_time_str = api_time.strftime("%Y-%m-%d %H:%M:%S")
|
| 70 |
-
time_diff = abs((parsed_time - api_time).total_seconds())
|
| 71 |
-
if time_diff > 60:
|
| 72 |
-
return f"Verification failed: Time '{time_str}' differs significantly from API time '{api_time_str}'."
|
| 73 |
-
except requests.RequestException as e:
|
| 74 |
-
return f"Verification warning: Could not verify with external API due to {str(e)}. Local time format is valid."
|
| 75 |
-
return f"Verification passed: Timezone '{timezone}' and time '{time_str}' are valid."
|
| 76 |
-
except Exception as e:
|
| 77 |
-
return f"Verification error: {str(e)}"
|
| 78 |
-
|
| 79 |
-
# Initialize FinalAnswerTool
|
| 80 |
-
final_answer = FinalAnswerTool()
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
except
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
#
|
| 100 |
-
|
| 101 |
|
| 102 |
-
#
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
prompt_templates = yaml.safe_load(stream)
|
| 106 |
-
except FileNotFoundError:
|
| 107 |
-
raise FileNotFoundError("prompts.yaml not found. Ensure the file exists in the working directory.")
|
| 108 |
|
| 109 |
-
#
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
planning_interval=None,
|
| 117 |
-
name=None,
|
| 118 |
-
description=None,
|
| 119 |
-
prompt_templates=prompt_templates
|
| 120 |
)
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
| 1 |
import datetime
|
|
|
|
| 2 |
import pytz
|
|
|
|
|
|
|
|
|
|
| 3 |
import gradio as gr
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
# Define tools
|
| 6 |
+
def combine_string_and_number(text: str, number: int) -> str:
|
| 7 |
+
"""Combines a string and a number into a message."""
|
| 8 |
+
return f"You entered '{text}' and the number {number}."
|
|
|
|
| 9 |
|
| 10 |
+
def get_time_in_timezone(timezone: str) -> str:
|
| 11 |
+
"""Gets the current time in the specified timezone."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
try:
|
| 13 |
tz = pytz.timezone(timezone)
|
| 14 |
local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 15 |
+
return f"Current time in {timezone}: {local_time}"
|
| 16 |
except Exception as e:
|
| 17 |
+
return f"Error: Invalid timezone '{timezone}'"
|
| 18 |
|
| 19 |
+
# Simple agent class
|
| 20 |
+
class MyFirstAgent:
|
| 21 |
+
def __init__(self):
|
| 22 |
+
self.tools = {
|
| 23 |
+
"combine": combine_string_and_number,
|
| 24 |
+
"time": get_time_in_timezone
|
| 25 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
def run(self, query: str) -> str:
|
| 28 |
+
query = query.lower().strip()
|
| 29 |
+
if query.startswith("combine"):
|
| 30 |
+
try:
|
| 31 |
+
parts = query.split("combine")[-1].strip().split("and")
|
| 32 |
+
text = parts[0].strip()
|
| 33 |
+
number = int(parts[1].strip())
|
| 34 |
+
return self.tools["combine"](text, number)
|
| 35 |
+
except:
|
| 36 |
+
return "Error: Please use format 'combine <text> and <number>'"
|
| 37 |
+
elif query.startswith("time in"):
|
| 38 |
+
try:
|
| 39 |
+
timezone = query.split("time in")[-1].strip()
|
| 40 |
+
return self.tools["time"](timezone)
|
| 41 |
+
except:
|
| 42 |
+
return "Error: Please use format 'time in <timezone>'"
|
| 43 |
+
else:
|
| 44 |
+
return "Sorry, I only understand 'combine <text> and <number>' or 'time in <timezone>'"
|
| 45 |
|
| 46 |
+
# Create agent
|
| 47 |
+
agent = MyFirstAgent()
|
| 48 |
|
| 49 |
+
# Define Gradio interface function
|
| 50 |
+
def run_agent(query: str) -> str:
|
| 51 |
+
return agent.run(query)
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
+
# Create and launch Gradio interface
|
| 54 |
+
interface = gr.Interface(
|
| 55 |
+
fn=run_agent,
|
| 56 |
+
inputs=gr.Textbox(label="Enter your command", placeholder="e.g., combine hello and 42 or time in America/New_York"),
|
| 57 |
+
outputs=gr.Textbox(label="Agent Response"),
|
| 58 |
+
title="My First Agent",
|
| 59 |
+
description="Try commands like 'combine hello and 42' or 'time in America/New_York'"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
)
|
| 61 |
|
| 62 |
+
if __name__ == "__main__":
|
| 63 |
+
interface.launch(server_port=7860, share=False, quiet=True)
|
| 64 |
+
|