SJinn
Tool API

Tool API

Directly invoke AI tools to generate videos and images with Veo3, Sora2, Nano Banana, and more

Tool API Overview

The Tool API allows you to directly invoke various AI tools on the SJinn platform, including video generation and image generation tools. Unlike the Agent API, the Tool API provides direct access to specific tools, giving you precise control over which model and parameters to use.

Supported Tools

Video Generation Tools

Veo3 Text-to-Video - veo3-text-to-video-fast-api

  • Type: Video Generation
  • Cost: 420 credits per task
  • Documentation: View Details

Veo3 Image-to-Video - veo3-image-to-video-fast-api

  • Type: Video Generation
  • Cost: 420 credits per task
  • Documentation: View Details

Sora2 Text-to-Video - sora2-text-to-video-api

  • Type: Video Generation
  • Cost: 420 credits (Std mode) / 2100 credits (Pro mode)
  • Documentation: View Details

Sora2 Image-to-Video - sora2-image-to-video-api

  • Type: Video Generation
  • Cost: 420 credits (Std mode) / 2100 credits (Pro mode)
  • Documentation: View Details

Image Generation Tools

Nano Banana Image - nano-banana-image-api

  • Type: Image Generation
  • Cost: 50 credits per task
  • Documentation: View Details

Nano Banana Pro - nano-banana-image-pro-api

  • Type: Image Generation
  • Cost: 150 credits per task
  • Documentation: View Details

Create Tool Task

Create a new task using a specified tool.

Request

POST /api/un-api/create_tool_task
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

Common Parameters

  • tool_type (string, required) - Tool identifier, see the supported tools table above
  • input (object, required) - Tool-specific input parameters object. Each tool has different parameters, see individual tool documentation for details

Important: All image URLs provided in the input parameters must be complete, accessible HTTP/HTTPS addresses (e.g., https://cdn.sjinn.ai/uploads/image.jpg). Relative paths are not supported.

Request Examples

Veo3 Text-to-Video

{
  "tool_type": "veo3-text-to-video-fast-api",
  "input": {
    "prompt": "A majestic dragon flying through clouds at sunset",
    "aspect_ratio": "16:9"
  }
}

Sora2 Image-to-Video (Pro Mode)

{
  "tool_type": "sora2-image-to-video-api",
  "input": {
    "prompt": "The person smiles and waves at the camera",
    "image": "https://cdn.sjinn.ai/uploads/portrait.jpg",
    "aspect_ratio": "16:9",
    "mode": "pro",
    "duration": "10s"
  }
}

Nano Banana Pro Image Generation

{
  "tool_type": "nano-banana-image-pro-api",
  "input": {
    "prompt": "A breathtaking landscape of northern lights",
    "aspect_ratio": "16:9",
    "resolution": "4K"
  }
}

Using cURL

curl -X POST https://sjinn.ai/api/un-api/create_tool_task \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "tool_type": "veo3-text-to-video-fast-api",
    "input": {
      "prompt": "A serene sunset over the ocean",
      "aspect_ratio": "16:9"
    }
  }'

Using JavaScript

const response = await fetch('https://sjinn.ai/api/un-api/create_tool_task', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    tool_type: 'veo3-text-to-video-fast-api',
    input: {
      prompt: 'A serene sunset over the ocean',
      aspect_ratio: '16:9',
    },
  }),
});

const result = await response.json();
console.log('Task ID:', result.data.task_id);

Using Python

import requests

url = 'https://sjinn.ai/api/un-api/create_tool_task'
headers = {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
}
data = {
    'tool_type': 'veo3-text-to-video-fast-api',
    'input': {
        'prompt': 'A serene sunset over the ocean',
        'aspect_ratio': '16:9'
    }
}

response = requests.post(url, json=data, headers=headers)
result = response.json()
print('Task ID:', result['data']['task_id'])

Success Response

{
  "success": true,
  "errorMsg": "",
  "error_code": 0,
  "data": {
    "task_id": "550e8400-e29b-41d4-a716-446655440000"
  }
}

Response Fields

  • success (boolean) - Whether the request was successful
  • errorMsg (string) - Error message (if failed)
  • error_code (number) - Error code (0 for success)
  • data.task_id (string) - Unique task identifier for status queries

