File size: 44,845 Bytes
65a33c1
 
 
290299d
 
 
 
65a33c1
 
 
 
 
 
 
 
 
 
290299d
 
65a33c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65a33c1
 
8506a5c
65a33c1
8506a5c
65a33c1
 
 
8506a5c
65a33c1
8506a5c
 
 
 
 
65a33c1
 
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65a33c1
8506a5c
 
 
 
290299d
8506a5c
 
290299d
8506a5c
 
 
 
290299d
 
8506a5c
 
 
290299d
 
 
 
8506a5c
 
 
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8506a5c
290299d
 
 
 
 
8506a5c
290299d
 
 
8506a5c
290299d
 
 
 
8506a5c
290299d
 
 
 
8506a5c
290299d
 
8506a5c
 
 
 
290299d
8506a5c
 
290299d
 
 
8506a5c
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8506a5c
290299d
8506a5c
 
290299d
8506a5c
290299d
 
 
 
 
 
8506a5c
290299d
 
 
 
 
 
 
 
8506a5c
290299d
8506a5c
 
290299d
 
 
 
 
 
 
 
8506a5c
 
65a33c1
290299d
 
 
8506a5c
290299d
 
 
8506a5c
290299d
8506a5c
 
290299d
8506a5c
290299d
 
 
8506a5c
290299d
 
 
 
 
 
 
 
 
 
8506a5c
 
290299d
 
 
 
8506a5c
290299d
 
 
 
8506a5c
 
290299d
8506a5c
290299d
 
 
 
 
 
 
 
 
 
8506a5c
 
290299d
 
 
 
 
 
 
 
 
 
8506a5c
 
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
8506a5c
 
290299d
451eed0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290299d
 
 
 
 
 
 
 
 
 
8506a5c
290299d
 
 
 
8506a5c
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8506a5c
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8506a5c
 
290299d
 
 
 
 
451eed0
 
290299d
 
 
 
 
8506a5c
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50d72b7
290299d
 
 
 
451eed0
 
 
 
 
8506a5c
 
290299d
 
 
 
50d72b7
 
 
 
 
 
 
 
 
 
 
 
 
8506a5c
290299d
50d72b7
 
 
 
 
 
 
290299d
 
 
50d72b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8506a5c
290299d
 
451eed0
290299d
 
 
 
 
 
 
 
 
 
 
8506a5c
451eed0
8506a5c
 
 
290299d
 
 
 
8506a5c
290299d
 
 
 
 
 
 
 
8506a5c
290299d
 
8506a5c
290299d
 
 
 
 
 
 
8506a5c
290299d
 
8506a5c
290299d
 
451eed0
50d72b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290299d
 
50d72b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290299d
451eed0
 
 
 
 
 
290299d
 
 
 
 
 
 
 
 
451eed0
290299d
 
 
 
 
451eed0
 
 
 
 
 
 
 
 
 
 
290299d
 
50d72b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290299d
 
50d72b7
 
 
 
 
 
 
 
 
 
8506a5c
50d72b7
 
290299d
 
 
 
50d72b7
 
 
 
 
 
 
 
 
 
290299d
 
 
 
 
 
 
 
 
 
8506a5c
290299d
8506a5c
290299d
 
 
 
 
 
8506a5c
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8506a5c
290299d
 
 
451eed0
 
290299d
 
 
 
 
50d72b7
 
 
 
290299d
50d72b7
290299d
 
 
451eed0
 
 
 
 
 
290299d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50d72b7
8506a5c
 
451eed0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50d72b7
451eed0
 
 
 
50d72b7
 
 
 
 
 
 
 
 
 
451eed0
290299d
50d72b7
451eed0
8506a5c
 
 
290299d
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
1050
1051
1052
1053
1054
import os
import functools
import re
import json
import time
from datetime import datetime
from typing import Dict, List, Any, Tuple
from openai import OpenAI
import tiktoken
import gradio as gr

# Configure API client
af_key = os.getenv("OPENAI_API_KEY")
if not af_key:
    raise ValueError("Please set the OPENAI_API_KEY environment variable.")
client = OpenAI(api_key=af_key)

# Available models
_env_models = os.getenv("OPENAI_MODEL_LIST", "gpt-3.5-turbo,gpt-4,gpt-4o,gpt-4o-mini")
ALL_MODELS = [m.strip() for m in _env_models.split(",") if m.strip()]
if not ALL_MODELS:
    ALL_MODELS = ["gpt-3.5-turbo"]

# Token encoder
@functools.lru_cache(maxsize=64)
def _get_encoding(model: str):
    try:
        return tiktoken.encoding_for_model(model)
    except KeyError:
        return tiktoken.get_encoding("cl100k_base")

def count_tokens(text: str, model: str) -> int:
    enc = _get_encoding(model)
    return len(enc.encode(text))

