Repository navigation
Expand file tree
/
Copy pathagent.py
More file actions
562 lines (476 loc) · 19.1 KB
/
Copy pathagent.py
File metadata and controls
562 lines (476 loc) · 19.1 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
"""
Agent Service for RAG-powered content generation.
This module orchestrates:
- Context-aware content suggestions using similar past assets
- Iterative content refinement with user instructions
- Flyer concept suggestions based on similar events
"""
import json
import logging
from typing import Dict, Any, Optional, List
from openai import OpenAI, AzureOpenAI
from app.core.config import settings
from app.db.supabase_client import supabase
from app.services.embeddings import embedding_service
logger = logging.getLogger(__name__)
# Channel types
CHANNELS = ["instagram", "whatsapp", "email_subject", "email_body", "engage"]
# Available flyer templates (must match frontend templates.ts)
FLYER_TEMPLATES = ["minimal", "bold", "gradient", "photo", "event"]
FLYER_FORMATS = ["instagram_post", "instagram_story", "general_flyer"]
def _get_llm_client():
"""Initialize and return the appropriate LLM client."""
if settings.LLM_PROVIDER == "azure":
return AzureOpenAI(
azure_endpoint=settings.AZURE_OPENAI_ENDPOINT,
api_key=settings.AZURE_OPENAI_API_KEY,
api_version=settings.AZURE_OPENAI_API_VERSION,
)
return OpenAI(api_key=settings.OPENAI_API_KEY)
def _get_model():
"""Get the model/deployment name based on provider."""
if settings.LLM_PROVIDER == "azure":
return settings.AZURE_OPENAI_DEPLOYMENT
return "gpt-4o-mini"
class AgentService:
"""
RAG-powered agent for context-aware content generation.
Uses embeddings to find similar past content and events,
then leverages that context to generate better suggestions.
"""
def __init__(self):
self.llm = _get_llm_client()
self.model = _get_model()
self.embeddings = embedding_service
async def get_event_context(self, event_id: str) -> Dict[str, Any]:
"""Fetch event details and org branding for context."""
# Get event
event_result = supabase.table("events").select(
"*, organizations(id, name)"
).eq("id", event_id).single().execute()
if not event_result.data:
raise ValueError(f"Event {event_id} not found")
event = event_result.data
org_id = event.get("org_id")
# Get org branding
branding_result = supabase.table("organization_branding").select(
"*"
).eq("org_id", org_id).execute()
branding = branding_result.data[0] if branding_result.data else {
"primary_color": "#00543C",
"secondary_color": "#003D2B",
"font_style": "sans-serif"
}
return {
"event": event,
"org_id": org_id,
"branding": branding
}
async def suggest_content(self, event_id: str) -> Dict[str, Any]:
"""
Generate content suggestions using RAG.
1. Load event + org branding
2. Build event description for embedding
3. Retrieve similar past assets per channel
4. Build context-rich prompt
5. Generate suggestions
6. Save as new iteration
Returns:
Dictionary with content, metadata, and context info
"""
# Get event context
ctx = await self.get_event_context(event_id)
event = ctx["event"]
org_id = ctx["org_id"]
branding = ctx["branding"]
# Build event text for similarity search
event_text = f"{event['title']}\n{event['description']}"
if event.get("audience"):
event_text += f"\nAudience: {event['audience']}"
# Retrieve similar assets for each channel
similar_by_channel = {}
total_similar = 0
for channel in CHANNELS:
similar = self.embeddings.get_similar_assets(
org_id=org_id,
channel=channel,
query_text=event_text,
limit=3
)
similar_by_channel[channel] = similar
total_similar += len(similar)
# Build the prompt with RAG context
prompt = self._build_suggest_prompt(event, branding, similar_by_channel)
# Generate content
response = self.llm.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": (
"You are EventBoost, an AI event marketing agent. "
"Generate channel-specific marketing content based on event details, "
"org branding, and examples of successful past content. "
"Always respond with valid JSON only."
)
},
{"role": "user", "content": prompt}
],
max_tokens=2000,
temperature=0.7,
response_format={"type": "json_object"}
)
content_text = response.choices[0].message.content
content = json.loads(content_text)
# Get current max iteration
iter_result = supabase.table("generated_assets").select(
"iteration"
).eq("event_id", event_id).order(
"iteration", desc=True
).limit(1).execute()
current_iter = iter_result.data[0]["iteration"] if iter_result.data else 0
new_iter = current_iter + 1
# Save each channel as a new asset and index it
for channel in CHANNELS:
channel_content = content.get(channel, "")
if channel_content:
insert_result = supabase.table("generated_assets").insert({
"event_id": event_id,
"type": channel,
"content": channel_content,
"iteration": new_iter,
"model_provider": settings.LLM_PROVIDER,
"model_name": self.model,
"prompt_version": "agent_v1"
}).execute()
# Index the new asset for future RAG
if insert_result.data:
asset_id = insert_result.data[0]["id"]
self.embeddings.index_generated_asset(asset_id, channel_content)
return {
"event_id": event_id,
"content": content,
"similar_assets_used": total_similar,
"context_summary": f"Used {total_similar} similar past assets for context",
"model_provider": settings.LLM_PROVIDER,
"model_name": self.model
}
def _build_suggest_prompt(
self,
event: Dict[str, Any],
branding: Dict[str, Any],
similar_by_channel: Dict[str, List[Dict]]
) -> str:
"""Build the prompt for content suggestion with RAG context."""
# Event details section
prompt = f"""Generate marketing content for this event:
EVENT DETAILS:
- Title: {event.get('title', '')}
- Description: {event.get('description', '')}
- Location: {event.get('location', '')}
- Date/Time: {event.get('starts_at', '')}
- Tone: {event.get('tone', 'casual')}
- Target Audience: {event.get('audience', 'general')}
"""
if event.get('perks'):
prompt += f"- Perks: {event['perks']}\n"
# Build channel-specific tracking URLs with UTM parameters
if event.get('tracking_slug'):
base_url = f"{settings.TRACKING_BASE_URL}/e/{event['tracking_slug']}"
prompt += f"""
RSVP LINKS (use the appropriate link for each channel):
- Instagram: {base_url}?utm_medium=instagram&utm_source=eventboost
- WhatsApp: {base_url}?utm_medium=whatsapp&utm_source=eventboost
- Email: {base_url}?utm_medium=email&utm_source=eventboost
- Engage: {base_url}?utm_medium=engage&utm_source=eventboost
"""
elif event.get('rsvp_link'):
prompt += f"- RSVP Link: {event['rsvp_link']}\n"
# Branding section
prompt += f"""
ORGANIZATION BRANDING:
- Primary Color: {branding.get('primary_color', '#00543C')}
- Secondary Color: {branding.get('secondary_color', '#003D2B')}
- Font Style: {branding.get('font_style', 'sans-serif')}
"""
# Similar past content section (RAG context)
prompt += "\nSIMILAR PAST CONTENT (for style reference):\n"
has_examples = False
for channel, assets in similar_by_channel.items():
if assets:
has_examples = True
prompt += f"\n{channel.upper()} examples:\n"
for i, asset in enumerate(assets[:2], 1):
prompt += f" {i}. \"{asset['content'][:200]}...\"\n"
if asset.get('feedback'):
prompt += f" (Feedback: {asset['feedback']})\n"
if not has_examples:
prompt += " (No previous examples available - generate fresh content)\n"
# Output instructions
prompt += """
GENERATE content for each channel. Return as JSON:
{
"instagram": "Instagram caption with emojis and hashtags (max 300 chars)",
"whatsapp": "WhatsApp message - conversational and concise (max 200 chars)",
"email_subject": "Email subject line (max 60 chars)",
"email_body": "Email body - professional but friendly (max 400 chars)",
"engage": "Campus engagement platform description (max 300 chars)"
}
GUIDELINES:
- Learn from the style and tone of similar past content
- Maintain consistency with org branding voice
- Adapt content to the specified tone
- Include key event details naturally
- Make each channel's content unique and platform-appropriate
"""
return prompt
async def iterate_content(
self,
event_id: str,
channel: str,
instruction: str
) -> Dict[str, Any]:
"""
Refine specific channel content based on user instruction.
Args:
event_id: Event UUID
channel: Channel to iterate on (instagram, whatsapp, etc.)
instruction: User's refinement instruction
Returns:
Updated content with explanation
"""
if channel not in CHANNELS:
raise ValueError(f"Invalid channel: {channel}")
# Get event context
ctx = await self.get_event_context(event_id)
event = ctx["event"]
org_id = ctx["org_id"]
branding = ctx["branding"]
# Get current content for this channel
current_result = supabase.table("generated_assets").select(
"id, content, iteration"
).eq("event_id", event_id).eq("type", channel).order(
"iteration", desc=True
).limit(1).execute()
if not current_result.data:
raise ValueError(f"No existing content for channel: {channel}")
current = current_result.data[0]
current_content = current["content"]
current_iter = current["iteration"]
# Get similar assets for context
similar = self.embeddings.get_similar_assets(
org_id=org_id,
channel=channel,
query_text=current_content,
limit=3
)
# Build iteration prompt
prompt = self._build_iterate_prompt(
event, branding, channel, current_content, instruction, similar
)
# Generate refined content
response = self.llm.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": (
"You are EventBoost, an AI content editor. "
"Refine the given content based on user instructions while "
"preserving key event details and brand voice. "
"Always respond with valid JSON only."
)
},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.7,
response_format={"type": "json_object"}
)
result = json.loads(response.choices[0].message.content)
new_content = result.get("updated_content", "")
explanation = result.get("explanation", "")
# Save as new iteration
new_iter = current_iter + 1
insert_result = supabase.table("generated_assets").insert({
"event_id": event_id,
"type": channel,
"content": new_content,
"iteration": new_iter,
"feedback": instruction,
"model_provider": settings.LLM_PROVIDER,
"model_name": self.model,
"prompt_version": "agent_iterate_v1"
}).execute()
# Index the new asset
if insert_result.data:
asset_id = insert_result.data[0]["id"]
self.embeddings.index_generated_asset(asset_id, new_content)
return {
"channel": channel,
"content": new_content,
"iteration": new_iter,
"explanation": explanation,
"previous_content": current_content
}
def _build_iterate_prompt(
self,
event: Dict[str, Any],
branding: Dict[str, Any],
channel: str,
current_content: str,
instruction: str,
similar: List[Dict]
) -> str:
"""Build prompt for content iteration."""
# Build channel-specific tracking URL
tracking_url = ""
if event.get('tracking_slug'):
base_url = f"{settings.TRACKING_BASE_URL}/e/{event['tracking_slug']}"
utm_medium = channel.replace('_subject', '').replace('_body', '') # email_subject -> email
tracking_url = f"{base_url}?utm_medium={utm_medium}&utm_source=eventboost"
prompt = f"""Refine this {channel.upper()} content based on the user's instruction.
CURRENT CONTENT:
"{current_content}"
USER INSTRUCTION:
{instruction}
EVENT CONTEXT:
- Title: {event.get('title', '')}
- Description: {event.get('description', '')}
- Date: {event.get('starts_at', '')}
- Location: {event.get('location', '')}
- Tone: {event.get('tone', 'casual')}
"""
if tracking_url:
prompt += f"- RSVP Link for this channel: {tracking_url}\n"
if similar:
prompt += "\nSIMILAR PAST CONTENT (for reference):\n"
for i, asset in enumerate(similar[:2], 1):
prompt += f" {i}. \"{asset['content'][:150]}...\"\n"
prompt += f"""
REQUIREMENTS:
- Apply the user's instruction
- Preserve essential event details (title, date, location)
- Maintain brand voice and tone
- Keep within platform character limits
Return JSON:
{{
"updated_content": "the refined content here",
"explanation": "brief explanation of changes made"
}}
"""
return prompt
async def suggest_flyer_concept(self, event_id: str) -> Dict[str, Any]:
"""
Suggest flyer styling based on event and similar past events.
Returns recommended format, template, colors, and background style.
"""
# Get event context
ctx = await self.get_event_context(event_id)
event = ctx["event"]
org_id = ctx["org_id"]
branding = ctx["branding"]
# Build event text for similarity
event_text = f"{event['title']}\n{event['description']}"
if event.get("audience"):
event_text += f"\nAudience: {event['audience']}"
# Find similar events
similar_events = self.embeddings.get_similar_events(
org_id=org_id,
query_text=event_text,
limit=3
)
# Get flyers from similar events
similar_flyers = []
if similar_events:
event_ids = [e["id"] for e in similar_events]
for eid in event_ids[:3]:
flyer_result = supabase.table("flyers").select(
"template_id, mode, generation_method, style_prompt"
).eq("event_id", eid).limit(2).execute()
if flyer_result.data:
similar_flyers.extend(flyer_result.data)
# Build prompt
prompt = self._build_flyer_concept_prompt(
event, branding, similar_events, similar_flyers
)
# Generate suggestion
response = self.llm.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": (
"You are EventBoost, a flyer design consultant. "
"Suggest flyer styling based on event type, branding, and past examples. "
"Always respond with valid JSON only."
)
},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.7,
response_format={"type": "json_object"}
)
result = json.loads(response.choices[0].message.content)
return {
"recommended_format": result.get("format", "instagram_post"),
"recommended_template": result.get("template", "bold"),
"recommended_colors": {
"primary": result.get("primary_color", branding.get("primary_color", "#00543C")),
"secondary": result.get("secondary_color", branding.get("secondary_color", "#003D2B"))
},
"background_style": result.get("background_style", "template"),
"ai_prompt_suggestion": result.get("ai_prompt", None),
"reasoning": result.get("reasoning", ""),
"similar_events_used": len(similar_events)
}
def _build_flyer_concept_prompt(
self,
event: Dict[str, Any],
branding: Dict[str, Any],
similar_events: List[Dict],
similar_flyers: List[Dict]
) -> str:
"""Build prompt for flyer concept suggestion."""
prompt = f"""Suggest flyer styling for this event:
EVENT:
- Title: {event.get('title', '')}
- Description: {event.get('description', '')}
- Tone: {event.get('tone', 'casual')}
- Audience: {event.get('audience', 'general')}
ORGANIZATION BRANDING:
- Primary Color: {branding.get('primary_color', '#00543C')}
- Secondary Color: {branding.get('secondary_color', '#003D2B')}
- Font Style: {branding.get('font_style', 'sans-serif')}
AVAILABLE OPTIONS:
- Formats: {FLYER_FORMATS}
- Templates: {FLYER_TEMPLATES}
- Background styles: ["template", "ai_generated"]
"""
if similar_events:
prompt += "\nSIMILAR PAST EVENTS:\n"
for e in similar_events[:2]:
prompt += f" - {e['title']}: {e.get('description', '')[:100]}...\n"
if similar_flyers:
prompt += "\nFLYERS FROM SIMILAR EVENTS:\n"
for f in similar_flyers[:3]:
prompt += f" - Template: {f.get('template_id')}, Method: {f.get('generation_method')}\n"
if f.get('style_prompt'):
prompt += f" Style: {f['style_prompt'][:50]}...\n"
prompt += """
Based on the event type, tone, and past examples, suggest:
Return JSON:
{
"format": "instagram_post" or "instagram_story" or "general_flyer",
"template": "minimal" or "bold" or "gradient" or "photo" or "event",
"primary_color": "#hexcode",
"secondary_color": "#hexcode",
"background_style": "template" or "ai_generated",
"ai_prompt": "if ai_generated, suggest a DALL-E prompt for abstract background (no text)",
"reasoning": "brief explanation of why these choices fit the event"
}
"""
return prompt
# Global instance
agent_service = AgentService()