Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604613 unmodified linesimport pytzimport asyncioimport requestsfrom typing import Dict, Any# Framework 1: LlamaIndexfrom llama_index.core.agent.workflow import AgentWorkflowfrom llama_index.core.tools import FunctionToolfrom llama_index.llms.huggingface_api import HuggingFaceInferenceAPI# Framework 2: smolagentsfrom smolagents import CodeAgent, DuckDuckGoSearchTool, tool, InferenceClientModel# 0. SHARED CONFIGHF_TOKEN = os.getenv("HF_TOKEN")WEATHER_API_KEY = os.getenv("WEATHER_API_KEY", "your-openweather-api-key") # Get from: https://openweathermap.org/apiMODEL_ID = "Qwen/Qwen2.5-7B-Instruct"# ==========================================# ENHANCED WEATHER FUNCTIONALITY# ==========================================class WeatherService:def __init__(self, api_key: str = None):self.api_key = api_key or WEATHER_API_KEYself.base_url = "http://api.openweathermap.org/data/2.5/weather"def get_weather(self, location: str) -> Dict[str, Any]:"""Get real weather data for a location"""try:params = {'q': location,'appid': self.api_key,'units': 'metric','lang': 'en'}response = requests.get(self.base_url, params=params, timeout=10)response.raise_for_status()data = response.json()return {'temperature': data['main']['temp'],'feels_like': data['main']['feels_like'],'humidity': data['main']['humidity'],'pressure': data['main']['pressure'],'description': data['weather'][0]['description'].title(),'wind_speed': data['wind']['speed'],'wind_direction': self.get_wind_direction(data['wind'].get('deg', 0)),'location': f"{data['name']}, {data['sys']['country']}",'icon': data['weather'][0]['icon'],'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}except Exception as e:# Fallback to mock data if API failsreturn self.get_mock_weather(location)def get_mock_weather(self, location: str) -> Dict[str, Any]:"""Fallback mock weather data"""mock_temps = {'tokyo': 18, 'london': 12, 'new york': 15,'paris': 14, 'sydney': 22, 'dubai': 28}temp = mock_temps.get(location.lower(), 20)return {'temperature': temp,'feels_like': temp + 2,'humidity': 65,'pressure': 1013,'description': 'Partly Cloudy','wind_speed': 3.5,'wind_direction': 'NW','location': location.title(),'icon': '03d','timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),'note': 'Using mock data (add real API key for live weather)'}def get_wind_direction(self, degrees: float) -> str:"""Convert wind degrees to cardinal direction"""directions = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE','S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']index = round(degrees / 22.5) % 16return directions[index]def format_weather_report(self, weather_data: Dict[str, Any]) -> str:"""Format weather data into a readable report"""emoji_map = {'Clear': 'โ๏ธ', 'Clouds': 'โ๏ธ', 'Rain': '๐ง๏ธ','Snow': 'โ๏ธ', 'Thunderstorm': 'โ๏ธ', 'Drizzle': '๐ฆ๏ธ','Mist': '๐ซ๏ธ', 'Smoke': '๐จ', 'Haze': '๐ถโ๐ซ๏ธ'}description = weather_data['description']emoji = emoji_map.get(description.split()[0], '๐')report = f"""{emoji} **Weather Report for {weather_data['location']}** {emoji}โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ**Temperature:** {weather_data['temperature']:.1f}ยฐC**Feels Like:** {weather_data['feels_like']:.1f}ยฐC**Conditions:** {description}**Humidity:** {weather_data['humidity']}%**Pressure:** {weather_data['pressure']} hPa**Wind:** {weather_data['wind_speed']} m/s {weather_data['wind_direction']}**Updated:** {weather_data['timestamp']}"""if 'note' in weather_data:report += f"\nโ ๏ธ *{weather_data['note']}*"return reportweather_service = WeatherService()# ==========================================# ENHANCED TIME FUNCTIONS# ==========================================def get_tokyo_time() -> str:"""Returns the current time in Tokyo, Japan."""tz = pytz.timezone('Asia/Tokyo')current_time = datetime.datetime.now(tz)return f"**Tokyo Time:** {current_time.strftime('%A, %B %d, %Y %H:%M:%S')} (JST)"def get_world_time(city: str = None) -> str:"""Get current time for various cities"""timezones = {'tokyo': 'Asia/Tokyo','new york': 'America/New_York','london': 'Europe/London','paris': 'Europe/Paris','sydney': 'Australia/Sydney','dubai': 'Asia/Dubai','singapore': 'Asia/Singapore','mumbai': 'Asia/Kolkata'}if not city:# Return all timesresult = "๐ **World Clock** ๐\nโโโโโโโโโโโโโโโโโโโโโโโโโโ\n"for city_name, tz_str in timezones.items():tz = pytz.timezone(tz_str)current_time = datetime.datetime.now(tz)result += f"โข **{city_name.title()}:** {current_time.strftime('%H:%M:%S')}\n"return resultcity_lower = city.lower()if city_lower in timezones:tz = pytz.timezone(timezones[city_lower])current_time = datetime.datetime.now(tz)return f"**{city.title()} Time:** {current_time.strftime('%A, %B %d, %Y %H:%M:%S')}"else:return f"Sorry, I don't have timezone data for {city}. Available cities: {', '.join(timezones.keys())}"# ==========================================# PART 1: LLAMAINDEX AGENT (ENHANCED)# ==========================================li_llm = HuggingFaceInferenceAPI(model_name=MODEL_ID,token=HF_TOKEN,provider="together")@tooldef enhanced_weather_tool(location: str) -> str:"""Get detailed weather information for any location worldwide.Args:location: City name (e.g., 'Tokyo', 'New York', 'London')"""weather_data = weather_service.get_weather(location)return weather_service.format_weather_report(weather_data)@tooldef world_time_tool(city: str = None) -> str:"""Get current time for world cities.Args:city: Optional city name. If not provided, shows all major cities."""return get_world_time(city)@tooldef calculator_tool(expression: str) -> str:"""Evaluate mathematical expressions.Args:expression: Mathematical expression to calculate (e.g., '2 + 2', 'sqrt(16)')"""try:# Safe evaluationimport mathallowed_names = {k: v for k, v in math.__dict__.items() if not k.startswith("_")}allowed_names.update({'abs': abs, 'round': round})# Compile the expressioncode = compile(expression, "<string>", "eval")# Check for disallowed namesfor name in code.co_names:if name not in allowed_names:raise NameError(f"Use of {name} is not allowed")result = eval(code, {"__builtins__": {}}, allowed_names)return f"**Result:** {expression} = {result}"except Exception as e:return f"Calculation Error: {str(e)}. Please use valid mathematical expressions."# Create LlamaIndex toolsli_tools = [FunctionTool.from_defaults(fn=get_tokyo_time),FunctionTool.from_defaults(fn=lambda location: enhanced_weather_tool(location)),FunctionTool.from_defaults(fn=lambda city=None: world_time_tool(city)),FunctionTool.from_defaults(fn=lambda expr: calculator_tool(expr))]li_agent = AgentWorkflow.from_tools_or_functions(li_tools,llm=li_llm,)async def chat_llama(message, history):try:# Add some thinking emojithinking_msg = "๐ค Thinking..."# Process the messageresult = await li_agent.run(user_msg=message)# Format responseresponse = str(result)if "weather" in message.lower() and "tokyo" not in message.lower():# Extract location from messagewords = message.lower().split()for word in words:if word in ['weather', 'forecast', 'temperature']:continue# Try to find a locationweather_data = weather_service.get_weather(word)if 'mock' not in str(weather_data.get('note', '')):response = weather_service.format_weather_report(weather_data)breakreturn responseexcept Exception as e:return f"โ LlamaIndex Error: {str(e)}"# ==========================================# PART 2: SMOLAGENTS (ENHANCED)# ==========================================smol_model = InferenceClientModel(model_id=MODEL_ID,token=HF_TOKEN,provider="together")smol_agent = CodeAgent(model=smol_model,tools=[enhanced_weather_tool, world_time_tool, calculator_tool, DuckDuckGoSearchTool()])def chat_smol(message, history):try:response = smol_agent.run(message)return str(response)except Exception as e:return f"โ Smolagents Error: {str(e)}"# ==========================================# PART 3: ENHANCED GRADIO UI# ==========================================def create_weather_component():"""Create a standalone weather component"""with gr.Column(variant="panel"):gr.Markdown("## ๐ค๏ธ Quick Weather Check")with gr.Row():location_input = gr.Textbox(label="City Name",placeholder="Enter city name...",scale=4)get_weather_btn = gr.Button("Get Weather", variant="primary", scale=1)weather_output = gr.Markdown(label="Weather Report")# Example locationsexamples = gr.Examples(examples=["Tokyo", "London", "New York", "Paris", "Sydney"],inputs=location_input,label="Try these cities:")def get_weather(location):if not location:return "Please enter a city name."weather_data = weather_service.get_weather(location)return weather_service.format_weather_report(weather_data)get_weather_btn.click(get_weather,inputs=location_input,outputs=weather_output)return location_input, weather_outputdef create_world_clock_component():"""Create a world clock component"""with gr.Column(variant="panel"):gr.Markdown("## ๐ World Clock")with gr.Row():refresh_btn = gr.Button("๐ Refresh Times", variant="secondary")all_cities_btn = gr.Button("Show All Cities", variant="primary")time_output = gr.Markdown()# Initial displaytime_output.value = get_world_time()def refresh_times():return get_world_time()refresh_btn.click(refresh_times, outputs=time_output)all_cities_btn.click(refresh_times, outputs=time_output)return time_outputdef create_calculator_component():"""Create a simple calculator component"""with gr.Column(variant="panel"):gr.Markdown("## ๐งฎ Quick Calculator")with gr.Row():calc_input = gr.Textbox(label="Math Expression",placeholder="e.g., 2 + 2, 3 * (4 + 5), sqrt(16)...",scale=4)calc_btn = gr.Button("Calculate", variant="primary", scale=1)calc_output = gr.Markdown(label="Result")examples = gr.Examples(examples=["2 + 2", "3 * (4 + 5)", "sqrt(16)", "sin(30)", "2 ** 8"],inputs=calc_input,label="Try these:")def calculate(expression):return calculator_tool(expression)calc_btn.click(calculate,inputs=calc_input,outputs=calc_output)return calc_input, calc_outputwith gr.Blocks(theme=gr.themes.Soft(), title="๐ค AI Agent Studio") as demo:# Headerwith gr.Row():gr.Markdown("# ๐ AI Agent Studio")with gr.Row():gr.Markdown(f"### Powered by **{MODEL_ID}** via Together AI")# API Key Noticeif "your-openweather-api-key" in WEATHER_API_KEY:gr.Markdown("""โ ๏ธ **Note:** Using mock weather data. For real weather, get a free API key from[OpenWeatherMap](https://openweathermap.org/api) and set it as `WEATHER_API_KEY` environment variable.""")# Sidebar with utility toolswith gr.Row():# Left sidebar - Utility toolswith gr.Column(scale=1, variant="panel"):create_weather_component()create_world_clock_component()create_calculator_component()# Agent Capabilities Infowith gr.Column(variant="panel"):gr.Markdown("## ๐ค Agent Capabilities")gr.Markdown("""**Both Agents Can:**โข ๐ Get current time worldwideโข ๐ค๏ธ Check weather forecastsโข ๐งฎ Perform calculationsโข ๐ Search the web (smolagents)โข ๐ฌ Natural conversation**Try asking:**- "What's the weather in London?"- "What time is it in Tokyo?"- "Calculate 15% of 200"- "Tell me about AI news"""")# Main content area - Chat interfaceswith gr.Column(scale=3):with gr.Tab("๐ฆ LlamaIndex Agent", id="llama"):llama_chat = gr.ChatInterface(fn=chat_llama,chatbot=gr.Chatbot(height=500, label="LlamaIndex Agent"),textbox=gr.Textbox(placeholder="Ask about weather, time, calculations...",container=False,scale=7),title="LlamaIndex Workflow Agent",description="Uses structured workflows with function tools",theme="soft",examples=["What's the weather in Tokyo?","What time is it in New York and Paris?","Calculate 25 * 4 + 18","Tell me about today's weather worldwide"])with gr.Tab("๐ฌ Smolagents CodeAgent", id="smol"):smol_chat = gr.ChatInterface(fn=chat_smol,chatbot=gr.Chatbot(height=500, label="Smolagents CodeAgent"),textbox=gr.Textbox(placeholder="Ask anything or request web search...",container=False,scale=7),title="Smolagents Code Agent",description="Uses code execution with search capabilities",theme="soft",examples=["Search for latest AI developments","What's the weather forecast for this week?","Explain quantum computing","Calculate the area of a circle with radius 5"])# Footerwith gr.Row():gr.Markdown("""---**Tips:**1. LlamaIndex is better for structured workflows2. Smolagents can search the web in real-time3. Use the sidebar for quick weather/time checks4. Both agents support natural language queries""")if __name__ == "__main__":demo.launch(server_name="0.0.0.0",server_port=7860,share=False,debug=True)3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993 unmodified linesimport pytzimport asyncioimport requests# Framework 1: LlamaIndexfrom llama_index.core.agent import ReActAgentfrom llama_index.core.tools import FunctionToolfrom llama_index.llms.huggingface import HuggingFaceInferenceAPI# Framework 2: smolagentsfrom smolagents import CodeAgent, DuckDuckGoSearchTool, tool# 0. SHARED CONFIGHF_TOKEN = os.getenv("HF_TOKEN")MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"# ==========================================# WEATHER FUNCTION WITH REAL API# ==========================================def get_weather(location: str) -> str:"""Get weather for a location using OpenWeatherMap API"""try:# You can get a free API key from https://openweathermap.org/apiapi_key = os.getenv("WEATHER_API_KEY", "")if api_key:url = f"http://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}&units=metric"response = requests.get(url, timeout=5)data = response.json()if response.status_code == 200:temp = data['main']['temp']desc = data['weather'][0]['description']humidity = data['main']['humidity']return f"๐ค๏ธ Weather in {location}: {desc}, {temp}ยฐC, Humidity: {humidity}%"else:# Fallback to mock data if API failsreturn f"๐ค๏ธ Weather in {location}: Sunny, 22ยฐC (mock data - add real API key for live weather)"else:# Mock weather if no API keyweather_data = {"tokyo": "Cloudy, 18ยฐC","london": "Rainy, 12ยฐC","new york": "Sunny, 15ยฐC","paris": "Partly Cloudy, 14ยฐC","sydney": "Clear, 22ยฐC"}for city, weather in weather_data.items():if city in location.lower():return f"๐ค๏ธ Weather in {location}: {weather} (mock data)"return f"๐ค๏ธ Weather in {location}: Sunny, 22ยฐC (mock data - set WEATHER_API_KEY for real data)"except Exception as e:return f"๐ค๏ธ Weather in {location}: Sunny, 22ยฐC (error: {str(e)[:50]})"# ==========================================# TIME FUNCTIONS# ==========================================def get_tokyo_time() -> str:"""Returns the current time in Tokyo, Japan."""tz = pytz.timezone('Asia/Tokyo')now = datetime.datetime.now(tz)return f"๐ Tokyo Time: {now.strftime('%A, %B %d, %Y %H:%M:%S')}"def get_world_time(city: str = "all") -> str:"""Get current time for various cities."""timezones = {"Tokyo": "Asia/Tokyo","New York": "America/New_York","London": "Europe/London","Paris": "Europe/Paris","Sydney": "Australia/Sydney","Dubai": "Asia/Dubai","Singapore": "Asia/Singapore"}if city.lower() != "all" and city.title() in timezones:tz = pytz.timezone(timezones[city.title()])now = datetime.datetime.now(tz)return f"๐ {city} Time: {now.strftime('%H:%M:%S')}"result = "๐ World Clock:\n"for city_name, tz_str in timezones.items():tz = pytz.timezone(tz_str)now = datetime.datetime.now(tz)result += f"โข {city_name}: {now.strftime('%H:%M:%S')}\n"return result# ==========================================# CALCULATOR FUNCTION# ==========================================def calculate(expression: str) -> str:"""Calculate mathematical expressions."""try:# Safe evaluation with basic math functionsimport math# Create a safe environmentsafe_dict = {'abs': abs, 'round': round, 'min': min, 'max': max,'sum': sum, 'len': len, 'int': int, 'float': float,'math': math, 'sqrt': math.sqrt, 'pow': math.pow,'sin': math.sin, 'cos': math.cos, 'tan': math.tan,'pi': math.pi, 'e': math.e}# Remove any dangerous charactersexpression = ''.join(c for c in expression if c.isalnum() or c in ' +-*/().,')result = eval(expression, {"__builtins__": {}}, safe_dict)return f"๐งฎ {expression} = {result}"except Exception as e:return f"โ Calculation error: {str(e)[:100]}"# ==========================================# PART 1: LLAMAINDEX AGENT (FIXED)# ==========================================try:li_llm = HuggingFaceInferenceAPI(model_name=MODEL_ID,token=HF_TOKEN,)# Create tools for LlamaIndexli_tools = [FunctionTool.from_defaults(fn=get_tokyo_time, name="get_tokyo_time"),FunctionTool.from_defaults(fn=get_weather, name="get_weather"),FunctionTool.from_defaults(fn=get_world_time, name="get_world_time"),FunctionTool.from_defaults(fn=calculate, name="calculate")]li_agent = ReActAgent.from_tools(li_tools,llm=li_llm,verbose=False)async def chat_llama(message, history):try:response = await li_agent.achat(message)return str(response)except Exception as e:return f"โ LlamaIndex Error: {str(e)[:200]}"except Exception as e:print(f"LlamaIndex setup error: {e}")async def chat_llama(message, history):return f"โ LlamaIndex not available: {str(e)[:200]}"# ==========================================# PART 2: SMOLAGENTS# ==========================================try:from smolagents import CodeAgent, DuckDuckGoSearchTool, tool@tooldef weather_tool(location: str) -> str:"""Get the current weather for a location."""return get_weather(location)@tooldef time_tool(city: str = "all") -> str:"""Get current time for a city or all major cities."""return get_world_time(city)@tooldef calculator_tool(expression: str) -> str:"""Calculate mathematical expressions."""return calculate(expression)smol_agent = CodeAgent(tools=[weather_tool, time_tool, calculator_tool, DuckDuckGoSearchTool()],model=MODEL_ID,max_steps=5)def chat_smol(message, history):try:response = smol_agent.run(message)return str(response)except Exception as e:return f"โ Smolagents Error: {str(e)[:200]}"except Exception as e:print(f"Smolagents setup error: {e}")def chat_smol(message, history):return f"โ Smolagents not available: {str(e)[:200]}"# ==========================================# PART 3: UNIFIED GRADIO UI# ==========================================with gr.Blocks(theme=gr.themes.Soft(), title="๐ค AI Agent Studio") as demo:# Headergr.Markdown("# ๐ค AI Agent Studio")gr.Markdown(f"**Model:** {MODEL_ID} | **Provider:** Together AI")# Quick Tools Sectionwith gr.Row():with gr.Column(scale=1):gr.Markdown("### ๐ ๏ธ Quick Tools")# Weather Toolwith gr.Group():weather_city = gr.Textbox(label="Check Weather",placeholder="Enter city name...",scale=4)weather_btn = gr.Button("๐ค๏ธ Get Weather", scale=1)weather_output = gr.Textbox(label="Result", interactive=False)def get_weather_quick(city):return get_weather(city) if city else "Please enter a city name."weather_btn.click(get_weather_quick,inputs=weather_city,outputs=weather_output)# Calculator Toolwith gr.Group():calc_expr = gr.Textbox(label="Calculator",placeholder="Enter math expression...",scale=4)calc_btn = gr.Button("๐งฎ Calculate", scale=1)calc_output = gr.Textbox(label="Result", interactive=False)calc_btn.click(calculate,inputs=calc_expr,outputs=calc_output)# Time Toolwith gr.Group():time_btn = gr.Button("๐ Show World Clock")time_output = gr.Textbox(label="World Times", interactive=False)time_btn.click(lambda: get_world_time("all"),outputs=time_output)# Chat Agents Sectionwith gr.Row():with gr.Tabs():with gr.TabItem("๐ฆ LlamaIndex Agent"):llama_chat = gr.ChatInterface(fn=chat_llama,title="LlamaIndex ReAct Agent",description="Structured agent with reasoning capabilities",examples=["What's the weather in Tokyo?","What time is it in New York?","Calculate 25 * 4 + 18","Tell me the time in London and Sydney"])with gr.TabItem("๐ฌ Smolagents"):smol_chat = gr.ChatInterface(fn=chat_smol,title="Smolagents CodeAgent",description="Code-based agent with web search",examples=["Search for AI news","What's the weather like today?","Calculate 15% of 200","Tell me about machine learning"])# Footergr.Markdown("---")gr.Markdown("""### ๐ก Try asking:- "What's the weather in London and what time is it there?"- "Calculate the area of a circle with radius 5"- "Search for latest technology news"- "Compare time between Tokyo and New York"""")# API Key Noticeif not os.getenv("WEATHER_API_KEY"):gr.Markdown("""โ ๏ธ **Note:** Using mock weather data. For real weather, add `WEATHER_API_KEY` to your Hugging Face Space secrets.""")if __name__ == "__main__":demo.launch(server_name="0.0.0.0",server_port=7860,share=True)
app.py+222-384