arittrabag commited on
Commit
91b91a6
·
verified ·
1 Parent(s): 02e306a

Update enhanced_prompt_builder.py

Browse files
Files changed (1) hide show
  1. enhanced_prompt_builder.py +114 -130
enhanced_prompt_builder.py CHANGED
@@ -1,131 +1,115 @@
1
- from enhanced_retriever import EnhancedRetriever
2
- from enhanced_knowledge_graph import EnhancedKnowledgeGraph
3
- from feedback_analyzer import FeedbackAnalyzer
4
- from typing import List, Dict
5
-
6
- class EnhancedPromptBuilder:
7
- """Enhanced prompt builder with all advanced features integrated"""
8
-
9
- def __init__(self):
10
- self.retriever = EnhancedRetriever()
11
- self.knowledge_graph = EnhancedKnowledgeGraph()
12
- self.feedback_analyzer = FeedbackAnalyzer()
13
-
14
- def build_adaptive_prompt(self, ad_text: str, tone: str, platforms: List[str]) -> str:
15
- """Build an adaptive prompt using all enhancement layers"""
16
-
17
- # 1. Get enhanced RAG results with relevance scores
18
- rag_results = self.retriever.retrieve_with_relevance(tone, platforms)
19
- formatted_guidance = self.retriever.format_guidance_with_scores(rag_results)
20
-
21
- # 2. Get knowledge graph insights with traversal
22
- kg_insights = []
23
-
24
- # Get recommendations for each platform
25
- for platform in platforms:
26
- recommendations = self.knowledge_graph.get_recommendations(tone, platform)
27
- kg_insights.append(f"\n{platform} Insights:")
28
- kg_insights.append(f" - Compatibility Score: {recommendations['compatibility_score']:.2f}")
29
-
30
- if recommendations['suggested_elements']:
31
- kg_insights.append(" - Suggestions: " + ", ".join(recommendations['suggested_elements']))
32
-
33
- if recommendations['warnings']:
34
- kg_insights.append(" - ⚠️ Warnings: " + ", ".join(recommendations['warnings']))
35
-
36
- if recommendations['creative_types']:
37
- kg_insights.append(" - Recommended Creative Types: " + ", ".join(recommendations['creative_types']))
38
-
39
- # Add relationship explanations
40
- relationship = self.knowledge_graph.explain_relationship(tone, platform)
41
- kg_insights.append(f" - Relationship: {relationship}")
42
-
43
- kg_insights_str = "\n".join(kg_insights)
44
-
45
- # 3. Get adaptive weights from feedback analysis
46
- weights = self.feedback_analyzer.get_adaptive_weights()
47
-
48
- # 4. Add performance insights if available
49
- analysis = self.feedback_analyzer.analyze_patterns()
50
- performance_notes = []
51
-
52
- if analysis.get("recommendations"):
53
- relevant_recs = [rec for rec in analysis["recommendations"]
54
- if any(p.lower() in rec.lower() for p in platforms) or tone.lower() in rec.lower()]
55
- if relevant_recs:
56
- performance_notes.append("\nHistorical Performance Notes:")
57
- performance_notes.extend([f" - {rec}" for rec in relevant_recs[:3]])
58
-
59
- performance_str = "\n".join(performance_notes) if performance_notes else ""
60
-
61
- # 5. Build the enhanced prompt
62
- platform_str = ", ".join(platforms)
63
-
64
- # Apply adaptive weights to emphasize better-performing combinations
65
- weight_notes = []
66
- for platform in platforms:
67
- combo_key = f"{tone}_{platform}"
68
- weight = weights.get(combo_key, 1.0)
69
- if weight > 0.8:
70
- weight_notes.append(f" - {platform}: High confidence (historical success)")
71
- elif weight < 0.6:
72
- weight_notes.append(f" - {platform}: Needs improvement (based on feedback)")
73
-
74
- weight_str = "\n".join(weight_notes) if weight_notes else ""
75
-
76
- prompt = f"""
77
- You are an expert ad copywriter with access to advanced AI assistance.
78
-
79
- TASK: Rewrite the following ad text in a {tone} tone and optimize it individually for: {platform_str}
80
-
81
- ORIGINAL AD TEXT: "{ad_text}"
82
-
83
- === ENHANCED GUIDANCE (with Relevance Scores) ===
84
- {formatted_guidance}
85
-
86
- === KNOWLEDGE GRAPH INSIGHTS ===
87
- {kg_insights_str}
88
-
89
- === ADAPTIVE LEARNING INSIGHTS ===
90
- {weight_str}
91
- {performance_str}
92
-
93
- === INSTRUCTIONS ===
94
- 1. Maintain the core message and key information from the original ad
95
- 2. Adapt the tone and style according to the guidelines above
96
- 3. Consider the compatibility scores and warnings for each platform
97
- 4. Use suggested elements where appropriate
98
- 5. Avoid any warned elements or approaches
99
- 6. Apply lessons from historical performance data
100
-
101
- OUTPUT FORMAT:
102
- Provide a separate, optimized version for each platform:
103
-
104
- {''.join([f'{p}:\n<Your rewritten ad text here>\n\n' for p in platforms])}
105
-
106
- Remember: Each platform version should be uniquely tailored while maintaining brand consistency.
107
- """
108
-
109
- return prompt
110
-
111
- def get_improvement_suggestions(self) -> List[str]:
112
- """Get suggestions for improving the system based on feedback"""
113
- analysis = self.feedback_analyzer.analyze_patterns()
114
- suggestions = []
115
-
116
- # Check overall performance
117
- avg_rating = analysis.get("average_rating", 0)
118
- if avg_rating < 3.5:
119
- suggestions.append("Consider updating tone guidelines based on feedback patterns")
120
-
121
- # Check for problematic combinations
122
- for pattern in analysis.get("low_performing_patterns", []):
123
- tone, platform = pattern["pattern"].split("_")
124
- suggestions.append(f"Review and update guidelines for {tone} tone on {platform}")
125
-
126
- # Suggest new relationships for KG
127
- high_performers = analysis.get("high_performing_patterns", [])
128
- if high_performers:
129
- suggestions.append("Consider strengthening KG relationships for high-performing combinations")
130
-
131
  return suggestions
 
