-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathprompt_journey.py
More file actions
1803 lines (1511 loc) Β· 70.8 KB
/
prompt_journey.py
File metadata and controls
1803 lines (1511 loc) Β· 70.8 KB
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
#!/usr/bin/env python3
"""
Prompt Management Journey: Building an AI-Powered Customer Service System
This comprehensive example demonstrates all 8 Prompt Management APIs through a narrative
of building an AI-powered customer service system for an e-commerce platform.
Journey Overview:
1. Initial Setup - Creating basic prompt templates
2. Template Organization - Using tags to categorize prompts
3. Testing and Refinement - Testing prompts with different parameters
3.5. Version Management - Creating and managing multiple versions
4. Production Deployment - Managing production-ready prompts
5. Multi-language Support - Creating localized prompt versions
6. Performance Optimization - Testing different models and parameters
7. Compliance and Audit - Tag-based compliance tracking
8. Cleanup and Migration - Managing prompt lifecycle
API Coverage (8 APIs):
β
save_prompt() - Create or update prompt templates (with version, models, auto_increment)
β
get_prompt() - Retrieve specific prompt template
β
get_prompts() - Get all prompt templates
β
delete_prompt() - Delete prompt template
β
get_tags_for_prompt_template() - Get tags for a prompt
β
update_tag_for_prompt_template() - Set/update tags on a prompt
β
delete_tag_for_prompt_template() - Remove tags from a prompt
β
test_prompt() - Test prompt with variables and AI model
Requirements:
- Conductor server with AI integration configured
- Python SDK installed: pip install conductor-python
- Valid authentication credentials
"""
import os
import sys
import time
import json
import random
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Any
from dataclasses import dataclass
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from conductor.client.configuration.configuration import Configuration
from conductor.client.configuration.settings.authentication_settings import AuthenticationSettings
from conductor.client.orkes.orkes_prompt_client import OrkesPromptClient
from conductor.client.orkes.orkes_integration_client import OrkesIntegrationClient
from conductor.client.orkes.models.metadata_tag import MetadataTag
from conductor.client.http.models.prompt_template import PromptTemplate
from conductor.client.http.models.integration_update import IntegrationUpdate
from conductor.client.http.models.integration_api_update import IntegrationApiUpdate
class PromptJourney:
"""
A comprehensive journey through all Prompt Management APIs.
Building an AI-powered customer service system for TechMart.
"""
def __init__(self):
"""Initialize the prompt client with configuration."""
# Get configuration from environment or use defaults
server_url = os.getenv('CONDUCTOR_SERVER_URL', 'http://localhost:8080/api')
key_id = os.getenv('CONDUCTOR_AUTH_KEY', None)
key_secret = os.getenv('CONDUCTOR_AUTH_SECRET', None)
# Configure the client
self.configuration = Configuration(
server_api_url=server_url,
debug=True
)
# Add authentication if credentials are provided
if key_id and key_secret:
self.configuration.authentication_settings = AuthenticationSettings(
key_id=key_id,
key_secret=key_secret
)
# Initialize the clients
self.prompt_client = OrkesPromptClient(self.configuration)
self.integration_client = OrkesIntegrationClient(self.configuration)
# Track created resources for cleanup
self.created_prompts = []
self.created_integrations = []
# AI integration name (configure based on your setup)
self.ai_integration = os.getenv('AI_INTEGRATION', 'openai')
def setup_integrations(self):
"""Set up AI integrations before using prompts."""
print("\n" + "="*60)
print(" INTEGRATION SETUP")
print("="*60)
print("\nSetting up AI integrations for prompt management...")
integration_ready = False
try:
# Check if the integration already exists
existing = self.integration_client.get_integration('openai')
integration_exists = existing is not None
if integration_exists:
print(f"β
Integration 'openai' already exists")
print(" Will ensure all required models are configured...")
integration_ready = True
else:
# Create OpenAI integration
print("\nπ Creating OpenAI integration...")
# Get API key from environment or use a placeholder
openai_key = os.getenv('OPENAI_API_KEY', 'sk-your-openai-key-here')
try:
# Create IntegrationUpdate using model class properly
integration_details = IntegrationUpdate(
type='openai',
category='AI_MODEL',
description='OpenAI GPT models for prompt templates',
enabled=True,
configuration={
'api_key': openai_key, # Use 'api_key' not 'apiKey' - must match ConfigKey enum
'endpoint': 'https://api.openai.com/v1'
}
)
self.integration_client.save_integration('openai', integration_details)
self.created_integrations.append('openai')
print("β
Created OpenAI integration")
# Verify it was created
verify = self.integration_client.get_integration('openai')
if verify:
integration_ready = True
else:
print("β οΈ Integration creation may have failed, verification returned None")
except Exception as create_error:
print(f"β Failed to create integration: {create_error}")
integration_ready = False
# Only configure models if we have a working integration
if not integration_ready:
print("\nβ οΈ Integration not ready. Skipping model configuration.")
print("Please ensure the integration 'openai' exists before proceeding.")
return
# ALWAYS configure models when integration is ready
print("\nπ Configuring required AI models...")
# Define all models we want to ensure are configured
models = [
{
'name': 'gpt-4o',
'description': 'GPT-4 Optimized - Latest and fastest model with 128K context',
'max_tokens': 128000
},
{
'name': 'gpt-4',
'description': 'GPT-4 - Most capable model for complex tasks',
'max_tokens': 8192
},
{
'name': 'gpt-3.5-turbo',
'description': 'GPT-3.5 Turbo - Fast and efficient for simple tasks',
'max_tokens': 16384
},
{
'name': 'gpt-4-turbo',
'description': 'GPT-4 Turbo - Faster GPT-4 with 128K context',
'max_tokens': 128000
}
]
# Add or update model configurations using proper model classes
for model in models:
try:
# Check if model already exists
existing_api = self.integration_client.get_integration_api(model['name'], 'openai')
# Create IntegrationApiUpdate object without invalid configuration keys
# The model name is passed as the API name parameter, not in configuration
api_details = IntegrationApiUpdate(
description=model['description'],
enabled=True,
max_tokens=model['max_tokens']
# Configuration should be None or contain only valid ConfigKey values
# Valid keys are: api_key, endpoint, environment, etc. NOT 'model'
)
self.integration_client.save_integration_api('openai', model['name'], api_details)
if existing_api:
print(f" β
Updated model: {model['name']}")
else:
print(f" β
Added model: {model['name']}")
except Exception as e:
print(f" β οΈ Error with model {model['name']}: {str(e)}")
# Verify the integration setup
print("\nπ Verifying integration setup...")
try:
# Get the integration details
integration = self.integration_client.get_integration('openai')
if integration:
print(f" β Integration 'openai' is active")
# List all configured models
apis = self.integration_client.get_integration_apis('openai')
if apis:
print(f" β Configured models ({len(apis)} total):")
for api in apis:
status = "enabled" if api.enabled else "disabled"
print(f" - {api.name}: {status}")
else:
print(" β οΈ No models configured yet")
except Exception as e:
print(f" β οΈ Could not verify integration: {str(e)}")
# Tag the integration and models for better organization
self.tag_integrations()
print("\nβ
Integration setup complete!")
except Exception as e:
print(f"\nβ οΈ Integration setup error: {e}")
print("Attempting to continue with existing integrations...")
# Try to list what integrations are available
try:
integrations = self.integration_client.get_integrations()
if integrations:
print("\nAvailable integrations:")
for integration in integrations:
print(f" - {integration.name}: {integration.type}")
else:
print("\nβ οΈ No integrations found. Prompts may not work with AI models.")
except Exception as list_error:
print(f"Could not list integrations: {list_error}")
def tag_integrations(self):
"""Tag integrations and models for better organization and tracking."""
print("\nπ·οΈ Tagging integrations for organization...")
try:
# Tag the main integration provider
integration_tags = [
MetadataTag("provider", "openai"),
MetadataTag("category", "ai_model"),
MetadataTag("environment", "production"),
MetadataTag("team", "ai_platform"),
MetadataTag("cost_center", "engineering"),
MetadataTag("created_date", datetime.now().strftime("%Y-%m-%d")),
MetadataTag("purpose", "prompt_management"),
MetadataTag("status", "active")
]
try:
self.integration_client.put_tag_for_integration_provider(integration_tags, 'openai')
print(" β
Tagged integration provider 'openai'")
# Verify tags were applied
provider_tags = self.integration_client.get_tags_for_integration_provider('openai')
if provider_tags:
print(f" Applied {len(provider_tags)} tags to integration")
except Exception as e:
print(f" β οΈ Could not tag integration provider: {str(e)[:50]}")
# Tag individual models with their characteristics
model_tags = {
'gpt-4o': [
MetadataTag("model_type", "optimized"),
MetadataTag("context_window", "128k"),
MetadataTag("performance", "fastest"),
MetadataTag("cost_tier", "premium"),
MetadataTag("use_case", "high_volume"),
MetadataTag("capabilities", "advanced"),
MetadataTag("release_date", "2024")
],
'gpt-4': [
MetadataTag("model_type", "standard"),
MetadataTag("context_window", "8k"),
MetadataTag("performance", "balanced"),
MetadataTag("cost_tier", "premium"),
MetadataTag("use_case", "complex_reasoning"),
MetadataTag("capabilities", "maximum"),
MetadataTag("release_date", "2023")
],
'gpt-3.5-turbo': [
MetadataTag("model_type", "turbo"),
MetadataTag("context_window", "16k"),
MetadataTag("performance", "fast"),
MetadataTag("cost_tier", "economy"),
MetadataTag("use_case", "simple_tasks"),
MetadataTag("capabilities", "standard"),
MetadataTag("release_date", "2022")
],
'gpt-4-turbo': [
MetadataTag("model_type", "turbo"),
MetadataTag("context_window", "128k"),
MetadataTag("performance", "fast"),
MetadataTag("cost_tier", "mid_tier"),
MetadataTag("use_case", "balanced"),
MetadataTag("capabilities", "advanced"),
MetadataTag("release_date", "2024")
]
}
print("\n π Tagging individual models...")
for model_name, tags in model_tags.items():
try:
# Check if model exists before tagging
model_api = self.integration_client.get_integration_api(model_name, 'openai')
if model_api:
self.integration_client.put_tag_for_integration(tags, model_name, 'openai')
print(f" β
Tagged model: {model_name} ({len(tags)} tags)")
# Verify tags
applied_tags = self.integration_client.get_tags_for_integration(model_name, 'openai')
if applied_tags:
# Show a sample of tags
sample_tags = applied_tags[:3] if len(applied_tags) > 3 else applied_tags
tag_str = ', '.join([f"{t.key}={t.value}" for t in sample_tags])
if len(applied_tags) > 3:
tag_str += f" ... +{len(applied_tags)-3} more"
print(f" Tags: {tag_str}")
except Exception as e:
# Model might not be configured yet
print(f" β οΈ Could not tag {model_name}: {str(e)[:50]}")
print("\n π Tag Summary:")
print(f" β’ Integration provider tagged with {len(integration_tags)} tags")
print(f" β’ {len(model_tags)} models tagged for tracking")
print(" β’ Tags enable filtering, reporting, and cost allocation")
except Exception as e:
print(f"\nβ οΈ Tagging error: {e}")
print("Integration will work but won't have organizational tags")
def associate_prompts_with_models(self):
"""Associate prompts with specific AI models using the integration client."""
print("\n" + "="*60)
print(" MODEL ASSOCIATIONS")
print("="*60)
print("\nAssociating prompts with optimal AI models...")
try:
# Define prompt-to-model associations based on use case
associations = [
{
'prompt': 'customer_greeting',
'model': 'gpt-3.5-turbo',
'reason': 'Simple greetings work well with faster, lighter models'
},
{
'prompt': 'order_inquiry',
'model': 'gpt-4o',
'reason': 'Order lookups need accuracy and speed'
},
{
'prompt': 'complaint_handling',
'model': 'gpt-4',
'reason': 'Complex complaints need the most capable model'
},
{
'prompt': 'faq_response',
'model': 'gpt-3.5-turbo',
'reason': 'FAQs are straightforward and benefit from speed'
},
{
'prompt': 'product_recommendation',
'model': 'gpt-4o',
'reason': 'Recommendations need both intelligence and speed'
},
{
'prompt': 'refund_process',
'model': 'gpt-4',
'reason': 'Financial operations require maximum accuracy'
}
]
print("\nπ Creating prompt-model associations...")
successful_associations = 0
for assoc in associations:
try:
# Associate the prompt with the model
self.integration_client.associate_prompt_with_integration(
ai_integration='openai',
model_name=assoc['model'],
prompt_name=assoc['prompt']
)
successful_associations += 1
print(f" β
{assoc['prompt']} β openai:{assoc['model']}")
print(f" Reason: {assoc['reason']}")
except Exception as e:
# Some prompts might not exist yet, which is okay
print(f" β οΈ Could not associate {assoc['prompt']}: {str(e)[:50]}")
print(f"\nβ
Successfully created {successful_associations} associations")
# List prompts associated with each model
print("\nπ Verifying model associations...")
models_to_check = ['gpt-4o', 'gpt-4', 'gpt-3.5-turbo']
for model in models_to_check:
try:
prompts = self.integration_client.get_prompts_with_integration('openai', model)
if prompts:
print(f"\n Model: openai:{model}")
print(f" Associated prompts ({len(prompts)}):")
for prompt in prompts[:5]: # Show first 5
print(f" - {prompt.name}")
if len(prompts) > 5:
print(f" ... and {len(prompts) - 5} more")
except Exception as e:
print(f" β οΈ Could not list prompts for {model}: {str(e)[:50]}")
except Exception as e:
print(f"\nβ οΈ Association setup error: {e}")
print("Prompts will still work but may not be optimized for specific models")
def track_token_usage(self):
"""Track and display token usage across integrations and models."""
print("\n" + "="*60)
print(" TOKEN USAGE TRACKING")
print("="*60)
print("\nMonitoring token usage for cost optimization...")
try:
# Get token usage for the integration provider
print("\nπ Token Usage by Integration:")
try:
usage = self.integration_client.get_token_usage_for_integration_provider('openai')
if usage:
print(f" OpenAI Integration:")
for key, value in usage.items():
print(f" {key}: {value}")
else:
print(" No token usage data available yet")
except Exception as e:
print(f" β οΈ Could not retrieve provider usage: {str(e)[:50]}")
# Get token usage for specific models
print("\nπ Token Usage by Model:")
models = ['gpt-4o', 'gpt-4', 'gpt-3.5-turbo']
for model in models:
try:
usage = self.integration_client.get_token_usage_for_integration(model, 'openai')
if usage:
print(f" {model}: {usage:,} tokens")
else:
print(f" {model}: No usage data")
except Exception as e:
print(f" {model}: Data not available")
# Calculate estimated costs (example rates)
print("\nπ° Estimated Costs (example rates):")
cost_per_1k_tokens = {
'gpt-4o': {'input': 0.01, 'output': 0.03},
'gpt-4': {'input': 0.03, 'output': 0.06},
'gpt-3.5-turbo': {'input': 0.001, 'output': 0.002}
}
print(" Model costs per 1K tokens:")
for model, rates in cost_per_1k_tokens.items():
print(f" {model}:")
print(f" Input: ${rates['input']:.3f}")
print(f" Output: ${rates['output']:.3f}")
except Exception as e:
print(f"\nβ οΈ Token tracking error: {e}")
print("Token usage tracking may not be available")
def display_prompt(self, prompt: PromptTemplate, title: str = "Prompt Template"):
"""Helper method to display prompt details."""
print(f"\n{title}:")
print(f" Name: {prompt.name}")
print(f" Description: {prompt.description}")
print(f" Variables: {prompt.variables}")
if prompt.tags:
print(" Tags:")
for tag in prompt.tags:
print(f" - {tag.key}: {tag.value}")
print(f" Created by: {prompt.created_by}")
print(f" Updated on: {datetime.fromtimestamp(prompt.updated_on/1000) if prompt.updated_on else 'N/A'}")
def display_tags(self, tags: List[MetadataTag], title: str = "Tags"):
"""Helper method to display tags."""
if tags:
print(f"\n{title} ({len(tags)} tags):")
for tag in tags:
print(f" π·οΈ {tag.key}: {tag.value}")
else:
print(f"\n{title}: No tags found")
def run(self):
"""Execute the complete prompt management journey."""
print("\n" + "="*80)
print(" PROMPT MANAGEMENT JOURNEY: AI-POWERED CUSTOMER SERVICE")
print("="*80)
print("\nWelcome to TechMart's journey to build an AI-powered customer service system!")
print("We'll explore all 8 Prompt Management APIs through real-world scenarios.")
try:
# Set up integrations first
self.setup_integrations()
# Then proceed with prompt management
self.chapter1_initial_setup()
self.chapter2_template_organization()
self.chapter3_testing_refinement()
self.chapter3_5_version_management()
self.chapter4_production_deployment()
# Associate prompts with optimal models
self.associate_prompts_with_models()
self.chapter5_multilanguage_support()
self.chapter6_performance_optimization()
# Track token usage for cost monitoring
self.track_token_usage()
self.chapter7_compliance_audit()
self.chapter8_cleanup_migration()
print("\n" + "="*80)
print(" JOURNEY COMPLETED SUCCESSFULLY!")
print("="*80)
print("\nCongratulations! You've successfully explored all Prompt Management APIs.")
print("Your AI-powered customer service system is ready for production!")
except Exception as e:
print(f"\nβ Journey failed: {str(e)}")
import traceback
traceback.print_exc()
finally:
self.cleanup()
def chapter1_initial_setup(self):
"""Chapter 1: Initial Setup - Creating Basic Prompt Templates"""
print("\n" + "="*60)
print(" CHAPTER 1: INITIAL SETUP")
print("="*60)
print("\nTechMart is launching AI-powered customer service.")
print("Let's create our first prompt templates...")
# API 1: save_prompt() - Create greeting prompt
print("\nπ Creating customer greeting prompt...")
greeting_prompt = """You are a friendly customer service representative for TechMart.
Customer Name: ${customer_name}
Customer Tier: ${customer_tier}
Time of Day: ${time_of_day}
Greet the customer appropriately based on their tier and the time of day.
Keep the greeting warm, professional, and under 50 words."""
self.prompt_client.save_prompt(
prompt_name="customer_greeting",
description="Personalized greeting for customers based on tier and time",
prompt_template=greeting_prompt
)
self.created_prompts.append("customer_greeting")
print("β
Created 'customer_greeting' prompt")
# API 2: get_prompt() - Retrieve the created prompt
print("\nπ Retrieving the greeting prompt to verify...")
retrieved_prompt = self.prompt_client.get_prompt("customer_greeting")
if retrieved_prompt:
self.display_prompt(retrieved_prompt, "Retrieved Greeting Prompt")
# Create order inquiry prompt
print("\nπ Creating order inquiry prompt...")
order_prompt = """You are a helpful customer service agent for TechMart.
Customer Information:
- Name: ${customer_name}
- Order ID: ${order_id}
- Order Status: ${order_status}
- Delivery Date: ${delivery_date}
Customer Query: ${query}
Provide a clear, empathetic response about their order.
Include relevant details and next steps if applicable."""
self.prompt_client.save_prompt(
prompt_name="order_inquiry",
description="Handle customer inquiries about order status",
prompt_template=order_prompt
)
self.created_prompts.append("order_inquiry")
print("β
Created 'order_inquiry' prompt")
# Create return request prompt
print("\nπ Creating return request prompt...")
return_prompt = """You are processing a return request for TechMart.
Product: ${product_name}
Purchase Date: ${purchase_date}
Reason: ${return_reason}
Condition: ${product_condition}
Return Policy: Items can be returned within 30 days in original condition.
Evaluate the return request and provide:
1. Whether the return is eligible
2. Next steps for the customer
3. Expected timeline
Be helpful and understanding while following company policy."""
self.prompt_client.save_prompt(
prompt_name="return_request",
description="Process and respond to product return requests",
prompt_template=return_prompt
)
self.created_prompts.append("return_request")
print("β
Created 'return_request' prompt")
print("\n⨠Chapter 1 Complete: Basic prompts created!")
def chapter2_template_organization(self):
"""Chapter 2: Template Organization - Using Tags to Categorize Prompts"""
print("\n" + "="*60)
print(" CHAPTER 2: TEMPLATE ORGANIZATION")
print("="*60)
print("\nOrganizing prompts with tags for better management...")
# API 5: update_tag_for_prompt_template() - Add tags to greeting prompt
print("\nπ·οΈ Adding tags to customer greeting prompt...")
greeting_tags = [
MetadataTag("category", "customer_service"),
MetadataTag("type", "greeting"),
MetadataTag("department", "support"),
MetadataTag("language", "english"),
MetadataTag("status", "active"),
MetadataTag("priority", "high")
]
self.prompt_client.update_tag_for_prompt_template(
"customer_greeting",
greeting_tags
)
print("β
Tags added to greeting prompt")
# API 6: get_tags_for_prompt_template() - Verify tags
print("\nπ Retrieving tags for greeting prompt...")
retrieved_tags = self.prompt_client.get_tags_for_prompt_template("customer_greeting")
self.display_tags(retrieved_tags, "Greeting Prompt Tags")
# Add tags to order inquiry prompt
print("\nπ·οΈ Adding tags to order inquiry prompt...")
order_tags = [
MetadataTag("category", "customer_service"),
MetadataTag("type", "inquiry"),
MetadataTag("department", "support"),
MetadataTag("language", "english"),
MetadataTag("status", "active"),
MetadataTag("priority", "high"),
MetadataTag("integration", "order_system")
]
self.prompt_client.update_tag_for_prompt_template(
"order_inquiry",
order_tags
)
print("β
Tags added to order inquiry prompt")
# Add tags to return request prompt
print("\nπ·οΈ Adding tags to return request prompt...")
return_tags = [
MetadataTag("category", "customer_service"),
MetadataTag("type", "returns"),
MetadataTag("department", "support"),
MetadataTag("language", "english"),
MetadataTag("status", "testing"),
MetadataTag("priority", "medium"),
MetadataTag("compliance", "requires_review")
]
self.prompt_client.update_tag_for_prompt_template(
"return_request",
return_tags
)
print("β
Tags added to return request prompt")
# API 3: get_prompts() - Get all prompts and display by category
print("\nπ Retrieving all prompts organized by tags...")
all_prompts = self.prompt_client.get_prompts()
# Organize by category
categorized = {}
for prompt in all_prompts:
if prompt.name in self.created_prompts:
if prompt.tags:
for tag in prompt.tags:
if tag.key == "type":
category = tag.value
if category not in categorized:
categorized[category] = []
categorized[category].append(prompt)
break
print("\nπ Prompts by Type:")
for category, prompts in categorized.items():
print(f"\n {category.upper()} ({len(prompts)} prompts):")
for prompt in prompts:
status = "N/A"
for tag in prompt.tags:
if tag.key == "status":
status = tag.value
break
print(f" - {prompt.name}: {prompt.description} [Status: {status}]")
print("\n⨠Chapter 2 Complete: Prompts organized with tags!")
def chapter3_testing_refinement(self):
"""Chapter 3: Testing and Refinement - Testing Prompts with Different Parameters"""
print("\n" + "="*60)
print(" CHAPTER 3: TESTING AND REFINEMENT")
print("="*60)
print("\nTesting prompts with real data and different parameters...")
# API 8: test_prompt() - Test greeting prompt
print("\nπ§ͺ Testing customer greeting prompt...")
test_cases = [
{
"customer_name": "John Smith",
"customer_tier": "Premium",
"time_of_day": "morning"
},
{
"customer_name": "Sarah Johnson",
"customer_tier": "Standard",
"time_of_day": "evening"
}
]
for i, test_case in enumerate(test_cases, 1):
print(f"\n Test Case {i}:")
print(f" Customer: {test_case['customer_name']} ({test_case['customer_tier']})")
print(f" Time: {test_case['time_of_day']}")
try:
response = self.prompt_client.test_prompt(
prompt_text=self.prompt_client.get_prompt("customer_greeting").template,
variables=test_case,
ai_integration="openai",
text_complete_model="gpt-4o",
temperature=0.7,
top_p=0.9
)
print(f" Response: {response[:200]}...")
except Exception as e:
print(f" Test skipped (AI integration required): {str(e)}")
# Test order inquiry prompt with different temperatures
print("\nπ§ͺ Testing order inquiry with different creativity levels...")
order_test = {
"customer_name": "Alex Chen",
"order_id": "ORD-2024-001234",
"order_status": "In Transit",
"delivery_date": "December 28, 2024",
"query": "When will my order arrive? I need it for a gift."
}
temperature_tests = [
{"name": "Conservative", "temp": 0.3},
{"name": "Balanced", "temp": 0.7},
{"name": "Creative", "temp": 0.9}
]
for test in temperature_tests:
print(f"\n Testing with {test['name']} temperature ({test['temp']}):")
try:
response = self.prompt_client.test_prompt(
prompt_text=self.prompt_client.get_prompt("order_inquiry").template,
variables=order_test,
ai_integration="openai",
text_complete_model="gpt-4o",
temperature=test['temp'],
top_p=0.9
)
print(f" Response preview: {response[:150]}...")
except Exception as e:
print(f" Test skipped (AI integration required): {str(e)}")
# Update prompt based on "testing feedback"
print("\nπ Refining order inquiry prompt based on testing...")
refined_prompt = """You are a helpful and empathetic customer service agent for TechMart.
Customer Information:
- Name: ${customer_name}
- Order ID: ${order_id}
- Order Status: ${order_status}
- Expected Delivery: ${delivery_date}
Customer Query: ${query}
Instructions:
1. Acknowledge their concern immediately
2. Provide current order status clearly
3. Explain what the status means
4. Give specific timeline if available
5. Offer assistance or alternatives if needed
6. Keep response under 100 words
Tone: Professional, empathetic, and solution-focused"""
self.prompt_client.save_prompt(
prompt_name="order_inquiry",
description="Handle customer inquiries about order status (v2 - refined)",
prompt_template=refined_prompt
)
print("β
Order inquiry prompt refined and updated")
print("\n⨠Chapter 3 Complete: Prompts tested and refined!")
def chapter3_5_version_management(self):
"""Chapter 3.5: Version Management - Creating and Managing Multiple Versions"""
print("\n" + "="*60)
print(" CHAPTER 3.5: VERSION MANAGEMENT")
print("="*60)
print("\nLearning to manage multiple versions of prompts...")
# Create a new prompt with explicit version 1
print("\nπ Creating FAQ response prompt - Version 1...")
faq_v1 = """Answer the customer's frequently asked question.
Question: ${question}
Provide a clear, concise answer."""
self.prompt_client.save_prompt(
prompt_name="faq_response",
description="FAQ response generator - Initial version",
prompt_template=faq_v1,
version=1 # Explicitly set version 1
)
self.created_prompts.append("faq_response")
print("β
Created FAQ response v1")
# Create version 2 with improvements
print("\nπ Creating improved Version 2...")
faq_v2 = """You are a knowledgeable TechMart support agent answering FAQs.
Category: ${category}
Question: ${question}
Customer Type: ${customer_type}
Instructions:
- Provide accurate information
- Keep answer under 150 words
- Include relevant links if applicable
- Be friendly and helpful"""
self.prompt_client.save_prompt(
prompt_name="faq_response",
description="FAQ response generator - Enhanced with category support",
prompt_template=faq_v2,
version=2 # Version 2
)
print("β
Created FAQ response v2 with category support")
# Create version 3 with multi-language hints
print("\nπ Creating Version 3 with multi-language support...")
faq_v3 = """You are a knowledgeable TechMart support agent answering FAQs.
Category: ${category}
Question: ${question}
Customer Type: ${customer_type}
Language Preference: ${language}
Instructions:
- Provide accurate information in a culturally appropriate manner
- Keep answer under 150 words
- Include relevant links if applicable
- Be friendly and helpful
- If language is not English, add a note that full support is available in that language"""
self.prompt_client.save_prompt(
prompt_name="faq_response",
description="FAQ response generator - Multi-language aware",
prompt_template=faq_v3,
version=3 # Version 3
)
print("β
Created FAQ response v3 with language support")
# Demonstrate auto-increment feature
print("\nπ Using auto-increment for minor update...")
faq_v3_1 = """You are a knowledgeable TechMart support agent answering FAQs.
Category: ${category}
Question: ${question}
Customer Type: ${customer_type}
Language Preference: ${language}
Urgency Level: ${urgency}
Instructions:
- Provide accurate information in a culturally appropriate manner
- Prioritize based on urgency level
- Keep answer under 150 words
- Include relevant links if applicable
- Be friendly and helpful
- If language is not English, add a note that full support is available in that language"""
self.prompt_client.save_prompt(
prompt_name="faq_response",
description="FAQ response generator - Added urgency handling",
prompt_template=faq_v3_1,
auto_increment=True # Auto-increment from current version
)
print("β
Auto-incremented version with urgency handling")
# Create a versioned prompt for A/B testing
print("\nπ Creating specific versions for A/B testing...")
# Version for formal tone
formal_greeting = """Dear ${customer_name},
Thank you for contacting TechMart support.
We appreciate your ${customer_tier} membership and are here to assist you.
How may we help you today?"""
self.prompt_client.save_prompt(
prompt_name="greeting_formal",
description="Formal greeting style for A/B testing",
prompt_template=formal_greeting,
version=1,
models=["openai:gpt-4", "openai:gpt-4o"] # Specify which models work best with this integration
)
self.created_prompts.append("greeting_formal")
print("β
Created formal greeting v1")
# Version for casual tone
casual_greeting = """Hey ${customer_name}! π
Thanks for reaching out to TechMart!
As a ${customer_tier} member, you get priority support.
What can I help you with today?"""
self.prompt_client.save_prompt(
prompt_name="greeting_casual",
description="Casual greeting style for A/B testing",
prompt_template=casual_greeting,
version=1,
models=["openai:gpt-3.5-turbo", "openai:gpt-4o"] # Different model preferences for this integration
)
self.created_prompts.append("greeting_casual")
print("β
Created casual greeting v1")
# Tag versions for tracking
print("\nπ·οΈ Tagging versions for management...")
version_tags = [
MetadataTag("version_status", "active"),
MetadataTag("tested_models", "openai:gpt-4o"),
MetadataTag("performance", "optimized"),
MetadataTag("last_updated", "2024-12-24")
]
self.prompt_client.update_tag_for_prompt_template(
"faq_response",
version_tags
)
print("β
Tagged FAQ response with version metadata")
# Show version management best practices
print("\nπ Version Management Best Practices:")
print(" 1. Use explicit version numbers for major changes")
print(" 2. Use auto-increment for minor updates")
print(" 3. Tag versions with testing status and performance metrics")
print(" 4. Specify compatible models for each version")
print(" 5. Keep version history for rollback capabilities")
print("\n⨠Chapter 3.5 Complete: Version management mastered!")
def chapter4_production_deployment(self):
"""Chapter 4: Production Deployment - Managing Production-Ready Prompts"""
print("\n" + "="*60)
print(" CHAPTER 4: PRODUCTION DEPLOYMENT")
print("="*60)
print("\nPreparing prompts for production deployment...")