# Advanced prompt templates
PROMPT_TEMPLATES = {
    "Writing & Content": {
        "Blog Post Writer": {
            "description": "Create engaging blog posts with SEO optimization",
            "system": "You are an expert content writer and SEO specialist.",
            "template": "Write a {tone} blog post about {topic} for {audience}. Include {word_count} words, SEO keywords, and a compelling hook.",
            "variables": ["tone", "topic", "audience", "word_count"],
            "examples": [
                {"input": "Topic: AI in healthcare, Tone: Professional, Audience: Medical professionals", "output": "# Revolutionizing Patient Care: How AI is Transforming Modern Healthcare\n\nThe stethoscope around a doctor's neck might soon be joined by..."}
            ]
        },
        "Email Composer": {
            "description": "Professional email writing for various contexts",
            "system": "You are a professional communication expert.",
            "template": "Write a {tone} email to {recipient} about {subject}. Purpose: {purpose}",
            "variables": ["tone", "recipient", "subject", "purpose"],
            "examples": []
        },
        "Social Media Creator": {
            "description": "Engaging social media content for all platforms",
            "system": "You are a social media expert who creates viral content.",
            "template": "Create a {platform} post about {topic} that is {tone} and includes relevant hashtags. Target audience: {audience}",
            "variables": ["platform", "topic", "tone", "audience"],
            "examples": []
        }
    },
    "Analysis & Research": {
        "Data Analyst": {
            "description": "Comprehensive data analysis and insights",
            "system": "You are a senior data analyst with expertise in statistical analysis and business intelligence.",
            "template": "Analyze the following data about {subject} and provide insights on {focus_area}. Include trends, patterns, and actionable recommendations.",
            "variables": ["subject", "focus_area"],
            "examples": []
        },
        "Competitive Analysis": {
            "description": "In-depth competitor research and positioning",
            "system": "You are a strategic business analyst specializing in competitive intelligence.",
            "template": "Conduct a competitive analysis of {company} in the {industry} market. Focus on {analysis_areas} and provide strategic recommendations.",
            "variables": ["company", "industry", "analysis_areas"],
            "examples": []
        },
        "Research Synthesizer": {
            "description": "Synthesize complex research into clear insights",
            "system": "You are a research expert who excels at synthesizing complex information.",
            "template": "Synthesize research on {topic} focusing on {key_questions}. Provide evidence-based conclusions and identify knowledge gaps.",
            "variables": ["topic", "key_questions"],
            "examples": []
        }
    },
    "Business & Strategy": {
        "Business Plan Creator": {
            "description": "Comprehensive business planning assistance",
            "system": "You are a business strategy consultant with expertise in business plan development.",
            "template": "Create a business plan section for {business_type} focusing on {section}. Include market analysis, financial projections, and risk assessment.",
            "variables": ["business_type", "section"],
            "examples": []
        },
        "SWOT Analyzer": {
            "description": "Strategic SWOT analysis for any situation",
            "system": "You are a strategic planning expert who conducts thorough SWOT analyses.",
            "template": "Conduct a SWOT analysis for {entity} in the context of {situation}. Provide specific, actionable insights for each quadrant.",
            "variables": ["entity", "situation"],
            "examples": []
        },
        "Project Manager": {
            "description": "Project planning and management guidance",
            "system": "You are an experienced project manager with PMP certification.",
            "template": "Create a project plan for {project_name} with timeline {duration}. Include milestones, risks, and resource requirements for {team_size} team members.",
            "variables": ["project_name", "duration", "team_size"],
            "examples": []
        }
    },
    "Technical & Code": {
        "Code Reviewer": {
            "description": "Professional code review and optimization",
            "system": "You are a senior software engineer and code review expert.",
            "template": "Review this {language} code for {purpose}. Focus on {review_areas} and provide specific improvement suggestions.",
            "variables": ["language", "purpose", "review_areas"],
            "examples": []
        },
        "Architecture Designer": {
            "description": "Software architecture and system design",
            "system": "You are a solutions architect with expertise in scalable system design.",
            "template": "Design a {system_type} architecture for {use_case}. Consider {requirements} and provide detailed technical specifications.",
            "variables": ["system_type", "use_case", "requirements"],
            "examples": []
        },
        "Debug Assistant": {
            "description": "Advanced debugging and troubleshooting",
            "system": "You are a debugging expert who can identify and solve complex technical issues.",
            "template": "Help debug this {technology} issue: {problem_description}. Provide step-by-step troubleshooting and root cause analysis.",
            "variables": ["technology", "problem_description"],
            "examples": []
        }
    },
    "Creative & Innovation": {
        "Creative Brainstormer": {
            "description": "Generate innovative ideas and solutions",
            "system": "You are a creative thinking expert who generates innovative solutions.",
            "template": "Generate {number} creative ideas for {challenge} targeting {target_audience}. Use {creativity_method} thinking approach.",
            "variables": ["number", "challenge", "target_audience", "creativity_method"],
            "examples": []
        },
        "Story Writer": {
            "description": "Creative storytelling and narrative development",
            "system": "You are a professional storyteller and creative writer.",
            "template": "Write a {genre} story about {theme} set in {setting}. Target audience: {audience}. Length: {length}",
            "variables": ["genre", "theme", "setting", "audience", "length"],
            "examples": []
        },
        "Innovation Consultant": {
            "description": "Innovation strategy and ideation",
            "system": "You are an innovation consultant who helps organizations think differently.",
            "template": "Develop innovative solutions for {industry} to address {challenge}. Use {innovation_framework} methodology.",
            "variables": ["industry", "challenge", "innovation_framework"],
            "examples": []
        }
    }
}

