File size: 25,392 Bytes
79180e5
 
 
c14aecf
bad4173
 
3ea0b26
91d2a21
79180e5
cd8b7fb
aab9b8a
79180e5
 
 
 
 
 
cd8b7fb
 
 
 
 
 
 
bad4173
 
 
 
 
 
 
 
 
 
 
 
 
cd8b7fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79180e5
cd8b7fb
 
aab9b8a
 
 
 
79180e5
c14aecf
 
 
 
aab9b8a
c14aecf
 
79180e5
 
 
c14aecf
 
 
 
aab9b8a
 
 
 
79180e5
aab9b8a
 
 
 
 
79180e5
cd8b7fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79180e5
91d2a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79180e5
 
91d2a21
79180e5
 
 
 
 
ba50457
 
 
91d2a21
ba50457
91d2a21
 
 
 
 
 
 
ba50457
 
 
91d2a21
ba50457
 
 
 
 
 
 
 
 
 
 
91d2a21
ba50457
 
91d2a21
 
 
 
 
 
 
ba50457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d6cfc5
 
ba50457
8d6cfc5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba50457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91d2a21
 
 
 
 
 
 
 
 
 
 
ba50457
91d2a21
 
 
 
ba50457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91d2a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c6725d
 
 
91d2a21
 
ba50457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91d2a21
 
 
 
 
 
 
 
ba50457
 
91d2a21
ba50457
 
 
 
91d2a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba50457
 
 
 
 
 
91d2a21
ba50457
91d2a21
ba50457
 
 
 
 
 
 
 
 
 
 
91d2a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c6725d
 
 
91d2a21
 
ba50457
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91d2a21
 
 
 
 
 
 
 
ba50457
 
91d2a21
ba50457
 
 
 
91d2a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba50457
 
 
 
 
 
91d2a21
ba50457
91d2a21
ba50457
 
91d2a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8230de
 
 
 
 
 
 
 
 
91d2a21
 
 
 
 
 
 
 
f8230de
 
 
ba50457
 
 
 
 
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
import gradio as gr
import os
import time
import requests
import json
import plotly.express as px
import pandas as pd
import re

# Model options for dropdown with both Together AI and Anthropic models
together_models = [
    "Qwen/Qwen2.5-Coder-32B-Instruct",
    "nvidia/Llama-3.1-Nemotron-70B-Instruct-HF",
    "deepseek-ai/DeepSeek-R1-Distill-Llama-70B",
    "meta-llama/Llama-3.3-70B-Instruct-Turbo-Free"
]

anthropic_models = [
    "claude-3-7-sonnet-20250219",
    "claude-3-haiku-20240307"
]

all_models = together_models + anthropic_models

VALIDATION_SCHEMA = {
    "quality_rating": "int (1–10)",
    "accuracy": "float (0.0–1.0)",
    "completeness": "float (0.0–1.0)",
    "best_practices_alignment": "float (0.0–1.0)",
    "explanations": {
        "quality_rating": "string",
        "accuracy": "string",
        "completeness": "string",
        "best_practices_alignment": "string"
    }
}

def get_api_key(provider):
    if provider == "together":
        api_key = os.getenv("TOGETHER_API_KEY")
        if not api_key:
            raise ValueError("TOGETHER_API_KEY not set. Please add it in Space secrets.")
        return api_key
    elif provider == "anthropic":
        api_key = os.getenv("ANTHROPIC_API_KEY")
        if not api_key:
            raise ValueError("ANTHROPIC_API_KEY not set. Please add it in Space secrets.")
        return api_key
    else:
        raise ValueError(f"Unknown provider: {provider}")

def get_provider(model):
    if model in together_models:
        return "together"
    elif model in anthropic_models:
        return "anthropic"
    else:
        raise ValueError(f"Unknown model: {model}")

