# OpenAI - GPT-4o Vision

> Invoca OpenAI GPT-4o (Omni) mediante la API de Chat Completions para comprensión de imágenes, OCR basado en visión y razonamiento visual sobre diagramas y gráficos.

Source: https://docs.sommatic.ai/es/nodes/integrations.openai.gpt-4o.vision/

- Slug: `integrations.openai.gpt-4o.vision`
- Familia: Integraciones
- Versión: 1.0.0
- Estado: Disponible
- Ejecución: async

Invoca OpenAI GPT-4o (Omni) mediante la API de Chat Completions para comprensión de imágenes, OCR basado en visión y razonamiento visual sobre diagramas y gráficos.

Se enruta por el endpoint del backend `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` con un `llm_provider_id` registrado en el registro de cognitive-assets. La facturación la gestiona directamente OpenAI o Azure OpenAI con cargo a tu suscripción. Compatible con cualquier modelo de la clase GPT-4 que exponga la capacidad `vision` (GPT-4o, GPT-4o mini, GPT-4 Turbo with vision).

**Operaciones:**
- **Descripción de imágenes:** Descripciones en lenguaje natural de fotografías, capturas de pantalla e imágenes de productos.
- **Interpretación de gráficos y diagramas:** Extracción estructurada de series de datos, etiquetas y relaciones a partir de gráficos de barras, gráficos de líneas, diagramas de flujo e imágenes que contienen tablas.
- **OCR basado en visión:** Lee texto en diseños en los que falla el OCR clásico: bajo contraste, tipografías inusuales, escritura a mano, escaneos torcidos, letreros estilizados.
- **Comprensión de escenas:** Identifica objetos, actividades y pistas de contexto para apoyar workflows de moderación, etiquetado y enrutamiento.

**Entradas:** imagen codificada en base64 o URL pública de una imagen.
**Controles:** prompt de sistema, prompt de usuario (admite expresiones), temperatura y máximo de tokens, expuestos como configuración del nodo para que el mismo nodo pueda hacer llamadas deterministas de tipo OCR o descripciones creativas.

## Configuración

- `llm_provider_id` (string, obligatorio): Elige un LlmProvider con capacidad de visión del registro de cognitive-assets (p. ej., un despliegue de GPT-4o en Azure OpenAI).
- `prompt` (string, opcional, acepta expresiones): Por defecto: `Describe the content of this image as accurately as possible. Include any visible text verbatim.`.
- `system_prompt` (string, opcional): Por defecto: `You are a vision assistant that describes images accurately and extracts any visible text verbatim.`.
- `max_tokens` (number, opcional): Por defecto: `1024`.
- `temperature` (number, opcional): Los valores más bajos producen una salida más determinista, mejor para tareas de tipo OCR. Por defecto: `0.2`.

Su configuración muestra los ajustes de ejecución compartidos, pero este nodo aún no aplica reintentos (`retryOnFail`, `maxTries`). Ningún nodo aplica `continueOnFail`.

## Puertos de salida

- `extracted` (por defecto): Extracted
- `empty`: Empty
- `error`: Error

## Contrato de entrada

- `content_base64` (string, opcional)
- `content_type` (string, opcional): Por defecto: `image/png`.
- `image_url` (string, opcional): URL pública de una imagen (alternativa a content_base64).

## Contrato de salida

- `text` (string, opcional)
- `chars` (number, opcional)
- `empty` (boolean, opcional)
- `method` (string, opcional)
- `metadata` (object, opcional)

## En expresiones

Lo que un nodo posterior puede leer de la salida de este nodo con `$("OpenAI - GPT-4o Vision").item.json.<ruta>` (escribe la etiqueta de tu nodo en lugar de `OpenAI - GPT-4o Vision`). **Editor** marca las rutas que sugiere el editor de workflows en Previous Nodes (el contrato de salida); **Worker** marca las rutas que el worker devuelve de verdad por `extracted`, según la salida que muestra Puertos.

- `$("OpenAI - GPT-4o Vision").item.json.text` (string) = `"Receipt from Example Store. Total: $42.10. D…"`
- `$("OpenAI - GPT-4o Vision").item.json.chars` (number) = `60`
- `$("OpenAI - GPT-4o Vision").item.json.empty` (boolean) = `false`
- `$("OpenAI - GPT-4o Vision").item.json.method` (string) = `"llm.vision"`
- `$("OpenAI - GPT-4o Vision").item.json.metadata` (object) = `{…}`
- `$("OpenAI - GPT-4o Vision").item.json.metadata.llm_provider_id` (string) = `"<llm_provider_id>"` (El editor no la sugiere)
- `$("OpenAI - GPT-4o Vision").item.json.metadata.usage` (object) = `{…}` (El editor no la sugiere)


