Spaces:
Sleeping
Sleeping
system_prompt = """You are a world-class direct response copywriter trained by Gary Halbert, Gary Bencivenga, and David Ogilvy. | |
Additionally, you are a digital advertising expert specializing in Facebook Ads. You have extensive experience in crafting high-converting ads using data-driven strategies, audience segmentation, A/B testing, and conversion rate optimization. | |
Your advertising philosophy follows these core principles: | |
1. **Attention is everything** – The first line must hook the audience instantly. | |
2. **Social proof builds trust** – Credibility and authority persuade people to take action. | |
3. **Clarity beats cleverness** – The message must be clear, persuasive, and results-driven. | |
4. **Emotion drives action** – Ads should tap into the audience's desires, fears, and aspirations. | |
5. **Every word must sell** – No fluff, just compelling, action-driven copy. | |
6. **Data-backed optimization** – Ads must be structured for continuous testing and performance tracking. | |
You write persuasive, high-converting Facebook ads that maximize engagement and ROI.""" | |
# Importar el diccionario de objetivos | |
from ad_objectives import ad_objectives | |
# Importar el diccionario de ángulos emocionales | |
from emotional_angles import emotional_angles | |
# Importar las fórmulas de anuncios desde la carpeta ads | |
from ads_formulas import ads_formulas | |
# Add this import at the top of the file | |
from fb_policies import fb_policies, get_policy_checklist | |
# Añadir esta importación al principio del archivo | |
from headline_generator import generate_random_headlines | |
def create_fb_ad_instruction(target_audience, product, selected_formula, selected_angle, selected_persona, ad_objective=None, language="español", story_prompt="", headline=None): | |
""" | |
Creates an instruction for generating Facebook ad copy | |
Parameters: | |
- target_audience: The target audience for the ad | |
- product: The product or service being advertised | |
- selected_formula: Formula to use for structuring the ad | |
- selected_angle: Angle to approach the ad from | |
- selected_persona: Copywriting legend personality to adopt | |
- ad_objective: The campaign objective (awareness, traffic, engagement, etc.) | |
- language: Target language for the ad (default: "español") | |
- story_prompt: Specific theme or idea for the ad story (default: "") | |
Returns: | |
- Instruction string for the model | |
""" | |
# Create objective instruction if provided | |
objective_instruction = "" | |
if ad_objective: | |
objective_instruction = f""" | |
**Campaign Objective: {ad_objective['name']}** | |
Focus on: {ad_objective['description']} | |
Key metrics to optimize for: | |
- {', '.join(ad_objective['key_metrics'])} | |
Copy strategy: | |
- {ad_objective['copy_strategy']} | |
""" | |
# Add headline examples if available | |
if 'headline_examples' in ad_objective: | |
headline_examples = "\n- ".join(ad_objective['headline_examples']) | |
objective_instruction += f""" | |
Recommended headline approaches for this objective: | |
- {headline_examples} | |
""" | |
# Add elements to avoid if available | |
if 'avoid' in ad_objective: | |
elements_to_avoid = "\n- ".join(ad_objective['avoid']) | |
objective_instruction += f""" | |
Elements to AVOID for this objective: | |
- {elements_to_avoid} | |
""" | |
# Add recommended CTAs if available | |
if 'recommended_ctas' in ad_objective: | |
recommended_ctas = "\n- ".join(ad_objective['recommended_ctas']) | |
objective_instruction += f""" | |
Recommended CTAs for this objective: | |
- {recommended_ctas} | |
""" | |
# Add tone guidance if available | |
if 'tone' in ad_objective: | |
objective_instruction += f""" | |
Recommended tone for this objective: | |
{ad_objective['tone']} | |
""" | |
# Create story prompt instruction if provided | |
story_instruction = "" | |
if story_prompt: | |
story_instruction = f""" | |
**Personalized Story - CRITICAL INSTRUCTION:** | |
BUILD THE ENTIRE AD NARRATIVE AROUND THIS SPECIFIC THEME: | |
"{story_prompt}" | |
THIS IS THE ABSOLUTE CORE OF THE AD - EVERY ELEMENT MUST CONNECT TO THIS THEME. | |
ESSENTIAL REQUIREMENTS: | |
- The headline MUST directly incorporate or reference "{story_prompt}" in a creative way | |
- The opening paragraph MUST immediately establish "{story_prompt}" as the central focus | |
- Every paragraph should maintain "{story_prompt}" as the primary narrative thread | |
- Use specific details that make {target_audience} think "this is exactly my experience with {story_prompt}" | |
- Include moments of frustration, challenge, or aspiration that are EXACTLY like those experienced by your audience regarding "{story_prompt}" | |
- Narrate the story in third person, describing situations that the target audience can identify with | |
- The product solution must be presented as directly addressing the "{story_prompt}" situation | |
- The CTA should reference back to the "{story_prompt}" theme for continuity | |
This story MUST feel as if you are describing common situations that your audience faces specifically in relation to "{story_prompt}". | |
IMPORTANT: If at any point the narrative drifts away from "{story_prompt}", the ad will fail completely. Keep returning to this theme throughout the entire ad. | |
""" | |
persona_instruction = f""" | |
Adopt the personality and writing style of {selected_persona['description']} | |
Key characteristics of this style: | |
- {' '.join(selected_persona['characteristics'])} | |
- Famous for: {selected_persona['famous_for']} | |
When writing as this copywriting legend: | |
- Use their signature tone and rhythm in your sentences | |
- Apply their known persuasion techniques throughout the ad | |
- Structure arguments in their characteristic way | |
- Incorporate their typical emotional appeals | |
""" | |
# Prepare angle instruction | |
angle_instruction = f""" | |
Apply this angle: {selected_angle['description']} | |
Style of the angle: {selected_angle['style']} | |
""" | |
# Add keywords if they exist in the selected angle | |
if 'keywords' in selected_angle: | |
angle_instruction += f""" | |
Suggested keywords: {', '.join(selected_angle['keywords'])} | |
""" | |
# Add power words if they exist in the selected angle (for emotional angles) | |
if 'power_words' in selected_angle: | |
angle_instruction += f""" | |
Power words to include: {', '.join(selected_angle['power_words'])} | |
""" | |
# Add example if it exists in the selected angle (for emotional angles) | |
if 'example' in selected_angle: | |
angle_instruction += f""" | |
Example of this angle: {selected_angle['example']} | |
""" | |
# Add formula examples if available | |
formula_examples = "" | |
if 'examples' in selected_formula: | |
examples_list = [] | |
# Usar todos los ejemplos disponibles en lugar de limitar a 3 | |
for example in selected_formula['examples']: | |
# Incluir título y target para mejor contexto | |
examples_list.append(f"- {example['title']} (Para: {example['target']})") | |
formula_examples = f""" | |
Get inspired by these examples from the selected formula: | |
{chr(10).join(examples_list)} | |
Note: These are just the titles. The full examples with detailed stories are available in the formula structure. | |
""" | |
# Obtener la lista de verificación de políticas | |
policy_checklist = get_policy_checklist() | |
# Crear la lista numerada de verificaciones | |
policy_checks = "\n".join([f"{i+1}. {check}" for i, check in enumerate(policy_checklist)]) | |
# Generar titulares aleatorios con diferentes estructuras | |
random_headlines = generate_random_headlines( | |
target_audience=target_audience, | |
product=product, | |
angle=selected_angle, | |
story_prompt=story_prompt, | |
language=language | |
) | |
# Verificar y corregir titulares que no tienen sentido gramatical | |
corrected_headlines = [] | |
for headline in random_headlines: | |
# Verificar si el titular termina con un verbo auxiliar sin complemento | |
if any(headline.strip().endswith(f" {verb}") for verb in ["puede", "podría", "debe", "debería", "va a", "tiene"]): | |
# Añadir un complemento genérico según el contexto | |
if "puede" in headline or "podría" in headline: | |
headline += " transformar vidas" | |
elif "debe" in headline or "debería" in headline: | |
headline += " considerarse seriamente" | |
elif "va a" in headline: | |
headline += " sorprender" | |
elif "tiene" in headline: | |
headline += " la respuesta" | |
corrected_headlines.append(headline) | |
random_headlines = corrected_headlines | |
# Dividir los titulares en grupos de 3 para cada anuncio | |
ad1_headlines = random_headlines[0:3] | |
ad2_headlines = random_headlines[3:6] | |
ad3_headlines = random_headlines[6:9] | |
# Crear instrucción específica para los titulares pre-generados | |
headline_instruction = f""" | |
**Pre-Generated Headlines:** | |
Para asegurar variedad en los tipos de titulares, considera estas opciones pre-generadas para cada anuncio: | |
Para el Anuncio #1: | |
1. {ad1_headlines[0]} | |
2. {ad1_headlines[1]} | |
3. {ad1_headlines[2]} | |
Para el Anuncio #2: | |
1. {ad2_headlines[0]} | |
2. {ad2_headlines[1]} | |
3. {ad2_headlines[2]} | |
Para el Anuncio #3: | |
1. {ad3_headlines[0]} | |
2. {ad3_headlines[1]} | |
3. {ad3_headlines[2]} | |
IMPORTANTE: Estos titulares representan diferentes estructuras (preguntas, declaraciones, historias, advertencias, etc.). | |
Puedes usar estos titulares directamente, modificarlos para que se alineen mejor con la narrativa del anuncio, | |
o crear nuevos titulares inspirados en estos, pero ASEGÚRATE de mantener VARIEDAD en los tipos de estructura | |
entre los tres anuncios finales. | |
VERIFICACIÓN DE TITULARES: | |
- Asegúrate de que cada titular tenga sentido gramatical completo | |
- Si un titular termina con un verbo auxiliar (puede, debe, va a), añade un complemento apropiado | |
- Verifica que las preguntas sean gramaticalmente correctas y tengan sentido | |
- Evita frases incompletas o que suenen artificiales | |
""" | |
# Modificación en el enfoque del problema y el uso de la segunda persona | |
instruction = f""" | |
{system_prompt} | |
Create three completely different high-converting Facebook ad copies for {product}, channeling the voice of {selected_persona['description']} while leveraging the selected angle to persuade {target_audience} to try it and share their positive experience. | |
{objective_instruction if ad_objective else ""} | |
{story_instruction if story_prompt else ""} | |
{persona_instruction} | |
{headline_instruction} | |
Ad Requirements for EACH of the three ads: | |
1. **Multiple Headline Options:** For EACH ad, create THREE distinct, powerful headline options that directly incorporate the story theme "{story_prompt if story_prompt else 'main benefit'}". Each headline should: | |
- Be bold, unexpected, and memorable | |
- Create curiosity and compel the reader to continue | |
- Be emotionally resonant and specific to the audience's desires | |
- Offer a different creative angle or approach to the same theme | |
Then SELECT ONE headline that best matches the ad's narrative flow, but DO NOT include the analysis or other headline options in your output - only show the selected headline. | |
2. **Seamless Opening Paragraph:** Begin with a smooth, conversational opening that DIRECTLY continues the exact theme from the SELECTED headline. The first paragraph MUST expand on the SAME concept from the headline, creating a natural flow as if they were written as one continuous thought. | |
3. **Social Proof & Credibility:** Include elements of social proof and credibility that relate to the central theme to build trust with the audience. | |
4. **Theme-Aligned Benefits:** Highlight why this product is the best solution for {target_audience}'s needs specifically in relation to the central theme. | |
5. **Theme-Connected CTA:** Integrate the call to action naturally into the narrative flow, making sure it references back to the central theme. It should feel like a logical next step rather than an abrupt command. | |
6. **Optimized for Multiple Ad Formats:** Ensure the copy works for image, video, and carousel ads while maintaining theme consistency. | |
7. **Facebook Policy Compliance:** Ensure all ad copy complies with Facebook's advertising policies by: | |
- Avoiding prohibited content (gambling, adult content, tobacco, weapons, etc.) | |
- Not using discriminatory language or targeting protected categories | |
- Avoiding excessive use of capital letters, punctuation, or sensationalist language | |
- Not making unrealistic claims or guarantees about results | |
- Ensuring appropriate disclaimers for regulated industries (finance, health, etc.) | |
- Not using "you" or "your" in a way that references personal attributes | |
- Avoiding content that could be considered misleading or creating false urgency | |
- Not mentioning Facebook or Instagram directly in the ad copy | |
IMPORTANT ABOUT OPENING PARAGRAPH: | |
- The opening paragraph MUST continue the EXACT SAME THEME as the headline - they must feel like one continuous thought | |
- It should feel like a direct continuation of the headline's specific concept, not a general introduction to the topic | |
- The headline and opening paragraph should read as if they were written together as one continuous piece | |
- CRITICAL: If the headline mentions a specific concept (e.g., "Padre Extraterrestre Con Estrés"), the opening paragraph MUST directly address this EXACT concept, not just the general topic of stress | |
- The transition between headline and opening paragraph should be seamless, as if they are part of the same thought | |
- IMPORTANT: Do NOT begin the opening paragraph with a question that mirrors or expands the headline concept. Instead, use declarative statements that continue the narrative | |
- If the headline contains a question, the opening paragraph should provide insight or expand on the scenario rather than asking another related question | |
- For question headlines: The opening paragraph should begin answering the question or elaborating on the implied situation, creating a natural flow of thought | |
- When a headline poses a question, treat the opening paragraph as the beginning of the answer or exploration of that question, not as a separate thought | |
- Example of good flow: Headline: "¿Te has preguntado por qué otros avanzan y tú te quedas estancado?" Opening: "El inglés, esa habilidad que subestimas, podría ser la llave que abre las puertas a promociones y proyectos internacionales..." | |
IMPORTANT ABOUT HEADLINE-STORY CONTINUITY: | |
- The headline and story must be perfectly aligned - they should feel like parts of the same narrative | |
- If the headline uses a specific metaphor, analogy, or concept, the story MUST continue with that SAME metaphor, analogy, or concept | |
- The story should feel like a natural expansion of the headline's promise or concept | |
- NEVER create a headline that introduces a concept that isn't immediately continued in the story | |
- The headline should set up a specific scenario that the opening paragraph immediately expands upon | |
IMPORTANT ABOUT CALL TO ACTION: | |
- The CTA should not feel like a separate, tacked-on element | |
- Avoid generic phrases like "Learn more" or "Click here" unless they're integrated into a more specific, compelling statement | |
- Connect the CTA directly to the specific benefit or solution mentioned in the ad | |
- Maintain the same voice, style and emotional tone used throughout the ad | |
- Make the CTA feel like a natural continuation of the conversation, not a marketing directive | |
**Product Integration:** Weave {product} into the narrative naturally and conversationally. Don't just mention it - make it an organic part of the story. The product should feel like the natural solution to the problem, not like an advertisement. Introduce it at the right moment when the audience is emotionally ready to receive it. | |
IMPORTANT ABOUT PRODUCT INTEGRATION: | |
- Never mention the product name directly as "{product}" - instead, refer to it indirectly or through its benefits | |
- Introduce it as part of the narrative solution, not as a formal offering | |
- When you do mention the product name, do it naturally as if it's already familiar to the reader | |
- Focus on what it does for people rather than what it is | |
- Use phrases like "muchos descubrieron que...", "resulta que...", "lo que realmente funciona es..." before subtly introducing the product | |
IMPORTANT ABOUT PROBLEM PRESENTATION: | |
- Present challenges and pain points subtly through relatable scenarios rather than direct statements | |
- Use third-person narratives that allow readers to see themselves in the story without being directly addressed | |
- Instead of "You struggle with X", use "Many find themselves facing X" or "It's common to encounter X" | |
- Create scenarios where readers naturally recognize their own experiences without being told directly | |
- Use phrases like "those who...", "people often...", "when someone experiences..." instead of direct "you" statements | |
- Let readers draw their own conclusions about how the problem affects them personally | |
- Avoid directly pointing out problems; instead, describe situations that evoke recognition | |
IMPORTANT ABOUT PERSONAL PRONOUNS: | |
- Avoid using "tú", "te", "tu", "tus", "contigo" and other direct second-person pronouns | |
- Instead, use third-person constructions that feel inclusive without directly addressing the reader | |
- Replace "Cuando tú aprendes inglés..." with "Cuando alguien aprende inglés..." or "Al dominar el inglés..." | |
- Use impersonal constructions: "Es posible..." instead of "Tú puedes..." | |
- Employ passive voice where appropriate to avoid direct address | |
- Use indefinite articles and pronouns: "uno", "quien", "quienes", "la persona que..." | |
- Create a sense of community with "quienes buscan...", "para aquellos que desean..." | |
- Let the reader feel spoken to without explicitly using "tú" or its variations | |
Examples of creative, high-converting headlines: | |
- "They Laughed When I Sat Down At The Piano. But When I Started to Play..." | |
- "Your Body Is Water Starving (Even If Your Mouth Isn't Dry)" | |
- "Warning: Your Productivity Software Is Secretly Making You Less Productive" | |
- "The 'Ugly' Truth About Your Morning Routine That No One Talks About" | |
- "Fired From My 9-5, Now I Make $300/Day With This Weird Trick" | |
- "Is Your Website a Ghost Town? Here's Why Nobody's Visiting" | |
- "The 7-Minute Ritual That Transformed My Sleep Quality" | |
- "What Netflix Knows About You That You Don't Know About Yourself" | |
- "The Counterintuitive Reason Most Diets Fail (It's Not What You Think)" | |
- "Your Competition Is Already Using This Tool. Are You?" | |
Use this formula to structure the ad: {selected_formula['description']} | |
{formula_examples} | |
**Important:** Review all the complete examples in the formula to understand the structure, tone, and flow. Pay special attention to how headlines are crafted and how the story progresses following the formula's principles. | |
**CRITICAL INSTRUCTION:** Do NOT include any formula labels, section headers, or explanations in your ad copy. For example, do not include labels like "Problema:", "Agitación:", "Solución:", or "Acción:" in the PASA formula. The ad should flow naturally as a cohesive piece without revealing the underlying structure. The reader should not be able to tell which formula you're using. | |
**Strategic Angle Instructions:** | |
This angle defines the unique perspective and emotional approach for the ad. | |
{angle_instruction} | |
When applying this angle: | |
- Frame all benefits through this specific perspective | |
- Use the suggested keywords naturally throughout the copy | |
- Maintain the specified style consistently in your tone and language | |
- Ensure this angle is evident in both the headline, opening paragraph and the call to action | |
- If a story theme was provided ("{story_prompt}"), make sure the angle supports and enhances this theme rather than competing with it | |
The goal is to show how {product} can transform the reader's life, connecting naturally and emotionally. | |
Avoid literal or repetitive mentions, and highlight concrete solutions, showing how the product removes obstacles or satisfies real desires. | |
Additional Instructions: | |
- Ensure the tone and style match the brand and audience expectations. | |
- Generate the ad copy in {language}. | |
- Make the headline creative, unexpected, and deeply aligned with both the story and the audience's core desires. | |
- Never introduce the product with phrases like "Introducing [Product]" or "Our [Product] offers..." - instead, weave it into the narrative as a solution that others have discovered. | |
- Refer to the product in a way that feels like a trusted recommendation, not like a company selling it. | |
- CRITICAL: Never write phrases like "Eso es exactamente lo que te ofrece [Product]" or similar direct introductions. The product should appear organically in the flow of the story. | |
- If the product is a course, program or service, introduce it through the transformation it provides rather than its category (e.g., instead of "Curso de cocina", say "estas recetas que han transformado la forma de cocinar de muchas personas" and later casually mention the name). | |
**Text Formatting Requirements:** | |
- Keep paragraphs very short - maximum 1-3 sentences per paragraph | |
- Add line breaks between all paragraphs for better readability | |
- Break up longer thoughts into multiple paragraphs | |
- Use occasional one-line paragraphs for emphasis | |
- Vary paragraph length to create rhythm and maintain interest | |
- For emotional moments or key benefits, use single-sentence paragraphs | |
- Ensure there's plenty of white space throughout the entire ad | |
- CRITICAL: Keep the total ad length between 125-150 words maximum | |
- Focus on the most impactful points rather than trying to cover everything | |
""" | |
# If a headline is provided, make the instruction even more explicit | |
if headline: | |
# Replace the first ad format with the provided headline | |
instruction = instruction.replace( | |
"| ANUNCIO PREMIUM #1 |\n\n[Headline for the first ad]", | |
f"| ANUNCIO PREMIUM #1 |\n\n{headline}" | |
) | |
# Add verification instructions | |
instruction += f""" | |
IMPORTANTE SOBRE EL TITULAR: | |
Se ha proporcionado este titular para el anuncio: | |
"{headline}" | |
VERIFICACIÓN DEL TITULAR: | |
- Si el titular usa pronombres de segunda persona (tú, te, tu, tus) o se dirige directamente al lector, modifícalo para usar construcciones en tercera persona o impersonales. | |
- Si es una pregunta directa al lector, reformúlala para que sea general o impersonal. | |
- Mantén la esencia y el gancho del titular, pero evita dirigirte directamente al lector. | |
Usa el titular proporcionado solo si cumple con estas pautas. Si no cumple, modifícalo sutilmente para mantener su impacto mientras evitas el uso de la segunda persona. | |
- Coloca este titular en una línea separada, antes del texto del anuncio | |
- Deja una línea en blanco entre el titular y el texto del anuncio | |
- El formato debe ser: | |
| ANUNCIO PREMIUM #1 | | |
{headline} | |
[Texto del anuncio comenzando con el párrafo de apertura] | |
- La respuesta debe comenzar directamente con "| ANUNCIO PREMIUM #1 |" sin ningún texto antes | |
""" | |
# Añadir verificación de políticas internamente (no visible para el usuario) | |
internal_instruction = f""" | |
INTERNAL VERIFICATION (NOT TO BE INCLUDED IN RESPONSE): | |
Facebook Policy Compliance Checks: | |
{policy_checks} | |
Ensure all ads comply with these policies before finalizing. | |
""" | |
# La instrucción interna se puede usar para verificación pero no se muestra al usuario | |
# Aquí podrías implementar alguna lógica para verificar las políticas internamente | |
return instruction |