该页面暂无中文版本,当前显示英文内容。
API Setup Guide
GLMImage.blog•15 分钟阅读.•中级
🔗 Official Documentation
This guide uses Z.ai's official API endpoint and requires a Z.ai API key.
Integrating GLM-Image into your Python workflow unlocks powerful automation capabilities. This guide walks you through every step—from initial setup to production-ready implementation using Z.ai's official API.
Prerequisites
- Python 3.8 or higher
- Z.ai API key (from z.ai)
- requests library:
pip install requests
API Endpoints
Choose the appropriate base URL based on your region:
- Overseas:
https://api.z.ai/api/paas/v4 - Mainland China:
https://open.bigmodel.cn/api/paas/v4
API Path: /images/generations
Basic Implementation
import os
import requests
import json
class GLMImageClient:
def __init__(self, api_key, region='overseas'):
self.api_key = api_key
# Choose base URL based on region
if region == 'mainland':
self.base_url = "https://open.bigmodel.cn/api/paas/v4"
else:
self.base_url = "https://api.z.ai/api/paas/v4"
def generate(self, prompt, size="1280x1280", quality="standard"):
"""
Generate an image using GLM-Image
Args:
prompt: Text description of the image to generate
size: Image size (e.g., "1280x1280", "1472x1088", "1056x1568")
quality: "standard" (faster) or "hd" (slower but more detailed)
Returns:
URL of the generated image
"""
headers = {
'Authorization': f'Bearer {self.api_key}',
'Content-Type': 'application/json'
}
payload = {
'model': 'glm-image',
'prompt': prompt,
'size': size,
'quality': quality
}
response = requests.post(
f"{self.base_url}/images/generations",
json=payload,
headers=headers
)
if response.status_code == 200:
result = response.json()
# The API returns a URL to the generated image
return result.get('image_url') or result.get('url')
else:
raise Exception(f"API Error: {response.status_code} - {response.text}")
# Usage example
client = GLMImageClient("your_zai_api_key_here")
# Generate a simple image
try:
image_url = client.generate("A sunset over mountains")
print(f"Generated image: {image_url}")
except Exception as e:
print(f"Error: {e}")💡 Tip: The API returns a URL to your generated image. You'll need to download it or display it directly in your application.
Available Sizes
GLM-Image supports these sizes (width x height):
1280x1280- Square format (1:1 ratio)1568x1056- Landscape format (3:2 ratio)1056x1568- Portrait format (2:3 ratio)1472x1088- Landscape format (4:3 ratio)1088x1472- Portrait format (3:4 ratio)1728x960- Wide landscape format (9:5 ratio)960x1728- Tall portrait format (5:9 ratio)
Quality Options
- standard: Faster generation, good for most use cases
- hd: Higher quality, more detailed output (slower, uses more credits)
Batch Processing
Process multiple prompts efficiently:
def generate_batch(prompts, size="1280x1280", max_workers=3):
from concurrent.futures import ThreadPoolExecutor
def generate_single(prompt):
return client.generate(prompt, size=size)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
results = list(executor.map(generate_single, prompts))
return results
# Process multiple prompts
prompts = [
"A dragon flying over mountains",
"A medieval castle at sunset",
"A knight in shining armor",
"A mysterious dark forest",
"A magical glowing sword"
]
image_urls = generate_batch(prompts, size="1472x1088")
for i, url in enumerate(image_urls):
print(f"Image {i+1}: {url}")Flask Web App Integration
Integrate GLM-Image into a Flask web application:
from flask import Flask, request, jsonify
from flask_cors import CORS
app = Flask(__name__)
CORS(app) # Enable CORS for web access
# Initialize client with API key from environment
client = GLMImageClient(
api_key=os.getenv("ZAI_API_KEY"),
region=os.getenv("ZAI_REGION", "overseas")
)
@app.route('/api/generate', methods=['POST'])
def generate_image():
try:
data = request.json
prompt = data.get('prompt')
size = data.get('size', '1280x1280')
quality = data.get('quality', 'standard')
if not prompt:
return jsonify({'error': 'Prompt is required'}), 400
image_url = client.generate(prompt, size=size, quality=quality)
return jsonify({'url': image_url, 'success': True})
except Exception as e:
return jsonify({'error': str(e), 'success': False}), 500
@app.route('/health', methods=['GET'])
def health_check():
return jsonify({'status': 'healthy', 'service': 'GLM-Image API'})
if __name__ == '__main__':
app.run(debug=True, port=5000)Error Handling
Robust error handling for production use:
import time
from typing import Optional
def generate_with_retry(prompt: str, max_retries: int = 3,
delay: float = 1.0) -> Optional[str]:
"""Generate image with automatic retry on failure"""
for attempt in range(max_retries):
try:
return client.generate(prompt)
except Exception as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
time.sleep(delay * (attempt + 1)) # Exponential backoff
else:
print("All retries exhausted")
return None
# Usage
image_url = generate_with_retry("A complex technical diagram", max_retries=3)
if image_url:
print(f"Success: {image_url}")
else:
print("Failed after all retries")Production Checklist
✓
Store API keys securely (environment variables)✓
Implement rate limiting (max 10 req/sec)✓
Add comprehensive error handling✓
Monitor API usage and costs✓
Use appropriate size and quality for your use case✓
Implement retry logic for failed requests