StyleSync-AI / agents /writer_agent.py
Pathakkunal's picture
Deploy: StyleSync AI Phase 5 (Fixes Applied)
0fc3485
raw
history blame
2.74 kB
import os
import json
import re
from groq import Groq
from dotenv import load_dotenv
load_dotenv()
class WriterAgent:
def __init__(self):
self.api_key = os.getenv("GROQ_API_KEY")
if not self.api_key:
print("⚠️ GROQ_API_KEY missing.")
self.client = None
else:
self.client = Groq(api_key=self.api_key)
self.model = "llama-3.3-70b-versatile"
def write_listing(self, visual_data: dict, seo_keywords: list) -> dict:
if not self.client:
return {"error": "No API Key"}
# Sanitization: Ensure data is clean string
style = str(visual_data.get('design_style', 'modern'))
system_prompt = """You are an expert e-commerce copywriter.
Your task is to write a high-converting product listing.
CRITICAL RULES:
1. Return ONLY valid JSON.
2. Do not include markdown formatting (like ```json).
3. Escape any double quotes inside the description string.
4. Keep the 'description' to 1-2 paragraphs max.
JSON Structure:
{
"title": "SEO Optimized Title",
"description": "Engaging product description...",
"features": ["Feature 1", "Feature 2", "Feature 3"],
"price_estimate": "$XX-$XX"
}
"""
user_content = f"""
PRODUCT DATA:
{json.dumps(visual_data, indent=2)}
KEYWORDS:
{', '.join(seo_keywords)}
"""
try:
completion = self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_content}
],
# LOWER TEMPERATURE TO 0.3 TO PREVENT SYNTAX ERRORS
temperature=0.3,
response_format={"type": "json_object"}
)
content = completion.choices[0].message.content
# Extra Safety: Attempt to repair common JSON strings if needed
try:
return json.loads(content)
except json.JSONDecodeError:
# If strict parsing fails, try to strip markdown
content = content.replace("```json", "").replace("```", "").strip()
return json.loads(content)
except Exception as e:
print(f"❌ Writer Error: {e}")
return {
"title": "Error Generating Listing",
"description": "Please try again. The AI model output invalid data.",
"features": [],
"error": str(e)
}