Home Blog API Integration Guide
Intermediate
30 min read
December 19, 2024

OmniGen2 API Integration Guide

Complete developer guide to integrating OmniGen2's powerful AI capabilities into your applications

1. API Overview

OmniGen2 provides a comprehensive RESTful API that allows developers to integrate advanced multimodal AI capabilities into their applications. The API supports text-to-image generation, image editing, visual understanding, and more.

Text-to-Image

Generate high-quality images from text descriptions

Image Editing

Modify existing images with natural language instructions

Visual Understanding

Analyze and describe image content with AI

Style Transfer

Apply artistic styles and transformations

API Specifications

  • Base URL: https://api.omnigen2.pro/v1
  • Protocol: HTTPS only
  • Format: JSON request/response
  • Authentication: API Key based
  • Rate Limits: Configurable per plan

2. Authentication

Getting Your API Key

To use the OmniGen2 API, you'll need an API key. Follow these steps:

1

Sign Up

Create an account at omnigen2.pro

2

Get API Key

Navigate to your dashboard and generate a new API key

3

Secure Storage

Store your API key securely and never expose it in client-side code

Authentication Methods

Header Authentication (Recommended)

curl -H "Authorization: Bearer YOUR_API_KEY" \
     -H "Content-Type: application/json" \
     https://api.omnigen2.pro/v1/generate

Query Parameter (Alternative)

curl "https://api.omnigen2.pro/v1/generate?api_key=YOUR_API_KEY"

3. API Endpoints

POST /v1/generate

Text-to-Image Generation

Generate images from text descriptions

Request Body:
{
  "prompt": "A beautiful sunset over mountains",
  "width": 1024,
  "height": 1024,
  "style": "photorealistic",
  "quality": "high",
  "num_images": 1
}
POST /v1/edit

Image Editing

Edit existing images with natural language instructions

Request Body:
{
  "image": "base64_encoded_image",
  "instruction": "Add a rainbow in the sky",
  "strength": 0.8,
  "preserve_structure": true
}
POST /v1/understand

Visual Understanding

Analyze and describe image content

Request Body:
{
  "image": "base64_encoded_image",
  "include_objects": true,
  "include_description": true,
  "include_emotions": true
}
GET /v1/models

List Available Models

Get information about available AI models

4. Python SDK

Installation

pip install omnigen2

Basic Usage

# 导入OmniGen2 SDK
import omnigen2
from omnigen2 import OmniGen2Client

# 初始化客户端
client = OmniGen2Client(
    api_key="your_api_key_here",
    base_url="https://api.omnigen2.pro/v1"
)

# 生成图像
response = client.text_to_image(
    prompt="A futuristic cityscape with flying cars",
    width=1024,
    height=1024,
    style="photorealistic",
    quality="high"
)

# 保存图像
with open("generated_image.png", "wb") as f:
    f.write(response.image_data)

print(f"Image generated successfully: {response.image_url}")

Advanced Python Examples

Batch Image Generation

# 批量生成图像
prompts = [
    "A serene lake at sunset",
    "A bustling city street at night",
    "A peaceful forest clearing"
]

for i, prompt in enumerate(prompts):
    response = client.text_to_image(
        prompt=prompt,
        width=512,
        height=512,
        num_images=3
    )
    
    # 保存每个生成的图像
    for j, image_data in enumerate(response.images):
        filename = f"batch_{i}_{j}.png"
        with open(filename, "wb") as f:
            f.write(image_data)
        print(f"Saved: {filename}")

Image Editing Pipeline

# 图像编辑流水线
import base64
from PIL import Image
import io

# 读取原始图像
with open("original.jpg", "rb") as f:
    image_data = f.read()
    image_b64 = base64.b64encode(image_data).decode()

# 应用多个编辑步骤
edits = [
    "Make the sky more dramatic",
    "Add warm lighting",
    "Enhance the colors"
]

current_image = image_b64
for edit in edits:
    response = client.edit_image(
        image=current_image,
        instruction=edit,
        strength=0.7
    )
    current_image = response.image_b64
    
    # 保存中间结果
    with open(f"edit_{edits.index(edit)}.png", "wb") as f:
        f.write(base64.b64decode(current_image))

print("Editing pipeline completed!")

5. JavaScript SDK

Installation

npm install omnigen2-js

Basic Usage

// 导入OmniGen2 JavaScript SDK
import { OmniGen2Client } from 'omnigen2-js';

// 初始化客户端
const client = new OmniGen2Client({
    apiKey: 'your_api_key_here',
    baseUrl: 'https://api.omnigen2.pro/v1'
});

// 生成图像
async function generateImage() {
    try {
        const response = await client.textToImage({
            prompt: 'A beautiful landscape with mountains and a lake',
            width: 1024,
            height: 1024,
            style: 'photorealistic',
            quality: 'high'
        });
        
        console.log('Image generated:', response.imageUrl);
        return response;
    } catch (error) {
        console.error('Error generating image:', error);
    }
}

// 调用函数
generateImage();

React Integration Example

// React组件示例
import React, { useState } from 'react';
import { OmniGen2Client } from 'omnigen2-js';