Query Task Status

Query the execution status and results of a tool task.

Request

POST Method:

POST /api/un-api/query_tool_task_status
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

GET Method:

GET /api/un-api/query_tool_task_status?task_id=YOUR_TASK_ID
Authorization: Bearer YOUR_API_KEY

Parameters

  • task_id (string, required) - Task ID returned from create_tool_task

Request Example (POST)

{
  "task_id": "550e8400-e29b-41d4-a716-446655440000"
}

Request Example (GET)

curl -X GET "https://sjinn.ai/api/un-api/query_tool_task_status?task_id=550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Bearer YOUR_API_KEY"

Using JavaScript

const response = await fetch('https://sjinn.ai/api/un-api/query_tool_task_status', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    task_id: '550e8400-e29b-41d4-a716-446655440000',
  }),
});

const result = await response.json();
console.log('Status:', result.data.status);
console.log('Output URLs:', result.data.output_urls);

Using Python

import requests

url = 'https://sjinn.ai/api/un-api/query_tool_task_status'
headers = {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
}
data = {
    'task_id': '550e8400-e29b-41d4-a716-446655440000'
}

response = requests.post(url, json=data, headers=headers)
result = response.json()
print('Status:', result['data']['status'])
if result['data'].get('output_urls'):
    print('Output URLs:', result['data']['output_urls'])

Success Response

{
  "success": true,
  "errorMsg": "",
  "error_code": 0,
  "data": {
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "task_type": "veo3-text-to-video-fast-api",
    "status": 1,
    "output_urls": [
      "https://cdn.sjinn.ai/videos/output_video.mp4"
    ],
    "input": {
      "prompt": "A serene sunset over the ocean",
      "aspect_ratio": "16:9"
    },
    "create_time": "2024-01-15T10:30:00Z",
    "update_time": "2024-01-15T10:35:00Z"
  }
}

Response Fields

  • success (boolean) - Whether the request was successful
  • data.task_id (string) - Task ID
  • data.task_type (string) - Tool type identifier
  • data.status (number) - Task status code
  • data.output_urls (string[]) - Output file URL array (available after task completion)
  • data.error (string) - Error message (if task failed)
  • data.input (object) - Task input parameters
  • data.create_time (string) - Task creation time
  • data.update_time (string) - Task last update time

Task Status Codes

  • 0 - Initializing/Processing
  • 1 - Completed
  • -1 - Failed

Complete Workflow Example

Here's a complete example of creating a task and polling for results:

const API_KEY = 'YOUR_API_KEY';
const BASE_URL = 'https://sjinn.ai/api/un-api';

// Step 1: Create task
async function createTask(toolType, input) {
  const response = await fetch(`${BASE_URL}/create_tool_task`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      tool_type: toolType,
      input: input,
    }),
  });
  
  const result = await response.json();
  if (!result.success) {
    throw new Error(result.errorMsg);
  }
  return result.data.task_id;
}

// Step 2: Poll for task status
async function waitForCompletion(taskId, maxAttempts = 60) {
  for (let i = 0; i < maxAttempts; i++) {
    const response = await fetch(`${BASE_URL}/query_tool_task_status`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ task_id: taskId }),
    });
    
    const result = await response.json();
    
    if (result.data.status === 1) {
      // Task completed
      return result.data;
    } else if (result.data.status === -1) {
      // Task failed
      throw new Error(result.data.error || 'Task failed');
    }
    
    // Task still processing, wait and retry
    console.log(`Task is processing... (${i + 1}/${maxAttempts})`);
    await new Promise(resolve => setTimeout(resolve, 10000)); // Wait 10 seconds
  }
  
  throw new Error('Timeout waiting for task completion');
}

// Usage example
async function main() {
  try {
    // Create Veo3 text-to-video task
    const taskId = await createTask('veo3-text-to-video-fast-api', {
      prompt: 'A cinematic shot of a dragon flying over mountains',
      aspect_ratio: '16:9',
    });
    
    console.log('Task created:', taskId);
    
    // Wait for task completion
    const result = await waitForCompletion(taskId);
    
    // Get output video URL
    if (result.output_urls && result.output_urls.length > 0) {
      console.log('Video URL:', result.output_urls[0]);
    }
  } catch (error) {
    console.error('Error:', error.message);
  }
}

