How to use Stable Diffusion on Replicate
Quick answer
Use the
replicate Python package to run Stable Diffusion models hosted on Replicate by calling replicate.run() with the model name and input prompt. Authenticate with your REPLICATE_API_TOKEN environment variable and pass the prompt to generate images easily.PREREQUISITES
Python 3.8+pip install replicateReplicate API token set as REPLICATE_API_TOKEN environment variable
Setup
Install the replicate Python package and set your Replicate API token as an environment variable for authentication.
pip install replicate output
Collecting replicate Downloading replicate-0.11.0-py3-none-any.whl (20 kB) Installing collected packages: replicate Successfully installed replicate-0.11.0
Step by step
Use the replicate.run() function to generate an image from a prompt using the Stable Diffusion model hosted on Replicate.
import os
import replicate
# Ensure your Replicate API token is set in the environment
# export REPLICATE_API_TOKEN="your_token_here"
model_name = "stability-ai/stable-diffusion"
prompt = "A fantasy landscape with mountains and a river at sunset"
output_urls = replicate.run(
model_name,
input={"prompt": prompt, "num_outputs": 1, "width": 512, "height": 512}
)
print("Generated image URL:", output_urls[0]) output
Generated image URL: https://replicate.delivery/pbxt/abc123xyz456/image.png
Common variations
- Adjust image size by changing
widthandheightin the input dictionary. - Generate multiple images by increasing
num_outputs. - Use asynchronous calls with
replicate.async_run()for non-blocking execution.
import asyncio
import os
import replicate
async def generate_images():
model_name = "stability-ai/stable-diffusion"
prompt = "A futuristic cityscape at night"
output_urls = await replicate.async_run(
model_name,
input={"prompt": prompt, "num_outputs": 2, "width": 512, "height": 512}
)
for url in output_urls:
print("Image URL:", url)
asyncio.run(generate_images()) output
Image URL: https://replicate.delivery/pbxt/def456uvw789/image1.png Image URL: https://replicate.delivery/pbxt/def456uvw789/image2.png
Troubleshooting
- If you get an authentication error, verify your
REPLICATE_API_TOKENis correctly set in your environment. - For timeout errors, try reducing image resolution or number of outputs.
- If the model name is invalid, check the latest Stable Diffusion model name on Replicate's model page.
Key Takeaways
- Use the official
replicatePython package with your API token for Stable Diffusion image generation. - Customize output images by adjusting prompt, resolution, and number of outputs in the input parameters.
- Async calls with
replicate.async_run()enable non-blocking image generation workflows. - Always verify your API token and model name to avoid authentication and model errors.