ysharma HF Staff commited on
Commit
ed8fa70
Β·
verified Β·
1 Parent(s): e6dde25

Update chat_handler.py

Browse files
Files changed (1) hide show
  1. chat_handler.py +39 -5
chat_handler.py CHANGED
@@ -21,7 +21,7 @@ class ChatHandler:
21
  def __init__(self, mcp_client: UniversalMCPClient):
22
  self.mcp_client = mcp_client
23
 
24
- def process_multimodal_message(self, message: Dict[str, Any], history: List[ChatMessage]) -> Tuple[List[ChatMessage], Dict[str, Any]]:
25
  """Enhanced MCP chat function with multimodal input support and ChatMessage formatting"""
26
 
27
  if not self.mcp_client.anthropic_client:
@@ -47,6 +47,31 @@ class ChatHandler:
47
  logger.info(f"πŸ’¬ Processing multimodal message:")
48
  logger.info(f" πŸ“ Text: {user_text}")
49
  logger.info(f" πŸ“ Files: {len(user_files)} files uploaded")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
  # Add uploaded files to chat history first
52
  for file_path in user_files:
@@ -87,15 +112,24 @@ class ChatHandler:
87
  history.append(ChatMessage(role="assistant", content=error_msg))
88
  return history, gr.MultimodalTextbox(value=None, interactive=False)
89
 
90
- def _prepare_claude_messages(self, history: List[ChatMessage]) -> List[Dict[str, Any]]:
91
- """Convert ChatMessage history to Claude API format"""
92
  messages = []
93
 
94
  # Convert history to Claude API format (text only for context)
95
  recent_history = history[-16:] if len(history) > 16 else history
96
  for msg in recent_history:
97
- if msg.role in ["user", "assistant"]:
 
 
98
  content = msg.content
 
 
 
 
 
 
 
99
 
100
  # Convert any non-string content to string description for context
101
  if isinstance(content, dict):
@@ -120,7 +154,7 @@ class ChatHandler:
120
  content = str(content)
121
 
122
  messages.append({
123
- "role": msg.role,
124
  "content": content
125
  })
126
 
 
21
  def __init__(self, mcp_client: UniversalMCPClient):
22
  self.mcp_client = mcp_client
23
 
24
+ def process_multimodal_message(self, message: Dict[str, Any], history: List) -> Tuple[List[ChatMessage], Dict[str, Any]]:
25
  """Enhanced MCP chat function with multimodal input support and ChatMessage formatting"""
26
 
27
  if not self.mcp_client.anthropic_client:
 
47
  logger.info(f"πŸ’¬ Processing multimodal message:")
48
  logger.info(f" πŸ“ Text: {user_text}")
49
  logger.info(f" πŸ“ Files: {len(user_files)} files uploaded")
50
+ logger.info(f" πŸ“‹ History type: {type(history)}, length: {len(history)}")
51
+
52
+ # Convert history to ChatMessage objects if needed
53
+ converted_history = []
54
+ for i, msg in enumerate(history):
55
+ try:
56
+ if isinstance(msg, dict):
57
+ # Convert dict to ChatMessage for internal processing
58
+ logger.info(f" πŸ“ Converting dict message {i}: {msg.get('role', 'unknown')}")
59
+ converted_history.append(ChatMessage(
60
+ role=msg.get('role', 'assistant'),
61
+ content=msg.get('content', ''),
62
+ metadata=msg.get('metadata', None)
63
+ ))
64
+ else:
65
+ # Already a ChatMessage
66
+ logger.info(f" βœ… ChatMessage {i}: {getattr(msg, 'role', 'unknown')}")
67
+ converted_history.append(msg)
68
+ except Exception as conv_error:
69
+ logger.error(f"Error converting message {i}: {conv_error}")
70
+ logger.error(f"Message content: {msg}")
71
+ # Skip problematic messages
72
+ continue
73
+
74
+ history = converted_history
75
 
76
  # Add uploaded files to chat history first
77
  for file_path in user_files:
 
112
  history.append(ChatMessage(role="assistant", content=error_msg))
113
  return history, gr.MultimodalTextbox(value=None, interactive=False)
114
 
115
+ def _prepare_claude_messages(self, history: List) -> List[Dict[str, Any]]:
116
+ """Convert history (ChatMessage or dict) to Claude API format"""
117
  messages = []
118
 
119
  # Convert history to Claude API format (text only for context)
120
  recent_history = history[-16:] if len(history) > 16 else history
121
  for msg in recent_history:
122
+ # Handle both ChatMessage objects and dictionary format for backward compatibility
123
+ if hasattr(msg, 'role'): # ChatMessage object
124
+ role = msg.role
125
  content = msg.content
126
+ elif isinstance(msg, dict) and 'role' in msg: # Dictionary format
127
+ role = msg.get('role')
128
+ content = msg.get('content')
129
+ else:
130
+ continue # Skip invalid messages
131
+
132
+ if role in ["user", "assistant"]:
133
 
134
  # Convert any non-string content to string description for context
135
  if isinstance(content, dict):
 
154
  content = str(content)
155
 
156
  messages.append({
157
+ "role": role,
158
  "content": content
159
  })
160