Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line23456715 unmodified lines2324252627286 unmodified lines3536373839404142434445464748495051525354555657585960616263646566676869707172737475763 unmodified lines80818283848586871 unmodified lineimport gradio as grfrom smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, tool@tooldef calculator(operation: str) -> str:"""15 unmodified linesexcept Exception as e:return f"Could not calculate. Error: {str(e)}"@tooldef get_current_time() -> str:"""6 unmodified linesnow = datetime.utcnow()return f"Current date and time (UTC): {now.strftime('%Y-%m-%d %H:%M:%S')}"model = InferenceClientModel(model_id="Qwen/Qwen2.5-72B-Instruct",token=os.environ.get("HF_TOKEN"),provider="hf-inference")alfred = CodeAgent(tools=[DuckDuckGoSearchTool(),calculator,get_current_time,],model=model,max_steps=5,)def chat_with_alfred(message, history):if not message.strip():return "Please ask me something. How may I assist you?"try:response = alfred.run(message)return f"Alfred: {str(response)}"except Exception as e:return f"I encountered an issue: {str(e)}"with gr.Blocks(title="Alfred - AI Butler Agent") as demo:gr.Markdown("""# Alfred - Your AI ButlerI can help you with:- Web searches- Calculations- Current time""")3 unmodified lines"What is artificial intelligence?","Calculate 25 * 4 + 10","What time is it now?",],)if __name__ == "__main__":demo.launch()1 unmodified line23456789101115 unmodified lines272829303132336 unmodified lines4041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331343 unmodified lines1381391401411421431441451461471481491501511521531541551561571581591 unmodified lineimport gradio as grfrom smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, tool# ============================================# CUSTOM TOOLS FOR ALFRED# ============================================@tooldef calculator(operation: str) -> str:"""15 unmodified linesexcept Exception as e:return f"Could not calculate. Error: {str(e)}"@tooldef get_current_time() -> str:"""6 unmodified linesnow = datetime.utcnow()return f"Current date and time (UTC): {now.strftime('%Y-%m-%d %H:%M:%S')}"@tooldef get_weather_info(city: str) -> str:"""Gets a simple weather description for a city (mock data for demo).Args:city: The name of the city to get weather forReturns:A weather description string"""# This is mock data - in production you'd use a real weather APIimport randomconditions = ["sunny", "partly cloudy", "cloudy", "rainy", "windy"]temp = random.randint(15, 30)condition = random.choice(conditions)return f"Weather in {city}: {temp}°C, {condition}"# ============================================# MODEL SETUP - Using free-tier compatible model# ============================================model = InferenceClientModel(model_id="Qwen/Qwen2.5-7B-Instruct", # Smaller model that works on free tiertoken=os.environ.get("HF_TOKEN"),)# ============================================# ALFRED AGENT SETUP# ============================================alfred = CodeAgent(tools=[DuckDuckGoSearchTool(),calculator,get_current_time,get_weather_info,],model=model,max_steps=5,verbosity_level=1,)# ============================================# CHAT FUNCTION# ============================================def chat_with_alfred(message, history):"""Process user message and return Alfred's response."""if not message.strip():return "Please ask me something. How may I assist you today?"try:response = alfred.run(message)return str(response)except Exception as e:error_msg = str(e)# Provide helpful error messagesif "404" in error_msg or "not found" in error_msg.lower():return "I'm having trouble connecting to my AI backend. Please check the HF_TOKEN and model availability."elif "rate" in error_msg.lower() or "limit" in error_msg.lower():return "I've hit a rate limit. Please wait a moment and try again."else:return f"I encountered an issue: {error_msg}"# ============================================# GRADIO INTERFACE# ============================================with gr.Blocks(title="Alfred - AI Butler Agent") as demo:gr.Markdown("""# 🎩 Alfred - Your AI ButlerGood day! I am Alfred, your personal AI assistant. I am at your service.### My Capabilities:- 🔍 **Web Search** - I can search the internet for information- 🧮 **Calculator** - I can perform mathematical calculations- 🕐 **Current Time** - I can tell you the current time (UTC)- 🌤️ **Weather** - I can provide weather information---""")3 unmodified lines"What is artificial intelligence?","Calculate 25 * 4 + 10","What time is it now?","What's the weather in London?","Search for the latest news about AI","Calculate (100 + 50) * 2 / 5",],)gr.Markdown("""---*Built with [smolagents](https://github.com/huggingface/smolagents) and Gradio | Unit 1 Project*""")# ============================================# LAUNCH APP# ============================================if __name__ == "__main__":demo.launch()
app.py+82-10