## Cómo funciona

Envía una imagen y un prompt a un proveedor LLM con visión registrado en Sommatic AI y devuelve el texto del modelo. La llamada pasa por el backend de Sommatic AI, que resuelve el proveedor y su secreto.

1. Resuelve la configuración del nodo y exige `llm_provider_id`.
2. Toma la imagen de `content_base64` (con `content_type`, por defecto `image/png`) o de `image_url`, leyendo cada clave primero de la configuración y luego del ítem de entrada. El contenido base64 se envía como URL `data:`.
3. Arma una solicitud de chat con `system_prompt`, un mensaje de usuario que contiene `prompt` y la imagen, `max_tokens` (por defecto 1024) y `temperature` (por defecto 0.2).
4. Llama al endpoint de invocación de proveedores LLM del backend con un tiempo de espera de `execution.timeout_ms` (por defecto 120000).
5. Recorta el texto devuelto y construye `{ text, chars, empty, method: "llm.vision", metadata: { llm_provider_id, usage } }`; si el texto está vacío sale por `empty`, si no por `extracted`.

## En un workflow

### Nodo

```json
{
  "node_id": "node-read-receipt",
  "label": "Read receipt image",
  "operator_slug": "integrations.openai.gpt-4o.vision",
  "operator_version": "1.0.0",
  "config": {
    "llm_provider_id": "<llm_provider_id>",
    "prompt": "Extract the store name, total and date from this receipt.",
    "max_tokens": 512,
    "temperature": 0
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "text": "Receipt from Example Store. Total: $42.10. Date: 2026-11-25.",
    "chars": 60,
    "empty": false,
    "method": "llm.vision",
    "metadata": {
      "llm_provider_id": "<llm_provider_id>",
      "usage": {
        "prompt_tokens": 1146,
        "completion_tokens": 21,
        "total_tokens": 1167
      }
    }
  },
  "port": "extracted"
}
```

## Puertos de salida (comportamiento en el código)

### `extracted`

El modelo devolvió texto.

```json
{
  "text": "Receipt from Example Store. Total: $42.10. Date: 2026-11-25.",
  "chars": 60,
  "empty": false,
  "method": "llm.vision",
  "metadata": {
    "llm_provider_id": "<llm_provider_id>",
    "usage": {
      "prompt_tokens": 1146,
      "completion_tokens": 21,
      "total_tokens": 1167
    }
  }
}
```

### `empty`

La llamada tuvo éxito pero el texto está vacío.

```json
{
  "text": "",
  "chars": 0,
  "empty": true,
  "method": "llm.vision",
  "metadata": {
    "llm_provider_id": "<llm_provider_id>",
    "usage": {
      "prompt_tokens": 1146,
      "completion_tokens": 0,
      "total_tokens": 1146
    }
  }
}
```

### `error`

Falló la validación, el backend respondió con HTTP 400 o superior o con `success: false`, o la solicitud superó el tiempo de espera.

```json
{
  "error": "Either content_base64 or image_url is required."
}
```

## Comportamiento en el código

- `llm_provider_id`: El modelo es el que tenga configurado este proveedor; el nombre del nodo no obliga a usar GPT-4o. Elige un despliegue con capacidad de visión.
- `content_base64`: No está declarado en el esquema de configuración; normalmente llega en el ítem de entrada junto con `content_type`. `image_url` solo se usa si falta `content_base64`.
- `temperature`: Debe ser un número; cualquier otro tipo vuelve a 0.2. Un `max_tokens` en 0 o vacío vuelve a 1024.
- `execution`: Solo se lee `timeout_ms` (por defecto 120000). La configuración de reintentos no se aplica.

## Errores

| Mensaje | Puerto | Causa y solución |
| --- | --- | --- |
| `llm_provider_id is required.` | `error` | No se seleccionó proveedor LLM. |
| `Either content_base64 or image_url is required.` | `error` | Ni la configuración ni el ítem de entrada traen una imagen. |
| `LLM provider invoke returned HTTP <status>` | `error` | El backend rechazó la llamada sin mensaje. Cuando envía uno (por ejemplo `LLM Invocation Error (SDK): <detail>`), se devuelve ese mensaje. |
| `timeout of <ms>ms exceeded` | `error` | El proveedor no respondió dentro de `execution.timeout_ms`. |

## Notas y límites

- El worker nunca llama directamente a OpenAI ni guarda la llave del proveedor; el consumo se factura a la cuenta del propio proveedor.
- `usage` se transmite desde la respuesta del proveedor y puede no venir. El nodo no reintenta.


