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

# Crear lote

> Crea un trabajo por lotes asíncrono y devuelve el objeto de lote del proveedor. La creación admite OpenAI, Anthropic, Google Gemini, Mistral, xAI, Groq y Together AI mediante el `model` solicitado. La pasarela infiere el proveedor a partir del modelo y también acepta `session_id` y `webhook` para observabilidad y notificaciones asíncronas. Use `provider` solo como restricción avanzada de enrutamiento.

Requiere acceso a la versión preliminar del espacio de trabajo. Consulta [Trabajos de vídeo y procesamiento por lotes](../../guides/async-video-and-batch.mdx) para la configuración, los webhooks y la gestión de resultados.


## OpenAPI

````yaml es/openapi/v1/openapi.localized.yaml POST /batches
openapi: 3.0.3
info:
  title: Phaseo Gateway API
  description: >-
    Una API de pasarela para acceder a diversos modelos de IA mediante endpoints
    compatibles con OpenAI.
  version: 1.0.0
  contact:
    name: Phaseo
    url: https://phaseo.app
    email: danielbutler500@gmail.com
servers:
  - url: https://api.phaseo.app/v1
    description: Enrutamiento global
security:
  - BearerAuth: []
tags:
  - name: Gateway
    description: Core Phaseo Gateway operations.
