Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines34567898 unmodified lines18192021222324252627281 unmodified line30313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596972 unmodified linesimport datetimeimport pytzimport asynciofrom typing import List, Dict# Framework 1: LlamaIndexfrom llama_index.core.agent.workflow import AgentWorkflow8 unmodified linesMODEL_ID = "Qwen/Qwen2.5-7B-Instruct"# ==========================================# AGENT SETUP# ==========================================li_llm = HuggingFaceInferenceAPI(model_name=MODEL_ID, token=HF_TOKEN, provider="together")li_agent = AgentWorkflow.from_tools_or_functions([FunctionTool.from_defaults(fn=lambda: f"Time: {datetime.datetime.now(pytz.timezone('Asia/Tokyo'))}")],llm=li_llm,)1 unmodified linesmol_agent = CodeAgent(model=smol_model, tools=[DuckDuckGoSearchTool()])# ==========================================# CHAT LOGIC (Gradio 6.0 Compatible)# ==========================================async def chat_llama(message, history):# LlamaIndex runresult = await li_agent.run(user_msg=message)# We yield the final responseyield str(result)def chat_smol(message, history):"""Simulates a 'Thinking' block before the final answer."""# 1. Send an initial 'Thinking' message using Gradio 6.0 Metadatayield gr.ChatMessage(role="assistant",content="Searching for information and executing code...",metadata={"title": "๐ง Agent is thinking"})try:# 2. Run the actual agentresponse = smol_agent.run(message)# 3. Yield the final answer as a normal messageyield str(response)except Exception as e:yield f"โ Error: {str(e)}"# ==========================================# ENHANCED UI LAYOUT# ==========================================with gr.Blocks(fill_height=True) as demo:# Sidebar for Specswith gr.Sidebar():gr.Markdown("## ๐ ๏ธ Global Settings")gr.Dropdown([MODEL_ID], label="Active Model", value=MODEL_ID)gr.Markdown("---")gr.Markdown("### Agent Capabilities")gr.CheckboxGroup(["Search", "Time", "Python Code"], label="Tools Enabled", value=["Search", "Time", "Python Code"], interactive=False)gr.Info("LlamaIndex is best for structured workflows. smolagents is best for dynamic code tasks.")with gr.Column():gr.Markdown(f"# ๐ค Multi-Agent Hub")with gr.Tabs():# TAB 1: LLAMAINDEXwith gr.Tab("๐๏ธ LlamaIndex Workflow"):gr.ChatInterface(fn=chat_llama,description="Specializes in persistent workflows and structured tool calling.",examples=["What's the current time in Tokyo?"],container=False)# TAB 2: SMOLAGENTSwith gr.Tab("๐ป smolagents CodeAgent"):gr.ChatInterface(fn=chat_smol,description="Writes and runs Python code to solve complex reasoning tasks.",examples=["How many people live in Paris and New York combined?"],container=False)if __name__ == "__main__":# Using a professional monochrome theme for the UIdemo.launch(theme=gr.themes.Monochrome())2 unmodified lines34567898 unmodified lines18192021222324252627281 unmodified line3031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485862 unmodified linesimport datetimeimport pytzimport asynciofrom gradio import ChatMessage# Framework 1: LlamaIndexfrom llama_index.core.agent.workflow import AgentWorkflow8 unmodified linesMODEL_ID = "Qwen/Qwen2.5-7B-Instruct"# ==========================================# PART 1: AGENT LOGIC# ==========================================li_llm = HuggingFaceInferenceAPI(model_name=MODEL_ID, token=HF_TOKEN, provider="together")li_agent = AgentWorkflow.from_tools_or_functions([FunctionTool.from_defaults(fn=lambda: f"Current time: {datetime.datetime.now(pytz.timezone('Asia/Tokyo'))}")],llm=li_llm,)1 unmodified linesmol_agent = CodeAgent(model=smol_model, tools=[DuckDuckGoSearchTool()])# ==========================================# PART 2: UI WRAPPERS (Gradio 6.0 Style)# ==========================================async def chat_llama(message, history):# Workflow-based logicresult = await li_agent.run(user_msg=message)return str(result)def chat_smol(message, history):# We yield a 'Thought' block firstyield ChatMessage(role="assistant",content="I am searching the web and writing Python code to verify the details...",metadata={"title": "๐ง Thinking Process", "status": "pending"})try:# Run agentresponse = smol_agent.run(message)# Yield the final result (this replaces the previous yield in the UI)yield ChatMessage(role="assistant", content=str(response))except Exception as e:yield ChatMessage(role="assistant", content=f"โ Error: {str(e)}")# ==========================================# PART 3: THE UI LAYOUT# ==========================================with gr.Blocks(fill_height=True) as demo:with gr.Row():gr.Markdown(f"# ๐ค Multi-Agent Hub\nRunning `{MODEL_ID}` via Together AI", elem_id="header")with gr.Tabs():with gr.Tab("๐๏ธ LlamaIndex (Workflow)"):gr.ChatInterface(fn=chat_llama,examples=["What time is it in Tokyo?"],# 'container' removed to fix your error)gr.Info("Best for structured, multi-step business logic.")with gr.Tab("๐ป smolagents (Code)"):gr.ChatInterface(fn=chat_smol,examples=["Search for the latest stock price of Nvidia."],# Customizing the chatbot component to look cleanerchatbot=gr.Chatbot(label="Code Execution Agent", show_label=False))gr.Warning("Best for dynamic problem solving and web searching.")# Launch with theme and CSSif __name__ == "__main__":demo.launch(theme=gr.themes.Soft(),css="#header { text-align: center; padding: 20px; }")
app.py+38-49