## Contratos (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "integrations.openai.gpt-4o.vision",
  "name": "OpenAI - GPT-4o Vision",
  "category": "integrations",
  "group": [
    {
      "key": "openai",
      "name": "OpenAI",
      "icon_url": "/icons/integrations/openai/openai.svg"
    }
  ],
  "icon_url": "/icons/integrations/openai/openai.svg",
  "version": "1.0.0",
  "description": "Invoke OpenAI GPT-4o (Omni) via the Chat Completions API for image understanding, vision-based OCR, and visual reasoning over diagrams and charts.\n\n  Routes through the backend `POST /cognitive-infrastructure/cognitive-assets/llm-provider/invoke` endpoint using an `llm_provider_id` registered in the cognitive-assets registry. Billing is handled directly by OpenAI or Azure OpenAI against your subscription. Compatible with any GPT-4 class model that exposes the `vision` capability (GPT-4o, GPT-4o mini, GPT-4 Turbo with vision).\n\n  **Operations:**\n  - **Image captioning:** Natural-language descriptions of photographs, screenshots, and product imagery.\n  - **Chart and diagram interpretation:** Structured extraction of data series, labels, and relationships from bar charts, line charts, flow diagrams, and images containing tables.\n  - **Vision-based OCR:** Reads text in layouts that defeat classical OCR — low contrast, unusual typography, handwriting, skewed scans, stylized signage.\n  - **Scene understanding:** Identifies objects, activities, and contextual cues to support moderation, tagging, and routing workflows.\n\n  **Inputs:** base64-encoded image or a public image URL.\n  **Controls:** system prompt, user prompt (expression-enabled), temperature, and max tokens exposed as node configuration so the same node can run deterministic OCR-style calls or creative captioning.",
  "capabilities": [
    "openai",
    "gpt-4o",
    "vision",
    "image-understanding",
    "ocr",
    "llm"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "llm_provider_id": {
        "type": "string",
        "title": "LLM Provider",
        "description": "Select a vision-capable LlmProvider from the cognitive-assets registry (e.g. an Azure OpenAI GPT-4o deployment).",
        "x-ui-widget": "llm-provider-picker"
      },
      "prompt": {
        "type": "string",
        "title": "User Prompt",
        "default": "Describe the content of this image as accurately as possible. Include any visible text verbatim.",
        "format": "expression"
      },
      "system_prompt": {
        "type": "string",
        "title": "System Prompt",
        "default": "You are a vision assistant that describes images accurately and extracts any visible text verbatim."
      },
      "max_tokens": {
        "type": "number",
        "title": "Max Tokens",
        "default": 1024
      },
      "temperature": {
        "type": "number",
        "title": "Temperature",
        "default": 0.2,
        "description": "Lower values produce more deterministic output, better for OCR-style tasks."
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    },
    "required": [
      "llm_provider_id"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content_base64": {
        "type": "string"
      },
      "content_type": {
        "type": "string",
        "default": "image/png"
      },
      "image_url": {
        "type": "string",
        "description": "Public URL to an image (alternative to content_base64)."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string"
      },
      "chars": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "metadata": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "Empty",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "cloud-io"
  ],
  "tags": [
    "openai",
    "gpt-4o",
    "vision",
    "llm",
    "image"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://sommatic.ai",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "llm_provider_id": {
      "type": "string",
      "title": "LLM Provider",
      "description": "Select a vision-capable LlmProvider from the cognitive-assets registry (e.g. an Azure OpenAI GPT-4o deployment).",
      "x-ui-widget": "llm-provider-picker"
    },
    "prompt": {
      "type": "string",
      "title": "User Prompt",
      "default": "Describe the content of this image as accurately as possible. Include any visible text verbatim.",
      "format": "expression"
    },
    "system_prompt": {
      "type": "string",
      "title": "System Prompt",
      "default": "You are a vision assistant that describes images accurately and extracts any visible text verbatim."
    },
    "max_tokens": {
      "type": "number",
      "title": "Max Tokens",
      "default": 1024
    },
    "temperature": {
      "type": "number",
      "title": "Temperature",
      "default": 0.2,
      "description": "Lower values produce more deterministic output, better for OCR-style tasks."
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  },
  "required": [
    "llm_provider_id"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content_base64": {
      "type": "string"
    },
    "content_type": {
      "type": "string",
      "default": "image/png"
    },
    "image_url": {
      "type": "string",
      "description": "Public URL to an image (alternative to content_base64)."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string"
    },
    "chars": {
      "type": "number"
    },
    "empty": {
      "type": "boolean"
    },
    "method": {
      "type": "string"
    },
    "metadata": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Extracted",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "Empty",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