def call_together_api(model, prompt, temperature=0.7, max_tokens=1500):
    api_key = get_api_key("together")
    system_message = (
        "You are a Salesforce development expert specializing in B2B Commerce migrations,"
        " CloudCraze to B2B Lightning Experience conversions, and Apex code optimization."
    )
    try:
        headers = {
            "Authorization": f"Bearer {api_key}",
            "Content-Type": "application/json"
        }
        payload = {
            "model": model,
            "messages": [
                {"role": "system", "content": system_message},
                {"role": "user", "content": prompt}
            ],
            "temperature": temperature,
            "max_tokens": max_tokens,
            "top_p": 0.9
        }
        resp = requests.post(
            "https://api.together.xyz/v1/chat/completions",
            headers=headers,
            json=payload
        )
        if resp.status_code != 200:
            return f"Error: Status {resp.status_code}: {resp.text}"
        data = resp.json()
        text = data["choices"][0]["message"]["content"]
        return text
    except Exception as e:
        return f"Error calling Together AI API: {e}"

def call_anthropic_api(model, prompt, temperature=0.7, max_tokens=1500):
    api_key = get_api_key("anthropic")
    system_message = (
        "You are a Salesforce development expert specializing in B2B Commerce migrations,"
        " CloudCraze to B2B Lightning Experience conversions, and Apex code optimization."
    )
    try:
        headers = {
            "x-api-key": api_key,
            "anthropic-version": "2023-06-01",
            "content-type": "application/json"
        }
        payload = {
            "model": model,
            "system": system_message,
            "messages": [
                {"role": "user", "content": prompt}
            ],
            "temperature": temperature,
            "max_tokens": max_tokens
        }
        resp = requests.post(
            "https://api.anthropic.com/v1/messages",
            headers=headers,
            json=payload
        )
        if resp.status_code != 200:
            return f"Error: Status {resp.status_code}: {resp.text}"
        data = resp.json()
        text = data["content"][0]["text"]
        return text
    except Exception as e:
        return f"Error calling Anthropic API: {e}"

def call_llm(model, prompt, temperature=0.7, max_tokens=1500):
    provider = get_provider(model)
    if provider == "together":
        return call_together_api(model, prompt, temperature, max_tokens)
    elif provider == "anthropic":
        return call_anthropic_api(model, prompt, temperature, max_tokens)
    else:
        return f"Error: Unknown provider for model {model}"

def extract_code_blocks(text):
    """Extract code blocks from the model's response"""
    # Pattern to match code blocks with ```apex or ```java or just ```
    pattern = r"```(?:apex|java)?(.*?)```"
    matches = re.findall(pattern, text, re.DOTALL)
    
    # Clean up extracted code blocks
    code_blocks = []
    for block in matches:
        # Remove leading/trailing whitespace
        cleaned_block = block.strip()
        if cleaned_block:
            code_blocks.append(cleaned_block)
    
    # If no code blocks found but text contains code-like content
    if not code_blocks and ("public" in text or "private" in text or "trigger" in text):
        # Try to extract the most code-like part
        lines = text.split('\n')
        potential_code = []
        in_code_section = False
        
        for line in lines:
            if any(keyword in line for keyword in ["public", "private", "class", "trigger", "@"]):
                in_code_section = True
            
            if in_code_section:
                potential_code.append(line)
        
        if potential_code:
            code_blocks.append('\n'.join(potential_code))
    
    return '\n\n'.join(code_blocks) if code_blocks else ""

def extract_explanations(text, code_blocks):
    """Extract explanations from the model's response by removing code blocks"""
    # Replace all code blocks with placeholders
    explanation = text
    for block in code_blocks.split('\n\n'):
        # Escape special regex characters in the block
        escaped_block = re.escape(block)
        explanation = re.sub(escaped_block, "[CODE BLOCK REMOVED]", explanation, flags=re.DOTALL)
    
    # Remove code block markers
    explanation = re.sub(r"```(?:apex|java)?.*?```", "", explanation, flags=re.DOTALL)
    
    # Clean up the explanation
    explanation = explanation.replace("[CODE BLOCK REMOVED]", "*Code has been moved to the Code Output section*")
    
    return explanation.strip()

