Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import osimport datetimeimport pytzimport mathimport requestsimport gradio as grfrom smolagents import CodeAgent, DuckDuckGoSearchTool, tool, InferenceClientModelfrom deep_translator import GoogleTranslatorfrom llama_index.core.agent import ReActAgentfrom llama_index.core.tools import FunctionToolfrom llama_index.llms.huggingface_api import HuggingFaceInferenceAPI# ============ 1. SMOLAGENTS TOOLS ============@tooldef time_tool(timezone: str = "UTC") -> str:"""Get current time in a specific timezone.Args:timezone: The timezone to check (e.g., 'Asia/Tokyo')."""try:tz = pytz.timezone(timezone)now = datetime.datetime.now(tz)return f"⏰ Time in {timezone}: {now.strftime('%Y-%m-%d %H:%M:%S')}"except Exception as e:return f"Error: {str(e)}"@tooldef translator_tool(text: str, target_language: str) -> str:"""Translates text into a specified language.Args:text: The text or phrase to translate.target_language: The destination language (e.g., 'french', 'german')."""try:translation = GoogleTranslator(source='auto', target=target_language).translate(text)return f"Translated to {target_language.title()}: {translation}"except Exception as e:return f"Translation error: {str(e)}"@tooldef weather_tool(location: str) -> str:"""Get the current weather for any location worldwide.Args:location: The name of the city or place (e.g., 'London' or 'Tokyo')."""try:geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1&language=en&format=json"geo_res = requests.get(geo_url).json()if not geo_res.get('results'): return "Location not found."data = geo_res['results'][0]weather_url = f"https://api.open-meteo.com/v1/forecast?latitude={data['latitude']}&longitude={data['longitude']}¤t=temperature_2m"w_res = requests.get(weather_url).json()return f"🌤️ {data['name']}: {w_res['current']['temperature_2m']}°C"except Exception as e:return f"Error: {str(e)}"# ============ AGENT CONFIGURATION ============HF_TOKEN = os.getenv("HF_TOKEN", "")smol_model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct", token=HF_TOKEN)smol_agent = CodeAgent(model=smol_model,tools=[DuckDuckGoSearchTool(), time_tool, translator_tool, weather_tool],max_steps=5)# LlamaIndex Setupllama_llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-7B-Instruct",token=HF_TOKEN,task="conversational")llama_agent = ReActAgent.from_tools([FunctionTool.from_defaults(fn=lambda: f"Tokyo: {datetime.datetime.now(pytz.timezone('Asia/Tokyo'))}", name="get_tokyo_time"),FunctionTool.from_defaults(fn=lambda a, b: a * b, name="multiply")],llm=llama_llm,verbose=True)# ============ GRADIO UI ============def chat_smol(message, history):return str(smol_agent.run(message))def chat_llama(message, history):response = llama_agent.chat(message)return str(response)with gr.Blocks(theme=gr.themes.Soft()) as demo:gr.Markdown("# 🤖 Multi-Framework AI Agent Space")with gr.Tab("Smolagents (Alfred)"):gr.ChatInterface(chat_smol)with gr.Tab("LlamaIndex (ReAct)"):gr.ChatInterface(chat_llama)if __name__ == "__main__":demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import osimport gradio as grimport datetimeimport pytzimport asyncio# 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")# 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,llm=li_llm,)async 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,token=HF_TOKEN,provider="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):try:response = 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()
app.py+65-79