Not being able to generate images, I am pro user but I am not able to generate images ? can someone guide me?

import requests
import json
import random
from datetime import datetime

def generate_facebook_post(api_key, topic=“positivity”):
“”“Generates post content and image using Perplexity AI”“”
try:
# Generate text post
post = generate_post_text(api_key, topic)
if not post:
return None

    # Save text post
    text_filename = save_text_to_file(post)
    
    # Generate image
    image_filename = generate_and_save_image(api_key, post, topic)
    
    return {
        "text_file": text_filename,
        "image_file": image_filename,
        "content": post
    }

except Exception as e:
    print(f"Error in main process: {e}")
    return None

def generate_post_text(api_key, topic):
“”“Generates post text using Perplexity’s chat API”“”
url = “https://api.perplexity.ai/chat/completions

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

prompt = f"""Create a Facebook post about {topic} that includes:
- 1-2 short paragraphs
- 3 relevant hashtags
- 1-2 emojis
- Friendly, inspirational tone"""

data = {
    "model": "sonar-pro",
    "messages": [
        {
            "role": "system",
            "content": "You are a social media content creator expert"
        },
        {
            "role": "user",
            "content": prompt
        }
    ]
}

try:
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()
    return response.json()['choices'][0]['message']['content'].strip()

except Exception as e:
    print(f"Text generation failed: {e}")
    return None

def generate_and_save_image(api_key, post_text, topic):
“”“Generates and saves image using Perplexity’s API”“”
url = “https://api.perplexity.ai/chat/completions

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json"
}

image_prompt = f"Create a detailed DALL-E 3 prompt for a social media image about {topic} that visually represents: {post_text}"

data = {
    "model": "sonar-pro",
    "messages": [
        {
            "role": "system",
            "content": "You are an AI image prompt generator"
        },
        {
            "role": "user",
            "content": image_prompt
        }
    ],
    "return_images": True
}

try:
    response = requests.post(url, headers=headers, json=data)
    response.raise_for_status()
    
    # Extract image URL from response
    image_url = response.json()['images'][0]['url']
    image_data = requests.get(image_url).content
    
    filename = f"facebook_post_{get_timestamp()}.png"
    with open(filename, 'wb') as f:
        f.write(image_data)
        
    return filename

except Exception as e:
    print(f"Image generation failed: {e}")
    return None

def save_text_to_file(content):
“”“Saves text content to a file with timestamp”“”
filename = f"facebook_post_{get_timestamp()}.txt"
with open(filename, ‘w’) as f:
f.write(content)
return filename

def get_timestamp():
“”“Generates timestamp for filenames”“”
return datetime.now().strftime(“%Y%m%d_%H%M%S”)

Example usage

if name == “main”:
API_KEY = YOUR_API_KEY

result = generate_facebook_post(API_KEY, "daily motivation")

if result:
    print("Successfully generated:")
    print(f"Post content: {result['content']}")
    print(f"Text file: {result['text_file']}")
    print(f"Image file: {result['image_file']}")
else:
    print("Failed to generate post")

The Perplexity API does not have the ability to generate images like it does in the main Perplexity UI. The return_images parameter is returning images that it finds on the web based on your search, like these from the Perplexity UI:

You will also need to be in tier 2 for it to actually return images it found on the web, see their usage tier documentation.


Just a side note, if you are already using Python, I highly recommend just using the OpenAI API, as Perplexity’s API is compatible with it. For example, if you were tier 2, you could ask a question and get internet images as follows:

import os
from openai import OpenAI
client = OpenAI(api_key=os.environ.get("PPLX_API_KEY"), base_url="https://api.perplexity.ai")

completion = client.chat.completions.create(
    model="sonar-pro",
    messages=[
        {
            "role": "user",
            "content": "What is the most recent version of Python?"
        }
    ],
    extra_body={"return_images": True}
)

print(completion.choices[0].message)