Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,484 +0,0 @@
|
|
| 1 |
-
# ==============================================================================
|
| 2 |
-
# Tool World: Advanced Prototype (Hugging Face Space Version)
|
| 3 |
-
# ==============================================================================
|
| 4 |
-
#
|
| 5 |
-
# This script has been updated to run as a Hugging Face Space.
|
| 6 |
-
#
|
| 7 |
-
# Key Upgrades from the original script:
|
| 8 |
-
# 1. **Hugging Face Model Integration**: Uses the 'google/gemma-3n-E4B' model
|
| 9 |
-
# from the Hugging Face Hub for argument extraction.
|
| 10 |
-
# 2. **Environment Variable Management**: Securely accesses the
|
| 11 |
-
# HUGGING_FACE_HUB_TOKEN using os.environ.get(), which is the standard
|
| 12 |
-
# for Hugging Face Spaces.
|
| 13 |
-
# 3. **Standard Dependencies**: All dependencies are managed via a
|
| 14 |
-
# `requirements.txt` file.
|
| 15 |
-
#
|
| 16 |
-
# ==============================================================================
|
| 17 |
-
|
| 18 |
-
# ------------------------------
|
| 19 |
-
# 1. INSTALL & IMPORT PACKAGES
|
| 20 |
-
# ------------------------------
|
| 21 |
-
import numpy as np
|
| 22 |
-
import umap
|
| 23 |
-
import gradio as gr
|
| 24 |
-
from sentence_transformers import SentenceTransformer, util
|
| 25 |
-
import matplotlib.pyplot as plt
|
| 26 |
-
import json
|
| 27 |
-
import os
|
| 28 |
-
from datetime import datetime, timedelta
|
| 29 |
-
import torch
|
| 30 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 31 |
-
|
| 32 |
-
# ------------------------------
|
| 33 |
-
# 2. CONFIGURE & LOAD MODELS
|
| 34 |
-
# ------------------------------
|
| 35 |
-
|
| 36 |
-
print("⚙️ Loading embedding model...")
|
| 37 |
-
# Using a powerful model for better semantic understanding
|
| 38 |
-
embedder = SentenceTransformer('all-mpnet-base-v2')
|
| 39 |
-
print("✅ Embedding model loaded.")
|
| 40 |
-
|
| 41 |
-
# --- Configuration for Hugging Face Model-based Argument Extraction ---
|
| 42 |
-
try:
|
| 43 |
-
HF_TOKEN = os.environ.get('HUGGING_FACE_HUB_TOKEN')
|
| 44 |
-
if HF_TOKEN is None:
|
| 45 |
-
raise ValueError("HUGGING_FACE_HUB_TOKEN secret not found.")
|
| 46 |
-
|
| 47 |
-
print("⚙️ Loading Hugging Face model for argument extraction...")
|
| 48 |
-
# Using the user-specified Gemma 3n model
|
| 49 |
-
model_id = "google/gemma-3n-E4B"
|
| 50 |
-
|
| 51 |
-
hf_tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN)
|
| 52 |
-
hf_model = AutoModelForCausalLM.from_pretrained(
|
| 53 |
-
model_id,
|
| 54 |
-
token=HF_TOKEN,
|
| 55 |
-
torch_dtype=torch.bfloat16, # Use bfloat16 for efficiency
|
| 56 |
-
device_map="auto" # Automatically use GPU if available
|
| 57 |
-
)
|
| 58 |
-
USE_HF_LLM = True
|
| 59 |
-
print(f"✅ Successfully loaded '{model_id}' model.")
|
| 60 |
-
|
| 61 |
-
except Exception as e:
|
| 62 |
-
USE_HF_LLM = False
|
| 63 |
-
print(f"⚠️ WARNING: Could not load the Hugging Face model. Reason: {e}")
|
| 64 |
-
print(" Argument extraction will be disabled.")
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
# ------------------------------
|
| 68 |
-
# 3. ADVANCED TOOL DEFINITION
|
| 69 |
-
# ------------------------------
|
| 70 |
-
|
| 71 |
-
class Tool:
|
| 72 |
-
"""
|
| 73 |
-
Represents a tool with structured arguments and rich descriptive data
|
| 74 |
-
for high-quality embedding.
|
| 75 |
-
"""
|
| 76 |
-
def __init__(self, name, description, args_schema, function, examples=None):
|
| 77 |
-
self.name = name
|
| 78 |
-
self.description = description
|
| 79 |
-
self.args_schema = args_schema
|
| 80 |
-
self.function = function
|
| 81 |
-
self.examples = examples or []
|
| 82 |
-
self.embedding = self._create_embedding()
|
| 83 |
-
|
| 84 |
-
def _create_embedding(self):
|
| 85 |
-
"""
|
| 86 |
-
Creates a rich embedding by combining the tool's name, description,
|
| 87 |
-
argument structure, and examples.
|
| 88 |
-
"""
|
| 89 |
-
schema_str = json.dumps(self.args_schema, indent=2)
|
| 90 |
-
examples_str = "\n".join([f" - Example: {ex['prompt']} -> Args: {json.dumps(ex['args'])}" for ex in self.examples])
|
| 91 |
-
|
| 92 |
-
embedding_text = (
|
| 93 |
-
f"Tool Name: {self.name}\n"
|
| 94 |
-
f"Description: {self.description}\n"
|
| 95 |
-
f"Argument Schema: {schema_str}\n"
|
| 96 |
-
f"Usage Examples:\n{examples_str}"
|
| 97 |
-
)
|
| 98 |
-
return embedder.encode(embedding_text, convert_to_tensor=True)
|
| 99 |
-
|
| 100 |
-
def __repr__(self):
|
| 101 |
-
return f"<Tool: {self.name}>"
|
| 102 |
-
|
| 103 |
-
# ------------------------------
|
| 104 |
-
# 4. TOOL IMPLEMENTATIONS
|
| 105 |
-
# ------------------------------
|
| 106 |
-
|
| 107 |
-
def get_weather_forecast(location: str, days: int = 1):
|
| 108 |
-
"""Simulates fetching a weather forecast."""
|
| 109 |
-
if not isinstance(location, str) or not isinstance(days, int):
|
| 110 |
-
return {"error": "Invalid argument types. 'location' must be a string and 'days' an integer."}
|
| 111 |
-
|
| 112 |
-
weather_conditions = ["Sunny", "Cloudy", "Rainy", "Windy", "Snowy"]
|
| 113 |
-
response = {"location": location, "forecast": []}
|
| 114 |
-
|
| 115 |
-
for i in range(days):
|
| 116 |
-
date = (datetime.now() + timedelta(days=i)).strftime('%Y-%m-%d')
|
| 117 |
-
condition = np.random.choice(weather_conditions)
|
| 118 |
-
temp = np.random.randint(5, 25)
|
| 119 |
-
response["forecast"].append({
|
| 120 |
-
"date": date,
|
| 121 |
-
"condition": condition,
|
| 122 |
-
"temperature_celsius": temp
|
| 123 |
-
})
|
| 124 |
-
return response
|
| 125 |
-
|
| 126 |
-
def create_calendar_event(title: str, date: str, duration_minutes: int = 60, participants: list = None):
|
| 127 |
-
"""Simulates creating a calendar event."""
|
| 128 |
-
try:
|
| 129 |
-
event_time = datetime.strptime(date, '%Y-%m-%d %H:%M')
|
| 130 |
-
return {
|
| 131 |
-
"status": "success",
|
| 132 |
-
"event_created": {
|
| 133 |
-
"title": title,
|
| 134 |
-
"start_time": event_time.isoformat(),
|
| 135 |
-
"end_time": (event_time + timedelta(minutes=duration_minutes)).isoformat(),
|
| 136 |
-
"participants": participants or ["organizer"]
|
| 137 |
-
}
|
| 138 |
-
}
|
| 139 |
-
except ValueError:
|
| 140 |
-
return {"error": "Invalid date format. Please use 'YYYY-MM-DD HH:MM'."}
|
| 141 |
-
|
| 142 |
-
def summarize_text(text: str, compression_level: str = 'medium'):
|
| 143 |
-
"""Summarizes a given text based on a compression level."""
|
| 144 |
-
word_count = len(text.split())
|
| 145 |
-
ratios = {'high': 0.2, 'medium': 0.4, 'low': 0.7}
|
| 146 |
-
ratio = ratios.get(compression_level, 0.4)
|
| 147 |
-
summary_length = int(word_count * ratio)
|
| 148 |
-
summary = " ".join(text.split()[:summary_length])
|
| 149 |
-
return {"summary": summary + "...", "original_word_count": word_count, "summary_word_count": summary_length}
|
| 150 |
-
|
| 151 |
-
def search_web(query: str, domain: str = None):
|
| 152 |
-
"""Simulates a web search, with an optional domain filter."""
|
| 153 |
-
results = [
|
| 154 |
-
f"Simulated result 1 for '{query}'",
|
| 155 |
-
f"Simulated result 2 for '{query}'",
|
| 156 |
-
f"Simulated result 3 for '{query}'"
|
| 157 |
-
]
|
| 158 |
-
if domain:
|
| 159 |
-
return {"status": f"Searching for '{query}' within '{domain}'...", "results": results}
|
| 160 |
-
return {"status": f"Searching for '{query}'...", "results": results}
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
# ------------------------------
|
| 164 |
-
# 5. DEFINE THE TOOLSET
|
| 165 |
-
# ------------------------------
|
| 166 |
-
|
| 167 |
-
tools = [
|
| 168 |
-
Tool(
|
| 169 |
-
name="weather_reporter",
|
| 170 |
-
description="Provides the weather forecast for a specific location for a given number of days.",
|
| 171 |
-
args_schema={
|
| 172 |
-
"type": "object",
|
| 173 |
-
"properties": {
|
| 174 |
-
"location": {"type": "string", "description": "The city and state, e.g., 'San Francisco, CA'"},
|
| 175 |
-
"days": {"type": "integer", "description": "The number of days to forecast", "default": 1}
|
| 176 |
-
},
|
| 177 |
-
"required": ["location"]
|
| 178 |
-
},
|
| 179 |
-
function=get_weather_forecast,
|
| 180 |
-
examples=[
|
| 181 |
-
{"prompt": "what's the weather like in London for the next 3 days", "args": {"location": "London", "days": 3}},
|
| 182 |
-
{"prompt": "forecast for New York tomorrow", "args": {"location": "New York", "days": 1}}
|
| 183 |
-
]
|
| 184 |
-
),
|
| 185 |
-
Tool(
|
| 186 |
-
name="calendar_creator",
|
| 187 |
-
description="Creates a new event in the user's calendar.",
|
| 188 |
-
args_schema={
|
| 189 |
-
"type": "object",
|
| 190 |
-
"properties": {
|
| 191 |
-
"title": {"type": "string", "description": "The title of the calendar event"},
|
| 192 |
-
"date": {"type": "string", "description": "The start date and time in 'YYYY-MM-DD HH:MM' format"},
|
| 193 |
-
"duration_minutes": {"type": "integer", "description": "The duration of the event in minutes", "default": 60},
|
| 194 |
-
"participants": {"type": "array", "items": {"type": "string"}, "description": "List of email addresses of participants"}
|
| 195 |
-
},
|
| 196 |
-
"required": ["title", "date"]
|
| 197 |
-
},
|
| 198 |
-
function=create_calendar_event,
|
| 199 |
-
examples=[
|
| 200 |
-
{"prompt": "Schedule a 'Project Sync' for tomorrow at 3pm with bob@example.com", "args": {"title": "Project Sync", "date": (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d 15:00'), "participants": ["bob@example.com"]}},
|
| 201 |
-
{"prompt": "new event: Dentist appointment on 2025-12-20 at 10:00 for 45 mins", "args": {"title": "Dentist appointment", "date": "2025-12-20 10:00", "duration_minutes": 45}}
|
| 202 |
-
]
|
| 203 |
-
),
|
| 204 |
-
Tool(
|
| 205 |
-
name="text_summarizer",
|
| 206 |
-
description="Summarizes a long piece of text. Can be set to high, medium, or low compression.",
|
| 207 |
-
args_schema={
|
| 208 |
-
"type": "object",
|
| 209 |
-
"properties": {
|
| 210 |
-
"text": {"type": "string", "description": "The text to be summarized."},
|
| 211 |
-
"compression_level": {"type": "string", "enum": ["high", "medium", "low"], "description": "The level of summarization.", "default": "medium"}
|
| 212 |
-
},
|
| 213 |
-
"required": ["text"]
|
| 214 |
-
},
|
| 215 |
-
function=summarize_text,
|
| 216 |
-
examples=[
|
| 217 |
-
{"prompt": "summarize this article for me, make it very short: [long text...]", "args": {"text": "[long text...]", "compression_level": "high"}}
|
| 218 |
-
]
|
| 219 |
-
),
|
| 220 |
-
Tool(
|
| 221 |
-
name="web_search",
|
| 222 |
-
description="Performs a web search to find information on a topic.",
|
| 223 |
-
args_schema={
|
| 224 |
-
"type": "object",
|
| 225 |
-
"properties": {
|
| 226 |
-
"query": {"type": "string", "description": "The search query."},
|
| 227 |
-
"domain": {"type": "string", "description": "Optional: a specific website domain to search within (e.g., 'wikipedia.org')."}
|
| 228 |
-
},
|
| 229 |
-
"required": ["query"]
|
| 230 |
-
},
|
| 231 |
-
function=search_web,
|
| 232 |
-
examples=[
|
| 233 |
-
{"prompt": "who invented the light bulb", "args": {"query": "who invented the light bulb"}},
|
| 234 |
-
{"prompt": "search for 'transformer models' on arxiv.org", "args": {"query": "transformer models", "domain": "arxiv.org"}}
|
| 235 |
-
]
|
| 236 |
-
)
|
| 237 |
-
]
|
| 238 |
-
|
| 239 |
-
print(f"✅ {len(tools)} tools defined and embedded.")
|
| 240 |
-
|
| 241 |
-
# ------------------------------
|
| 242 |
-
# 6. CORE LOGIC: TOOL SELECTION & ARGUMENT EXTRACTION
|
| 243 |
-
# ------------------------------
|
| 244 |
-
|
| 245 |
-
def find_best_tool(user_intent: str):
|
| 246 |
-
"""Finds the most semantically similar tool for a user's intent."""
|
| 247 |
-
intent_embedding = embedder.encode(user_intent, convert_to_tensor=True)
|
| 248 |
-
# Move tool embeddings to the same device as the intent embedding
|
| 249 |
-
tool_embeddings = [tool.embedding.to(intent_embedding.device) for tool in tools]
|
| 250 |
-
similarities = [util.pytorch_cos_sim(intent_embedding, tool_emb).item() for tool_emb in tool_embeddings]
|
| 251 |
-
best_index = int(np.argmax(similarities))
|
| 252 |
-
best_tool = tools[best_index]
|
| 253 |
-
best_score = similarities[best_index]
|
| 254 |
-
return best_tool, best_score, similarities
|
| 255 |
-
|
| 256 |
-
def extract_arguments_hf(user_prompt: str, tool: Tool):
|
| 257 |
-
"""
|
| 258 |
-
Uses a local Hugging Face model to extract structured arguments.
|
| 259 |
-
"""
|
| 260 |
-
system_prompt = f"""
|
| 261 |
-
You are an expert at extracting structured data from natural language.
|
| 262 |
-
Your task is to analyze the user's prompt and extract the arguments required to call the tool: '{tool.name}'.
|
| 263 |
-
|
| 264 |
-
You must adhere to the following JSON schema for the arguments:
|
| 265 |
-
{json.dumps(tool.args_schema, indent=2)}
|
| 266 |
-
|
| 267 |
-
- If a value is not present in the prompt for a non-required field, omit it from the JSON.
|
| 268 |
-
- If a required value is missing, return a JSON object with an "error" key explaining what is missing.
|
| 269 |
-
- Today's date is {datetime.now().strftime('%Y-%m-%d')}.
|
| 270 |
-
- Respond ONLY with a valid JSON object. Do not include any other text, explanation, or markdown code blocks.
|
| 271 |
-
"""
|
| 272 |
-
|
| 273 |
-
# Gemma instruction-following format
|
| 274 |
-
chat = [
|
| 275 |
-
{"role": "user", "content": f"{system_prompt}\n\nUser Prompt: \"{user_prompt}\""},
|
| 276 |
-
]
|
| 277 |
-
|
| 278 |
-
prompt = hf_tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
|
| 279 |
-
|
| 280 |
-
try:
|
| 281 |
-
inputs = hf_tokenizer.encode(prompt, add_special_tokens=False, return_tensors="pt").to(hf_model.device)
|
| 282 |
-
|
| 283 |
-
# Generate with the model
|
| 284 |
-
outputs = hf_model.generate(input_ids=inputs, max_new_tokens=256, do_sample=False)
|
| 285 |
-
decoded_output = hf_tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)
|
| 286 |
-
|
| 287 |
-
# Clean the response to find the JSON object
|
| 288 |
-
json_str = decoded_output.strip()
|
| 289 |
-
|
| 290 |
-
# Find the first '{' and the last '}' to get the JSON part
|
| 291 |
-
json_start = json_str.find('{')
|
| 292 |
-
json_end = json_str.rfind('}')
|
| 293 |
-
|
| 294 |
-
if json_start != -1 and json_end != -1:
|
| 295 |
-
json_str = json_str[json_start : json_end + 1]
|
| 296 |
-
return json.loads(json_str)
|
| 297 |
-
else:
|
| 298 |
-
raise json.JSONDecodeError("No JSON object found in the model output.", json_str, 0)
|
| 299 |
-
|
| 300 |
-
except Exception as e:
|
| 301 |
-
print(f"Error during HF model inference or JSON parsing: {e}")
|
| 302 |
-
return {"error": f"Failed to extract arguments with the local LLM. Details: {str(e)}"}
|
| 303 |
-
|
| 304 |
-
def execute_tool(user_prompt: str):
|
| 305 |
-
"""The main pipeline: Find tool, extract args, execute."""
|
| 306 |
-
selected_tool, score, _ = find_best_tool(user_prompt)
|
| 307 |
-
|
| 308 |
-
if USE_HF_LLM:
|
| 309 |
-
print(f"⚙️ Selected Tool: {selected_tool.name}. Extracting arguments with Gemma...")
|
| 310 |
-
extracted_args = extract_arguments_hf(user_prompt, selected_tool)
|
| 311 |
-
else:
|
| 312 |
-
# Fallback if the model failed to load
|
| 313 |
-
extracted_args = {"error": "Argument extraction is disabled because the Hugging Face model could not be loaded."}
|
| 314 |
-
|
| 315 |
-
if 'error' in extracted_args:
|
| 316 |
-
print(f"❌ Argument extraction failed: {extracted_args['error']}")
|
| 317 |
-
# Ensure the final output string is valid JSON
|
| 318 |
-
final_output_str = json.dumps({
|
| 319 |
-
"error": "Execution failed during argument extraction.",
|
| 320 |
-
"details": extracted_args['error']
|
| 321 |
-
})
|
| 322 |
-
return (
|
| 323 |
-
user_prompt,
|
| 324 |
-
selected_tool.name,
|
| 325 |
-
f"{score:.3f}",
|
| 326 |
-
json.dumps(extracted_args, indent=2),
|
| 327 |
-
final_output_str
|
| 328 |
-
)
|
| 329 |
-
|
| 330 |
-
print(f"✅ Arguments extracted: {json.dumps(extracted_args, indent=2)}")
|
| 331 |
-
|
| 332 |
-
try:
|
| 333 |
-
print(f"🚀 Executing tool function: {selected_tool.name}...")
|
| 334 |
-
output = selected_tool.function(**extracted_args)
|
| 335 |
-
print(f"✅ Execution complete.")
|
| 336 |
-
output_str = json.dumps(output, indent=2)
|
| 337 |
-
except Exception as e:
|
| 338 |
-
print(f"❌ Tool execution failed: {e}")
|
| 339 |
-
output_str = f'{{"error": "Tool execution failed", "details": "{str(e)}"}}'
|
| 340 |
-
|
| 341 |
-
return (
|
| 342 |
-
user_prompt,
|
| 343 |
-
selected_tool.name,
|
| 344 |
-
f"{score:.3f}",
|
| 345 |
-
json.dumps(extracted_args, indent=2),
|
| 346 |
-
output_str
|
| 347 |
-
)
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
# ------------------------------
|
| 351 |
-
# 7. VISUALIZATION
|
| 352 |
-
# ------------------------------
|
| 353 |
-
|
| 354 |
-
def plot_tool_world(user_intent=None):
|
| 355 |
-
"""Generates a 2D UMAP plot of the tool latent space."""
|
| 356 |
-
tool_vectors = [tool.embedding.cpu().numpy() for tool in tools]
|
| 357 |
-
labels = [tool.name for tool in tools]
|
| 358 |
-
all_vectors = tool_vectors
|
| 359 |
-
|
| 360 |
-
if user_intent and user_intent.strip():
|
| 361 |
-
intent_vector = embedder.encode(user_intent, convert_to_tensor=True).cpu().numpy()
|
| 362 |
-
all_vectors.append(intent_vector)
|
| 363 |
-
labels.append("Your Intent")
|
| 364 |
-
|
| 365 |
-
# UMAP requires at least 2 neighbors
|
| 366 |
-
n_neighbors = min(len(all_vectors) - 1, 5)
|
| 367 |
-
if n_neighbors < 1:
|
| 368 |
-
n_neighbors = 1
|
| 369 |
-
|
| 370 |
-
reducer = umap.UMAP(n_neighbors=n_neighbors, min_dist=0.3, metric='cosine', random_state=42)
|
| 371 |
-
|
| 372 |
-
# UMAP fit_transform requires at least 2 samples
|
| 373 |
-
if len(all_vectors) < 2:
|
| 374 |
-
# Create a dummy plot if there's not enough data
|
| 375 |
-
fig, ax = plt.subplots(figsize=(10, 7))
|
| 376 |
-
ax.text(0.5, 0.5, "Not enough data to create a plot.", ha='center', va='center')
|
| 377 |
-
return fig
|
| 378 |
-
|
| 379 |
-
reduced_vectors = reducer.fit_transform(all_vectors)
|
| 380 |
-
|
| 381 |
-
plt.style.use('seaborn-v0_8-whitegrid')
|
| 382 |
-
fig, ax = plt.subplots(figsize=(10, 7))
|
| 383 |
-
|
| 384 |
-
for i, label in enumerate(labels):
|
| 385 |
-
x, y = reduced_vectors[i]
|
| 386 |
-
if label == "Your Intent":
|
| 387 |
-
ax.scatter(x, y, color='red', s=150, zorder=5, label=label, marker='*')
|
| 388 |
-
ax.text(x, y + 0.05, label, fontsize=12, ha='center', color='red', weight='bold')
|
| 389 |
-
else:
|
| 390 |
-
ax.scatter(x, y, s=100, alpha=0.8, label=label)
|
| 391 |
-
ax.text(x, y + 0.05, label, fontsize=10, ha='center')
|
| 392 |
-
|
| 393 |
-
ax.set_title("Tool World: Latent Space Map", fontsize=16)
|
| 394 |
-
ax.set_xlabel("UMAP Dimension 1", fontsize=12)
|
| 395 |
-
ax.set_ylabel("UMAP Dimension 2", fontsize=12)
|
| 396 |
-
ax.grid(True)
|
| 397 |
-
|
| 398 |
-
handles, labels_legend = ax.get_legend_handles_labels()
|
| 399 |
-
by_label = dict(zip(labels_legend, handles))
|
| 400 |
-
ax.legend(by_label.values(), by_label.keys())
|
| 401 |
-
|
| 402 |
-
plt.tight_layout()
|
| 403 |
-
return fig
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
# ------------------------------
|
| 407 |
-
# 8. GRADIO INTERFACE
|
| 408 |
-
# ------------------------------
|
| 409 |
-
|
| 410 |
-
print("🚀 Launching Gradio interface...")
|
| 411 |
-
|
| 412 |
-
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 413 |
-
gr.Markdown("# 🛠️ Tool World: Advanced Prototype (Hugging Face Version)")
|
| 414 |
-
gr.Markdown(
|
| 415 |
-
"Enter a natural language command. The system will select the best tool, "
|
| 416 |
-
"extract structured arguments with **google/gemma-3n-E4B**, and execute it."
|
| 417 |
-
)
|
| 418 |
-
|
| 419 |
-
with gr.Row():
|
| 420 |
-
with gr.Column(scale=1):
|
| 421 |
-
inp = gr.Textbox(
|
| 422 |
-
label="Your Intent",
|
| 423 |
-
placeholder="e.g., What's the weather in Paris for 2 days?",
|
| 424 |
-
lines=3
|
| 425 |
-
)
|
| 426 |
-
run_btn = gr.Button("Invoke Tool", variant="primary")
|
| 427 |
-
|
| 428 |
-
gr.Markdown("---")
|
| 429 |
-
gr.Markdown("### Examples")
|
| 430 |
-
gr.Examples(
|
| 431 |
-
examples=[
|
| 432 |
-
"Schedule a 'Team Meeting' for tomorrow at 10:30 am",
|
| 433 |
-
"What is the weather forecast in Tokyo for the next 5 days?",
|
| 434 |
-
"search for the latest news on generative AI on reuters.com",
|
| 435 |
-
"Please give me a very short summary of this text: The Industrial Revolution was the transition to new manufacturing processes in Europe and the United States, in the period from about 1760 to sometime between 1820 and 1840."
|
| 436 |
-
],
|
| 437 |
-
inputs=inp
|
| 438 |
-
)
|
| 439 |
-
|
| 440 |
-
with gr.Column(scale=2):
|
| 441 |
-
gr.Markdown("### Invocation Details")
|
| 442 |
-
with gr.Row():
|
| 443 |
-
out_tool = gr.Textbox(label="Selected Tool", interactive=False)
|
| 444 |
-
out_score = gr.Textbox(label="Similarity Score", interactive=False)
|
| 445 |
-
|
| 446 |
-
out_args = gr.JSON(label="Extracted Arguments")
|
| 447 |
-
out_result = gr.JSON(label="Tool Execution Output")
|
| 448 |
-
|
| 449 |
-
with gr.Row():
|
| 450 |
-
gr.Markdown("---")
|
| 451 |
-
gr.Markdown("### Latent Space Visualization")
|
| 452 |
-
plot_output = gr.Plot(label="Tool World Map")
|
| 453 |
-
|
| 454 |
-
def process_and_plot(user_prompt):
|
| 455 |
-
if not user_prompt or not user_prompt.strip():
|
| 456 |
-
# Return empty state and the default plot
|
| 457 |
-
return "", "", {}, {}, plot_tool_world()
|
| 458 |
-
|
| 459 |
-
prompt, tool_name, score, args_json, result_json = execute_tool(user_prompt)
|
| 460 |
-
fig = plot_tool_world(user_prompt)
|
| 461 |
-
|
| 462 |
-
# Safely load JSON strings into objects for the UI
|
| 463 |
-
try:
|
| 464 |
-
args_obj = json.loads(args_json)
|
| 465 |
-
except (json.JSONDecodeError, TypeError):
|
| 466 |
-
args_obj = {"error": "Invalid JSON in arguments", "raw": args_json}
|
| 467 |
-
|
| 468 |
-
try:
|
| 469 |
-
result_obj = json.loads(result_json)
|
| 470 |
-
except (json.JSONDecodeError, TypeError):
|
| 471 |
-
result_obj = {"error": "Invalid JSON in result", "raw": result_json}
|
| 472 |
-
|
| 473 |
-
return tool_name, score, args_obj, result_obj, fig
|
| 474 |
-
|
| 475 |
-
run_btn.click(
|
| 476 |
-
fn=process_and_plot,
|
| 477 |
-
inputs=inp,
|
| 478 |
-
outputs=[out_tool, out_score, out_args, out_result, plot_output]
|
| 479 |
-
)
|
| 480 |
-
|
| 481 |
-
# Load the initial plot when the app starts
|
| 482 |
-
demo.load(fn=lambda: plot_tool_world(None), inputs=None, outputs=plot_output)
|
| 483 |
-
|
| 484 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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