""" Chat handling logic for Universal MCP Client - Fixed Version with File Upload Support """ import asyncio import re import logging import traceback from datetime import datetime from typing import Dict, Any, List, Tuple, Optional import gradio as gr from gradio import ChatMessage from gradio_client import Client import time import json import httpx from config import AppConfig from mcp_client import UniversalMCPClient logger = logging.getLogger(__name__) class ChatHandler: """Handles chat interactions with HF Inference Providers and MCP servers using ChatMessage dataclass""" def __init__(self, mcp_client: UniversalMCPClient): self.mcp_client = mcp_client # Initialize the file uploader client for converting local files to public URLs try: self.uploader_client = Client("abidlabs/file-uploader") logger.info("āœ… File uploader client initialized") except Exception as e: logger.error(f"Failed to initialize file uploader: {e}") self.uploader_client = None def _upload_file_to_gradio_server(self, file_path: str) -> str: """Upload a file to the Gradio server and get a public URL""" if not self.uploader_client: logger.error("File uploader client not initialized") return file_path try: # Open file in binary mode as your peer discovered with open(file_path, "rb") as f_: files = [("files", (file_path.split("/")[-1], f_))] r = httpx.post( self.uploader_client.upload_url, files=files, ) r.raise_for_status() result = r.json() uploaded_path = result[0] # Construct the full public URL public_url = f"{self.uploader_client.src}/gradio_api/file={uploaded_path}" logger.info(f"āœ… Uploaded {file_path} -> {public_url}") return public_url except Exception as e: logger.error(f"Failed to upload file {file_path}: {e}") return file_path # Return original path as fallback def process_multimodal_message(self, message: Dict[str, Any], history: List) -> Tuple[List[ChatMessage], Dict[str, Any]]: """Enhanced MCP chat function with multimodal input support and ChatMessage formatting""" if not self.mcp_client.hf_client: error_msg = "āŒ HuggingFace token not configured. Please set HF_TOKEN environment variable or login." history.append(ChatMessage(role="user", content=error_msg)) history.append(ChatMessage(role="assistant", content=error_msg)) return history, gr.MultimodalTextbox(value=None, interactive=False) if not self.mcp_client.current_provider or not self.mcp_client.current_model: error_msg = "āŒ Please select an inference provider and model first." history.append(ChatMessage(role="user", content=error_msg)) history.append(ChatMessage(role="assistant", content=error_msg)) return history, gr.MultimodalTextbox(value=None, interactive=False) # Initialize variables for error handling user_text = "" user_files = [] uploaded_file_urls = [] # Store uploaded file URLs self.file_url_mapping = {} # Map local paths to uploaded URLs try: # Handle multimodal input - message is a dict with 'text' and 'files' user_text = message.get("text", "") if message else "" user_files = message.get("files", []) if message else [] # Handle case where message might be a string (backward compatibility) if isinstance(message, str): user_text = message user_files = [] logger.info(f"šŸ’¬ Processing multimodal message:") logger.info(f" šŸ“ Text: {user_text}") logger.info(f" šŸ“ Files: {len(user_files)} files uploaded") logger.info(f" šŸ“‹ History type: {type(history)}, length: {len(history)}") # Convert history to ChatMessage objects if needed converted_history = [] for i, msg in enumerate(history): try: if isinstance(msg, dict): # Convert dict to ChatMessage for internal processing logger.info(f" šŸ“ Converting dict message {i}: {msg.get('role', 'unknown')}") converted_history.append(ChatMessage( role=msg.get('role', 'assistant'), content=msg.get('content', ''), metadata=msg.get('metadata', None) )) else: # Already a ChatMessage logger.info(f" āœ… ChatMessage {i}: {getattr(msg, 'role', 'unknown')}") converted_history.append(msg) except Exception as conv_error: logger.error(f"Error converting message {i}: {conv_error}") logger.error(f"Message content: {msg}") # Skip problematic messages continue history = converted_history # Upload files and get public URLs for file_path in user_files: logger.info(f" šŸ“„ Local File: {file_path}") try: # Upload file to get public URL uploaded_url = self._upload_file_to_gradio_server(file_path) # Store the mapping self.file_url_mapping[file_path] = uploaded_url uploaded_file_urls.append(uploaded_url) logger.info(f" āœ… Uploaded File URL: {uploaded_url}") # Add to history with public URL history.append(ChatMessage(role="user", content={"path": uploaded_url})) except Exception as upload_error: logger.error(f"Failed to upload file {file_path}: {upload_error}") # Fallback to local path with warning history.append(ChatMessage(role="user", content={"path": file_path})) logger.warning(f"āš ļø Using local path for {file_path} - MCP servers may not be able to access it") # Add text message if provided if user_text and user_text.strip(): history.append(ChatMessage(role="user", content=user_text)) # If no text and no files, return early if not user_text.strip() and not user_files: return history, gr.MultimodalTextbox(value=None, interactive=False) # Create messages for HF Inference API messages = self._prepare_hf_messages(history, uploaded_file_urls) # Process the chat and get structured responses response_messages = self._call_hf_api(messages, uploaded_file_urls) # Add all response messages to history history.extend(response_messages) return history, gr.MultimodalTextbox(value=None, interactive=False) except Exception as e: error_msg = f"āŒ Error: {str(e)}" logger.error(f"Chat error: {e}") logger.error(traceback.format_exc()) # Add user input to history if it exists if user_text and user_text.strip(): history.append(ChatMessage(role="user", content=user_text)) if user_files: for file_path in user_files: history.append(ChatMessage(role="user", content={"path": file_path})) history.append(ChatMessage(role="assistant", content=error_msg)) return history, gr.MultimodalTextbox(value=None, interactive=False) def _prepare_hf_messages(self, history: List, uploaded_file_urls: List[str] = None) -> List[Dict[str, Any]]: """Convert history (ChatMessage or dict) to HF OpenAI-compatible format with multimodal support""" messages: List[Dict[str, Any]] = [] # Get optimal context settings for current model/provider if self.mcp_client.current_model and self.mcp_client.current_provider: context_settings = AppConfig.get_optimal_context_settings( self.mcp_client.current_model, self.mcp_client.current_provider, len(self.mcp_client.get_enabled_servers()) ) max_history = context_settings['recommended_history_limit'] else: max_history = 20 # Fallback # Convert history to HF API format (text only for context) recent_history = history[-max_history:] if len(history) > max_history else history last_role = None is_gpt_oss = AppConfig.is_gpt_oss_model(self.mcp_client.current_model) if self.mcp_client.current_model else False for msg in recent_history: # Handle both ChatMessage objects and dictionary format for backward compatibility if hasattr(msg, 'role'): # ChatMessage object role = msg.role content = msg.content elif isinstance(msg, dict) and 'role' in msg: # Dictionary format role = msg.get('role') content = msg.get('content') else: continue # Skip invalid messages if role == "user": if is_gpt_oss: # Text-only content for GPT-OSS (no multimodal parts) if isinstance(content, dict) and "path" in content: file_path = content.get("path", "") # Omit media content; optionally note the upload as text text_piece = "" # Choose to ignore media fully to avoid confusing the model elif isinstance(content, (list, tuple)): text_piece = f"[List: {str(content)[:50]}...]" elif content is None: text_piece = "[Empty]" else: text_piece = str(content) if messages and last_role == "user" and isinstance(messages[-1].get("content"), str): # Concatenate text if text_piece: messages[-1]["content"] = (messages[-1]["content"] + "\n" + text_piece) if messages[-1]["content"] else text_piece else: messages.append({"role": "user", "content": text_piece}) last_role = "user" else: # Build multimodal user messages with parts (for non-GPT-OSS) part = None if isinstance(content, dict) and "path" in content: file_path = content.get("path", "") if isinstance(file_path, str) and file_path.startswith("http") and AppConfig.is_image_file(file_path): part = {"type": "image_url", "image_url": {"url": file_path}} else: part = {"type": "text", "text": f"[File: {file_path}]"} elif isinstance(content, (list, tuple)): part = {"type": "text", "text": f"[List: {str(content)[:50]}...]"} elif content is None: part = {"type": "text", "text": "[Empty]"} else: part = {"type": "text", "text": str(content)} if messages and last_role == "user" and isinstance(messages[-1].get("content"), list): messages[-1]["content"].append(part) elif messages and last_role == "user" and isinstance(messages[-1].get("content"), str): # Convert existing string content to parts and append existing_text = messages[-1]["content"] messages[-1]["content"] = [{"type": "text", "text": existing_text}, part] else: messages.append({"role": "user", "content": [part]}) last_role = "user" elif role == "assistant": # Assistant content remains text for chat.completions API if isinstance(content, dict): text = f"[Object: {str(content)[:50]}...]" elif isinstance(content, (list, tuple)): text = f"[List: {str(content)[:50]}...]" elif content is None: text = "[Empty]" else: text = str(content) messages.append({"role": "assistant", "content": text}) last_role = "assistant" return messages def _call_hf_api(self, messages: List[Dict[str, Any]], uploaded_file_urls: List[str] = None) -> List[ChatMessage]: """Call HuggingFace Inference API and return structured ChatMessage responses""" # Check if we have enabled MCP servers to use enabled_servers = self.mcp_client.get_enabled_servers() if not enabled_servers: return self._call_hf_without_mcp(messages) else: return self._call_hf_with_mcp(messages, uploaded_file_urls) def _call_hf_without_mcp(self, messages: List[Dict[str, Any]]) -> List[ChatMessage]: """Call HF Inference API without MCP servers. Streams tokens for faster feedback.""" logger.info("šŸ’¬ No MCP servers available, using streaming HF Inference chat when possible") system_prompt = self._get_native_system_prompt() # Add system prompt to messages if messages and messages[0].get("role") == "system": messages[0]["content"] = system_prompt + "\n\n" + messages[0]["content"] else: messages.insert(0, {"role": "system", "content": system_prompt}) # Get optimal token settings if self.mcp_client.current_model and self.mcp_client.current_provider: context_settings = AppConfig.get_optimal_context_settings( self.mcp_client.current_model, self.mcp_client.current_provider, 0 # No MCP servers ) max_tokens = context_settings['max_response_tokens'] else: max_tokens = 8192 # Try streaming first; fall back to non-streaming on error try: stream = self.mcp_client.generate_chat_completion_stream(messages, **{"max_tokens": max_tokens}) accumulated = "" for chunk in stream: try: delta = chunk.choices[0].delta.content or "" except Exception: # Some SDK variants stream as message deltas differently delta = getattr(getattr(chunk.choices[0], "delta", None), "content", "") or "" if delta: accumulated += delta if not accumulated: accumulated = "I understand your request and I'm here to help." return [ChatMessage(role="assistant", content=accumulated)] except Exception as e: logger.warning(f"Streaming failed, retrying without stream: {e}") try: response = self.mcp_client.generate_chat_completion(messages, **{"max_tokens": max_tokens}) response_text = response.choices[0].message.content if not response_text: response_text = "I understand your request and I'm here to help." return [ChatMessage(role="assistant", content=response_text)] except Exception as e2: logger.error(f"HF Inference API call failed: {e2}") return [ChatMessage(role="assistant", content=f"āŒ API call failed: {str(e2)}")] def _call_hf_with_mcp(self, messages: List[Dict[str, Any]], uploaded_file_urls: List[str] = None) -> List[ChatMessage]: """Call HF Inference API with MCP servers and return structured responses""" # Enhanced system prompt with multimodal and MCP instructions system_prompt = self._get_mcp_system_prompt(uploaded_file_urls) # Add system prompt to messages if messages and messages[0].get("role") == "system": messages[0]["content"] = system_prompt + "\n\n" + messages[0]["content"] else: messages.insert(0, {"role": "system", "content": system_prompt}) # Get optimal token settings enabled_servers = self.mcp_client.get_enabled_servers() if self.mcp_client.current_model and self.mcp_client.current_provider: context_settings = AppConfig.get_optimal_context_settings( self.mcp_client.current_model, self.mcp_client.current_provider, len(enabled_servers) ) max_tokens = context_settings['max_response_tokens'] else: max_tokens = 8192 # Debug logging logger.info(f"šŸ“¤ Sending {len(messages)} messages to HF Inference API") logger.info(f"šŸ”§ Using {len(self.mcp_client.servers)} MCP servers") logger.info(f"šŸ¤– Model: {self.mcp_client.current_model} via {self.mcp_client.current_provider}") logger.info(f"šŸ“ Max tokens: {max_tokens}") start_time = time.time() try: # Pass file mapping to MCP client if hasattr(self, 'file_url_mapping'): self.mcp_client.chat_handler_file_mapping = self.file_url_mapping # Call HF Inference with MCP tool support - using optimal max_tokens response = self.mcp_client.generate_chat_completion_with_mcp_tools(messages, **{"max_tokens": max_tokens}) return self._process_hf_response(response, start_time) except Exception as e: logger.error(f"HF Inference API call with MCP failed: {e}") return [ChatMessage(role="assistant", content=f"āŒ API call failed: {str(e)}")] def _process_hf_response(self, response, start_time: float) -> List[ChatMessage]: """Process HF Inference response with simplified media handling and nested errors""" chat_messages = [] try: response_text = response.choices[0].message.content if not response_text: response_text = "I understand your request and I'm here to help." # Check if this response includes tool execution info if hasattr(response, '_tool_execution'): tool_info = response._tool_execution logger.info(f"šŸ”§ Processing response with tool execution: {tool_info}") duration = round(time.time() - start_time, 2) tool_id = f"tool_{tool_info['tool']}_{int(time.time())}" if tool_info['success']: tool_result = str(tool_info['result']) # Extract media URL if present media_url = self._extract_media_url(tool_result, tool_info.get('server', '')) # Create tool usage metadata message chat_messages.append(ChatMessage( role="assistant", content="", metadata={ "title": f"šŸ”§ Used {tool_info['tool']}", "status": "done", "duration": duration, "id": tool_id } )) # Add nested success message with the raw result if media_url: result_preview = f"āœ… Successfully generated media\nURL: {media_url[:100]}..." else: result_preview = f"āœ… Tool executed successfully\nResult: {tool_result[:200]}..." chat_messages.append(ChatMessage( role="assistant", content=result_preview, metadata={ "title": "šŸ“Š Server Response", "parent_id": tool_id, "status": "done" } )) # Add LLM's descriptive text if present (before media) if response_text and not response_text.startswith('{"use_tool"'): # Clean the response text by removing URLs and tool JSON clean_response = response_text if media_url and media_url in clean_response: clean_response = clean_response.replace(media_url, "").strip() # Remove any remaining JSON tool call patterns clean_response = re.sub(r'\{"use_tool"[^}]+\}', '', clean_response).strip() # Remove all markdown link/image syntax completely clean_response = re.sub(r'!\[([^\]]*)\]\([^)]*\)', '', clean_response) # Remove image markdown clean_response = re.sub(r'\[([^\]]*)\]\([^)]*\)', '', clean_response) # Remove link markdown clean_response = re.sub(r'!\[([^\]]*)\]', '', clean_response) # Remove broken image refs clean_response = re.sub(r'\[([^\]]*)\]', '', clean_response) # Remove broken link refs clean_response = re.sub(r'\(\s*\)', '', clean_response) # Remove empty parentheses clean_response = clean_response.strip() # Final strip # Only add if there's meaningful text left after cleaning if clean_response and len(clean_response) > 10: chat_messages.append(ChatMessage( role="assistant", content=clean_response )) # Handle media content if present if media_url: # Add media as a separate message - Gradio will auto-detect type chat_messages.append(ChatMessage( role="assistant", content={"path": media_url} )) else: # No media URL found, check if we need to show non-media result if not response_text or response_text.startswith('{"use_tool"'): # Only show result if there wasn't descriptive text from LLM if len(tool_result) > 500: result_preview = f"Operation completed successfully. Result preview: {tool_result[:500]}..." else: result_preview = f"Operation completed successfully. Result: {tool_result}" chat_messages.append(ChatMessage( role="assistant", content=result_preview )) else: # Tool execution failed error_details = tool_info['result'] # Create main tool message with pending status (error reflected in content) chat_messages.append(ChatMessage( role="assistant", content="", metadata={ "title": f"āŒ Used {tool_info['tool']}", "status": "pending", "duration": duration, "id": tool_id } )) # Add nested error response from server chat_messages.append(ChatMessage( role="assistant", content=f"āŒ Tool execution failed\n```\n{error_details}\n```", metadata={ "title": "šŸ“Š Server Response", "parent_id": tool_id, "status": "done" } )) # Add suggestions as another nested message chat_messages.append(ChatMessage( role="assistant", content="**Suggestions:**\n• Try modifying your request slightly\n• Wait a moment and try again\n• Use a different MCP server if available", metadata={ "title": "šŸ’” Possible Solutions", "parent_id": tool_id, "status": "done" } )) else: # No tool usage, just return the response chat_messages.append(ChatMessage( role="assistant", content=response_text )) except Exception as e: logger.error(f"Error processing HF response: {e}") logger.error(traceback.format_exc()) chat_messages.append(ChatMessage( role="assistant", content="I understand your request and I'm here to help." )) return chat_messages def process_multimodal_message_stream(self, message: Dict[str, Any], history: List): """Generator that streams assistant output to the UI as it arrives. - Streams for plain LLM chats - Streams initial planning/tool JSON for MCP flows, executes tool, then streams final answer - Attempts to surface reasoning/thinking traces when available """ try: # Pre-checks if not self.mcp_client.hf_client: error_msg = "āŒ HuggingFace token not configured. Please set HF_TOKEN environment variable or login." history.append(ChatMessage(role="assistant", content=error_msg)) yield history, gr.MultimodalTextbox(value=None, interactive=False) return if not self.mcp_client.current_provider or not self.mcp_client.current_model: error_msg = "āŒ Please select an inference provider and model first." history.append(ChatMessage(role="assistant", content=error_msg)) yield history, gr.MultimodalTextbox(value=None, interactive=False) return # Parse user input user_text = message.get("text", "") if message else "" user_files = message.get("files", []) if message else [] # Upload files and update history similarly to non-stream path self.file_url_mapping = {} uploaded_file_urls: List[str] = [] if isinstance(message, str): user_text = message user_files = [] if user_files: for file_path in user_files: try: uploaded_url = self._upload_file_to_gradio_server(file_path) self.file_url_mapping[file_path] = uploaded_url uploaded_file_urls.append(uploaded_url) history.append(ChatMessage(role="user", content={"path": uploaded_url})) except Exception: history.append(ChatMessage(role="user", content={"path": file_path})) if user_text and user_text.strip(): history.append(ChatMessage(role="user", content=user_text)) if not user_text.strip() and not user_files: yield history, gr.MultimodalTextbox(value=None, interactive=False) return # Prepare messages for HF messages = self._prepare_hf_messages(history, uploaded_file_urls) # Choose streaming path based on MCP servers if self.mcp_client.get_enabled_servers(): # Stream with MCP planning/tool execution yield from self._stream_with_mcp(messages, uploaded_file_urls, history) else: # Plain LLM streaming with optional thinking trace yield from self._stream_without_mcp(messages, history) except Exception as e: history.append(ChatMessage(role="assistant", content=f"āŒ Error: {str(e)}")) yield history, gr.MultimodalTextbox(value=None, interactive=True) def _stream_without_mcp(self, messages: List[Dict[str, Any]], history: List): """Stream tokens for plain LLM chats; attempts to surface reasoning traces if available.""" # Add system prompt system_prompt = self._get_native_system_prompt() if messages and messages[0].get("role") == "system": messages[0]["content"] = system_prompt + "\n\n" + messages[0]["content"] else: messages.insert(0, {"role": "system", "content": system_prompt}) # Compute max tokens if self.mcp_client.current_model and self.mcp_client.current_provider: ctx = AppConfig.get_optimal_context_settings( self.mcp_client.current_model, self.mcp_client.current_provider, 0 ) max_tokens = ctx["max_response_tokens"] else: max_tokens = 8192 # Insert placeholders: optional thinking + main assistant thinking_index = None # Prepare a thinking message only when we actually receive thinking tokens history.append(ChatMessage(role="assistant", content="")) main_index = len(history) - 1 yield history, gr.MultimodalTextbox(value=None, interactive=False) accumulated = "" thinking_accum = "" try: stream = self.mcp_client.generate_chat_completion_stream(messages, **{"max_tokens": max_tokens}) for chunk in stream: delta = getattr(chunk.choices[0], "delta", None) # Reasoning/thinking traces (best-effort extraction) reason_delta = None if delta is not None: # Some providers expose .reasoning or .thinking reason_delta = ( getattr(delta, "reasoning", None) or getattr(delta, "thinking", None) ) if reason_delta: thinking_accum += str(reason_delta) if thinking_index is None: history.insert(main_index, ChatMessage( role="assistant", content=f"{thinking_accum}", metadata={"title": "🧠 Reasoning", "status": "pending"} )) thinking_index = main_index main_index += 1 else: history[thinking_index] = ChatMessage( role="assistant", content=f"{thinking_accum}", metadata={"title": "🧠 Reasoning", "status": "pending"} ) # Main content delta_text = "" try: delta_text = delta.content or "" except Exception: delta_text = getattr(delta, "content", "") or "" if not delta_text: yield history, gr.MultimodalTextbox(value=None, interactive=False) continue accumulated += delta_text history[main_index] = ChatMessage(role="assistant", content=accumulated) yield history, gr.MultimodalTextbox(value=None, interactive=False) except Exception as e: # Fallback to non-stream try: resp = self.mcp_client.generate_chat_completion(messages, **{"max_tokens": max_tokens}) final_text = resp.choices[0].message.content or "I understand your request and I'm here to help." history[main_index] = ChatMessage(role="assistant", content=final_text) yield history, gr.MultimodalTextbox(value=None, interactive=True) return except Exception as e2: history[main_index] = ChatMessage(role="assistant", content=f"āŒ API call failed: {str(e2)}") yield history, gr.MultimodalTextbox(value=None, interactive=True) return # Final yield yield history, gr.MultimodalTextbox(value=None, interactive=True) def _stream_with_mcp(self, messages: List[Dict[str, Any]], uploaded_file_urls: List[str], history: List): """Stream initial planning/tool JSON, execute MCP tool, then stream final response.""" # Enhanced system prompt with MCP guidance system_prompt = self._get_mcp_system_prompt(uploaded_file_urls) if messages and messages[0].get("role") == "system": messages[0]["content"] = system_prompt + "\n\n" + messages[0]["content"] else: messages.insert(0, {"role": "system", "content": system_prompt}) # Compute max tokens taking enabled servers into account enabled_servers = self.mcp_client.get_enabled_servers() if self.mcp_client.current_model and self.mcp_client.current_provider: ctx = AppConfig.get_optimal_context_settings( self.mcp_client.current_model, self.mcp_client.current_provider, len(enabled_servers) ) max_tokens = ctx["max_response_tokens"] else: max_tokens = 8192 # Placeholders: planning/tool JSON + main assistant planning_index = None thinking_index = None history.append(ChatMessage(role="assistant", content="")) main_index = len(history) - 1 yield history, gr.MultimodalTextbox(value=None, interactive=False) text_accum = "" tool_json_accum = "" in_tool_json = False tool_json_detected = False try: stream = self.mcp_client.generate_chat_completion_stream(messages, **{"max_tokens": max_tokens}) for chunk in stream: delta = getattr(chunk.choices[0], "delta", None) # Optional reasoning reason_delta = None if delta is not None: reason_delta = ( getattr(delta, "reasoning", None) or getattr(delta, "thinking", None) ) if reason_delta: if thinking_index is None: history.insert(main_index, ChatMessage( role="assistant", content=str(reason_delta), metadata={"title": "🧠 Reasoning", "status": "pending"} )) thinking_index = main_index main_index += 1 else: history[thinking_index] = ChatMessage( role="assistant", content=(history[thinking_index].content + str(reason_delta)), metadata={"title": "🧠 Reasoning", "status": "pending"} ) # Main content streaming and tool JSON detection (content-based JSON protocol) piece = "" try: piece = delta.content or "" except Exception: piece = getattr(delta, "content", "") or "" if not piece: yield history, gr.MultimodalTextbox(value=None, interactive=False) continue # Detect start of tool JSON if not tool_json_detected and '{"use_tool":' in piece: in_tool_json = True tool_json_detected = True if in_tool_json: tool_json_accum += piece # Initialize planning message if planning_index is None: history.insert(main_index, ChatMessage( role="assistant", content=tool_json_accum, metadata={"title": "šŸ”§ Tool call (planning)", "status": "pending"} )) planning_index = main_index main_index += 1 else: history[planning_index] = ChatMessage( role="assistant", content=tool_json_accum, metadata={"title": "šŸ”§ Tool call (planning)", "status": "pending"} ) # Try to reconstruct JSON when braces close reconstructed = self.mcp_client._reconstruct_json_from_start(tool_json_accum) if reconstructed: # We have a complete JSON in_tool_json = False # Clean planning content to the reconstructed JSON (for clarity) history[planning_index] = ChatMessage( role="assistant", content=reconstructed, metadata={"title": "šŸ”§ Tool call", "status": "done"} ) yield history, gr.MultimodalTextbox(value=None, interactive=False) # Execute tool now import json as _json try: tool_req = _json.loads(reconstructed) except Exception: tool_req = None if tool_req and tool_req.get("use_tool"): server_name = tool_req.get("server") tool_name = tool_req.get("tool") arguments = tool_req.get("arguments", {}) # Status message exec_msg = ChatMessage( role="assistant", content=f"Executing {tool_name} on {server_name}…", metadata={"title": "šŸ”§ Tool execution", "status": "pending"} ) history.insert(main_index, exec_msg) exec_index = main_index main_index += 1 yield history, gr.MultimodalTextbox(value=None, interactive=False) # Replace any local paths with uploaded URLs if hasattr(self, 'file_url_mapping'): for k, v in list(arguments.items()): if isinstance(v, str) and v.startswith('/tmp/gradio/'): for lpath, url in self.file_url_mapping.items(): if lpath in v or v in lpath: arguments[k] = url break # Run tool (blocking) def _run_tool(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: return loop.run_until_complete( self.mcp_client.call_mcp_tool_async(server_name, tool_name, arguments) ) finally: loop.close() success, result = _run_tool() # Update exec message if success: content = str(result) history[exec_index] = ChatMessage( role="assistant", content=content if len(content) < 800 else content[:800] + "…", metadata={"title": "šŸ“Š Server Response", "status": "done"} ) else: history[exec_index] = ChatMessage( role="assistant", content=f"āŒ Tool failed: {result}", metadata={"title": "šŸ“Š Server Response", "status": "done"} ) yield history, gr.MultimodalTextbox(value=None, interactive=False) # Start final streamed response using tool result final_messages = messages.copy() # Remove tools instruction portion from system if present if final_messages and final_messages[0].get("role") == "system": sys_text = final_messages[0]["content"] cut = sys_text.split("You have access to the following MCP tools:")[0].strip() final_messages[0]["content"] = cut # Add prior assistant (planning) and user tool result follow-up final_messages.append({"role": "assistant", "content": text_accum}) final_messages.append({ "role": "user", "content": f"Tool '{tool_name}' from server '{server_name}' completed. Result: {result}. Please provide a helpful response." }) # Stream final answer into main message final_accum = "" try: final_stream = self.mcp_client.generate_chat_completion_stream(final_messages, **{"max_tokens": max_tokens}) for fchunk in final_stream: fdelta = getattr(fchunk.choices[0], "delta", None) ftext = getattr(fdelta, "content", "") if fdelta is not None else "" if not ftext: yield history, gr.MultimodalTextbox(value=None, interactive=False) continue final_accum += ftext history[main_index] = ChatMessage(role="assistant", content=(text_accum + final_accum)) yield history, gr.MultimodalTextbox(value=None, interactive=False) except Exception: # Fallback non-stream finalization try: fresp = self.mcp_client.generate_chat_completion(final_messages, **{"max_tokens": max_tokens}) ftxt = fresp.choices[0].message.content or "" history[main_index] = ChatMessage(role="assistant", content=(text_accum + ftxt)) yield history, gr.MultimodalTextbox(value=None, interactive=True) return except Exception as e3: history[main_index] = ChatMessage(role="assistant", content=(text_accum + f"\nāŒ Finalization failed: {e3}")) yield history, gr.MultimodalTextbox(value=None, interactive=True) return # Done yield history, gr.MultimodalTextbox(value=None, interactive=True) return else: # Normal assistant visible text outside of tool JSON text_accum += piece history[main_index] = ChatMessage(role="assistant", content=text_accum) yield history, gr.MultimodalTextbox(value=None, interactive=False) except Exception as e: # Fallback: Use non-streaming MCP path responses = self._call_hf_with_mcp(messages, uploaded_file_urls) history.extend(responses) yield history, gr.MultimodalTextbox(value=None, interactive=True) return # If we streamed without any tool usage, finalize yield history, gr.MultimodalTextbox(value=None, interactive=True) def _extract_media_url(self, result_text: str, server_name: str) -> Optional[str]: """Extract media URL from MCP response with improved pattern matching""" if not isinstance(result_text, str): return None logger.info(f"šŸ” Extracting media from result: {result_text[:500]}...") # Try JSON parsing first try: if result_text.strip().startswith('[') or result_text.strip().startswith('{'): data = json.loads(result_text.strip()) # Handle array format if isinstance(data, list) and len(data) > 0: item = data[0] if isinstance(item, dict): # Check for nested media structure for media_type in ['audio', 'video', 'image']: if media_type in item and isinstance(item[media_type], dict): if 'url' in item[media_type]: url = item[media_type]['url'].strip('\'"') logger.info(f"šŸŽÆ Found {media_type} URL in JSON: {url}") return url # Check for direct URL if 'url' in item: url = item['url'].strip('\'"') logger.info(f"šŸŽÆ Found direct URL in JSON: {url}") return url # Handle object format elif isinstance(data, dict): # Check for nested media structure for media_type in ['audio', 'video', 'image']: if media_type in data and isinstance(data[media_type], dict): if 'url' in data[media_type]: url = data[media_type]['url'].strip('\'"') logger.info(f"šŸŽÆ Found {media_type} URL in JSON: {url}") return url # Check for direct URL if 'url' in data: url = data['url'].strip('\'"') logger.info(f"šŸŽÆ Found direct URL in JSON: {url}") return url except json.JSONDecodeError: pass # Check for Gradio file URLs (common pattern) gradio_patterns = [ r'https://[^/]+\.hf\.space/gradio_api/file=/[^/]+/[^/]+/[^\s"\'<>,]+', r'https://[^/]+\.hf\.space/file=[^\s"\'<>,]+', r'/gradio_api/file=/[^\s"\'<>,]+' ] for pattern in gradio_patterns: match = re.search(pattern, result_text) if match: url = match.group(0).rstrip('\'",:;') logger.info(f"šŸŽÆ Found Gradio file URL: {url}") return url # Check for any HTTP URLs with media extensions url_pattern = r'https?://[^\s"\'<>]+\.(?:mp3|wav|ogg|m4a|flac|aac|opus|wma|mp4|webm|avi|mov|mkv|m4v|wmv|png|jpg|jpeg|gif|webp|bmp|svg)' match = re.search(url_pattern, result_text, re.IGNORECASE) if match: url = match.group(0) logger.info(f"šŸŽÆ Found media URL by extension: {url}") return url # Check for data URLs if result_text.startswith('data:'): logger.info("šŸŽÆ Found data URL") return result_text logger.info("āŒ No media URL found in result") return None def _get_native_system_prompt(self) -> str: """Get system prompt for HF Inference without MCP servers""" model_info = AppConfig.AVAILABLE_MODELS.get(self.mcp_client.current_model, {}) context_length = model_info.get("context_length", 128000) return f"""You are an AI assistant powered by {self.mcp_client.current_model} via {self.mcp_client.current_provider}. You have native capabilities for: - **Text Processing**: You can analyze, summarize, translate, and process text directly - **General Knowledge**: You can answer questions, explain concepts, and have conversations - **Code Analysis**: You can read, analyze, and explain code - **Reasoning**: You can perform step-by-step reasoning and problem-solving - **Context Window**: You have access to {context_length:,} tokens of context Current time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Please provide helpful, accurate, and engaging responses to user queries.""" def _get_mcp_system_prompt(self, uploaded_file_urls: List[str] = None) -> str: """Get enhanced system prompt for HF Inference with MCP servers""" model_info = AppConfig.AVAILABLE_MODELS.get(self.mcp_client.current_model, {}) context_length = model_info.get("context_length", 128000) uploaded_files_context = "" if uploaded_file_urls: uploaded_files_context = f"\n\nFILES UPLOADED BY USER (Public URLs accessible to MCP servers):\n" for i, file_url in enumerate(uploaded_file_urls, 1): file_name = file_url.split('/')[-1] if '/' in file_url else file_url if AppConfig.is_image_file(file_url): file_type = "Image" elif AppConfig.is_audio_file(file_url): file_type = "Audio" elif AppConfig.is_video_file(file_url): file_type = "Video" else: file_type = "File" uploaded_files_context += f"{i}. {file_type}: {file_name}\n URL: {file_url}\n" # Get available tools with correct names from enabled servers only enabled_servers = self.mcp_client.get_enabled_servers() tools_info = [] for server_name, config in enabled_servers.items(): tools_info.append(f"- **{server_name}**: {config.description}") return f"""You are an AI assistant powered by {self.mcp_client.current_model} via {self.mcp_client.current_provider}, with access to various MCP tools. YOUR NATIVE CAPABILITIES: - **Text Processing**: You can analyze, summarize, translate, and process text directly - **General Knowledge**: You can answer questions, explain concepts, and have conversations - **Code Analysis**: You can read, analyze, and explain code - **Reasoning**: You can perform step-by-step reasoning and problem-solving - **Context Window**: You have access to {context_length:,} tokens of context AVAILABLE MCP TOOLS: You have access to the following MCP servers: {chr(10).join(tools_info)} WHEN TO USE MCP TOOLS: - **Image Generation**: Creating new images from text prompts - **Image Editing**: Modifying, enhancing, or transforming existing images - **Audio Processing**: Transcribing audio, generating speech, audio enhancement - **Video Processing**: Creating or editing videos - **Text to Speech**: Converting text to audio - **Specialized Analysis**: Tasks requiring specific models or APIs TOOL USAGE FORMAT: When you need to use an MCP tool, respond with JSON in this exact format: {{"use_tool": true, "server": "exact_server_name", "tool": "exact_tool_name", "arguments": {{"param": "value"}}}} IMPORTANT: Always describe what you're going to do BEFORE the JSON tool call. For example: "I'll generate speech for your text using the TTS tool." {{"use_tool": true, "server": "text to speech", "tool": "Kokoro_TTS_mcp_test_generate_first", "arguments": {{"text": "hello"}}}} IMPORTANT TOOL NAME MAPPING: - For TTS server: use tool name "Kokoro_TTS_mcp_test_generate_first" - For image generation: use tool name "dalle_3_xl_lora_v2_generate" - For video generation: use tool name "ysharma_ltx_video_distilledtext_to_video" - For letter counting: use tool name "gradio_app_dummy1_letter_counter" EXACT SERVER NAMES TO USE: {', '.join([f'"{name}"' for name in enabled_servers.keys()])} FILE HANDLING FOR MCP TOOLS: When using MCP tools with uploaded files, always use the public URLs provided above. These URLs are accessible to remote MCP servers. {uploaded_files_context} MEDIA HANDLING: When tool results contain media URLs (images, audio, videos), the system will automatically embed them as playable media. IMPORTANT NOTES: - Always use the EXACT server names and tool names as specified above - Use proper JSON format for tool calls - Include all required parameters in arguments - For file inputs to MCP tools, use the public URLs provided, not local paths - ALWAYS provide a descriptive message before the JSON tool call - After tool execution, you can provide additional context or ask if the user needs anything else Current time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Current model: {self.mcp_client.current_model} via {self.mcp_client.current_provider}"""