# Role personas
ROLE_PERSONAS = {
    "Expert Consultant": "You are a world-class expert consultant with 20+ years of experience. You provide authoritative, evidence-based advice.",
    "Creative Collaborator": "You are a creative partner who thinks outside the box and offers innovative perspectives.",
    "Analytical Thinker": "You are a logical, systematic thinker who breaks down complex problems methodically.",
    "Supportive Mentor": "You are a patient, encouraging mentor who guides others to discover insights themselves.",
    "Critical Reviewer": "You are a constructive critic who identifies weaknesses and suggests improvements.",
    "Visionary Strategist": "You are a forward-thinking strategist who sees big-picture opportunities and trends.",
    "Practical Implementer": "You are focused on practical, actionable solutions that can be implemented immediately.",
    "Research Scholar": "You are a meticulous researcher who values accuracy and comprehensive analysis."
}

# Advanced instruction categories
ADVANCED_CATEGORIES = {
    "Cognitive Techniques": [
        "Use chain-of-thought reasoning, showing your step-by-step thinking",
        "Apply the six thinking hats method (white, red, black, yellow, green, blue)",
        "Use the SCAMPER technique for creative problem-solving",
        "Apply first principles thinking to break down complex problems",
        "Use analogical reasoning to explain complex concepts"
    ],
    "Output Structure": [
        "Provide an executive summary followed by detailed analysis",
        "Use the pyramid principle: conclusion first, then supporting arguments",
        "Structure response with clear headings and subheadings",
        "Include a TL;DR section at the beginning",
        "End with specific action items and next steps",
        "Use bullet points for key insights and numbered lists for processes"
    ],
    "Quality Assurance": [
        "Fact-check all claims and provide sources when possible",
        "Include confidence levels for uncertain statements",
        "Acknowledge limitations and assumptions in your analysis",
        "Provide alternative perspectives or counterarguments",
        "Include risk assessment for recommendations"
    ],
    "Audience Adaptation": [
        "Adjust technical depth based on audience expertise level",
        "Use relevant examples and analogies for the target audience",
        "Consider cultural context and sensitivities",
        "Tailor tone and formality to the professional setting",
        "Include stakeholder impact analysis"
    ]
}

# Default filtering
DEFAULT_BANNED_WORDS = [
    "Hurdles", "Tapestry", "Bustling", "Harnessing", "Unveiling the power",
    "Realm", "Depicted", "Demystify", "Insurmountable", "New Era",
    "Poised", "Unravel", "Entanglement", "Unprecedented", "Beacon",
    "Unleash", "Delve", "Enrich", "Multifaceted", "Discover", "Unlock",
    "Tailored", "Elegant", "Dive", "Ever-evolving", "Adventure",
    "Journey", "Navigate", "Navigation"
]

DEFAULT_FILTER_PATTERNS = [
    r"As an AI language model,?\s*",
    r"I(?:'m|'m|\s+am)\s+sorry,?\s*",
    r"I\s+apologize,?\s*",
    r"In\s+conclusion,?\s*",
    r"At\s+the\s+end\s+of\s+the\s+day,?\s*"
]

# Global state for saved prompts and analytics
class PromptState:
    def __init__(self):
        self.saved_prompts = {}
        self.analytics = []
        self.ab_tests = {}
        self.custom_categories = {}
        
    def save_prompt(self, name: str, prompt_data: dict):
        self.saved_prompts[name] = {
            **prompt_data,
            "created_at": datetime.now().isoformat(),
            "id": len(self.saved_prompts)
        }
    
    def log_usage(self, prompt: str, response: str, model: str, tokens: int, rating: int = None):
        self.analytics.append({
            "timestamp": datetime.now().isoformat(),
            "prompt_length": len(prompt),
            "response_length": len(response),
            "model": model,
            "tokens": tokens,
            "rating": rating
        })

state = PromptState()

def validate_regex_patterns(patterns: list) -> tuple[list, list]:
    """Validate regex patterns and return valid ones plus any errors"""
    valid_patterns = []
    errors = []
    
    for pattern in patterns:
        if not pattern.strip():
            continue
        try:
            re.compile(pattern.strip())
            valid_patterns.append(pattern.strip())
        except re.error as e:
            errors.append(f"Invalid pattern '{pattern}': {str(e)}")
    
    return valid_patterns, errors

def smart_filter_text(text: str, banned_words: list, banned_patterns: list) -> str:
    """Apply smart filtering that preserves sentence structure"""
    result = text
    
    # Filter patterns first (more specific) - patterns are pre-validated
    for pattern in banned_patterns:
        if pattern.strip():
            result = re.sub(pattern.strip(), "", result, flags=re.IGNORECASE)
    
    # Filter banned words (preserve word boundaries)
    for word in banned_words:
        if word.strip():
            escaped_word = re.escape(word.strip())
            pattern = rf"\b{escaped_word}\b"
            result = re.sub(pattern, "", result, flags=re.IGNORECASE)
    
    # Clean up extra whitespace and punctuation
    result = re.sub(r'\s+', ' ', result)
    result = re.sub(r'\s+([.!?])', r'\1', result)
    result = re.sub(r'([.!?])\s*([.!?])', r'\1\2', result)
    result = re.sub(r'^[.!?]\s*', '', result)
    
    return result.strip()

def substitute_variables(template: str, variables: dict) -> str:
    """Replace {variable} placeholders with actual values"""
    result = template
    for var, value in variables.items():
        if value:  # Only substitute if value is provided
            result = result.replace(f"{{{var}}}", str(value))
    return result