paths:
  /batches:
    post:
      tags:
        - Gateway
      summary: Crear lote
      description: >-
        Crea un trabajo por lotes asíncrono y devuelve el objeto de lote del
        proveedor. La creación admite OpenAI, Anthropic, Google Gemini, Mistral,
        xAI, Groq y Together AI mediante el `model` solicitado. La pasarela
        infiere el proveedor a partir del modelo y también acepta `session_id` y
        `webhook` para observabilidad y notificaciones asíncronas. Use
        `provider` solo como restricción avanzada de enrutamiento.
      operationId: createBatch
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/BatchRequest'
      responses:
        '200':
          description: Respuesta de estado del lote
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/BatchResponse'
        '401':
          description: No autorizado
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
components:
  schemas:
    BatchRequest:
      type: object
      properties:
        provider_options:
          type: object
          description: >-
            Extensiones limitadas por ID canónico del proveedor. OpenAI acepta
            output_expires_after; Mistral acepta metadata. Solo se aplican las
            opciones del proveedor seleccionado. No duplique una opción en el
            nivel superior. Las opciones no pueden sustituir filas valoradas,
            modelos ni archivos.
          additionalProperties:
            type: object
            additionalProperties: true
        model:
          type: string
          description: >-
            ID del modelo usado para inferir el proveedor del lote. Las filas de
            solicitud también pueden incluir body.model; se prefiere el modelo
            de nivel superior.
        prompts:
          type: array
          description: >-
            Formato abreviado de prompt simple. Phaseo convierte cada prompt en
            una fila de lote nativa del proveedor para el modelo seleccionado.
          items:
            type: string
        items:
          type: array
          description: >-
            Formato abreviado de prompt estructurado. Los elementos pueden
            incluir `id`, `custom_id`, `prompt`, `messages`, `input`, `system`,
            `max_tokens`, `temperature` o un `body` avanzado.
          items:
            type: object
            additionalProperties: true
        system:
          type: string
          description: >-
            Instrucción de sistema opcional aplicada a las filas de prompts
            abreviados.
        max_tokens:
          type: integer
          description: >-
            Límite máximo de tokens opcional aplicado a las filas de prompts
            abreviados.
        temperature:
          type: number
          description: >-
            Temperatura de muestreo opcional aplicada a las filas de prompts
            abreviados.
        input_file_id:
          type: string
          description: >-
            ID de archivo existente del proveedor para crear lotes mediante
            carga de archivos.
        requests:
          type: array
          description: >-
            Filas avanzadas de solicitud por lotes. Proporcione exactamente uno
            de `prompts`, `items`, `requests` o `input_file_id`.
          items:
            $ref: '#/components/schemas/BatchRequestItem'
        endpoint:
          type: string
          enum:
            - /v1/chat/completions
            - /v1/responses
            - /v1/messages
            - /v1/embeddings
            - /v1/generateContent
          description: >-
            Formato de solicitud para el cliente. Todas las solicitudes de un
            lote usan este endpoint. Si se omite, Phaseo elige un valor
            predeterminado nativo del proveedor a partir del modelo.
        completion_window:
          type: string
        metadata:
          type: object
          additionalProperties: true
        session_id:
          type: string
          maxLength: 256
          description: >-
            Identificador único para agrupar solicitudes relacionadas (por
            ejemplo, una conversación o un flujo de trabajo de agente) y
            facilitar la observabilidad.
        webhook:
          type: object
          required:
            - endpoint_id
          additionalProperties: false
          properties:
            endpoint_id:
              type: string
              description: ID del endpoint de webhook gestionado por el espacio de trabajo.
            events:
              type: array
              description: >-
                Suscripciones opcionales a eventos. Use eventos genéricos job.*
                o eventos batch.* correspondientes, por ejemplo batch.progress o
                batch.completed. Si se omiten, se usan eventos finales job.*.
                Incluya job.progress o batch.progress explícitamente para
                callbacks de progreso del recuento de solicitudes. Si se
                especifican, al menos un evento debe ser válido para trabajos
                por lotes; se rechazan las listas mal formadas o compuestas solo
                de eventos de otro tipo.
              items:
                type: string
        webhook_endpoint_id:
          type: string
          description: Alias práctico de webhook.endpoint_id.
        debug:
          $ref: '#/components/schemas/DebugOptions'
        provider:
          allOf:
            - $ref: '#/components/schemas/ProviderRoutingOptions'
          description: >-
            Restricción avanzada de enrutamiento. La mayoría de las solicitudes
            deberían inferir el proveedor a partir del modelo.
    BatchResponse:
      type: object
      properties:
        id:
          type: string
        native_batch_id:
          type: string
          nullable: true
          description: >-
            ID de lote nativo del proveedor cuando difiere del ID propio de la
            pasarela.
        object:
          type: string
        endpoint:
          type: string
        errors:
          type: object
        input_file_id:
          type: string
        completion_window:
          type: string
        status:
          type: string
        lifecycle_status:
          type: string
          enum:
            - pending
            - running
            - completed
            - failed
            - cancelled
            - expired
          description: >-
            Estado normalizado del ciclo de vida asíncrono para consumidores de
            sondeo, WebSocket y webhooks.
        progress:
          type: integer
          minimum: 0
          maximum: 100
          description: >-
            Porcentaje aproximado de finalización del lote derivado de los
            recuentos de solicitudes del proveedor, si están disponibles. Los
            lotes completados informan 100.
        polling_url:
          type: string
          format: uri
        websocket_url:
          type: string
          format: uri
          description: >-
            URL de WebSocket para suscribirse a actualizaciones normalizadas del
            ciclo de vida de trabajos asíncronos.
        cancel_url:
          type: string
          format: uri
          nullable: true
          description: Reservado por compatibilidad; actualmente siempre es null.
        results_url:
          type: string
          format: uri
          nullable: true
          description: >-
            URL autenticada de descarga JSONL de Phaseo para lotes compatibles
            en estado final. Es null durante el procesamiento. Un lote en estado
            final puede no tener salida. Use una clave API del espacio de
            trabajo propietario; se aplican los límites de retención del
            proveedor.
        output_file_id:
          type: string
        error_file_id:
          type: string
        created_at:
          type: integer
        in_progress_at:
          type: integer
        expires_at:
          type: integer
        finalizing_at:
          type: integer
        completed_at:
          type: integer
        failed_at:
          type: integer
        expired_at:
          type: integer
        cancelling_at:
          type: integer
        cancelled_at:
          type: integer
        request_counts:
          $ref: '#/components/schemas/BatchRequestCounts'
        metadata:
          type: object
        request_id:
          type: string
        provider:
          type: string
        session_id:
          type: string
        webhook:
          $ref: '#/components/schemas/AsyncWebhookPublicState'
        next_webhook_retry_at:
          type: string
          nullable: true
        last_webhook_progress:
          type: number
          nullable: true
        last_webhook_progress_at:
          type: string
          nullable: true
        last_webhook_dispatched_at:
          type: string
          nullable: true
        finalized_at:
          type: string
          nullable: true
        pricing_lines:
          type: array
          items:
            type: object
            additionalProperties: true
        usage:
          type: object
          description: Uso y coste agregados normalizados tras la finalización.
          properties:
            requests:
              type: integer
              nullable: true
            input_tokens:
              type: integer
              nullable: true
            output_tokens:
              type: integer
              nullable: true
            total_tokens:
              type: integer
              nullable: true
            cost_nanos:
              type: integer
              nullable: true
            cost_usd:
              type: number
              nullable: true
            currency:
              type: string
        billing:
          $ref: '#/components/schemas/BatchBillingSummary'
    ErrorResponse:
      type: object
      required:
        - error
      properties:
        ok:
          type: boolean
          example: false
        error:
          oneOf:
            - type: string
            - type: object
              additionalProperties: true
          example: error_type
        message:
          type: string
          example: Human-readable error message
        description:
          type: string
          example: Additional error details.
        generation_id:
          type: string
          example: G-abc123
        status_code:
          type: integer
          example: 502
        error_type:
          type: string
          enum:
            - user
            - system
          example: system
        error_origin:
          type: string
          enum:
            - user
            - gateway
            - upstream
          example: upstream
        reason:
          type: string
          example: all_candidates_failed
        attempt_count:
          type: integer
          example: 2
        failed_providers:
          type: array
          items:
            type: string
          example:
            - google-ai-studio
            - openai
        failed_statuses:
          type: array
          items:
            type: integer
          example:
            - 403
            - 429
        upstream_error:
          $ref: '#/components/schemas/ErrorUpstreamError'
        failure_sample:
          type: array
          items:
            $ref: '#/components/schemas/ErrorFailureSampleItem'
        provider_failure_diagnostics:
          $ref: '#/components/schemas/ErrorProviderFailureDiagnostics'
        routing_diagnostics:
          $ref: '#/components/schemas/ErrorRoutingDiagnostics'
        provider_candidate_diagnostics:
          $ref: '#/components/schemas/ErrorProviderCandidateDiagnostics'
        provider_enablement:
          $ref: '#/components/schemas/ErrorProviderEnablementDiagnostics'
        missing_pricing_providers:
          type: array
          items:
            type: string
        provider_payment_required_provider:
          type: string
          example: openai
        provider_payment_required_support_notice:
          type: string
          example: >-
            Our upstream provider billing appears to be unavailable. If this
            persists, contact support.
        details:
          type: array
          items:
            type: object
            additionalProperties: true
      additionalProperties: true
    BatchRequestItem:
      type: object
      required:
        - body
      properties:
        custom_id:
          type: string
        method:
          type: string
          default: POST
          enum:
            - POST
        url:
          type: string
          description: >-
            Ruta del endpoint de esta fila. Si se especifica, debe coincidir con
            el endpoint del lote principal. Por defecto se usa el endpoint del
            lote principal.
        body:
          type: object
          additionalProperties: true
    DebugOptions:
      type: object
      description: >-
        Controles de depuración de la pasarela. Estas opciones nunca se reenvían
        al proveedor.
      properties:
        enabled:
          type: boolean
        return_upstream_request:
          type: boolean
        return_upstream_response:
          type: boolean
        trace:
          type: boolean
        trace_level:
          type: string
          enum:
            - summary
            - full
    ProviderRoutingOptions:
      type: object
      description: >-
        Preferencias de enrutamiento de proveedores para la selección de la
        pasarela.
      properties:
        order:
          type: array
          items:
            type: string
        only:
          type: array
          items:
            type: string
        ignore:
          type: array
          items:
            type: string
        include_alpha:
          type: boolean
          description: >-
            Incluir proveedores alpha en el enrutamiento (desactivado de forma
            predeterminada).
        allow_fallbacks:
          type: boolean
          nullable: true
          description: Permitir recurrir a otro proveedor apto tras un fallo.
        require_parameters:
          type: boolean
          nullable: true
          description: >-
            Exigir que el proveedor admita los parámetros solicitados antes del
            enrutamiento.
        required_execution_region:
          type: string
          nullable: true
          description: >-
            Restringir el enrutamiento a proveedores con la región de ejecución
            solicitada.
        required_data_region:
          type: string
          nullable: true
          description: >-
            Restringir el enrutamiento a proveedores con la región de datos
            solicitada.
        require_zero_data_retention:
          type: boolean
          nullable: true
          description: >-
            Restringir el enrutamiento a proveedores que admiten la retención
            cero de datos.
        data_collection:
          type: string
          nullable: true
          enum:
            - allow
            - deny
        zdr:
          type: boolean
          nullable: true
        enforce_distillable_text:
          type: boolean
          nullable: true
        quantizations:
          type: array
          nullable: true
          items:
            type: string
        sort:
          oneOf:
            - type: string
            - type: object
              additionalProperties: true
          description: >-
            Ordenar los proveedores para esta solicitud, por ejemplo, por
            precio, latencia o rendimiento.
        max_price:
          type: object
          properties:
            prompt:
              oneOf:
                - type: number
                - type: string
            completion:
              oneOf:
                - type: number
                - type: string
            image:
              oneOf:
                - type: number
                - type: string
            audio:
              oneOf:
                - type: number
                - type: string
            request:
              oneOf:
                - type: number
                - type: string
        preferred_min_throughput:
          oneOf:
            - type: number
            - type: object
              additionalProperties:
                type: number
        preferred_max_latency:
          oneOf:
            - type: number
            - type: object
              additionalProperties:
                type: number
    BatchRequestCounts:
      type: object
      properties:
        total:
          type: integer
        completed:
          type: integer
        failed:
          type: integer
    AsyncWebhookPublicState:
      type: object
      description: >-
        Configuración depurada del webhook asíncrono y estado de entrega. Nunca
        se devuelven secretos; `has_secret` indica si las entregas firmadas
        están habilitadas. Las entregas firmadas incluyen las cabeceras
        x-phaseo-signature, x-phaseo-timestamp, x-phaseo-event-id,
        x-phaseo-event-type, x-phaseo-delivery-key, x-phaseo-attempt y
        x-phaseo-max-attempts.
      properties:
        url:
          type: string
          format: uri
          nullable: true
        events:
          type: array
          items:
            type: string
        has_secret:
          type: boolean
        delivery:
          $ref: '#/components/schemas/AsyncWebhookDeliverySummary'
        attempts:
          type: array
          items:
            $ref: '#/components/schemas/AsyncWebhookDeliveryAttempt'
    BatchBillingSummary:
      type: object
      properties:
        currency:
          type: string
        billed:
          type: boolean
        charged:
          type: boolean
        reason:
          type: string
        state:
          type: string
          enum:
            - pending
            - estimated
            - settled
            - void
        reservation_id:
          type: string
          nullable: true
        reservation_status:
          type: string
          nullable: true
        estimated_provider_cost:
          type: string
          nullable: true
        estimated_user_cost:
          type: string
          nullable: true
        settled_provider_cost:
          type: string
          nullable: true
        settled_user_cost:
          type: string
          nullable: true
        estimated_nanos:
          type: integer
          nullable: true
        reserved_nanos:
          type: integer
          nullable: true
        estimation_truncated:
          type: boolean
          nullable: true
          description: >-
            True si la estimación de reserva se escaló a partir de una muestra
            limitada de un archivo de entrada de lote mayor.
        estimation_sample_size:
          type: integer
          nullable: true
          description: >-
            Número de filas de entrada valoradas directamente para estimar la
            reserva.
        estimation_total_rows:
          type: integer
          nullable: true
          description: >-
            Total de filas de entrada representadas por la estimación de
            reserva.
        total_nanos:
          type: integer
          nullable: true
        cost_nanos:
          type: integer
          nullable: true
        cost_usd:
          type: number
          nullable: true
        finalized_at:
          type: string
          nullable: true
        pricing_breakdown:
          type: object
          additionalProperties: true
    ErrorUpstreamError:
      type: object
      properties:
        code:
          type: string
          nullable: true
          example: PERMISSION_DENIED
        message:
          type: string
          nullable: true
          example: The caller does not have permission.
        description:
          type: string
          nullable: true
        param:
          type: string
          nullable: true
    ErrorFailureSampleItem:
      type: object
      properties:
        provider:
          type: string
          nullable: true
        type:
          type: string
          nullable: true
        status:
          type: integer
          nullable: true
        upstream_error_code:
          type: string
          nullable: true
        upstream_error_message:
          type: string
          nullable: true
        upstream_error_description:
          type: string
          nullable: true
        upstream_error_param:
          type: string
          nullable: true
        upstream_payload_preview:
          type: string
          nullable: true
        retryable:
          type: boolean
          nullable: true
      additionalProperties: true
    ErrorProviderFailureDiagnostics:
      type: object
      properties:
        category:
          type: string
          enum:
            - credentials_not_configured
            - credentials_invalid_or_forbidden
            - provider_access_missing
            - region_or_project_restriction
            - model_unavailable_for_endpoint
            - rate_limited
            - server_error
        hint:
          type: string
        provider:
          type: string
          nullable: true
    ErrorRoutingDiagnostics:
      type: object
      properties:
        filterStages:
          type: array
          items:
            type: object
            properties:
              stage:
                type: string
              beforeCount:
                type: integer
              afterCount:
                type: integer
              droppedProviders:
                type: array
                items:
                  type: object
                  properties:
                    providerId:
                      type: string
                      nullable: true
                    reason:
                      type: string
                      nullable: true
                  additionalProperties: true
            additionalProperties: true
      additionalProperties: true
    ErrorProviderCandidateDiagnostics:
      type: object
      properties:
        totalProviders:
          type: integer
        supportsEndpointCount:
          type: integer
        candidateCount:
          type: integer
        droppedUnsupportedEndpoint:
          type: array
          items:
            type: string
        droppedMissingAdapter:
          type: array
          items:
            type: object
            properties:
              providerId:
                type: string
                nullable: true
              endpoint:
                type: string
                nullable: true
            additionalProperties: true
      additionalProperties: true
    ErrorProviderEnablementDiagnostics:
      type: object
      properties:
        capability:
          type: string
        providersBefore:
          type: array
          items:
            type: string
        providersAfter:
          type: array
          items:
            type: string
        dropped:
          type: array
          items:
            type: object
            properties:
              providerId:
                type: string
                nullable: true
              reason:
                type: string
                nullable: true
            additionalProperties: true
      additionalProperties: true
    AsyncWebhookDeliverySummary:
      type: object
      description: >-
        Resumen público de entrega de webhooks asíncronos gestionados por la
        pasarela. Permite distinguir el estado de ejecución del trabajo del
        estado de entrega del webhook.
      properties:
        total_attempts:
          type: integer
          description: Total de intentos de entrega registrados para este trabajo.
        delivered_events:
          type: integer
          description: Número de claves de entrega que han alcanzado el estado entregado.
        delivered_event_types:
          type: array
          description: Claves de entrega entregadas al menos una vez.
          items:
            type: string
          example:
            - video.completed
        pending_retries:
          type: integer
          description: Número de claves de entrega con un reintento programado actualmente.
        next_retry_at:
          type: string
          nullable: true
          description: Marca de tiempo ISO del próximo reintento programado, si existe.
        last_attempt_at:
          type: string
          nullable: true
          description: Marca de tiempo ISO del intento de entrega más reciente.
        last_attempt_status:
          type: string
          nullable: true
          enum:
            - delivered
            - scheduled_retry
            - failed_permanently
          description: Resultado del intento de entrega más reciente.
        last_response_status:
          type: integer
          nullable: true
          description: Estado HTTP devuelto por el destino del webhook, si está disponible.
        last_delivered_at:
          type: string
          nullable: true
          description: Marca de tiempo ISO de la entrega correcta más reciente.
        last_failure_at:
          type: string
          nullable: true
          description: Marca de tiempo ISO del intento fallido o en reintento más reciente.
        last_error_message:
          type: string
          nullable: true
          description: Mensaje de error de entrega más reciente, si está disponible.
    AsyncWebhookDeliveryAttempt:
      type: object
      description: >-
        Intento reciente de entrega de un webhook asíncrono gestionado por la
        pasarela.
      properties:
        id:
          type: string
          description: Identificador estable del intento para auditoría y depuración.
        delivery_key:
          type: string
          description: Clave de idempotencia para la entrega de este evento.
          example: video.completed
        event_type:
          type: string
          description: Tipo de evento entregado al destino del webhook.
          example: video.completed
        status:
          type: string
          enum:
            - delivered
            - scheduled_retry
            - failed_permanently
        attempt_number:
          type: integer
          description: Número de intento para esta clave de entrega, comenzando en uno.
        max_attempts:
          type: integer
          description: >-
            Máximo de intentos antes de marcar la entrega como fallida
            permanentemente.
        tried_at:
          type: string
          description: Marca de tiempo ISO de este intento.
        delivered_at:
          type: string
          nullable: true
          description: Marca de tiempo ISO de la entrega correcta de este intento.
        next_retry_at:
          type: string
          nullable: true
          description: >-
            Marca de tiempo ISO del próximo reintento tras este intento, si está
            programado.
        response_status:
          type: integer
          nullable: true
          description: Estado HTTP devuelto por el destino del webhook, si está disponible.
        error_message:
          type: string
          nullable: true
          description: Mensaje de error de entrega, si está disponible.
        response_body_preview:
          type: string
          nullable: true
          description: >-
            Vista previa del cuerpo de respuesta del destino del webhook con
            información sensible oculta.
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      description: Autenticación con token Bearer

````

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