Article·replicate.com
AIinferenceAPIaiapimachine-learningpythonstable-diffusion
Replicate
Quickly run open-source AI models like Stable Diffusion or Llama via a simple API. This action pack shows you how to integrate powerful AI inference into your applications without managing complex infrastructure.
beginner15 min5 steps
The play
- Get Your Replicate API TokenSign up for a free account at replicate.com and navigate to your account settings to find your API token. Keep it secure.
- Install the Replicate Python ClientOpen your terminal or command prompt and install the official Replicate Python client using pip.
- Choose an AI ModelBrowse replicate.com/explore to find a model you want to use (e.g., an image generation, text, or audio model). Note its full identifier (e.g., 'stability-ai/stable-diffusion:ac732df83cea7fff18b47247d0d2feb6b4ee548ecdc1a9ff72a417eef4672c67').
- Make an API CallWrite a Python script to call your chosen model. Set your API token as an environment variable and pass your inputs to the `replicate.run()` function.
- Process the OutputThe `output` variable will contain the model's results. For image models, this is often a list of URLs. For text models, it's typically a string or list of strings. Handle the output according to the model's documentation.
Starter code
import replicate
import os
# 1. Replace with your actual Replicate API token
os.environ["REPLICATE_API_TOKEN"] = "YOUR_REPLICATE_API_TOKEN"
# 2. Choose a model ID (e.g., Stable Diffusion 2.1)
model_id = "stability-ai/stable-diffusion:ac732df83cea7fff18b47247d0d2feb6b4ee548ecdc1a9ff72a417eef4672c67"
# 3. Define your model inputs
input_data = {
"prompt": "a serene Japanese garden with cherry blossoms, digital art, highly detailed",
"width": 768,
"height": 768
}
print(f"Running model '{model_id}' with prompt: '{input_data['prompt']}'...")
# 4. Run the model
output = replicate.run(model_id, input=input_data)
# 5. Print the output (e.g., URL to the generated image)
if output:
print("Generated Image URL:")
for item in output:
print(item)
else:
print("No output received from the model.")Source