def correct_apex_trigger(model, trigger_code):
    if not trigger_code.strip():
        return "Please provide Apex Trigger code to correct.", "", ""
    prompt = f"""
Please analyze and correct the following Apex Trigger code for migration from CloudCraze to B2B Lightning Experience.
Identify any issues, optimize it according to best practices, and provide the corrected code.

```apex
{trigger_code}
```

Please return the corrected code with explanations of changes. Put the corrected code in ```apex code blocks.
"""
    response = call_llm(model, prompt)
    
    # Extract code blocks and explanations
    code_output = extract_code_blocks(response)
    explanation = extract_explanations(response, code_output)
    
    return response, code_output, explanation

def convert_cc_object(model, cc_object_code):
    if not cc_object_code.strip():
        return "Please provide CloudCraze Object code to convert.", "", ""
    prompt = f"""
Please convert the following CloudCraze Object code to B2B Lightning Experience format.
Identify the corresponding B2B LEx system object, map fields, and provide the full definition.

```
{cc_object_code}
```

Return:
1. Equivalent B2B LEx object name
2. Field mappings
3. Full implementation code in ```apex code blocks
4. Additional steps if needed
"""
    response = call_llm(model, prompt)
    
    # Extract code blocks and explanations
    code_output = extract_code_blocks(response)
    explanation = extract_explanations(response, code_output)
    
    return response, code_output, explanation

def validate_apex_trigger(validation_model, original_code, corrected_code):
    if not validation_model or not original_code.strip() or not corrected_code.strip():
        return "Please provide all required inputs for validation."
    
    prompt = f"""
I need you to validate and review the following Apex code migration. This involves both CloudCraze to B2B Lightning Experience conversions AND general Apex code optimization.

ORIGINAL CODE:
```apex
{original_code}
```

CORRECTED CODE:
```apex
{corrected_code}
```

Please review the corrected code and provide:
1. Is the correction accurate and complete? Highlight any missed issues.
2. Are there any potential runtime errors or performance concerns?
3. Does it follow Salesforce best practices for B2B Lightning Experience?
4. Are there optimization opportunities that were missed?
5. Evaluate both the B2B Commerce conversion aspects AND the general Apex optimization.
6. Rate the quality of the correction on a scale of 1-10 with explanation.

Additionally, provide a structured assessment in JSON format following this schema:
{json.dumps(VALIDATION_SCHEMA, indent=2)}

Be thorough and detailed in your assessment, addressing both the conversion and optimization aspects.
"""
    return call_llm(validation_model, prompt)

def validate_cc_object_conversion(validation_model, original_object, converted_object):
    if not validation_model or not original_object.strip() or not converted_object.strip():
        return "Please provide all required inputs for validation."
    
    prompt = f"""
I need you to validate and review the following CloudCraze Object conversion to B2B Lightning Experience format. This involves both CloudCraze to B2B Lightning Experience conversions AND optimization of the resulting code.

ORIGINAL CLOUDCRAZE OBJECT:
```
{original_object}
```

CONVERTED B2B LEX OBJECT:
```
{converted_object}
```

Please review the conversion and provide:
1. Is the object mapping correct and complete? Identify any missed fields or relationships.
2. Are there any potential data migration issues or concerns?
3. Does the converted object follow B2B Lightning Experience best practices?
4. Are there optimization opportunities that were missed in the conversion?
5. Evaluate both the B2B Commerce conversion aspects AND the optimization of the resulting code.
6. Rate the quality of the conversion on a scale of 1-10 with explanation.

Additionally, provide a structured assessment in JSON format following this schema:
{json.dumps(VALIDATION_SCHEMA, indent=2)}

Be thorough and detailed in your assessment, addressing both the conversion and optimization aspects.
"""
    return call_llm(validation_model, prompt)

