Python Integration Guide

This guide provides comprehensive Python code examples for integrating with NeuraSutra API Management, with a focus on image models.

Basic Setup

Installation

pip install requests pillow

Client Configuration

import requests
import base64
from pathlib import Path
from PIL import Image
from io import BytesIO

class NeuraSutraClient:
    """Simple client for NeuraSutra API Management."""

    def __init__(self, api_key: str, base_url: str = "http://localhost:8000/api/v1"):
        self.api_key = api_key
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            "Content-Type": "application/json",
            "X-API-Key": api_key
        })

    def generate(self, service: str, model: str, inputs: list, parameters: dict = None, history: list = None):
        """Make a generation request."""
        payload = {
            "service_name": service,
            "model_name": model,
            "input": inputs
        }
        if parameters:
            payload["parameters"] = parameters
        if history:
            payload["history"] = history

        response = self.session.post(f"{self.base_url}/generate", json=payload)
        return response.json()

    def get_usage(self):
        """Get current usage stats."""
        response = self.session.get(f"{self.base_url}/usage")
        return response.json()

# Initialize client
client = NeuraSutraClient(api_key="sk_your_api_key_here")

Input Types Reference

The API uses typed inputs for flexibility:

# Text input
{"type": "text", "name": "input", "content": "Your prompt here"}

# Image input (base64 data URL)
{"type": "image", "name": "input", "content": "data:image/png;base64,iVBOR..."}

# Context (background information)
{"type": "text", "name": "context", "content": "Background context..."}

# Reference (for image editing)
{"type": "image", "name": "reference", "content": "data:image/png;base64,..."}

Text Generation

Simple Text Request

result = client.generate(
    service="google-gemini",
    model="gemini-2.0-flash",
    inputs=[
        {"type": "text", "name": "input", "content": "Explain quantum computing in simple terms."}
    ],
    parameters={
        "temperature": 0.7,
        "max_output_tokens": 500
    }
)

if result["status"] == "success":
    for item in result["output"]:
        if item["type"] == "text" and item["name"] == "output":
            print(item["content"])
    print(f"\nCost: ${result['cost']['total']:.4f}")
else:
    print(f"Error: {result['error']['message']}")

With System Prompt

result = client.generate(
    service="google-gemini",
    model="gemini-2.0-flash",
    inputs=[
        {"type": "text", "name": "input", "content": "What are the best practices for API design?"}
    ],
    parameters={
        "system_instruction": "You are a senior software architect. Provide concise, actionable advice.",
        "temperature": 0.5
    }
)

With Conversation History

result = client.generate(
    service="google-gemini",
    model="gemini-2.0-flash",
    inputs=[
        {"type": "text", "name": "input", "content": "What about error handling?"}
    ],
    history=[
        {"role": "user", "content": "I'm building a REST API in Python."},
        {"role": "assistant", "content": "Great! I can help with that. What framework are you using?"},
        {"role": "user", "content": "FastAPI"}
    ],
    parameters={"temperature": 0.7}
)

Image Analysis (Vision)

Analyzing a Local Image

def encode_image(image_path: str) -> str:
    """Encode image to base64 data URL."""
    path = Path(image_path)
    mime_type = {
        ".jpg": "image/jpeg",
        ".jpeg": "image/jpeg",
        ".png": "image/png",
        ".gif": "image/gif",
        ".webp": "image/webp"
    }.get(path.suffix.lower(), "image/png")

    with open(path, "rb") as f:
        b64 = base64.b64encode(f.read()).decode("utf-8")
    return f"data:{mime_type};base64,{b64}"

# Analyze an image
image_url = encode_image("product_photo.jpg")

result = client.generate(
    service="google-gemini",
    model="gemini-2.0-flash",
    inputs=[
        {"type": "text", "name": "input", "content": "Describe this image in detail. What objects are visible?"},
        {"type": "image", "name": "input", "content": image_url}
    ]
)

if result["status"] == "success":
    description = next(
        item["content"] for item in result["output"]
        if item["type"] == "text" and item["name"] == "output"
    )
    print(description)

Comparing Multiple Images

image1 = encode_image("before.jpg")
image2 = encode_image("after.jpg")

