Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011 unmodified lines222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219# ============================================# ALFRED - Your AI Butler Agent# HuggingFace AI Agents Course - Unit 1# ============================================import gradio as grfrom smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, HfApiModel, tool# ============================================# CUSTOM TOOLS FOR ALFRED11 unmodified linesThe result of the calculation as a string"""try:# Only allow safe mathematical operationsallowed_chars = set('0123456789+-*/(). ')if all(c in allowed_chars for c in operation):result = eval(operation)return f"The result of {operation} is: {result}"else:return "Invalid operation. Please use only numbers and basic operators (+, -, *, /)."except Exception as e:return f"Could not calculate that expression. Error: {str(e)}"@tooldef get_current_time(timezone: str = "UTC") -> str:"""Gets the current date and time.Args:timezone: The timezone to get time for (default is UTC)Returns:The current date and time as a string"""from datetime import datetimetry:now = datetime.utcnow()return f"The current date and time (UTC) is: {now.strftime('%Y-%m-%d %H:%M:%S')}"except Exception as e:return f"Could not get the time. Error: {str(e)}"@tooldef text_summarizer(text: str) -> str:"""Summarizes a given text into key points.Args:text: The text to summarizeReturns:A summarized version of the text"""if len(text) < 100:return f"Text is already short: {text}"# Simple summarization: return first 500 characters with ellipsissummary = text[:500] + "..." if len(text) > 500 else textreturn f"Summary: {summary}"# ============================================# ALFRED AGENT SETUP# ============================================# Custom system prompt to give Alfred his personalityALFRED_SYSTEM_PROMPT = """You are Alfred, a polite, professional, and highly capable AI butler assistant.Your characteristics:- You are courteous and address users respectfully- You are thorough and provide complete answers- You use your available tools wisely to help users- You explain your reasoning when solving problems- You admit when you don't know somethingAvailable tools:1. DuckDuckGoSearchTool - Search the web for information2. VisitWebpageTool - Visit and read webpage content3. calculator - Perform mathematical calculations4. get_current_time - Get the current date and time5. text_summarizer - Summarize long textsAlways think step by step and use the most appropriate tool for each task."""# Initialize the language model (using HuggingFace's free inference API)model = HfApiModel()# Create Alfred with all toolsalfred = CodeAgent(tools=[DuckDuckGoSearchTool(),VisitWebpageTool(),calculator,get_current_time,text_summarizer,],model=model,system_prompt=ALFRED_SYSTEM_PROMPT,max_steps=10, # Maximum number of steps Alfred can takeverbosity_level=1 # Show some logging for debugging)# ============================================# GRADIO INTERFACE# ============================================def chat_with_alfred(message, history):"""Process user message and return Alfred's response.Args:message: The user's input messagehistory: Chat history (for context)Returns:Alfred's response as a string"""if not message.strip():return "I beg your pardon, but you haven't asked me anything. How may I assist you?"try:# Run Alfred on the user's queryresponse = alfred.run(message)# Format the response nicelyformatted_response = f"🎩 **Alfred's Response:**\n\n{str(response)}"return formatted_responseexcept Exception as e:error_message = (f"I do apologize, but I encountered an issue while processing your request.\n\n"f"**Error details:** {str(e)}\n\n"f"Please try rephrasing your question or ask something else.")return error_message# Create the Gradio interfacewith gr.Blocks(title="Alfred - AI Butler Agent",theme=gr.themes.Soft()) as demo:# Headergr.Markdown("""# 🎩 Alfred - Your AI ButlerWelcome! I am Alfred, your personal AI assistant. I can help you with:- 🔍 **Web searches** - Find information on any topic- 🌐 **Reading webpages** - Extract content from URLs- 🔢 **Calculations** - Perform mathematical operations- 🕐 **Time queries** - Get current date and time- 📝 **Text summarization** - Summarize long texts*How may I be of service today?*---""")# Chat interfacechatbot = gr.ChatInterface(fn=chat_with_alfred,examples=["What is the latest news about artificial intelligence?","Calculate 1547 * 32 + 89","What time is it now?","Search for information about climate change solutions","What are the top programming languages in 2024?",],retry_btn="🔄 Retry",undo_btn="↩️ Undo",clear_btn="🗑️ Clear",)# Footergr.Markdown("""---### About AlfredAlfred is an AI agent built using the **smolagents** framework from HuggingFace.This agent was created as part of the **HuggingFace AI Agents Course - Unit 1**.**Framework:** smolagents | **Model:** HuggingFace Inference API*Built with ❤️ for the AI Agents Course*""")# ============================================# LAUNCH THE APPLICATION# ============================================if __name__ == "__main__":# Launch with share=False for local testing# Set share=True if you want a public linkdemo.launch(server_name="0.0.0.0",server_port=7860,share=False)12345611 unmodified lines18192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159import osimport gradio as grfrom smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, tool# ============================================# CUSTOM TOOLS FOR ALFRED11 unmodified linesThe result of the calculation as a string"""try:allowed_chars = set('0123456789+-*/(). ')if all(c in allowed_chars for c in operation):result = eval(operation)return f"The result of {operation} is: {result}"else:return "Invalid operation. Please use only numbers and basic operators."except Exception as e:return f"Could not calculate. Error: {str(e)}"@tooldef get_current_time() -> str:"""Gets the current date and time in UTC.Returns:The current date and time as a string"""from datetime import datetimenow = 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---""")chatbot = gr.ChatInterface(fn=chat_with_alfred,examples=["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+63-123