Spaces:
Running
Running
File size: 16,325 Bytes
2a5ead4 a58e6a3 2a5ead4 4c24c65 2a5ead4 c0c69f5 b75e768 d86459e c0c69f5 2a5ead4 b75e768 2a5ead4 4c24c65 2a5ead4 583c5ee 2a5ead4 f508f01 4c24c65 2a5ead4 583c5ee 2a5ead4 d86459e 2a5ead4 4c24c65 d86459e 2a5ead4 4c24c65 2a5ead4 583c5ee 2a5ead4 f508f01 4c24c65 2a5ead4 583c5ee 2a5ead4 b75e768 4c24c65 b75e768 4c24c65 b75e768 f508f01 b75e768 f508f01 b75e768 d86459e 2a5ead4 f508f01 4c24c65 2a5ead4 d86459e 2a5ead4 d86459e 2a5ead4 583c5ee 2a5ead4 583c5ee d86459e 2a5ead4 9bcfe23 d86459e 583c5ee f508f01 4c24c65 f508f01 2a5ead4 4c24c65 2a5ead4 0d3d041 2a5ead4 4c24c65 f508f01 a58e6a3 0d3d041 2a5ead4 9bcfe23 2a5ead4 0d3d041 2a5ead4 0d3d041 2a5ead4 4c24c65 2a5ead4 9bcfe23 2a5ead4 f508f01 2a5ead4 583c5ee 2a5ead4 d86459e 2a5ead4 d86459e 2a5ead4 4c24c65 a58e6a3 2a5ead4 583c5ee f508f01 583c5ee 4c24c65 583c5ee 4c24c65 583c5ee 4c24c65 a58e6a3 2a5ead4 | 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 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | """
Image agent backend β multimodal agent with HuggingFace image generation tools.
Uses the same tool-calling loop pattern as agent.py:
LLM call β parse tool_calls β execute β update history β repeat
Key difference: maintains a figure store (Dict[str, str]) mapping names like
"figure_T1_1" to base64 data, so the VLM can reference images across tool calls
without passing huge base64 strings in arguments.
"""
import base64
import json
import logging
import re
from typing import List, Dict, Optional
from .tools import (
generate_image, edit_image, read_image, save_image,
execute_generate_image, execute_edit_image, execute_read_image,
)
logger = logging.getLogger(__name__)
TOOLS = [generate_image, edit_image, read_image, save_image]
# Max dimension for images sent to the VLM context (keeps token count manageable)
VLM_IMAGE_MAX_DIM = 512
VLM_IMAGE_JPEG_QUALITY = 70
def resize_image_for_vlm(base64_png: str) -> str:
"""Resize and compress an image for VLM context to avoid token overflow.
Takes a full-res base64 PNG and returns a smaller base64 JPEG thumbnail
that fits within VLM_IMAGE_MAX_DIM on its longest side.
"""
try:
from PIL import Image
import io as _io
img_bytes = base64.b64decode(base64_png)
img = Image.open(_io.BytesIO(img_bytes))
# Resize if larger than max dimension
if max(img.size) > VLM_IMAGE_MAX_DIM:
img.thumbnail((VLM_IMAGE_MAX_DIM, VLM_IMAGE_MAX_DIM), Image.LANCZOS)
# Convert to RGB (JPEG doesn't support alpha)
if img.mode in ("RGBA", "P"):
img = img.convert("RGB")
# Save as JPEG for much smaller base64
buffer = _io.BytesIO()
img.save(buffer, format="JPEG", quality=VLM_IMAGE_JPEG_QUALITY)
return base64.b64encode(buffer.getvalue()).decode("utf-8")
except Exception as e:
logger.error(f"Failed to resize image for VLM: {e}")
# Fall back to original β better to try than to lose the image entirely
return base64_png
MAX_TURNS = 20
def execute_tool(tool_name: str, args: dict, hf_token: str, image_store: dict, image_counter: int, default_gen_model: str = None, default_edit_model: str = None, files_root: str = None, image_prefix: str = "figure_") -> dict:
"""
Execute a tool by name and return result dict.
Returns:
dict with keys:
- "content": str result for the LLM
- "image": optional base64 PNG
- "image_name": optional image reference name (e.g., "image_1")
- "display": dict with display-friendly data for frontend
- "image_counter": updated counter
"""
if tool_name == "generate_image":
prompt = args.get("prompt", "")
model = args.get("model") or default_gen_model or "black-forest-labs/FLUX.1-schnell"
base64_png, error = execute_generate_image(prompt, hf_token, model)
if base64_png:
image_counter += 1
name = f"{image_prefix}{image_counter}"
image_store[name] = {"type": "png", "data": base64_png}
return {
"content": f"Image generated successfully as '{name}'. The image is attached.",
"image": base64_png,
"image_name": name,
"display": {"type": "generate", "prompt": prompt, "model": model, "image_name": name},
"image_counter": image_counter,
}
else:
return {
"content": f"Failed to generate image: {error}",
"display": {"type": "generate_error", "prompt": prompt},
"image_counter": image_counter,
}
elif tool_name == "edit_image":
prompt = args.get("prompt", "")
source = args.get("source", "")
model = args.get("model") or default_edit_model or "black-forest-labs/FLUX.1-Kontext-dev"
# Resolve source: image store reference, URL, or local path
source_bytes = None
if source in image_store:
source_bytes = base64.b64decode(image_store[source]["data"])
else:
source_base64 = execute_read_image(source, files_root=files_root)
if source_base64:
source_bytes = base64.b64decode(source_base64)
if source_bytes is None:
return {
"content": f"Could not resolve image source '{source}'. Use a URL or a reference from a previous tool call (e.g., 'figure_T1_1').",
"display": {"type": "edit_error", "source": source},
"image_counter": image_counter,
}
base64_png, error = execute_edit_image(prompt, source_bytes, hf_token, model)
if base64_png:
image_counter += 1
name = f"{image_prefix}{image_counter}"
image_store[name] = {"type": "png", "data": base64_png}
return {
"content": f"Image edited successfully as '{name}'. The image is attached.",
"image": base64_png,
"image_name": name,
"display": {"type": "edit", "prompt": prompt, "source": source, "model": model, "image_name": name},
"image_counter": image_counter,
}
else:
return {
"content": f"Failed to edit image: {error}",
"display": {"type": "edit_error", "source": source},
"image_counter": image_counter,
}
elif tool_name == "save_image":
source = args.get("source", "")
filename = args.get("filename", "image.png")
# Ensure .png extension
if not filename.lower().endswith(".png"):
filename += ".png"
# Resolve source from image store or URL
image_data = None
if source in image_store:
image_data = base64.b64decode(image_store[source]["data"])
else:
source_base64 = execute_read_image(source, files_root=files_root)
if source_base64:
image_data = base64.b64decode(source_base64)
if image_data is None:
return {
"content": f"Could not resolve image source '{source}'. Use a reference (e.g., 'figure_T1_1') or a URL.",
"display": {"type": "save_error", "source": source},
"image_counter": image_counter,
}
# Save to files_root
import os
save_dir = files_root or "."
os.makedirs(save_dir, exist_ok=True)
# Sanitize filename
filename = os.path.basename(filename)
save_path = os.path.join(save_dir, filename)
with open(save_path, "wb") as f:
f.write(image_data)
# Include base64 so frontend can show a preview of the saved image
saved_base64 = base64.b64encode(image_data).decode("utf-8")
return {
"content": f"Image saved as '{filename}'.",
"image": saved_base64,
"display": {"type": "save_image", "filename": filename, "source": source},
"image_counter": image_counter,
}
elif tool_name in ("read_image", "read_image_url"):
source = args.get("source") or args.get("url", "")
base64_png = execute_read_image(source, files_root=files_root)
if base64_png:
image_counter += 1
name = f"{image_prefix}{image_counter}"
image_store[name] = {"type": "png", "data": base64_png}
return {
"content": f"Image loaded successfully as '{name}'. The image is attached.",
"image": base64_png,
"image_name": name,
"display": {"type": "read_image", "url": source, "image_name": name},
"image_counter": image_counter,
}
else:
# Provide more specific error for SVG files
is_svg = source.lower().endswith(".svg") or "/svg" in source.lower()
if is_svg:
error_msg = f"Failed to load image from '{source}'. SVG format is not supported β only raster formats (PNG, JPEG, GIF, WebP, BMP) are accepted. Ask the user for a raster version of the image."
else:
error_msg = f"Failed to load image from '{source}'. Check that the path or URL is correct and that it is a raster image (PNG, JPEG, GIF, WebP, BMP)."
return {
"content": error_msg,
"display": {"type": "read_image_error", "url": source},
"image_counter": image_counter,
}
return {
"content": f"Unknown tool: {tool_name}",
"display": {"type": "error"},
"image_counter": image_counter,
}
def stream_image_execution(
client,
model: str,
messages: List[Dict],
hf_token: str,
image_gen_model: Optional[str] = None,
image_edit_model: Optional[str] = None,
extra_params: Optional[Dict] = None,
abort_event=None,
files_root: str = None,
multimodal: bool = False,
tab_id: str = "0",
image_store: Optional[Dict[str, dict]] = None,
image_counter: int = 0,
):
"""
Run the image agent tool-calling loop.
Yields dicts with SSE event types:
- thinking: { content }
- content: { content }
- tool_start: { tool, args }
- tool_result: { tool, result, image? }
- result_preview: { content }
- result: { content, figures? }
- generating: {}
- retry: { attempt, max_attempts, delay, message }
- error: { content }
- done: {}
"""
from .agents import call_llm
turns = 0
done = False
image_prefix = f"figure_T{tab_id}_"
# Use provided persistent store, or create a local one as fallback
if image_store is None:
image_store = {}
result_sent = False
debug_call_number = 0
while not done and turns < MAX_TURNS:
# Check abort before each turn
if abort_event and abort_event.is_set():
yield {"type": "aborted"}
return
turns += 1
# LLM call with retries and debug events
response = None
for event in call_llm(client, model, messages, tools=TOOLS, extra_params=extra_params, abort_event=abort_event, call_number=debug_call_number):
if "_response" in event:
response = event["_response"]
debug_call_number = event["_call_number"]
else:
yield event
if event.get("type") in ("error", "aborted"):
return
if response is None:
return
# --- Parse response ---
assistant_message = response.choices[0].message
content = assistant_message.content or ""
tool_calls = assistant_message.tool_calls or []
# Check for <result> tags
result_match = re.search(r'<result>(.*?)</result>', content, re.DOTALL | re.IGNORECASE)
result_content = None
thinking_content = content
if result_match:
result_content = result_match.group(1).strip()
thinking_content = re.sub(r'<result>.*?</result>', '', content, flags=re.DOTALL | re.IGNORECASE).strip()
# Send thinking/content
if thinking_content.strip():
if tool_calls:
yield {"type": "thinking", "content": thinking_content}
else:
yield {"type": "content", "content": thinking_content}
# Send result preview
if result_content:
figures = dict(image_store)
yield {"type": "result_preview", "content": result_content, "figures": figures}
# --- Handle tool calls ---
if tool_calls:
for tool_call in tool_calls:
# Check abort between tool calls
if abort_event and abort_event.is_set():
yield {"type": "aborted"}
return
func_name = tool_call.function.name
# Parse arguments
try:
args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError as e:
output = f"Error parsing arguments: {e}"
messages.append({
"role": "assistant",
"content": content,
"tool_calls": [{"id": tool_call.id, "type": "function", "function": {"name": func_name, "arguments": tool_call.function.arguments}}]
})
messages.append({"role": "tool", "tool_call_id": tool_call.id, "content": output})
yield {"type": "error", "content": output}
continue
# Signal tool start
yield {
"type": "tool_start",
"tool": func_name,
"args": args,
"tool_call_id": tool_call.id,
"arguments": tool_call.function.arguments,
"thinking": content,
}
# Execute tool
result = execute_tool(func_name, args, hf_token, image_store, image_counter, default_gen_model=image_gen_model, default_edit_model=image_edit_model, files_root=files_root, image_prefix=image_prefix)
image_counter = result.get("image_counter", image_counter)
# Build tool response content for LLM
if result.get("image") and multimodal:
vlm_image = resize_image_for_vlm(result["image"])
tool_response_content = [
{"type": "text", "text": result["content"]},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{vlm_image}"}}
]
else:
tool_response_content = result["content"]
# Add to message history
messages.append({
"role": "assistant",
"content": content,
"tool_calls": [{"id": tool_call.id, "type": "function", "function": {"name": func_name, "arguments": tool_call.function.arguments}}]
})
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": tool_response_content
})
# Signal tool result to frontend
tool_result_event = {
"type": "tool_result",
"tool": func_name,
"tool_call_id": tool_call.id,
"result": result.get("display", {}),
"response": result.get("content", ""),
}
if result.get("image"):
tool_result_event["image"] = result["image"]
if result.get("image_name"):
tool_result_event["image_name"] = result["image_name"]
yield tool_result_event
else:
# No tool calls β we're done
messages.append({"role": "assistant", "content": content})
done = True
# Send result if found
if result_content:
figures = dict(image_store)
yield {"type": "result", "content": result_content, "figures": figures}
result_sent = True
# Signal between-turn processing
if not done:
yield {"type": "generating"}
# If agent finished without a <result>, nudge it for one
if not result_sent:
from .agents import nudge_for_result
nudge_produced_result = False
figures = dict(image_store)
for event in nudge_for_result(client, model, messages, extra_params=extra_params, extra_result_data={"figures": figures}, call_number=debug_call_number):
yield event
if event.get("type") == "result":
nudge_produced_result = True
# Final fallback: synthesize a result with all figures
if not nudge_produced_result:
fallback_parts = [f"<{name}>" for name in image_store]
figures = dict(image_store)
yield {"type": "result", "content": "\n\n".join(fallback_parts), "figures": figures}
yield {"type": "done"}
|