def optimize_prompt(prompt: str) -> str:
    """Provide optimization suggestions for prompts"""
    suggestions = []
    
    # Check length
    if len(prompt) < 50:
        suggestions.append("Consider adding more context and specific requirements")
    elif len(prompt) > 2000:
        suggestions.append("Consider breaking this into smaller, focused prompts")
    
    # Check for vague terms
    vague_terms = ["good", "better", "nice", "improve", "optimize", "enhance"]
    found_vague = [term for term in vague_terms if term.lower() in prompt.lower()]
    if found_vague:
        suggestions.append(f"Replace vague terms ({', '.join(found_vague)}) with specific criteria")
    
    # Check for examples
    if "example" not in prompt.lower() and len(prompt) > 100:
        suggestions.append("Consider adding specific examples to clarify your expectations")
    
    # Check for output format specification
    format_words = ["format", "structure", "organize", "layout"]
    if not any(word in prompt.lower() for word in format_words):
        suggestions.append("Specify the desired output format (bullet points, paragraphs, etc.)")
    
    if not suggestions:
        return "βœ… Your prompt looks well-optimized!"
    
    return "πŸ’‘ Optimization suggestions:\nβ€’ " + "\nβ€’ ".join(suggestions)

def make_api_call(model: str, prompt: str, temperature: float = 0.7) -> tuple[str, str, int]:
    """Make API call with error handling and token tracking"""
    try:
        response = client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": prompt}],
            temperature=temperature,
            max_tokens=2000
        )
        content = response.choices[0].message.content
        tokens = response.usage.total_tokens if response.usage else count_tokens(prompt + content, model)
        return content, "", tokens
    except Exception as e:
        return "", f"API Error: {str(e)}", 0

def calculate_analytics() -> dict:
    """Calculate usage analytics"""
    if not state.analytics:
        return {}
    
    total_prompts = len(state.analytics)
    avg_tokens = sum(a["tokens"] for a in state.analytics) / total_prompts if total_prompts > 0 else 0
    rated_prompts = [a for a in state.analytics if a["rating"] is not None]
    avg_rating = sum(a["rating"] for a in rated_prompts) / len(rated_prompts) if rated_prompts else 0
    
    return {
        "total_prompts": total_prompts,
        "avg_tokens": round(avg_tokens, 1),
        "avg_rating": round(avg_rating, 2),
        "models_used": len(set(a["model"] for a in state.analytics))
    }

# Custom CSS
custom_css = """
.gradio-container {
    max-width: 1400px !important;
}
.template-card {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    padding: 20px;
    color: white;
    margin: 10px 0;
}
.analytics-card {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    border-radius: 12px;
    padding: 15px;
    color: white;
    text-align: center;
}
.prompt-preview {
    background-color: #f8f9fa;
    border: 2px dashed #dee2e6;
    border-radius: 8px;
    padding: 15px;
    font-family: monospace;
}
.feature-highlight {
    background: linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%);
    border-radius: 8px;
    padding: 10px;
    color: white;
    margin: 5px 0;
}
"""