const ImageGenerator = () => {
    const [prompt, setPrompt] = useState('');
    const [imageUrl, setImageUrl] = useState('');
    const [loading, setLoading] = useState(false);
    
    const client = new OmniGen2Client({
        apiKey: process.env.REACT_APP_OMNIGEN2_API_KEY
    });
    
    const handleGenerate = async () => {
        setLoading(true);
        try {
            const response = await client.textToImage({
                prompt: prompt,
                width: 512,
                height: 512
            });
            setImageUrl(response.imageUrl);
        } catch (error) {
            console.error('Generation failed:', error);
        } finally {
            setLoading(false);
        }
    };
    
    return (
        <div className="image-generator">
            <input
                type="text"
                value={prompt}
                onChange={(e) => setPrompt(e.target.value)}
                placeholder="Enter your image description..."
            />
            <button onClick={handleGenerate} disabled={loading}>
                {loading ? 'Generating...' : 'Generate Image'}
            </button>
            {imageUrl && <img src={imageUrl} alt="Generated" />}
        </div>
    );
};

export default ImageGenerator;

6. Code Examples

Node.js Express Server

// Express服务器示例
const express = require('express');
const { OmniGen2Client } = require('omnigen2-js');

const app = express();
const client = new OmniGen2Client({
    apiKey: process.env.OMNIGEN2_API_KEY
});

app.use(express.json());

// 图像生成端点
app.post('/api/generate', async (req, res) => {
    try {
        const { prompt, width = 512, height = 512 } = req.body;
        
        const response = await client.textToImage({
            prompt,
            width,
            height,
            quality: 'high'
        });
        
        res.json({
            success: true,
            imageUrl: response.imageUrl,
            metadata: response.metadata
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            error: error.message
        });
    }
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

PHP Integration

<?php
// PHP集成示例
class OmniGen2Client {
    private $apiKey;
    private $baseUrl;
    
    public function __construct($apiKey) {
        $this->apiKey = $apiKey;
        $this->baseUrl = 'https://api.omnigen2.pro/v1';
    }
    
    public function textToImage($prompt, $options = []) {
        $data = array_merge([
            'prompt' => $prompt,
            'width' => 512,
            'height' => 512,
            'quality' => 'high'
        ], $options);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->baseUrl . '/generate');
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Authorization: Bearer ' . $this->apiKey,
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        return json_decode($response, true);
    }
}

// 使用示例
$client = new OmniGen2Client('your_api_key_here');
$result = $client->textToImage('A beautiful sunset over the ocean');

if ($result['success']) {
    echo "Image generated: " . $result['imageUrl'];
} else {
    echo "Error: " . $result['error'];
}
?>

7. Error Handling

Common Error Codes

400 - Bad Request

Invalid request parameters or malformed JSON

Example Response:
{
  "error": "Invalid prompt length",
  "code": "INVALID_PROMPT",
  "message": "Prompt must be between 1 and 1000 characters"
}

401 - Unauthorized

Invalid or missing API key

429 - Rate Limited

Too many requests, rate limit exceeded

500 - Server Error

Internal server error, try again later

Error Handling Best Practices

# Python错误处理示例
import time
from omnigen2 import OmniGen2Client, OmniGen2Error

def generate_with_retry(client, prompt, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = client.text_to_image(prompt=prompt)
            return response
        except OmniGen2Error as e:
            if e.status_code == 429:  # 速率限制
                wait_time = 2 ** attempt  # 指数退避
                print(f"Rate limited, waiting {wait_time}s...")
                time.sleep(wait_time)
            elif e.status_code == 500:  # 服务器错误
                print(f"Server error, retrying in {attempt + 1}s...")
                time.sleep(attempt + 1)
            else:
                raise e  # 其他错误直接抛出
    
    raise Exception("Max retries exceeded")

9. Best Practices

Security

  • Never expose API keys in client-side code
  • Use environment variables for API keys
  • Implement proper authentication in your app
  • Rotate API keys regularly

Performance

  • Implement caching for repeated requests
  • Use appropriate image sizes for your use case
  • Implement request queuing for high volume
  • Monitor API usage and optimize accordingly

Error Handling

  • Implement exponential backoff for retries
  • Handle rate limiting gracefully
  • Provide meaningful error messages to users
  • Log errors for debugging and monitoring

User Experience

  • Show loading states during generation
  • Provide progress feedback when possible
  • Allow users to cancel long-running requests
  • Implement proper error messaging

10. Production Deployment

Environment Configuration

# .env文件示例
OMNIGEN2_API_KEY=your_production_api_key
OMNIGEN2_BASE_URL=https://api.omnigen2.pro/v1
REDIS_URL=redis://localhost:6379
DATABASE_URL=postgresql://user:pass@localhost/db

Docker Deployment

# Dockerfile示例
FROM node:18-alpine

WORKDIR /app

# 复制package.json和安装依赖
COPY package*.json ./
RUN npm ci --only=production

# 复制应用代码
COPY . .

# 设置环境变量
ENV NODE_ENV=production

# 暴露端口
EXPOSE 3000

# 启动应用
CMD ["npm", "start"]

Monitoring and Logging

API Usage Monitoring

Track API calls, response times, and error rates to optimize performance and costs.

Error Tracking

Implement comprehensive error logging to quickly identify and resolve issues.

Performance Metrics

Monitor generation times, cache hit rates, and user satisfaction metrics.