File size: 54,875 Bytes
1cdb77b 6fe806a 1cdb77b 0044564 1cdb77b 0044564 1cdb77b 0044564 6dd2b83 1cdb77b 6dd2b83 1cdb77b 6dd2b83 1cdb77b 6dd2b83 1cdb77b 6dd2b83 6fe806a 1cdb77b 6dd2b83 1cdb77b 6dd2b83 1cdb77b 6dd2b83 0044564 6fe806a 1cdb77b 6fe806a 6dd2b83 6fe806a 0044564 6dd2b83 0044564 6dd2b83 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a 1cdb77b 6fe806a |
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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 |
"""
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}"""
|