1
+ from enhanced_retriever import EnhancedRetriever
2
+ from enhanced_knowledge_graph import EnhancedKnowledgeGraph
3
+ from feedback_analyzer import FeedbackAnalyzer
4
+ from typing import List, Dict
5
+
6
+ class EnhancedPromptBuilder:
7
+ """Enhanced prompt builder with all advanced features integrated"""
8
+
9
+ def __init__(self):
10
+ self.retriever = EnhancedRetriever()
11
+ self.knowledge_graph = EnhancedKnowledgeGraph()
12
+ self.feedback_analyzer = FeedbackAnalyzer()
13
+
14
+ def build_adaptive_prompt(self, ad_text: str, tone: str, platforms: List[str]) -> str:
15
+ """Build an adaptive prompt using all enhancement layers"""
16
+
17
+ # 1. Get enhanced RAG results with relevance scores
18
+ rag_results = self.retriever.retrieve_with_relevance(tone, platforms)
19
+ formatted_guidance = self.retriever.format_guidance_with_scores(rag_results)
20
+
21
+ # 2. Get knowledge graph insights with traversal
22
+ kg_insights = []
23
+
24
+ # Get recommendations for each platform
25
+ for platform in platforms:
26
+ recommendations = self.knowledge_graph.get_recommendations(tone, platform)
27
+ kg_insights.append(f"\n{platform} Insights:")
28
+ kg_insights.append(f" - Compatibility Score: {recommendations['compatibility_score']:.2f}")
29
+
30
+ if recommendations['suggested_elements']:
31
+ kg_insights.append(" - Suggestions: " + ", ".join(recommendations['suggested_elements']))
32
+
33
+ if recommendations['warnings']:
34
+ kg_insights.append(" - ⚠️ Warnings: " + ", ".join(recommendations['warnings']))
35
+
36
+ if recommendations['creative_types']:
37
+ kg_insights.append(" - Recommended Creative Types: " + ", ".join(recommendations['creative_types']))
38
+
39
+ # Add relationship explanations
40
+ relationship = self.knowledge_graph.explain_relationship(tone, platform)
41
+ kg_insights.append(f" - Relationship: {relationship}")
42
+
43
+ kg_insights_str = "\n".join(kg_insights)
44
+
45
+ # 3. Get adaptive weights from feedback analysis
46
+ weights = self.feedback_analyzer.get_adaptive_weights()
47
+
48
+ # 4. Add performance insights if available
49
+ analysis = self.feedback_analyzer.analyze_patterns()
50
+ performance_notes = []
51
+
52
+ if analysis.get("recommendations"):
53
+ relevant_recs = [rec for rec in analysis["recommendations"]
54
+ if any(p.lower() in rec.lower() for p in platforms) or tone.lower() in rec.lower()]
55
+ if relevant_recs:
56
+ performance_notes.append("\nHistorical Performance Notes:")
57
+ performance_notes.extend([f" - {rec}" for rec in relevant_recs[:3]])
58
+
59
+ performance_str = "\n".join(performance_notes) if performance_notes else ""
60
+
61
+ # 5. Build the enhanced prompt
62
+ platform_str = ", ".join(platforms)
63
+
64
+ # Apply adaptive weights to emphasize better-performing combinations
65
+ weight_notes = []
66
+ for platform in platforms:
67
+ combo_key = f"{tone}_{platform}"
68
+ weight = weights.get(combo_key, 1.0)
69
+ if weight > 0.8:
70
+ weight_notes.append(f" - {platform}: High confidence (historical success)")
71
+ elif weight < 0.6:
72
+ weight_notes.append(f" - {platform}: Needs improvement (based on feedback)")
73
+
74
+ weight_str = "\n".join(weight_notes) if weight_notes else ""
75
+
76
+ prompt = f"""
77
+ You are an expert ad copywriter with access to advanced AI assistance.
78
+
79
+ TASK: Rewrite the following ad text in a {tone} tone and optimize it individually for: {platform_str}
80
+
81
+ ORIGINAL AD TEXT: "{ad_text}"
82
+
83
+ === ENHANCED GUIDANCE (with Relevance Scores) ===
84
+ {formatted_guidance}
85
+
86
+ === KNOWLEDGE GRAPH INSIGHTS ===
87
+ {kg_insights_str}
88
+
89
+ === ADAPTIVE LEARNING INSIGHTS ===
90
+ {weight_str}
91
+ {performance_str}
92
+
93
+ return prompt
94
+
95
+ def get_improvement_suggestions(self) -> List[str]:
96
+ """Get suggestions for improving the system based on feedback"""
97
+ analysis = self.feedback_analyzer.analyze_patterns()
98
+ suggestions = []
99
+
100
+ # Check overall performance
101
+ avg_rating = analysis.get("average_rating", 0)
102
+ if avg_rating < 3.5:
103
+ suggestions.append("Consider updating tone guidelines based on feedback patterns")
104
+
105
+ # Check for problematic combinations
106
+ for pattern in analysis.get("low_performing_patterns", []):
107
+ tone, platform = pattern["pattern"].split("_")
108
+ suggestions.append(f"Review and update guidelines for {tone} tone on {platform}")
109
+
110
+ # Suggest new relationships for KG
111
+ high_performers = analysis.get("high_performing_patterns", [])
112
+ if high_performers:
113
+ suggestions.append("Consider strengthening KG relationships for high-performing combinations")
114
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  return suggestions