Spaces:
Running
Running
File size: 7,513 Bytes
fb09fd5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
import gradio as gr
import os
from smolagents import CodeAgent, ToolCollection, Tool
from smolagents.models import HfApiModel, LiteLLMModel
# Default model to use
DEFAULT_MODEL = "Qwen/Qwen2.5-Coder-7B-Instruct"
# Tool descriptions for the UI
TOOL_DESCRIPTIONS = {
"Hub Collections": "Add tool collections from Hugging Face Hub.",
"Spaces": "Add tools from Hugging Face Spaces.",
}
# Function to create an agent with selected tools
def create_agent(model_name, hub_tool=None, space_tool=None):
tools = []
# Add tool from Hub if provided
if hub_tool:
try:
hub_collection = ToolCollection.from_hub(collection_slug=hub_tool)
tools.extend(hub_collection.tools)
except Exception as e:
print(f"Error loading Hub tool: {e}")
# Add tool from Space if provided
if space_tool:
try:
space_tool_obj = Tool.from_space(
space_id=space_tool,
name=f"space_{space_tool.replace('/', '_')}",
description=f"Tool from Hugging Face Space: {space_tool}",
)
tools.append(space_tool_obj)
except Exception as e:
print(f"Error loading Space tool: {e}")
# Create and return the agent
try:
# Try to use HfApiModel first
model = HfApiModel(model_id=model_name)
return CodeAgent(tools=tools, model=model)
except Exception:
# Fall back to LiteLLMModel if HfApiModel fails
try:
model = LiteLLMModel(model_id=model_name)
return CodeAgent(tools=tools, model=model)
except Exception as e:
print(f"Error creating agent: {e}")
return None
# Main application
def main():
with gr.Blocks(title="AI Agent Builder") as app:
gr.Markdown("# AI Agent Builder with SmolaGents")
gr.Markdown(
"Build your own AI agent by selecting tools from Hugging Face Hub and Spaces."
)
with gr.Tabs():
with gr.TabItem("Build Agent"):
with gr.Row():
with gr.Column(scale=1):
# Model selection
model_input = gr.Textbox(
label="Model Name",
placeholder="Enter model name or ID",
value=DEFAULT_MODEL,
)
# Hub tool input
hub_tool_input = gr.Textbox(
label="Add Tool Collection from Hub (collection slug)",
placeholder="e.g., huggingface-tools/diffusion-tools-...",
)
# Space tool input
space_tool_input = gr.Textbox(
label="Add Tool from Space (space ID)",
placeholder="e.g., black-forest-labs/FLUX.1-schnell",
)
# Create agent button
create_button = gr.Button("Create Agent")
# Status message
status_msg = gr.Markdown("")
with gr.Column(scale=2):
# Chat interface for the agent
chatbot = gr.Chatbot(label="Agent Chat")
msg = gr.Textbox(label="Your message")
with gr.Row():
clear = gr.Button("Clear Chat")
regenerate = gr.Button("Regenerate Response")
with gr.TabItem("Tool Descriptions"):
tool_descriptions_md = """
## Hugging Face Hub Tool Collections
You can add tool collections from Hugging Face Hub by providing the collection slug.
Example: `huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f`
## Hugging Face Spaces as Tools
You can add tools from Hugging Face Spaces by providing the space ID.
Example: `black-forest-labs/FLUX.1-schnell`
This allows you to use any Gradio app on Hugging Face Spaces as a tool for your agent.
"""
gr.Markdown(tool_descriptions_md)
# Agent state
agent_state = gr.State(None)
last_message = gr.State("")
# Event handlers
def on_create_agent(model, hub_tool, space_tool):
if not model:
return None, [], "", "⚠️ Please enter a model name."
if not hub_tool and not space_tool:
return None, [], "", "⚠️ Please add at least one tool from Hub or Space."
agent = create_agent(model, hub_tool, space_tool)
if agent is None:
return (
None,
[],
"",
"❌ Failed to create agent. Check console for details.",
)
tools_info = []
if hub_tool:
tools_info.append(f"Hub collection: {hub_tool}")
if space_tool:
tools_info.append(f"Space: {space_tool}")
tools_str = " | ".join(tools_info)
return (
agent,
[],
"",
f"✅ Agent created successfully with {model}! ({tools_str})",
)
create_button.click(
on_create_agent,
inputs=[model_input, hub_tool_input, space_tool_input],
outputs=[agent_state, chatbot, msg, status_msg],
)
def on_message(message, chat_history, agent, last_msg):
if not message:
return "", chat_history, last_msg
if agent is None:
chat_history.append((message, "Please create an agent first."))
return "", chat_history, last_msg
try:
response = agent.run(message, reset=False)
chat_history.append((message, response))
return "", chat_history, message
except Exception as e:
error_msg = f"Error: {str(e)}"
chat_history.append((message, error_msg))
return "", chat_history, message
msg.submit(
on_message,
inputs=[msg, chatbot, agent_state, last_message],
outputs=[msg, chatbot, last_message],
)
def on_regenerate(chat_history, agent, last_msg):
if not chat_history or not last_msg or agent is None:
return chat_history, last_msg
try:
# Remove the last exchange
if chat_history:
chat_history.pop()
# Regenerate the response
response = agent.run(last_msg, reset=False)
chat_history.append((last_msg, response))
return chat_history, last_msg
except Exception as e:
error_msg = f"Error regenerating response: {str(e)}"
chat_history.append((last_msg, error_msg))
return chat_history, last_msg
regenerate.click(
on_regenerate,
inputs=[chatbot, agent_state, last_message],
outputs=[chatbot, last_message],
)
def on_clear():
return None, [], "", "Agent cleared. Create a new one to continue."
clear.click(on_clear, outputs=[agent_state, chatbot, last_message, status_msg])
return app
if __name__ == "__main__":
app = main()
app.launch()
|