Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines3456785 unmodified lines1415161718192021222324252627282930313233343536372 unmodified lines404142434445464748495051521 unmodified line54555657585960616263646566676869701 unmodified line72737475767778798081828384858687888990912 unmodified linesimport datetimeimport pytzimport asyncio# Framework 1: LlamaIndexfrom llama_index.core.agent.workflow import AgentWorkflow5 unmodified lines# 0. SHARED CONFIGHF_TOKEN = os.getenv("HF_TOKEN")# 7B is the sweet spot for free serverless inference in 2026MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"# ==========================================# PART 1: LLAMAINDEX AGENT# ==========================================li_llm = HuggingFaceInferenceAPI(model_name=MODEL_ID,token=HF_TOKEN,provider="together")def get_tokyo_time() -> str:"""Returns the current time in Tokyo, Japan."""tz = pytz.timezone('Asia/Tokyo')return f"The current time in Tokyo is {datetime.datetime.now(tz).strftime('%H:%M:%S')}"li_tools = [FunctionTool.from_defaults(fn=get_tokyo_time)]li_agent = AgentWorkflow.from_tools_or_functions(li_tools,2 unmodified linesasync def chat_llama(message, history):try:result = await li_agent.run(user_msg=message)return str(result)except Exception as e:return f"LlamaIndex Error: {str(e)}"# ==========================================# PART 2: SMOLAGENTS# ==========================================smol_model = InferenceClientModel(model_id=MODEL_ID,1 unmodified lineprovider="together")@tooldef weather_tool(location: str) -> str:"""Get the current weather for a location.Args:location: The city name."""return f"The weather in {location} is currently sunny and 22ยฐC."smol_agent = CodeAgent(model=smol_model,tools=[weather_tool, DuckDuckGoSearchTool()])def chat_smol(message, history):1 unmodified lineresponse = smol_agent.run(message)return str(response)except Exception as e:return f"Smolagents Error: {str(e)}"# ==========================================# PART 3: UNIFIED GRADIO UI# ==========================================with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# ๐ค Consolidated AI Agent Space")gr.Markdown(f"Currently using **{MODEL_ID}** via Together AI Provider.")with gr.Tab("LlamaIndex (Workflow)"):gr.ChatInterface(fn=chat_llama)with gr.Tab("smolagents (CodeAgent)"):gr.ChatInterface(fn=chat_smol)if __name__ == "__main__":demo.launch()2 unmodified lines3456789105 unmodified lines1617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172 unmodified lines2202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502511 unmodified line2532542552562572582592602611 unmodified line2632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604612 unmodified linesimport datetimeimport pytzimport asyncioimport requestsfrom typing import Dict, Any# Framework 1: LlamaIndexfrom llama_index.core.agent.workflow import AgentWorkflow5 unmodified lines# 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,2 unmodified linesasync 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,1 unmodified lineprovider="together")smol_agent = CodeAgent(model=smol_model,tools=[enhanced_weather_tool, world_time_tool, calculator_tool, DuckDuckGoSearchTool()])def chat_smol(message, history):1 unmodified lineresponse = 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)
app.py+400-30