Prompt Engineering Templates for Marketers
Marketers waste hours manually rewriting prompts to fix inconsistent AI outputs. Python f-string templating solves this by enforcing deterministic variable injection and structured JSON responses. This guide delivers three production-ready scripts for ad copy, email sequences, and social calendars. Copy, paste, and run.
Environment Setup and API Configuration
Isolate dependencies and configure your API key before execution:
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install openai python-dotenv
Create a .env file in your project root:
OPENAI_API_KEY=your_api_key_here
Before executing these scripts, ensure your environment is configured according to the core principles outlined in Python AI Fundamentals for Non-Developers.
Core Template Architecture
Every template follows a strict pattern: static system instructions, dynamic f-string variable mapping, API payload construction, and enforced JSON parsing. This architecture eliminates hallucination drift and guarantees machine-readable outputs.
import os, json, time, csv
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
def safe_api_call(prompt: str, retries: int = 2) -> dict | list:
for attempt in range(retries):
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "system", "content": "Return ONLY valid JSON."},
{"role": "user", "content": prompt}],
response_format={"type": "json_object"},
temperature=0.3,
timeout=30
)
return json.loads(response.choices[0].message.content)
except Exception as e:
if attempt == retries - 1: raise
time.sleep(2)
Template 1: High-Converting Ad Copy Generator
def generate_ad_copy(product_name: str, target_audience: str, platform: str, tone: str) -> dict:
prompt = f"""Generate a {platform} ad for '{product_name}' targeting {target_audience}.
Tone: {tone}. Return JSON with keys: 'headline', 'body', 'cta'."""
return safe_api_call(prompt)
Template 2: Automated Email Sequence Builder
def build_email_sequence(campaign_goal: str, customer_segment: str, sequence_length: int) -> list:
emails = []
for i in range(1, sequence_length + 1):
prompt = f"""Write email {i} of a {sequence_length}-part sequence.
Goal: {campaign_goal}. Segment: {customer_segment}.
Return JSON: 'subject', 'preview_text', 'body_snippet'."""
emails.append(safe_api_call(prompt))
return emails
Template 3: Social Media Content Calendar
def generate_social_calendar(niche: str, post_count: int, content_pillars: list) -> list:
prompt = f"""Create a {post_count}-post calendar for the {niche} niche.
Pillars: {', '.join(content_pillars)}.
Return JSON array of objects: 'post_text', 'hashtags', 'visual_prompt', 'scheduled_date'."""
return safe_api_call(prompt)
Execution, Validation, and Output Parsing
Run scripts directly in your terminal or notebook. Validate LLM responses using Python’s native json module and structured error handling. Export results to CSV for immediate CRM or scheduling tool import:
def export_to_csv(data: list[dict], filename: str = "marketing_outputs.csv"):
if not data: return
with open(filename, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=data[0].keys())
writer.writeheader()
writer.writerows(data)
# Example execution
if __name__ == "__main__":
ads = generate_ad_copy("EcoBottle", "fitness enthusiasts", "Instagram", "motivational")
export_to_csv([ads])
Optimization and Iteration Workflows
Control output variance by adjusting temperature (0.0–0.5 for consistency), top_p, and max_tokens. Implement A/B prompt testing by iterating through parameter lists and logging performance metrics. For deeper control over model behavior and instruction hierarchy, review the structural guidelines in Prompt Engineering Basics.