> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hiperai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Edición de Imágenes

> Edit existing images using Google Gemini 2.5 Flash Image with text instructions.
All requests and responses are processed through SMLTP for security and compliance.

This endpoint is specifically designed for **image-to-image editing** where:
- An image file is **required** (unlike `/images/generations` where it's optional)
- A text prompt describes how to edit or transform the image
- The edited image is returned with the same quality and format options

All prompts and responses are automatically processed through SMLTP for audit logging and compliance.


# Editar imágenes

Edite imágenes existentes utilizando Google Gemini 2.5 Flash Image con instrucciones de texto.

## Endpoint

```
POST /images/edits
```

## Descripción

Edite imágenes existentes utilizando Google Gemini 2.5 Flash Image con instrucciones de texto. Este endpoint está diseñado específicamente para **edición de imagen a imagen** donde:

* Un archivo de imagen es **obligatorio** (a diferencia de `/images/generations` donde es opcional)
* Un mensaje de texto describe cómo editar o transformar la imagen.
* La imagen editada se devuelve con la misma calidad y opciones de formato.

Todas las indicaciones y respuestas se procesan automáticamente a través de SMLTP para el registro de auditoría y el cumplimiento.

## Autenticación

Requerido: Clave API

```bash theme={null}
Authorization: Bearer sk-your-api-key-here
```

## Cuerpo de solicitud

Este endpoint acepta el formato `multipart/form-data`.

### Parámetros

| Parámetro | Tipo | Requerido | Descripción |
| - | - | - | - |
| `prompt` | cadena | Sí | Instrucciones de texto que describen cómo editar o transformar la imagen cargada (1-4000 caracteres) |
| `image` | binario | Sí | Archivo de imagen para editar (JPEG, PNG, WEBP o GIF, máximo 10 MB) |
| `smltp_policy` | cadena | No | Política de seguridad SMLTP (predeterminada: "interna") |
| `response_format` | cadena | No | Formato de respuesta: "url" o "b64\_json" (predeterminado: "url") |

## Ejemplos de solicitudes

### rizo

```bash theme={null}
curl -X POST "https://{customer.name}.hiperai.ai/api/external/images/edits" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -F "prompt=Add dramatic sunset colors to the sky and enhance the overall atmosphere" \
  -F "image=@/path/to/image.jpg" \
  -F "smltp_policy=internal" \
  -F "response_format=url"
```

### JavaScript/Node.js

```javascript theme={null}
const formData = new FormData();
formData.append('prompt', 'Add dramatic sunset colors to the sky and enhance the overall atmosphere');
formData.append('image', fileInput.files[0]);
formData.append('smltp_policy', 'internal');
formData.append('response_format', 'url');

const response = await fetch('https://{customer.name}.hiperai.ai/api/external/images/edits', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer sk-your-api-key-here'
  },
  body: formData
});

const data = await response.json();
console.log('Edited image URL:', data.data[0].url);
```

### Pitón

```python theme={null}
import requests

url = "https://{customer.name}.hiperai.ai/api/external/images/edits"
headers = {
    "Authorization": "Bearer sk-your-api-key-here"
}

with open('image.jpg', 'rb') as f:
    files = {'image': f}
    data = {
        'prompt': 'Add dramatic sunset colors to the sky and enhance the overall atmosphere',
        'smltp_policy': 'internal',
        'response_format': 'url'
    }
    response = requests.post(url, headers=headers, files=files, data=data)
    result = response.json()
    print('Edited image URL:', result['data'][0]['url'])
```

## Respuesta

### Respuesta exitosa (200)

```json theme={null}
{
  "success": true,
  "id": "f55bb4aa-ad9a-4b5a-9c94-511bf6fce806",
  "object": "image.edit",
  "created": 1705312200,
  "data": [
    {
      "url": "http://localhost:5173/uploads/secureai_image_api_edit_68c5c6d2d57c85b102eb05e2_f55bb4aa_0.png",
      "revised_prompt": "Add dramatic sunset colors to the sky and enhance the overall atmosphere"
    }
  ],
  "metadata": {
    "model": "google/gemini-2.5-flash-image-preview",
    "provider": "Google",
    "total_images": 1,
    "is_image_to_image": true,
    "text_response": null,
    "smltp_trace_id": "trx-6caec994-73af-4f2c-9e13-572d53262f2a",
    "smltp_bundle_id": "jti-26464307-d455-4a3d-9ca4-8ec144cb601c",
    "smltp_policy": "internal"
  }
}
```

### Campos de respuesta

| Campo | Tipo | Descripción |
| - | - | - |
| `success` | booleano | Siempre es cierto para solicitudes exitosas |
| `id` | cadena | Identificador de solicitud único |
| `object` | cadena | Tipo de objeto: "imagen.edit" |
| `created` | entero | Marca de tiempo Unix de cuando se editó la imagen |
| `data` | matriz | Conjunto de imágenes editadas |
| `metadata` | objeto | Metadatos adicionales, incluido el seguimiento SMLTP |

### Objeto de imagen

| Campo | Tipo | Descripción |
| - | - | - |
| `url` | cadena | URL para acceder a la imagen editada (cuando el formato\_respuesta es "url") |
| `b64_json` | cadena | Datos de imagen codificados en Base64 (cuando el formato\_respuesta es "b64\_json") |
| `revised_prompt` | cadena | El mensaje realmente utilizado para la edición (puede diferir del ingresado) |

### Objeto de metadatos

| Campo | Tipo | Descripción |
| - | - | - |
| `model` | cadena | Modelo utilizado: "google/gemini-2.5-flash-image-preview" |
| `provider` | cadena | Proveedor: "Google" |
| `total_images` | entero | Número total de imágenes (siempre 1 para ediciones) |
| `is_image_to_image` | booleano | Siempre es cierto para este endpoint |
| `text_response` | cadena\|nulo | Respuesta de texto opcional del modelo |
| `smltp_trace_id` | cadena | ID de seguimiento SMLTP para seguimiento de auditoría |
| `smltp_bundle_id` | cadena | ID de paquete SMLTP para seguimiento de auditorías |
| `smltp_policy` | cadena | Política SMLTP que se aplicó |

## Respuestas de error

### 400 Solicitud incorrecta

```json theme={null}
{
  "success": false,
  "error": "Missing image",
  "message": "An image file is required for image-to-image editing",
  "request_id": "f55bb4aa-ad9a-4b5a-9c94-511bf6fce806"
}
```

### 401 No autorizado

```json theme={null}
{
  "success": false,
  "error": "Invalid API key",
  "message": "The provided API key is invalid or has been revoked"
}
```

### 403 Prohibido

```json theme={null}
{
  "success": false,
  "error": "Access denied",
  "message": "SMLTP policy not allowed"
}
```

### 413 Carga útil demasiado grande

```json theme={null}
{
  "success": false,
  "error": "File too large",
  "message": "Maximum image size is 10MB",
  "request_id": "f55bb4aa-ad9a-4b5a-9c94-511bf6fce806"
}
```

### 500 Error interno del servidor

```json theme={null}
{
  "success": false,
  "error": "Internal server error",
  "message": "Image editing failed"
}
```

### Servicio 503 no disponible

```json theme={null}
{
  "success": false,
  "error": "Service unavailable",
  "message": "Image generation service is not configured",
  "request_id": "f55bb4aa-ad9a-4b5a-9c94-511bf6fce806"
}
```

## Notas

* Formatos de imagen admitidos: JPEG, PNG, WEBP, GIF
* Tamaño máximo de archivo: 10 MB por imagen
* El archivo de imagen es **obligatorio** para este endpoint (a diferencia de `/images/generations`)
* El mensaje describe cómo editar o transformar la imagen cargada.
* Todas las solicitudes se procesan a través de SMLTP por motivos de seguridad y cumplimiento.
* Utilice `response_format: "b64_json"` para recibir datos de imágenes codificados en base64 en lugar de URL


## OpenAPI

````yaml POST /images/edits
openapi: 3.0.3
info:
  title: SecureAI External API
  description: >
    SecureAI External API provides AI chat completion and image generation
    capabilities with knowledge base retrieval, 

    security policies, and comprehensive usage tracking. This API is designed
    for external developers 

    and integrations using API key authentication.


    ## Key Features

    - **RAG (Retrieval-Augmented Generation)**: Automatically search knowledge
    bases for relevant context

    - **Multi-Model Support**: OpenAI, Anthropic, Google, Meta, and other AI
    models

    - **Model Redundancy & Failover**: Caller-defined failover chains (primary +
    fallbacks) with per-attempt timeouts

    - **OpenAI-Compatible Endpoint**: Point any OpenAI SDK at `/api/external/v1`
    — no code changes

    - **Image Generation**: Generate and edit images using Google Gemini 2.5
    Flash Image

    - **Speech-to-Speech (S2S)**: Real-time voice conversations using OpenAI
    Realtime API with WebRTC

    - **Security Policies**: SMLTP policy enforcement, per-call Prompt Shield,
    and signed compliance receipts

    - **Usage Tracking**: Comprehensive usage monitoring, self-service quota,
    and rate limiting

    - **Knowledge Base Integration**: Access to personal and shared knowledge
    bases

    - **User Management**: Complete user, group, and role management
    capabilities

    - **Audit Logging**: Comprehensive activity and security audit logs


    ## Authentication

    All endpoints (except health check) require API key authentication using
    Bearer token:

    ```

    Authorization: Bearer sk-your-api-key-here

    ```


    ## Billing and Usage

    By default, API requests are billed to the user account that owns the API
    key. You can specify 

    a different user to bill by including the `user_id` parameter in your
    request. This allows for:

    - Multi-tenant applications with per-user billing

    - Flexible completion limit management

    - Per-user "Usage by Model" settings


    ## Rate Limits

    - Default: 60 requests per minute, 1000 requests per hour

    - Daily limits: 100 requests (configurable)

    - Monthly limits: 10,000 requests (configurable)


    ## Base URL

    ```

    https://secureai.hiperai.ai/api/external

    ```
  version: 1.1.0
  contact:
    name: SecureAI Support
    email: support@secureai.hiperai.ai
  license:
    name: Proprietary
    url: https://secureai.hiperai.ai/terms
servers:
  - url: https://secureai.hiperai.ai/api/external
    description: Production server
  - url: http://localhost:3010/api/external
    description: Development server
security:
  - ApiKeyAuth: []
tags:
  - name: System
    description: System health and status endpoints
  - name: Discovery
    description: Endpoints to discover available models, indexes, and policies
  - name: Chat
    description: AI chat completion endpoints
  - name: User Management
    description: Endpoints for managing user accounts and roles
  - name: Index Management
    description: Endpoints for managing knowledge base indexes
  - name: Group Management
    description: Endpoints for managing user groups
  - name: SMLTP Security
    description: Endpoints for managing SMLTP security policies and audit logs
  - name: Role Management
    description: Endpoints for managing user roles
  - name: Activity Logs
    description: Endpoints for retrieving activity logs
externalDocs:
  description: SecureAI Documentation
  url: https://secureai.hiperai.ai/docs
paths:
  /images/edits:
    post:
      tags:
        - Images
      summary: Image-to-Image Editing
      description: >
        Edit existing images using Google Gemini 2.5 Flash Image with text
        instructions.

        All requests and responses are processed through SMLTP for security and
        compliance.


        This endpoint is specifically designed for **image-to-image editing**
        where:

        - An image file is **required** (unlike `/images/generations` where it's
        optional)

        - A text prompt describes how to edit or transform the image

        - The edited image is returned with the same quality and format options


        All prompts and responses are automatically processed through SMLTP for
        audit logging and compliance.
      requestBody:
        required: true
        content:
          multipart/form-data:
            schema:
              type: object
              required:
                - prompt
                - image
              properties:
                prompt:
                  type: string
                  description: >-
                    Text instructions describing how to edit or transform the
                    uploaded image
                  example: >-
                    Add dramatic sunset colors to the sky and enhance the
                    overall atmosphere
                  minLength: 1
                  maxLength: 4000
                image:
                  type: string
                  format: binary
                  description: >-
                    Image file to edit (required, JPEG, PNG, WEBP, or GIF, max
                    10MB)
                smltp_policy:
                  type: string
                  description: >-
                    SMLTP security policy to apply (e.g., 'internal', 'public',
                    'confidential', 'hipaa', 'gdpr')
                  default: internal
                  example: internal
                response_format:
                  type: string
                  description: The format of the response images
                  enum:
                    - url
                    - b64_json
                  default: url
                  example: url
      responses:
        '200':
          description: Image edited successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  id:
                    type: string
                    description: Unique request identifier
                    example: f55bb4aa-ad9a-4b5a-9c94-511bf6fce806
                  object:
                    type: string
                    example: image.edit
                  created:
                    type: integer
                    description: Unix timestamp of when the image was edited
                    example: 1705312200
                  data:
                    type: array
                    description: Array of edited images
                    items:
                      type: object
                      properties:
                        url:
                          type: string
                          format: uri
                          description: >-
                            URL to access the edited image (when response_format
                            is 'url')
                          example: >-
                            http://localhost:5173/uploads/secureai_image_api_edit_68c5c6d2d57c85b102eb05e2_f55bb4aa_0.png
                        b64_json:
                          type: string
                          description: >-
                            Base64-encoded image data (when response_format is
                            'b64_json')
                          example: iVBORw0KGgoAAAANSUhEUgAA...
                        revised_prompt:
                          type: string
                          description: >-
                            The prompt that was actually used for editing (may
                            differ from input)
                          example: >-
                            Add dramatic sunset colors to the sky and enhance
                            the overall atmosphere
                  metadata:
                    type: object
                    properties:
                      model:
                        type: string
                        example: google/gemini-2.5-flash-image-preview
                      provider:
                        type: string
                        example: Google
                      total_images:
                        type: integer
                        example: 1
                      is_image_to_image:
                        type: boolean
                        description: Always true for this endpoint
                        example: true
                      text_response:
                        type: string
                        nullable: true
                        description: Optional text response from the model
                        example: null
                      smltp_trace_id:
                        type: string
                        description: SMLTP trace ID for audit tracking
                        example: trx-6caec994-73af-4f2c-9e13-572d53262f2a
                      smltp_bundle_id:
                        type: string
                        description: SMLTP bundle ID for audit tracking
                        example: jti-26464307-d455-4a3d-9ca4-8ec144cb601c
                      smltp_policy:
                        type: string
                        description: SMLTP policy that was applied
                        example: internal
              example:
                success: true
                id: f55bb4aa-ad9a-4b5a-9c94-511bf6fce806
                object: image.edit
                created: 1705312200
                data:
                  - url: >-
                      http://localhost:5173/uploads/secureai_image_api_edit_68c5c6d2d57c85b102eb05e2_f55bb4aa_0.png
                    revised_prompt: >-
                      Add dramatic sunset colors to the sky and enhance the
                      overall atmosphere
                metadata:
                  model: google/gemini-2.5-flash-image-preview
                  provider: Google
                  total_images: 1
                  is_image_to_image: true
                  text_response: null
                  smltp_trace_id: trx-6caec994-73af-4f2c-9e13-572d53262f2a
                  smltp_bundle_id: jti-26464307-d455-4a3d-9ca4-8ec144cb601c
                  smltp_policy: internal
        '400':
          description: >-
            Invalid request parameters (missing prompt, missing image, invalid
            image format, etc.)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                error: Missing image
                message: An image file is required for image-to-image editing
                request_id: f55bb4aa-ad9a-4b5a-9c94-511bf6fce806
        '401':
          description: Invalid API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Access denied (SMLTP policy not allowed)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '413':
          description: Image file too large (maximum 10MB)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                error: File too large
                message: Maximum image size is 10MB
                request_id: f55bb4aa-ad9a-4b5a-9c94-511bf6fce806
        '500':
          description: Internal server error or image editing failed
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '503':
          description: Image generation service unavailable (Gemini service not configured)
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
              example:
                success: false
                error: Service unavailable
                message: Image generation service is not configured
                request_id: f55bb4aa-ad9a-4b5a-9c94-511bf6fce806
      security:
        - ApiKeyAuth: []
components:
  schemas:
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          example: Invalid API key
        message:
          type: string
          example: The provided API key is invalid or has been revoked
        request_id:
          type: string
          example: req-abc123
          description: Request ID for tracking (if available)
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      description: |
        API key authentication using Bearer token format.
        Example: `Authorization: Bearer sk-your-api-key-here`

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.