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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
import gradio as gr
import os
import time
import requests
import json
import plotly.express as px
import pandas as pd

# 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 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.
"""
    return call_llm(model, prompt)

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
4. Additional steps if needed
"""
    return call_llm(model, prompt)

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]
            data = json.loads(json_str)
            
            # Extract the required metrics
            metrics = {
                "quality_rating": data.get("quality_rating", 0),
                "accuracy": data.get("accuracy", 0.0),
                "completeness": data.get("completeness", 0.0),
                "best_practices_alignment": data.get("best_practices_alignment", 0.0)
            }
            
            return metrics
        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 main():
    with gr.Blocks(title="Salesforce B2B Commerce Migration Assistant") as app:
        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"
            )
            trigger_output = gr.Textbox(
                lines=15,
                label="Corrected Apex Trigger",
                interactive=True
            )
            trigger_button = gr.Button("Correct Apex Trigger")
            trigger_button.click(
                fn=correct_apex_trigger,
                inputs=[primary_model_dropdown, trigger_input],
                outputs=trigger_output,
                show_progress=True
            )
            
            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
            
            validate_trigger_button.click(
                fn=validate_and_chart_trigger,
                inputs=[validation_model_dropdown, trigger_input, trigger_output],
                outputs=[trigger_validation_output, trigger_chart],
                show_progress=True
            )
            
            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_output, 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"
            )
            object_output = gr.Textbox(
                lines=15,
                label="Converted B2B LEx Object",
                interactive=True
            )
            object_button = gr.Button("Convert Object")
            object_button.click(
                fn=convert_cc_object,
                inputs=[primary_model_dropdown, object_input],
                outputs=object_output,
                show_progress=True
            )
            
            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
            
            validate_object_button.click(
                fn=validate_and_chart_object,
                inputs=[validation_model_dropdown, object_input, object_output],
                outputs=[object_validation_output, object_chart],
                show_progress=True
            )
            
            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_output, object_validation_output, object_chart]
                )

        with gr.Accordion("About This Tool", open=False):
    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.
        
        Validation now outputs four key metrics (quality, accuracy, completeness, best practices) as both JSON and a fun chart.
        Always review AI-generated code before production use.
        """)

    app.launch()

if __name__ == "__main__":
    main()