result = client.generate(
    service="google-gemini",
    model="gemini-2.0-flash",
    inputs=[
        {"type": "text", "name": "input", "content": "Compare these two images. What changed between them?"},
        {"type": "image", "name": "input", "content": image1},
        {"type": "image", "name": "input", "content": image2}
    ]
)

Extract Structured Data from Image

import json

result = client.generate(
    service="google-gemini",
    model="gemini-2.0-flash",
    inputs=[
        {"type": "text", "name": "input", "content": """
Analyze this receipt image and extract:
- Store name
- Date
- Items (name, quantity, price)
- Total amount

Return as JSON.
"""},
        {"type": "image", "name": "input", "content": encode_image("receipt.jpg")}
    ],
    parameters={"temperature": 0.2}
)

if result["status"] == "success":
    text = next(
        item["content"] for item in result["output"]
        if item["type"] == "text"
    )
    # Parse JSON from response
    receipt_data = json.loads(text)
    print(json.dumps(receipt_data, indent=2))

Image Generation

Text-to-Image

def save_generated_image(data_url: str, output_path: str):
    """Decode and save a base64 image."""
    # Remove data URL prefix
    header, b64_data = data_url.split(",", 1)
    image_bytes = base64.b64decode(b64_data)
    image = Image.open(BytesIO(image_bytes))
    image.save(output_path)
    return image

# Generate an image
result = client.generate(
    service="google-gemini",
    model="gemini-3-pro-image-preview",
    inputs=[
        {"type": "text", "name": "input", "content": "A serene Japanese garden with a koi pond at sunset, digital art style"}
    ],
    parameters={
        "number_of_images": 1,
        "aspect_ratio": "16:9"
    }
)

if result["status"] == "success":
    for i, item in enumerate(result["output"]):
        if item["type"] == "image" and item["name"] == "output":
            img = save_generated_image(item["content"], f"generated_{i}.png")
            print(f"Saved: generated_{i}.png ({img.size})")
    print(f"Cost: ${result['cost']['total']:.4f}")

Generate Multiple Images

result = client.generate(
    service="google-gemini",
    model="gemini-3-pro-image-preview",
    inputs=[
        {"type": "text", "name": "input", "content": "Minimalist logo design for a tech startup called 'Nexus', clean lines"}
    ],
    parameters={
        "number_of_images": 4,  # Generate 4 variations
        "aspect_ratio": "1:1"
    }
)

if result["status"] == "success":
    images = [item for item in result["output"] if item["type"] == "image"]
    for i, img_item in enumerate(images):
        save_generated_image(img_item["content"], f"logo_option_{i+1}.png")

Image Editing with Reference

# Edit an existing image based on instructions
reference_image = encode_image("original_photo.jpg")

result = client.generate(
    service="google-gemini",
    model="gemini-3-pro-image-preview",
    inputs=[
        {"type": "text", "name": "input", "content": "Remove the background and replace with a gradient blue sky"},
        {"type": "image", "name": "reference", "content": reference_image}
    ],
    parameters={"aspect_ratio": "preserve"}
)

if result["status"] == "success":
    for item in result["output"]:
        if item["type"] == "image":
            save_generated_image(item["content"], "edited_photo.png")

Style Transfer

# Apply style from one image to another
content_image = encode_image("photo.jpg")
style_image = encode_image("style_reference.jpg")

result = client.generate(
    service="google-gemini",
    model="gemini-3-pro-image-preview",
    inputs=[
        {"type": "text", "name": "input", "content": "Apply the artistic style from the reference to the main image"},
        {"type": "image", "name": "input", "content": content_image},
        {"type": "image", "name": "reference", "content": style_image}
    ]
)

Complete Image Workflow Example

