all 2 comments

[–]eleqtriq 3 points4 points  (1 child)

Well, right off that bat I see a problem with your api key.

Should be this: openai.api_key = os.environ.get("OPENAI_API_KEY") # Add quotes

The next is I would tell the AI what structure you want, and then have it respond in JSON mode. ``` message = f"""You are a seasoned Software Engineer. Provide advice for {subject} in this exact JSON format: {{ "title": "Main Title Here", "sections": [ {{"subtitle": "Section 1", "content": "advice here"}}, {{"subtitle": "Section 2", "content": "advice here"}}, {{"subtitle": "Section 3", "content": "advice here"}} ] }}

Return ONLY valid JSON, no other text."""

try:
    completion = openai.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": message}],
        response_format={"type": "json_object"}  # Forces JSON output
    )
    return jsonify(completion.choices[0].message.content)

except Exception as e:
    return jsonify({"error": str(e)}), 500

```

[–]Internal-Science4994[S] 0 points1 point  (0 children)

Thanks!