File size: 2,899 Bytes
de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 de08998 76c3397 |
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 |
"""
GPT-based researcher implementation.
Uses Chat Completions API with response_format for structured JSON output.
"""
import json
from openai import OpenAI
from backend.pydantic_schema import ImageAdEssentialsOutput
from backend.prompt import get_system_prompt, get_user_prompt
from dotenv import load_dotenv
import os
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# JSON schema for strict structured output (matches ImageAdEssentialsOutput)
RESEARCH_RESPONSE_SCHEMA = {
"type": "object",
"properties": {
"output": {
"type": "array",
"items": {
"type": "object",
"properties": {
"phsychologyTriggers": {"type": "string"},
"angles": {"type": "array", "items": {"type": "string"}},
"concepts": {"type": "array", "items": {"type": "string"}},
},
"required": ["phsychologyTriggers", "angles", "concepts"],
"additionalProperties": False,
},
}
},
"required": ["output"],
"additionalProperties": False,
}
def researcher_gpt(
target_audience: str,
product_category: str,
product_description: str,
count: int = 5,
):
"""
GPT-based researcher function using Chat Completions with structured output.
Args:
target_audience: Target audience from the predefined list
product_category: Product category (e.g., "ring", "bangles")
product_description: Description of the product
count: Number of psychology triggers (concepts/angles) to generate
Returns:
list[ImageAdEssentials]: List of psychology triggers, angles, and concepts
"""
if not OPENAI_API_KEY:
raise ValueError("OPENAI_API_KEY is not set in the environment.")
gpt_client = OpenAI(api_key=OPENAI_API_KEY)
system_prompt = get_system_prompt()
user_prompt = get_user_prompt(
target_audience, product_category, product_description, count
)
response = gpt_client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
response_format={
"type": "json_schema",
"json_schema": {
"name": "image_ad_essentials_output",
"strict": True,
"schema": RESEARCH_RESPONSE_SCHEMA,
},
},
temperature=0.7,
)
msg = response.choices[0].message
if not msg.content:
raise ValueError("GPT returned an empty response.")
try:
data = json.loads(msg.content)
parsed = ImageAdEssentialsOutput(**data)
return parsed.output
except (json.JSONDecodeError, TypeError) as e:
raise ValueError(f"GPT returned invalid JSON: {e}") from e
|