def extract_validation_metrics(validation_text):
    try:
        # Try to find JSON in the response
        start_idx = validation_text.find('{')
        end_idx = validation_text.rfind('}') + 1
        
        if start_idx != -1 and end_idx != -1 and start_idx < end_idx:
            json_str = validation_text[start_idx:end_idx]
            # Print for debugging
            print("Extracted JSON:", json_str)
            
            try:
                data = json.loads(json_str)
                
                # Extract the required metrics with default values
                metrics = {
                    "quality_rating": float(data.get("quality_rating", 0)),
                    "accuracy": float(data.get("accuracy", 0.0)),
                    "completeness": float(data.get("completeness", 0.0)),
                    "best_practices_alignment": float(data.get("best_practices_alignment", 0.0))
                }
                
                return metrics
            except json.JSONDecodeError as je:
                print(f"JSON decode error: {je}")
                return None
        else:
            print("No JSON found in validation text")
            return None
    except Exception as e:
        print(f"Error extracting metrics: {e}")
        return None

def create_radar_chart(metrics):
    if not metrics:
        return None
    
    # Create data for the radar chart
    categories = ["Quality", "Accuracy", "Completeness", "Best Practices"]
    values = [
        metrics["quality_rating"] / 10,  # Normalize to 0-1 scale
        metrics["accuracy"],
        metrics["completeness"],
        metrics["best_practices_alignment"]
    ]
    
    # Create a DataFrame for plotting
    df = pd.DataFrame({
        'Category': categories,
        'Value': values
    })
    
    # Create the radar chart
    fig = px.line_polar(
        df, r='Value', theta='Category', line_close=True,
        range_r=[0, 1], title="Validation Assessment"
    )
    fig.update_traces(fill='toself')
    
    return fig

