Spaces:
Sleeping
Sleeping
Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import osimport datetimeimport pytzimport mathimport requestsimport gradio as grfrom deep_translator import GoogleTranslator
# --- LLAMAINDEX IMPORTS ---from llama_index.core.agent import ReActAgentfrom llama_index.core.tools import FunctionToolfrom llama_index.llms.huggingface_api import HuggingFaceInferenceAPI
# --- SMOLAGENTS IMPORTS ---from smolagents import CodeAgent, DuckDuckGoSearchTool, tool, InferenceClientModel
# 1. SHARED SETUP & TOKENS# Ensure you set these in your Hugging Face Space Settings -> SecretsHF_TOKEN = os.getenv("HF_TOKEN")
# ==========================================# PART 1: LLAMAINDEX AGENT SETUP# ==========================================li_llm = HuggingFaceInferenceAPI( model_name="Qwen/Qwen2.5-7B-Instruct", token=HF_TOKEN, task="conversational", provider="together")
def get_tokyo_time_li() -> 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')}"
def multiply_li(a: float, b: float) -> float: """Multiplies two numbers (a and b) and returns the result.""" return a * b
li_tools = [ FunctionTool.from_defaults(fn=get_tokyo_time_li), FunctionTool.from_defaults(fn=multiply_li)]
RE_ACT_PROMPT = """You are a helpful assistant.For every query, you MUST follow this sequence:Thought: <your reasoning>Action: <tool_name>Action Input: {"arg1": value}Observation: <result from tool>... (repeat if needed)Thought: I have the final answer.Answer: <your final response to the user>"""
li_agent = ReActAgent.from_tools( li_tools, llm=li_llm, verbose=True, context=RE_ACT_PROMPT)
def li_chat_fn(message, history): try: return str(li_agent.chat(message)) except Exception as e: return f"LlamaIndex Error: {str(e)}"
li_interface = gr.ChatInterface(li_chat_fn, title="LlamaIndex Agent")
# ==========================================# PART 2: SMOLAGENTS SETUP# ==========================================smol_model = InferenceClientModel( model_id="Qwen/Qwen2.5-Coder-32B-Instruct", token=HF_TOKEN )
@tooldef weather_tool(location: str) -> str: """Get current weather for any location. Args: location: The name of the city. """ geo_url = f"https://geocoding-api.open-meteo.com/v1/search?name={location}&count=1" geo_res = requests.get(geo_url).json() if not geo_res.get('results'): return "Location not found." data = geo_res['results'][0] w_url = f"https://api.open-meteo.com/v1/forecast?latitude={data['latitude']}&longitude={data['longitude']}¤t=temperature_2m" w_res = requests.get(w_url).json() return f"Temp in {location}: {w_res['current']['temperature_2m']}°C"
smol_agent = CodeAgent( model=smol_model, tools=[weather_tool, DuckDuckGoSearchTool()], additional_authorized_imports=['requests', 'math', 'pytz'])
def smol_chat_fn(message, history): try: return str(smol_agent.run(message)) except Exception as e: return f"Smolagents Error: {str(e)}"
smol_interface = gr.ChatInterface(smol_chat_fn, title="Smolagents Assistant")
# ==========================================# PART 3: COMBINE INTO TABS# ==========================================demo = gr.TabbedInterface( [li_interface, smol_interface], ["LlamaIndex Agent", "Smolagents Agent"], title="Multi-Framework Agent Comparison")
if __name__ == "__main__": demo.launch()app.pyAdded+117