main();

Python Complete Example

import requests
import time

API_KEY = 'YOUR_API_KEY'
BASE_URL = 'https://sjinn.ai/api/un-api'

def create_task(tool_type, input_data):
    """Create a tool task"""
    url = f'{BASE_URL}/create_tool_task'
    headers = {
        'Authorization': f'Bearer {API_KEY}',
        'Content-Type': 'application/json'
    }
    data = {
        'tool_type': tool_type,
        'input': input_data
    }
    
    response = requests.post(url, json=data, headers=headers)
    result = response.json()
    
    if not result['success']:
        raise Exception(result['errorMsg'])
    
    return result['data']['task_id']

def wait_for_completion(task_id, max_attempts=60):
    """Poll task status until completion"""
    url = f'{BASE_URL}/query_tool_task_status'
    headers = {
        'Authorization': f'Bearer {API_KEY}',
        'Content-Type': 'application/json'
    }
    
    for i in range(max_attempts):
        response = requests.post(url, json={'task_id': task_id}, headers=headers)
        result = response.json()
        
        if result['data']['status'] == 1:
            # Task completed
            return result['data']
        elif result['data']['status'] == -1:
            # Task failed
            raise Exception(result['data'].get('error', 'Task failed'))
        
        # Task still processing
        print(f'Task is processing... ({i + 1}/{max_attempts})')
        time.sleep(10)  # Wait 10 seconds
    
    raise Exception('Timeout waiting for task completion')

# Usage example
def main():
    try:
        # Create Nano Banana Pro image generation task
        task_id = create_task('nano-banana-image-pro-api', {
            'prompt': 'A breathtaking landscape of northern lights over snowy mountains',
            'aspect_ratio': '16:9',
            'resolution': '2K'
        })
        
        print(f'Task created: {task_id}')
        
        # Wait for task completion
        result = wait_for_completion(task_id)
        
        # Get output image URL
        if result.get('output_urls') and len(result['output_urls']) > 0:
            print(f'Image URL: {result["output_urls"][0]}')
    
    except Exception as e:
        print(f'Error: {str(e)}')

if __name__ == '__main__':
    main()

Error Codes

  • 0 - Success
  • 100 - Insufficient balance
  • 101 - Membership required or insufficient membership tier
  • 400 - Invalid request parameters
  • 401 - Invalid or missing access token
  • 403 - Unauthorized access
  • 404 - Resource not found
  • 500 - Internal server error

Error Response Examples

{
  "success": false,
  "errorMsg": "Insufficient balance",
  "error_code": 100
}
{
  "success": false,
  "errorMsg": "prompt is required",
  "error_code": 400
}
{
  "success": false,
  "errorMsg": "Invalid API token",
  "error_code": 401
}

Best Practices

1. Tool Selection

  • Video Generation:

    • Veo3: Ideal for fast, high-quality video generation with start/end frame control
    • Sora2: Offers Std and Pro modes, Pro mode delivers higher quality
  • Image Generation:

    • Nano Banana Standard: Fast and economical, suitable for everyday use
    • Nano Banana Pro: Supports high resolution (up to 4K), ideal for professional use

2. Polling Strategy

  • Video Tasks: Poll every 10-15 seconds, typically takes 2-10 minutes
  • Image Tasks: Poll every 5-10 seconds, typically takes 10-90 seconds
  • Timeout Setting: Recommend setting a 10-15 minute timeout

3. Error Handling

  • Always check the success field
  • Handle errors based on error_code
  • Credits are automatically refunded when tasks fail (if already deducted)

4. Cost Optimization

  • Use Std mode for testing and prototyping
  • Switch to Pro mode or high resolution after confirming results
  • Monitor credit usage to optimize costs

5. Best Practices

  • Save the returned task_id for subsequent queries
  • Implement reasonable retry mechanisms
  • Log task input parameters and output results
  • Control concurrency for batch tasks to avoid overload

Rate Limits

  • Tool tasks consume credits based on the tool used
  • See the Supported Tools table for costs per tool
  • Concurrent task limits depend on your subscription plan
  • Recommend implementing a request queue to avoid exceeding limits

Related Links