def toggle_dark_mode(dark_mode, elements):
    """Toggle between light and dark mode for interface elements"""
    if dark_mode:
        style = "background-color: #2e2e2e; color: #ffffff;"
        code_style = "background-color: #1e1e1e; color: #e0e0e0; font-family: 'Courier New', monospace;"
    else:
        style = "background-color: #ffffff; color: #333333;"
        code_style = "background-color: #f5f5f5; color: #333333; font-family: 'Courier New', monospace;"
    
    return [style for _ in range(len(elements) // 2)] + [code_style for _ in range(len(elements) // 2)]

def main():
    with gr.Blocks(title="Salesforce B2B Commerce Migration Assistant", theme=gr.themes.Soft(primary_hue="blue")) as app:
        # Initialize dark mode state
        dark_mode = gr.State(False)
        
        gr.Markdown("# Salesforce B2B Commerce Migration Assistant")
        gr.Markdown("This tool helps migrate CloudCraze code to B2B Lightning Experience.")

        # Create model dropdowns
        with gr.Row():
            with gr.Column():
                gr.Markdown("### Primary Model")
                primary_model_dropdown = gr.Dropdown(
                    choices=all_models,
                    value=anthropic_models[0],  # Default to Claude 3.7 Sonnet
                    label="Select Primary AI Model for Conversion"
                )
            
            with gr.Column():
                gr.Markdown("### Validation Model")
                validation_model_dropdown = gr.Dropdown(
                    choices=all_models,
                    value=anthropic_models[1],  # Default to Claude 3 Haiku
                    label="Select Validation AI Model for Review",
                    info="This model will validate and review the output from the primary model"
                )

        with gr.Tab("Apex Trigger Correction"):
            gr.Markdown("### Apex Trigger Correction")
            gr.Markdown("Paste your Apex Trigger code below:")

            trigger_input = gr.Textbox(
                lines=12,
                placeholder="Paste Apex Trigger code here...",
                label="Apex Trigger Code"
            )
            
            with gr.Row():
                trigger_button = gr.Button("Correct Apex Trigger", variant="primary")
                copy_code_button = gr.Button("Copy Code", variant="secondary")
                
            with gr.Accordion("Full Model Response (Hidden by Default)", open=False):
                trigger_full_response = gr.Textbox(
                    lines=15,
                    label="Full Model Response",
                    interactive=False
                )
            
            with gr.Row():
                with gr.Column():
                    trigger_explanation = gr.Textbox(
                        lines=10,
                        label="Explanation",
                        placeholder="Explanation will appear here after correction",
                        interactive=False,
                        elem_id="trigger_explanation"
                    )
                
                with gr.Column():
                    trigger_code_output = gr.Code(
                        language="python",  # Using Python syntax highlighting as it's supported
                        label="Corrected Code (Apex)",
                        value="# Corrected Apex code will appear here",
                        elem_id="trigger_code_output"
                    )
            
            gr.Markdown("### Validation Results")
            with gr.Row():
                with gr.Column(scale=2):
                    trigger_validation_output = gr.Textbox(
                        lines=15,
                        label="Validation Assessment",
                        placeholder="Validation results will appear here after clicking 'Validate Correction'",
                        interactive=True
                    )
                with gr.Column(scale=1):
                    trigger_chart = gr.Plot(label="Validation Metrics")
            
            validate_trigger_button = gr.Button("Validate Correction")
            
            def validate_and_chart_trigger(model, original, corrected):
                validation_text = validate_apex_trigger(model, original, corrected)
                metrics = extract_validation_metrics(validation_text)
                chart = create_radar_chart(metrics) if metrics else None
                return validation_text, chart
            
            # Handle button clicks
            trigger_button.click(
                fn=correct_apex_trigger,
                inputs=[primary_model_dropdown, trigger_input],
                outputs=[trigger_full_response, trigger_code_output, trigger_explanation],
                show_progress=True
            )
            
            validate_trigger_button.click(
                fn=validate_and_chart_trigger,
                inputs=[validation_model_dropdown, trigger_input, trigger_code_output],
                outputs=[trigger_validation_output, trigger_chart],
                show_progress=True
            )
            
            # Copy code button functionality
            def trigger_copy_to_clipboard():
                # This function doesn't need to return anything - the copy happens in the frontend
                return None
            
            copy_code_button.click(
                fn=trigger_copy_to_clipboard,
                inputs=[],
                outputs=[],
                _js="""() => {
                    const codeElem = document.getElementById('trigger_code_output');
                    if (codeElem) {
                        navigator.clipboard.writeText(codeElem.textContent);
                        return [];
                    }
                }"""
            )
            
            with gr.Row():
                trigger_clear = gr.Button("Clear Input")
                trigger_clear.click(lambda: "", [], trigger_input)
                
                results_clear = gr.Button("Clear Results")
                results_clear.click(
                    lambda: ["", "", "", "", None],
                    [],
                    [trigger_full_response, trigger_code_output, trigger_explanation, trigger_validation_output, trigger_chart]
                )

        with gr.Tab("CloudCraze Object Conversion"):
            gr.Markdown("### CloudCraze Object Conversion")
            gr.Markdown("Paste your CloudCraze Object code below:")

            object_input = gr.Textbox(
                lines=12,
                placeholder="Paste CC object code here...",
                label="CloudCraze Object Code"
            )
            
            with gr.Row():
                object_button = gr.Button("Convert Object", variant="primary")
                object_copy_code_button = gr.Button("Copy Code", variant="secondary")
                
            with gr.Accordion("Full Model Response (Hidden by Default)", open=False):
                object_full_response = gr.Textbox(
                    lines=15,
                    label="Full Model Response",
                    interactive=False
                )
            
            with gr.Row():
                with gr.Column():
                    object_explanation = gr.Textbox(
                        lines=10,
                        label="Explanation",
                        placeholder="Explanation will appear here after conversion",
                        interactive=False,
                        elem_id="object_explanation"
                    )
                
                with gr.Column():
                    object_code_output = gr.Code(
                        language="python",  # Using Python syntax highlighting as it's supported
                        label="Converted Code (Apex)",
                        value="# Converted Apex code will appear here",
                        elem_id="object_code_output"
                    )
            
            gr.Markdown("### Validation Results")
            with gr.Row():
                with gr.Column(scale=2):
                    object_validation_output = gr.Textbox(
                        lines=15,
                        label="Validation Assessment",
                        placeholder="Validation results will appear here after clicking 'Validate Conversion'",
                        interactive=True
                    )
                with gr.Column(scale=1):
                    object_chart = gr.Plot(label="Validation Metrics")
            
            validate_object_button = gr.Button("Validate Conversion")
            
            def validate_and_chart_object(model, original, converted):
                validation_text = validate_cc_object_conversion(model, original, converted)
                metrics = extract_validation_metrics(validation_text)
                chart = create_radar_chart(metrics) if metrics else None
                return validation_text, chart
            
            # Handle button clicks
            object_button.click(
                fn=convert_cc_object,
                inputs=[primary_model_dropdown, object_input],
                outputs=[object_full_response, object_code_output, object_explanation],
                show_progress=True
            )
            
            validate_object_button.click(
                fn=validate_and_chart_object,
                inputs=[validation_model_dropdown, object_input, object_code_output],
                outputs=[object_validation_output, object_chart],
                show_progress=True
            )
            
            # Copy code button functionality
            def object_copy_to_clipboard():
                # This function doesn't need to return anything - the copy happens in the frontend
                return None
            
            object_copy_code_button.click(
                fn=object_copy_to_clipboard,
                inputs=[],
                outputs=[],
                _js="""() => {
                    const codeElem = document.getElementById('object_code_output');
                    if (codeElem) {
                        navigator.clipboard.writeText(codeElem.textContent);
                        return [];
                    }
                }"""
            )
            
            with gr.Row():
                object_clear = gr.Button("Clear Input")
                object_clear.click(lambda: "", [], object_input)
                
                object_results_clear = gr.Button("Clear Results")
                object_results_clear.click(
                    lambda: ["", "", "", "", None],
                    [],
                    [object_full_response, object_code_output, object_explanation, object_validation_output, object_chart]
                )

        # UI Preferences
        with gr.Accordion("UI Preferences", open=False):
            dark_mode_toggle = gr.Checkbox(label="Dark Mode", value=False)
            
            # Create a list of UI elements to update
            ui_elements = [
                trigger_explanation, trigger_code_output,
                object_explanation, object_code_output
            ]
            
            dark_mode_toggle.change(
                fn=toggle_dark_mode,
                inputs=[dark_mode_toggle, gr.State(ui_elements)],
                outputs=ui_elements
            )

        gr.Markdown("### About This Tool")
        gr.Markdown(
            """
                 **Primary Model**: Performs the initial code conversion or correction.
                **Validation Model**: Reviews and validates the output from the primary model, identifying potential issues or improvements.
                **Trigger Correction**: Fixes Apex Triggers for B2B LEx compatibility.
                **Object Conversion**: Maps and converts CloudCraze object definitions to B2B LEx.
                **Model Selection**: Choose from Together AI models or Anthropic's Claude models.
                
                **New Interface Features**:
                - Separated code output in dedicated code editor interface with syntax highlighting
                - Clear separation between explanations and code
                - "Copy Code" button for easy copying
                - Dark mode option for comfortable viewing
                - Hidden full model response to reduce clutter
                
                **Validation** outputs four key metrics (quality, accuracy, completeness, best practices) as both JSON and a radar chart.
                Always review AI-generated code before production use.
                """
        )

    app.launch()

if __name__ == "__main__":
    main()