with gr.Blocks(css=custom_css, title="Ultimate LLM Prompt Builder", theme=gr.themes.Soft()) as demo:
    
    # Header
    gr.Markdown("""
    # πŸš€ Ultimate LLM Prompt Builder v2.0
    
    **The most comprehensive prompt engineering tool** with templates, variables, A/B testing, analytics, and more!
    
    [![Features](https://img.shields.io/badge/Features-10/10-success)]() [![Templates](https://img.shields.io/badge/Templates-15+-blue)]() [![AI Models](https://img.shields.io/badge/Models-Multiple-orange)]()
    """)
    
    # Quick stats
    with gr.Row():
        with gr.Column(scale=1):
            analytics_display = gr.HTML(value="<div class='analytics-card'>πŸ“Š No usage data yet</div>")
        with gr.Column(scale=3):
            gr.Markdown("""
            **🎯 Quick Start:** Choose a template β†’ Customize variables β†’ Add instructions β†’ Generate!
            **πŸ’‘ Pro Tip:** Use the A/B testing feature to optimize your prompts for better results.
            """, elem_classes=["feature-highlight"])

    # Main interface
    with gr.Tabs() as main_tabs:
        
        # Template Library Tab
        with gr.TabItem("πŸ“š Template Library"):
            gr.Markdown("### Choose from professional prompt templates")
            
            with gr.Row():
                template_category = gr.Dropdown(
                    choices=list(PROMPT_TEMPLATES.keys()),
                    label="πŸ—‚οΈ Category",
                    value=list(PROMPT_TEMPLATES.keys())[0]
                )
                template_name = gr.Dropdown(
                    choices=list(PROMPT_TEMPLATES[list(PROMPT_TEMPLATES.keys())[0]].keys()),
                    label="πŸ“„ Template",
                    value=list(PROMPT_TEMPLATES[list(PROMPT_TEMPLATES.keys())[0]].keys())[0]
                )
            
            template_info = gr.Markdown(value="")
            
            # Variable inputs (dynamically generated)
            variables_section = gr.Column(visible=False)
            with variables_section:
                gr.Markdown("### πŸ”§ Customize Variables")
                variable_inputs = {}
                for i in range(10):  # Support up to 10 variables
                    variable_inputs[f"var_{i}"] = gr.Textbox(label="", visible=False)
        
        # Advanced Prompt Builder Tab  
        with gr.TabItem("βš™οΈ Advanced Builder"):
            with gr.Row():
                with gr.Column(scale=2):
                    gr.Markdown("### 🎭 Role & System Prompt")
                    role_persona = gr.Dropdown(
                        choices=list(ROLE_PERSONAS.keys()),
                        label="🎭 Role Persona",
                        value="Expert Consultant"
                    )
                    custom_system = gr.Textbox(
                        label="πŸ› οΈ Custom System Prompt",
                        placeholder="Override the role persona with a custom system prompt...",
                        lines=3
                    )
                    
                    gr.Markdown("### πŸ“ Main Prompt")
                    main_prompt = gr.Textbox(
                        label="✍️ Your Prompt",
                        placeholder="Enter your main prompt here...",
                        lines=6
                    )
                    
                    # Few-shot examples
                    gr.Markdown("### 🎯 Few-Shot Examples (Optional)")
                    with gr.Accordion("Add Examples", open=False):
                        example_1_input = gr.Textbox(label="Example 1 - Input", lines=2)
                        example_1_output = gr.Textbox(label="Example 1 - Output", lines=2)
                        example_2_input = gr.Textbox(label="Example 2 - Input", lines=2)
                        example_2_output = gr.Textbox(label="Example 2 - Output", lines=2)
                
                with gr.Column(scale=1):
                    gr.Markdown("### 🧠 Cognitive Instructions")
                    # Create individual components instead of a list
                    with gr.Accordion("πŸ“Œ Cognitive Techniques", open=False):
                        cognitive_techniques = gr.CheckboxGroup(
                            choices=ADVANCED_CATEGORIES["Cognitive Techniques"],
                            label="Cognitive Techniques",
                            value=[]
                        )
                    with gr.Accordion("πŸ“Œ Output Structure", open=False):
                        output_structure = gr.CheckboxGroup(
                            choices=ADVANCED_CATEGORIES["Output Structure"],
                            label="Output Structure",
                            value=[]
                        )
                    with gr.Accordion("πŸ“Œ Quality Assurance", open=False):
                        quality_assurance = gr.CheckboxGroup(
                            choices=ADVANCED_CATEGORIES["Quality Assurance"],
                            label="Quality Assurance",
                            value=[]
                        )
                    with gr.Accordion("πŸ“Œ Audience Adaptation", open=False):
                        audience_adaptation = gr.CheckboxGroup(
                            choices=ADVANCED_CATEGORIES["Audience Adaptation"],
                            label="Audience Adaptation",
                            value=[]
                        )
        
        # Style & Filtering Tab
        with gr.TabItem("🎨 Style & Filtering"):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### ✨ Response Style")
                    tone_style = gr.Dropdown(
                        choices=["Professional", "Conversational", "Academic", "Creative", "Technical", "Friendly"],
                        label="🎨 Tone",
                        value="Professional"
                    )
                    length_preference = gr.Dropdown(
                        choices=["Concise", "Moderate", "Detailed", "Comprehensive"],
                        label="πŸ“ Length",
                        value="Moderate"
                    )
                    format_preference = gr.Dropdown(
                        choices=["Paragraph", "Bullet Points", "Numbered List", "Mixed", "Custom"],
                        label="πŸ“‹ Format",
                        value="Mixed"
                    )
                
                with gr.Column():
                    gr.Markdown("### 🚫 Content Filtering")
                    banned_words = gr.Textbox(
                        label="🚫 Banned Words (comma-separated)",
                        value=",".join(DEFAULT_BANNED_WORDS[:10]),  # Show fewer by default
                        lines=3
                    )
                    banned_patterns = gr.Textbox(
                        label="πŸ” Banned Patterns (regex)",
                        value=",".join(DEFAULT_FILTER_PATTERNS),
                        lines=2
                    )
        
        # Multi-Model Testing Tab
        with gr.TabItem("πŸ”¬ A/B Testing"):
            gr.Markdown("### Compare responses across different models and prompts")
            
            with gr.Row():
                model_a = gr.Dropdown(choices=ALL_MODELS, label="πŸ€– Model A", value=ALL_MODELS[0])
                model_b = gr.Dropdown(choices=ALL_MODELS, label="πŸ€– Model B", value=ALL_MODELS[1] if len(ALL_MODELS) > 1 else ALL_MODELS[0])
            
            with gr.Row():
                prompt_a = gr.Textbox(label="πŸ“ Prompt A", lines=4)
                prompt_b = gr.Textbox(label="πŸ“ Prompt B", lines=4)
            
            test_btn = gr.Button("πŸš€ Run A/B Test", variant="primary", size="lg")
            
            with gr.Row():
                response_a = gr.Textbox(label="Response A", lines=8, interactive=False)
                response_b = gr.Textbox(label="Response B", lines=8, interactive=False)
            
            with gr.Row():
                rating_a = gr.Slider(minimum=1, maximum=5, step=1, label="Rate Response A", value=3)
                rating_b = gr.Slider(minimum=1, maximum=5, step=1, label="Rate Response B", value=3)
        
        # Chat Interface Tab
        with gr.TabItem("πŸ’¬ Smart Chat"):
            with gr.Row():
                with gr.Column(scale=2):
                    selected_model = gr.Dropdown(
                        choices=ALL_MODELS,
                        label="πŸ€– Model",
                        value=ALL_MODELS[0]
                    )
                    temperature = gr.Slider(
                        minimum=0.0,
                        maximum=2.0,
                        step=0.1,
                        value=0.7,
                        label="🌑️ Temperature (creativity)"
                    )
                
                with gr.Column(scale=1):
                    optimization_display = gr.Textbox(
                        label="πŸ’‘ Prompt Optimization",
                        lines=4,
                        interactive=False
                    )
            
            chat_input = gr.Textbox(
                label="✍️ Your Message",
                placeholder="Ask anything or use variables like {topic}, {style}...",
                lines=3
            )
            
            with gr.Row():
                send_btn = gr.Button("πŸš€ Send", variant="primary", size="lg")
                clear_chat_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
                save_prompt_btn = gr.Button("πŸ’Ύ Save Prompt", variant="secondary")
            
            save_status = gr.Textbox(label="πŸ’Ύ Save Status", visible=False, interactive=False)
            
            chatbot = gr.Chatbot(
                label="πŸ€– AI Assistant",
                type="messages",
                height=500,
                show_copy_button=True
            )
            
            # Prompt preview and stats
            with gr.Row():
                final_prompt_preview = gr.Textbox(
                    label="πŸ‘€ Final Prompt Preview",
                    lines=5,
                    interactive=False
                )
                prompt_stats = gr.JSON(
                    label="πŸ“Š Prompt Statistics",
                    value={}
                )
        
        # Saved Prompts & Analytics Tab
        with gr.TabItem("πŸ“Š Analytics & Library"):
            with gr.Row():
                with gr.Column():
                    gr.Markdown("### πŸ’Ύ Saved Prompts")
                    saved_prompts_list = gr.Dropdown(
                        choices=[],
                        label="πŸ“š Select Saved Prompt",
                        allow_custom_value=False
                    )
                    
                    with gr.Row():
                        load_prompt_btn = gr.Button("πŸ“₯ Load Prompt")
                        delete_prompt_btn = gr.Button("πŸ—‘οΈ Delete", variant="stop")
                    
                    saved_prompt_display = gr.JSON(label="πŸ“„ Prompt Details", value={})
                
                with gr.Column():
                    gr.Markdown("### πŸ“ˆ Usage Analytics")
                    refresh_analytics_btn = gr.Button("πŸ”„ Refresh Analytics")
                    analytics_json = gr.JSON(label="πŸ“Š Statistics", value={})
                    
                    gr.Markdown("### πŸ“€ Export/Import")
                    with gr.Row():
                        export_btn = gr.Button("πŸ“€ Export Data")
                        import_file = gr.File(label="πŸ“₯ Import Data", file_types=[".json"])
                    
                    export_data_display = gr.Textbox(
                        label="πŸ“‹ Export Data (Copy this)",
                        lines=8,
                        interactive=False
                    )
                    
                    import_status = gr.Textbox(
                        label="πŸ“₯ Import Status",
                        interactive=False
                    )

    # State management
    chat_history = gr.State([])

    # Helper functions
    def update_template_info(category, template_name):
        """Update template information display safely"""
        try:
            if category in PROMPT_TEMPLATES and template_name in PROMPT_TEMPLATES[category]:
                template = PROMPT_TEMPLATES[category][template_name]
                info = f"**{template['description']}**\n\n"
                info += f"**System:** {template['system']}\n\n"
                info += f"**Template:** {template['template']}\n\n"
                if template.get('variables'):
                    info += f"**Variables:** {', '.join(template['variables'])}"
                return info
        except Exception as e:
            return f"Error loading template: {str(e)}"
        return "Select a template to see details"

    def update_template_dropdown(category):
        """Update template dropdown safely"""
        try:
            if category in PROMPT_TEMPLATES:
                choices = list(PROMPT_TEMPLATES[category].keys())
                return gr.update(choices=choices, value=choices[0] if choices else None)
        except Exception:
            pass
        return gr.update(choices=[], value=None)

    def show_template_variables(category, template_name):
        """Show template variables safely"""
        try:
            if category in PROMPT_TEMPLATES and template_name in PROMPT_TEMPLATES[category]:
                template = PROMPT_TEMPLATES[category][template_name]
                variables = template.get('variables', [])
                
                updates = []
                visible_count = 0
                
                for i in range(10):
                    if i < len(variables):
                        var_name = variables[i].replace('_', ' ').title()
                        updates.append(gr.update(visible=True, label=f"πŸ“ {var_name}"))
                        visible_count += 1
                    else:
                        updates.append(gr.update(visible=False))
                
                section_visible = visible_count > 0
                return [gr.update(visible=section_visible)] + updates
        except Exception:
            pass
        
        return [gr.update(visible=False)] + [gr.update(visible=False) for _ in range(10)]

    def build_prompt_from_template(category, template_name, *var_values):
        if category in PROMPT_TEMPLATES and template_name in PROMPT_TEMPLATES[category]:
            template = PROMPT_TEMPLATES[category][template_name]
            variables = template.get('variables', [])
            
            # Create variable dictionary
            var_dict = {}
            for i, var in enumerate(variables):
                if i < len(var_values) and var_values[i]:
                    var_dict[var] = var_values[i]
            
            # Build prompt
            system = template['system']
            main_prompt = substitute_variables(template['template'], var_dict)
            
            return system, main_prompt, var_dict
        
        return "", "", {}

    def create_final_prompt(system, main_prompt, cognitive_tech, output_struct, quality_assur, audience_adapt, examples, tone, length, format_pref, role_persona, custom_system):
        components = []
        
        # System prompt
        if custom_system.strip():
            components.append(f"System: {custom_system.strip()}")
        elif system.strip():
            components.append(f"System: {system}")
        elif role_persona in ROLE_PERSONAS:
            components.append(f"System: {ROLE_PERSONAS[role_persona]}")
        
        # Add cognitive instructions
        all_selected = []
        for selected_list in [cognitive_tech, output_struct, quality_assur, audience_adapt]:
            if selected_list:
                all_selected.extend(selected_list)
        
        if all_selected:
            components.append("Instructions:")
            for i, instruction in enumerate(all_selected, 1):
                components.append(f"{i}. {instruction}")
        
        # Add style preferences
        style_instructions = []
        if tone != "Professional":
            style_instructions.append(f"Tone: {tone}")
        if length != "Moderate":
            style_instructions.append(f"Length: {length}")
        if format_pref != "Mixed":
            style_instructions.append(f"Format: {format_pref}")
        
        if style_instructions:
            components.append("Style: " + ", ".join(style_instructions))
        
        # Add examples if provided
        if examples and any(examples):
            components.append("Examples:")
            for i in range(0, len(examples), 2):
                if i+1 < len(examples) and examples[i] and examples[i+1]:
                    components.append(f"Input: {examples[i]}")
                    components.append(f"Output: {examples[i+1]}")
        
        # Main prompt
        components.append(f"Task: {main_prompt}")
        
        return "\n\n".join(components)

    def process_chat_message(message, history, model, temp, system, cognitive_tech, output_struct, quality_assur, audience_adapt, tone, length, format_pref, role, custom_sys, banned_w, banned_p, *examples):
        """Process chat message with comprehensive error handling"""
        try:
            if not message.strip():
                return history or [], history or [], "", {}, ""
            
            # Create final prompt
            final_prompt = create_final_prompt(
                system, message, cognitive_tech or [], output_struct or [], 
                quality_assur or [], audience_adapt or [], examples, 
                tone, length, format_pref, role, custom_sys
            )
            
            # Get optimization suggestions
            optimization = optimize_prompt(final_prompt)
            
            # Make API call
            response, error, tokens = make_api_call(model, final_prompt, temp)
            
            if error:
                return history or [], history or [], final_prompt, {"error": error}, optimization
            
            # Filter response
            banned_words_list = [w.strip() for w in (banned_w or "").split(",") if w.strip()]
            banned_patterns_input = [p.strip() for p in (banned_p or "").split(",") if p.strip()]
            banned_patterns_list, _ = validate_regex_patterns(banned_patterns_input)
            
            filtered_response = smart_filter_text(response, banned_words_list, banned_patterns_list)
            
            # Log analytics
            state.log_usage(final_prompt, filtered_response, model, tokens)
            
            # Update history
            if history is None:
                history = []
            
            new_history = history + [
                {"role": "user", "content": message},
                {"role": "assistant", "content": filtered_response}
            ]
            
            # Stats
            stats = {
                "tokens": tokens,
                "model": model,
                "temperature": temp,
                "prompt_length": len(final_prompt),
                "response_length": len(filtered_response)
            }
            
            return new_history, new_history, final_prompt, stats, optimization
            
        except Exception as e:
            error_msg = f"Processing error: {str(e)}"
            return history or [], history or [], "", {"error": error_msg}, error_msg

    def run_ab_test(model_a, model_b, prompt_a, prompt_b):
        """Run A/B test with error handling"""
        try:
            if not prompt_a.strip() or not prompt_b.strip():
                return "⚠️ Please enter both prompts", "⚠️ Please enter both prompts"
            
            response_a, error_a, tokens_a = make_api_call(model_a, prompt_a)
            response_b, error_b, tokens_b = make_api_call(model_b, prompt_b)
            
            if error_a:
                response_a = f"❌ Error: {error_a}"
            if error_b:
                response_b = f"❌ Error: {error_b}"
            
            return response_a, response_b
            
        except Exception as e:
            error_msg = f"❌ A/B Test Error: {str(e)}"
            return error_msg, error_msg

    def save_current_prompt(final_prompt, model, stats):
        # Simple prompt saving - in a real app you'd want a name input
        prompt_name = f"Prompt_{len(state.saved_prompts)+1}_{datetime.now().strftime('%H%M')}"
        
        if not final_prompt:
            return gr.update(value="❌ No prompt to save", visible=True)
        
        prompt_data = {
            "prompt": final_prompt,
            "model": model,
            "stats": stats
        }
        
        state.save_prompt(prompt_name, prompt_data)
        
        return gr.update(value=f"βœ… Saved as '{prompt_name}'", visible=True)

    def load_saved_prompt(prompt_name):
        if prompt_name in state.saved_prompts:
            return state.saved_prompts[prompt_name]
        return {}
    
    def delete_saved_prompt(prompt_name):
        if prompt_name in state.saved_prompts:
            del state.saved_prompts[prompt_name]
            choices = list(state.saved_prompts.keys())
            return gr.update(choices=choices, value=None), {}
        return gr.update(), {}
    
    def update_saved_prompts_dropdown():
        choices = list(state.saved_prompts.keys())
        return gr.update(choices=choices)

    def refresh_analytics():
        """Refresh analytics with error handling"""
        try:
            analytics = calculate_analytics()
            
            # Update analytics display
            if analytics:
                html = f"""
                <div class='analytics-card'>
                    <h3>πŸ“Š Usage Statistics</h3>
                    <p><strong>{analytics['total_prompts']}</strong> prompts generated</p>
                    <p><strong>{analytics['avg_tokens']}</strong> avg tokens per prompt</p>
                    <p><strong>{analytics['avg_rating']}/5</strong> avg rating</p>
                    <p><strong>{analytics['models_used']}</strong> different models used</p>
                </div>
                """
            else:
                html = "<div class='analytics-card'>πŸ“Š No usage data yet</div>"
            
            return html, analytics
            
        except Exception as e:
            error_html = f"<div class='analytics-card'>❌ Analytics Error: {str(e)}</div>"
            return error_html, {}

    def export_data():
        """Export data with error handling"""
        try:
            export = {
                "saved_prompts": state.saved_prompts,
                "analytics": state.analytics,
                "export_date": datetime.now().isoformat()
            }
            return json.dumps(export, indent=2)
        except Exception as e:
            return f'{{"error": "Export failed: {str(e)}"}}'

    def import_data_handler(file):
        """Handle file import with proper error handling"""
        if file is None:
            return "❌ No file selected"
        
        try:
            # Read file content
            if hasattr(file, 'read'):
                content = file.read()
                if isinstance(content, bytes):
                    content = content.decode('utf-8')
            else:
                # If file is a path string
                with open(file, 'r', encoding='utf-8') as f:
                    content = f.read()
            
            data = json.loads(content)
            
            if "saved_prompts" in data:
                state.saved_prompts.update(data["saved_prompts"])
            if "analytics" in data:
                state.analytics.extend(data["analytics"])
            
            return "βœ… Data imported successfully"
        except Exception as e:
            return f"❌ Import failed: {str(e)}"

    # Wire up all the interactions
    
    # Template system
    template_category.change(
        update_template_dropdown,
        inputs=[template_category],
        outputs=[template_name]
    )
    
    template_category.change(
        update_template_info,
        inputs=[template_category, template_name],
        outputs=[template_info]
    )
    
    template_name.change(
        update_template_info,
        inputs=[template_category, template_name],
        outputs=[template_info]
    )
    
    template_name.change(
        show_template_variables,
        inputs=[template_category, template_name],
        outputs=[variables_section] + [variable_inputs[f"var_{i}"] for i in range(10)]
    )
    
    # Chat interface
    send_btn.click(
        process_chat_message,
        inputs=[
            chat_input, chat_history, selected_model, temperature,
            custom_system, cognitive_techniques, output_structure, quality_assurance, audience_adaptation,
            tone_style, length_preference, format_preference, role_persona, custom_system, banned_words, banned_patterns,
            example_1_input, example_1_output, example_2_input, example_2_output
        ],
        outputs=[chatbot, chat_history, final_prompt_preview, prompt_stats, optimization_display]
    )
    
    def clear_chat_handler():
        """Clear chat history safely"""
        return [], []
    
    clear_chat_btn.click(
        clear_chat_handler,
        outputs=[chatbot, chat_history]
    )
    
    save_prompt_btn.click(
        save_current_prompt,
        inputs=[final_prompt_preview, selected_model, prompt_stats],
        outputs=[save_status]
    )
    
    # A/B Testing
    test_btn.click(
        run_ab_test,
        inputs=[model_a, model_b, prompt_a, prompt_b],
        outputs=[response_a, response_b]
    )
    
    # Analytics
    refresh_analytics_btn.click(
        refresh_analytics,
        outputs=[analytics_display, analytics_json]
    )
    
    # Export/Import
    export_btn.click(
        export_data,
        outputs=[export_data_display]
    )
    
    # Load and delete saved prompts
    load_prompt_btn.click(
        load_saved_prompt,
        inputs=[saved_prompts_list],
        outputs=[saved_prompt_display]
    )
    
    delete_prompt_btn.click(
        delete_saved_prompt,
        inputs=[saved_prompts_list],
        outputs=[saved_prompts_list, saved_prompt_display]
    )
    
    # Import functionality
    import_file.upload(
        import_data_handler,
        inputs=[import_file],
        outputs=[import_status]
    )
    
    def refresh_all_on_load():
        """Helper function to refresh analytics and update dropdowns on load"""
        try:
            analytics_html, analytics_data = refresh_analytics()
            saved_choices = list(state.saved_prompts.keys())
            return analytics_html, analytics_data, gr.update(choices=saved_choices)
        except Exception as e:
            error_html = f"<div class='analytics-card'>❌ Load Error: {str(e)}</div>"
            return error_html, {}, gr.update(choices=[])
    
    # Auto-refresh analytics on load and update saved prompts
    demo.load(
        refresh_all_on_load,
        outputs=[analytics_display, analytics_json, saved_prompts_list]
    )

if __name__ == "__main__":
    demo.launch(share=False, debug=True, show_api=False)