class ImageWorkflow:
    """Complete image processing workflow using NeuraSutra API."""

    def __init__(self, api_key: str):
        self.client = NeuraSutraClient(api_key=api_key)

    def analyze_image(self, image_path: str) -> dict:
        """Analyze an image and return structured data."""
        result = self.client.generate(
            service="google-gemini",
            model="gemini-2.0-flash",
            inputs=[
                {"type": "text", "name": "input", "content": """
Analyze this image and provide:
1. Main subject
2. Color palette (top 5 colors)
3. Mood/atmosphere
4. Suggested improvements
Return as JSON.
"""},
                {"type": "image", "name": "input", "content": encode_image(image_path)}
            ],
            parameters={"temperature": 0.3}
        )

        if result["status"] == "success":
            text = next(item["content"] for item in result["output"] if item["type"] == "text")
            return {"analysis": json.loads(text), "cost": result["cost"]["total"]}
        return {"error": result["error"]["message"]}

    def generate_variations(self, prompt: str, count: int = 4) -> list:
        """Generate multiple image variations."""
        result = self.client.generate(
            service="google-gemini",
            model="gemini-3-pro-image-preview",
            inputs=[{"type": "text", "name": "input", "content": prompt}],
            parameters={"number_of_images": count, "aspect_ratio": "1:1"}
        )

        if result["status"] == "success":
            images = []
            for i, item in enumerate(result["output"]):
                if item["type"] == "image":
                    path = f"variation_{i}.png"
                    save_generated_image(item["content"], path)
                    images.append(path)
            return {"images": images, "cost": result["cost"]["total"]}
        return {"error": result["error"]["message"]}

    def enhance_with_prompt(self, image_path: str, enhancement: str) -> str:
        """Enhance an image based on text instructions."""
        result = self.client.generate(
            service="google-gemini",
            model="gemini-3-pro-image-preview",
            inputs=[
                {"type": "text", "name": "input", "content": enhancement},
                {"type": "image", "name": "reference", "content": encode_image(image_path)}
            ]
        )

        if result["status"] == "success":
            for item in result["output"]:
                if item["type"] == "image":
                    output_path = "enhanced_" + Path(image_path).name
                    save_generated_image(item["content"], output_path)
                    return {"image": output_path, "cost": result["cost"]["total"]}
        return {"error": result["error"]["message"]}

    def get_remaining_budget(self) -> dict:
        """Check remaining API budget."""
        usage = self.client.get_usage()
        return {
            "hour_remaining": usage["hour"]["limit_block"] - usage["hour"]["cost"],
            "day_remaining": usage["day"]["limit_block"] - usage["day"]["cost"],
            "month_remaining": usage["month"]["limit_block"] - usage["month"]["cost"]
        }


# Usage
workflow = ImageWorkflow(api_key="sk_your_api_key")

# Check budget first
budget = workflow.get_remaining_budget()
print(f"Hourly budget remaining: ${budget['hour_remaining']:.2f}")

# Analyze an image
analysis = workflow.analyze_image("input.jpg")
print(json.dumps(analysis["analysis"], indent=2))

# Generate variations
variations = workflow.generate_variations(
    "Modern minimalist living room with natural lighting",
    count=4
)
print(f"Generated {len(variations['images'])} images for ${variations['cost']:.4f}")

# Enhance an existing image
enhanced = workflow.enhance_with_prompt(
    "photo.jpg",
    "Increase contrast, enhance colors, add subtle vignette"
)
print(f"Enhanced image saved: {enhanced['image']}")

Error Handling

def safe_generate(client, **kwargs):
    """Generate with comprehensive error handling."""
    try:
        result = client.generate(**kwargs)

        if result["status"] == "success":
            # Check for warnings
            if result.get("warnings"):
                for warning in result["warnings"]:
                    print(f"Warning: {warning}")
            return result

        # Handle API errors
        error = result["error"]
        if error["code"] == "RATE_LIMIT_EXCEEDED":
            print(f"Rate limit hit: {error['details']['period']}")
            print(f"Reset at: {error['details']['reset_at']}")
        elif error["code"] == "MODEL_NOT_FOUND":
            print(f"Model not available: {kwargs.get('model')}")
        elif error["code"] == "INVALID_INPUT":
            print(f"Invalid input: {error['message']}")
        else:
            print(f"Error: {error['message']}")

        return None

    except requests.exceptions.ConnectionError:
        print("Cannot connect to API server")
        return None
    except requests.exceptions.Timeout:
        print("Request timed out")
        return None
    except Exception as e:
        print(f"Unexpected error: {e}")
        return None

Next Steps