import json
def format_user_message(msg):
"""Format a user message for display."""
# Extract the content based on role
content = msg.get("content", "")
# Handle None content
if content is None:
content = ""
elif isinstance(content, (int, float)):
content = str(content)
elif isinstance(content, list):
# Handle list-type content (may contain multiple parts)
content_text = ""
for item in content:
if item is None:
continue
if isinstance(item, dict) and "text" in item:
text_value = item.get("text", "")
if text_value is not None:
content_text += str(text_value) + "\n"
elif isinstance(item, str):
content_text += item + "\n"
elif item is not None:
content_text += str(item) + "\n"
content = content_text.strip()
# User message - align right using text-align instead of flex
return f"""
"""
def format_tool_call(tool_name, tool_input):
"""Format a tool call for display."""
# Ensure tool_name is a string
if tool_name is None:
tool_name = "Unknown Tool"
elif not isinstance(tool_name, str):
tool_name = str(tool_name)
# Ensure tool_input is serializable
if tool_input is None:
tool_input = {}
try:
# Try to serialize the tool input as JSON
tool_input_json = json.dumps(tool_input, indent=2)
except TypeError:
# If serialization fails, create a simplified representation
if isinstance(tool_input, dict):
simplified_input = {}
for k, v in tool_input.items():
if v is None or isinstance(v, (str, int, float, bool, list, dict)):
simplified_input[k] = v
else:
simplified_input[k] = str(v)
tool_input_json = json.dumps(simplified_input, indent=2)
else:
tool_input_json = str(tool_input)
return f"""
🔧{tool_name}
{tool_input_json}
"""
def extract_assistant_content(msg):
"""Extract text content and tool calls from an assistant message."""
assistant_text = ""
tool_calls_html = ""
if "content" in msg:
content = msg["content"]
# Handle string content
if content is None:
assistant_text = ""
elif isinstance(content, str):
assistant_text = content
elif isinstance(content, (int, float)):
assistant_text = str(content)
# Handle list content with text and tool calls
elif isinstance(content, list):
for item in content:
if item is None:
continue
if isinstance(item, dict):
if "text" in item:
text_value = item.get("text", "")
if text_value is not None:
assistant_text += str(text_value) + "\n"
elif "type" in item and item["type"] == "tool_use":
# Format tool call in a nicer way
tool_name = item.get("name", "Unknown Tool")
tool_input = item.get("input", {})
if tool_input is None:
tool_input = {}
tool_calls_html += format_tool_call(tool_name, tool_input)
elif isinstance(item, str):
assistant_text += item + "\n"
elif item is not None:
assistant_text += str(item) + "\n"
# Extract tool calls if present
elif "tool_calls" in msg:
assistant_text = "The assistant used the following tools:"
tool_calls = msg.get("tool_calls", [])
if tool_calls is None:
tool_calls = []
for tool_call in tool_calls:
if tool_call is None:
continue
tool_name = tool_call.get("name", "Unknown Tool")
tool_args = tool_call.get("args", {})
if tool_args is None:
tool_args = {}
tool_calls_html += format_tool_call(tool_name, tool_args)
return assistant_text.strip(), tool_calls_html
def format_assistant_message(msg):
"""Format an assistant message for display."""
assistant_text, tool_calls_html = extract_assistant_content(msg)
return f"""
🤖Assistant
{assistant_text}
{tool_calls_html}
"""
def format_system_message(msg):
"""Format a system or other message for display."""
content = msg.get("content", "")
# Handle None content
if content is None:
content = ""
elif isinstance(content, (int, float)):
content = str(content)
elif isinstance(content, list):
content_text = ""
for item in content:
if item is None:
continue
if isinstance(item, dict) and "text" in item:
text_value = item.get("text", "")
if text_value is not None:
content_text += str(text_value) + "\n"
elif isinstance(item, str):
content_text += item + "\n"
elif item is not None:
content_text += str(item) + "\n"
content = content_text.strip()
return f"""
"""
def parse_complex_response(response):
"""Parse complex JSON response and extract text and tool calls."""
try:
# Ensure response is a string
if response is None:
return "", ""
if isinstance(response, (int, float)):
return str(response), ""
# Convert to string if it's not already
if not isinstance(response, str):
response = str(response)
# Try to parse as JSON
if not response.strip().startswith("[") and not response.strip().startswith(
"{"
):
return response, ""
response_obj = json.loads(response)
# Handle array format like in the example
if isinstance(response_obj, list) and len(response_obj) > 0:
response_obj = response_obj[0] # Take first item in array
# Extract text content and tool calls
text_content = ""
tool_calls_html = ""
# Handle content field which can be string or list
if "content" in response_obj:
content = response_obj["content"]
if content is None:
text_content = ""
elif isinstance(content, str):
text_content = content
elif isinstance(content, (int, float)):
text_content = str(content)
elif isinstance(content, list):
# Extract only text content from items with type="text"
for item in content:
if item is None:
continue
if isinstance(item, dict):
if "type" in item and item["type"] == "text" and "text" in item:
text_value = item.get("text", "")
if text_value is not None:
text_content += str(text_value) + "\n"
# Get formatted tool calls if they exist
if "tool_calls" in response_obj:
tool_calls = response_obj.get("tool_calls", [])
if tool_calls is None:
tool_calls = []
if tool_calls:
try:
tool_calls_html = f"""
🔧Tool Calls
{json.dumps(tool_calls, indent=2)}
"""
except:
# Fallback if JSON serialization fails
tool_calls_html = (
"Tool calls present but could not be formatted.
"
)
return text_content.strip(), tool_calls_html
except Exception as e:
# If parsing fails, return the original response with error info
return f"{response}\n\nError parsing response: {str(e)}", ""
def format_final_response(response):
"""Format the final response for display."""
# First try to process as complex JSON with tool calls
text_content, tool_calls_html = parse_complex_response(response)
# If that didn't work, try basic JSON parsing
if text_content == response:
# Clean up JSON response if it looks like JSON
if response.strip().startswith("{") and "content" in response:
try:
response_obj = json.loads(response)
if isinstance(response_obj, dict) and "content" in response_obj:
if isinstance(response_obj["content"], str):
text_content = response_obj["content"]
else:
text_content = json.dumps(response_obj["content"], indent=2)
else:
text_content = response
except:
text_content = response
else:
text_content = response
return f"""
🤖Final Response
{text_content}
{tool_calls_html}
"""
def update_chat_display(existing_display, new_message):
"""Update an existing chat display with a new message."""
try:
# Parse the new message
role = new_message.get("role", "unknown").lower()
# Format the new message based on its role
if role == "user":
message_html = format_user_message(new_message)
elif role == "assistant" or role == "ai":
message_html = format_assistant_message(new_message)
else:
message_html = format_system_message(new_message)
# Find the position to insert the new message (before the Final Response section)
insert_marker = '
Error Updating Chat
{str(e)}
"""
)
def format_chat_display(row):
"""Format the chat display with better styling for user and assistant messages."""
try:
# Parse the conversation JSON
messages = json.loads(row["conversation"])
# Create HTML for all messages
messages_html = ""
for msg in messages:
role = msg.get("role", "unknown").lower()
if role == "user":
messages_html += format_user_message(msg)
elif role == "assistant" or role == "ai":
messages_html += format_assistant_message(msg)
else:
# System or other message types
messages_html += format_system_message(msg)
# Format the final response from the assistant
response_html = format_final_response(row["response"])
# Combine all HTML
full_chat_html = f"""
{messages_html}
{response_html}
"""
return full_chat_html
except Exception as e:
return f"""
Error Formatting Chat
{str(e)}
Original conversation: {str(row["conversation"])}
"""
def parse_tool_schema(tool):
"""Parse tool schema to extract name, description, and parameters properly."""
# Handle schema wrapped in a list
if isinstance(tool, list) and len(tool) > 0:
tool = tool[0]
# Extract function information from the new schema structure with "function" key
if "function" in tool:
function_data = tool["function"]
name = function_data.get("name", "Unnamed Tool")
description = function_data.get("description", "No description available")
parameters = {}
if (
"parameters" in function_data
and "properties" in function_data["parameters"]
):
properties = function_data["parameters"]["properties"]
for param_name, param_data in properties.items():
param_desc = param_data.get("description", "No description")
param_type = param_data.get("type", "unknown")
param_default = param_data.get("default", "None")
# Include default value in parameter description
parameters[param_name] = (
f"{param_desc} (Type: {param_type}, Default: {param_default})"
)
# Check for required parameters
required_params = function_data.get("parameters", {}).get("required", [])
if required_params:
for param_name in required_params:
if param_name in parameters:
parameters[param_name] = f"[REQUIRED] {parameters[param_name]}"
else:
# Original schema parsing
name = tool.get("title", "Unnamed Tool")
description = tool.get("description", "No description available")
parameters = {}
if "properties" in tool:
for param_name, param_data in tool["properties"].items():
param_desc = param_data.get("description", "No description")
param_type = param_data.get("type", "unknown")
param_title = param_data.get("title", param_name)
parameters[param_name] = (
f"{param_desc} (Type: {param_type}, Title: {param_title})"
)
# Check for required parameters in the original schema
required_params = tool.get("required", [])
if required_params:
for param_name in required_params:
if param_name in parameters:
parameters[param_name] = f"[REQUIRED] {parameters[param_name]}"
return name, description, parameters
def format_parameters(parameters):
if not parameters:
return 'No parameters
'
params_html = ""
for name, desc in parameters.items():
is_required = "[REQUIRED]" in desc
param_style = "required" if is_required else "optional"
# Clean up the description to remove the REQUIRED marker but keep the info
cleaned_desc = desc.replace("[REQUIRED] ", "") if is_required else desc
params_html += f"""
{name}
{f"Required" if is_required else "Optional"}
{cleaned_desc}
"""
# Remove the border-bottom from the last parameter
params_html = params_html.replace("last-child: border-bottom: none;", "")
return (
params_html
+ """
"""
)
def format_metrics(score, rationale, explanation):
"""Format metrics display with improved visual hierarchy and dark theme support."""
# Determine score color and add emoji indicator
if score >= 0.7:
score_color = "var(--score-high)"
score_emoji = "🟢"
score_text = "High"
elif score >= 0.4:
score_color = "var(--score-med)"
score_emoji = "🟠"
score_text = "Medium"
else:
score_color = "var(--score-low)"
score_emoji = "🔴"
score_text = "Low"
return f"""
TSQ Score
{score:.2f}
{score_emoji}{score_text}
Explanation
{explanation}
"""
def format_metrics_display(row):
"""Format the metrics display with score, rationale and explanation."""
try:
score = row["score"]
rationale = row["rationale"]
explanation = row["explanation"]
# Determine score color and add emoji indicator
if score >= 0.7:
score_color = "var(--score-high)"
score_emoji = "🟢"
score_text = "High"
elif score >= 0.4:
score_color = "var(--score-med)"
score_emoji = "🟠"
score_text = "Medium"
else:
score_color = "var(--score-low)"
score_emoji = "🔴"
score_text = "Low"
metrics_html = f"""
TSQ Score
{score:.2f}
{score_emoji} {score_text}
Explanation
{explanation}
"""
return metrics_html
except Exception as e:
return f"""
Error Formatting Metrics
{str(e)}
"""
def format_tool_info(tools_data):
"""Format the tool information with improved styling."""
try:
if not tools_data or tools_data == "[]":
return """
🔍
No Tool Information
This conversation doesn't use any tools
"""
if isinstance(tools_data, str):
try:
tools = json.loads(tools_data)
except:
tools = []
else:
tools = tools_data
if not tools:
return """
🔍
No Tool Information
This conversation doesn't use any tools
"""
# Format each tool
tool_items = ""
for tool in tools:
name = tool.get("title", tool.get("name", "Unnamed Tool"))
description = tool.get("description", "No description available")
# Get parameters
parameters = {}
required_params = []
# Handle different schema formats
if "function" in tool:
# Function schema format
function_data = tool["function"]
name = function_data.get("name", name)
description = function_data.get("description", description)
if (
"parameters" in function_data
and "properties" in function_data["parameters"]
):
properties = function_data["parameters"]["properties"]
for param_name, param_data in properties.items():
param_desc = param_data.get("description", "No description")
param_type = param_data.get("type", "unknown")
param_default = param_data.get("default", "None")
parameters[param_name] = {
"description": param_desc,
"type": param_type,
"default": param_default,
}
required_params = function_data.get("parameters", {}).get(
"required", []
)
elif "properties" in tool:
# Original schema format
if "properties" in tool:
for param_name, param_data in tool["properties"].items():
param_desc = param_data.get("description", "No description")
param_type = param_data.get("type", "unknown")
param_title = param_data.get("title", param_name)
parameters[param_name] = {
"description": param_desc,
"type": param_type,
"title": param_title,
}
required_params = tool.get("required", [])
# Format parameters
params_html = ""
if parameters:
for param_name, param_data in parameters.items():
is_required = param_name in required_params
param_style = "required" if is_required else "optional"
params_html += f"""
{param_name}
{f"Required" if is_required else "Optional"}
{param_data.get("description", "No description")}
Type: {param_data.get("type", "unknown")}
{f'
Default: {param_data.get("default", "None")}
' if "default" in param_data else ''}
"""
else:
params_html = """
No parameters
"""
# Remove border from last parameter
params_html += """
"""
tool_items += f"""
⚙️ {name}
{description}
Parameters:
{params_html}
"""
full_tools_html = f"""
"""
return full_tools_html
except Exception as e:
return f"""
Error Formatting Tool Info
{str(e)}
"""