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

# Run Variational Workload

> Train the parameters of a variational circuit, on a device or classically.

Use this tool for VQE-style workloads on a stored parameterized circuit. Set
``mode`` to ``optimization`` to minimize an observable by running the circuit
on a backend, or to ``pretraining`` to fit the parameters classically before
spending any quantum time.

When to Use:
    - Call this with ``mode='optimization'`` when the user wants a ground-state
      energy, a minimized cost observable, or a VQE run.
    - Call this with ``mode='pretraining'`` first when the circuit has many
      parameters, then feed the resulting parameters into an optimization run
      as ``initial_parameters``.

Constraints:
    - ``mode='optimization'`` requires ``observable`` and ``device_id``;
      ``mode='pretraining'`` requires ``loss_expression`` and ``observables``.
      Fields belonging to the other mode are rejected with ``422`` rather than
      silently ignored.
    - ``circuit_id`` must reference a stored circuit with free parameters.
    - Both modes are asynchronous and billable. Poll with
      ``get_job_results_and_status``; stop a run with ``cancel_job``.
    - Optimization runs many circuit evaluations, so wall-clock time and cost
      scale with the optimizer's iteration budget, not with a single shot count.

Notes:
    - Confirm the iteration budget with the user before submitting an
      optimization run against real hardware.
    - Backend credentials go in ``options``, in the same form
      ``run_circuits_on_qpu_or_simulator`` documents.

Args:
    user: Authenticated user resolved from the API key.
    data: Mode selector plus the fields required by that mode.
    db: Active database session.

Returns:
    The created job identifier, the mode, and the next polling step.

Raises:
    HTTPException: Raised with ``402`` when the caller cannot submit billable
        jobs, ``404`` when the experiment or circuit is unavailable, or ``422``
        when the payload does not match the selected mode.



## OpenAPI

````yaml https://api.haiqu.ai/openapi.json post /ai/run_variational_workload
openapi: 3.1.0
info:
  title: Haiqu API
  summary: Haiqu RESTful API service.
  description: Cloud service providing the access to Haiqu cloud runtime
  contact:
    name: Haiqu Inc.
    url: https://haiqu.ai/
    email: info@haiqu.ai
  version: 1.5.0
servers: []
security: []
paths:
  /ai/run_variational_workload:
    post:
      summary: Run Variational Workload
      description: >-
        Train the parameters of a variational circuit, on a device or
        classically.


        Use this tool for VQE-style workloads on a stored parameterized circuit.
        Set

        ``mode`` to ``optimization`` to minimize an observable by running the
        circuit

        on a backend, or to ``pretraining`` to fit the parameters classically
        before

        spending any quantum time.


        When to Use:
            - Call this with ``mode='optimization'`` when the user wants a ground-state
              energy, a minimized cost observable, or a VQE run.
            - Call this with ``mode='pretraining'`` first when the circuit has many
              parameters, then feed the resulting parameters into an optimization run
              as ``initial_parameters``.

        Constraints:
            - ``mode='optimization'`` requires ``observable`` and ``device_id``;
              ``mode='pretraining'`` requires ``loss_expression`` and ``observables``.
              Fields belonging to the other mode are rejected with ``422`` rather than
              silently ignored.
            - ``circuit_id`` must reference a stored circuit with free parameters.
            - Both modes are asynchronous and billable. Poll with
              ``get_job_results_and_status``; stop a run with ``cancel_job``.
            - Optimization runs many circuit evaluations, so wall-clock time and cost
              scale with the optimizer's iteration budget, not with a single shot count.

        Notes:
            - Confirm the iteration budget with the user before submitting an
              optimization run against real hardware.
            - Backend credentials go in ``options``, in the same form
              ``run_circuits_on_qpu_or_simulator`` documents.

        Args:
            user: Authenticated user resolved from the API key.
            data: Mode selector plus the fields required by that mode.
            db: Active database session.

        Returns:
            The created job identifier, the mode, and the next polling step.

        Raises:
            HTTPException: Raised with ``402`` when the caller cannot submit billable
                jobs, ``404`` when the experiment or circuit is unavailable, or ``422``
                when the payload does not match the selected mode.
      operationId: run_variational_workload
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ContextVariationalSubmitModel'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ContextVariationalJobModel'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - APIKeyQuery: []
        - APIKeyHeader: []
components:
  schemas:
    ContextVariationalSubmitModel:
      properties:
        mode:
          type: string
          enum:
            - optimization
            - pretraining
          title: Mode
          description: >-
            Use `optimization` to minimize an observable on a device or
            simulator (requires `observable` and `device_id`), or `pretraining`
            to fit circuit parameters classically before any quantum execution
            (requires `loss_expression` and `observables`).
        experiment_id:
          type: string
          title: Experiment Id
        circuit_id:
          type: string
          title: Circuit Id
          description: Parameterized circuit to train, from a prior MCP response.
        name:
          anyOf:
            - type: string
            - type: 'null'
          title: Name
          default: ''
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
          default: ''
        initial_parameters:
          anyOf:
            - items:
                type: number
              type: array
            - type: 'null'
          title: Initial Parameters
          description: >-
            Optional starting parameter values. Length must match the circuit's
            parameter count.
        observable:
          anyOf:
            - prefixItems:
                - items:
                    type: string
                  type: array
                - items:
                    type: number
                  type: array
              type: array
              maxItems: 2
              minItems: 2
            - type: 'null'
          title: Observable
          description: >-
            Cost observable for `optimization` mode as `[[pauli_strings],
            [coefficients]]`, for example `[["ZZ", "XX"], [1.0, 0.5]]`.
        device_id:
          anyOf:
            - type: string
            - type: 'null'
          title: Device Id
          description: Backend for `optimization` mode, from `list_qpus_and_simulators`.
        shots:
          type: integer
          title: Shots
          description: Shots per circuit evaluation in `optimization` mode.
          default: 1000
        optimizer_options:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Optimizer Options
          description: >-
            Classical optimizer for `optimization` mode. Either `{'type': 'nft',
            'maxiter': 100, 'maxfev': 200, 'reset_interval': 32}` or `{'type':
            'scipy', 'method': 'cobyla', 'maxfev': 200, 'options': {}}`.
            Defaults to NFT with library defaults when omitted.
        options:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Options
          description: >-
            Backend options, including device credentials where the backend
            requires them.
        use_mitigation:
          type: boolean
          title: Use Mitigation
          description: Apply error mitigation in `optimization` mode.
          default: false
        use_compression:
          type: boolean
          title: Use Compression
          description: Apply state compression in `optimization` mode.
          default: false
        compression_options:
          anyOf:
            - additionalProperties: true
              type: object
            - type: 'null'
          title: Compression Options
          description: State-compression parameters used when `use_compression` is true.
        loss_expression:
          anyOf:
            - type: string
            - type: 'null'
          title: Loss Expression
          description: >-
            Loss formula for `pretraining` mode, written over the keys of
            `observables`, for example `"(energy - target) ** 2"`.
        observables:
          anyOf:
            - additionalProperties:
                prefixItems:
                  - items:
                      type: string
                    type: array
                  - items:
                      type: number
                    type: array
                type: array
                maxItems: 2
                minItems: 2
              type: object
            - type: 'null'
          title: Observables
          description: >-
            Named observables for `pretraining` mode, each as `[[pauli_strings],
            [coefficients]]`, for example `{"energy": [["ZZ"], [1.0]]}`.
        max_time:
          anyOf:
            - type: number
            - type: 'null'
          title: Max Time
          description: Pretraining wall-clock budget in seconds.
        seed:
          anyOf:
            - type: integer
            - type: 'null'
          title: Seed
          description: Pretraining random seed.
      type: object
      required:
        - mode
        - experiment_id
        - circuit_id
      title: ContextVariationalSubmitModel
      description: >-
        Define payload for variational optimization and pretraining jobs.


        One model covers both modes of the variational family. ``mode`` selects
        the

        behavior and determines which of the remaining fields are required; the

        unused fields for a mode are rejected with ``422`` rather than ignored.


        Attributes:
            mode: Which variational workload to run.
            experiment_id: Parent experiment identifier.
            circuit_id: Parameterized circuit to train.
            name: Optional job name.
            description: Optional job description.
            initial_parameters: Optional starting parameter values.
            observable: Cost observable, required for ``optimization``.
            device_id: Execution backend, required for ``optimization``.
            shots: Shots per circuit evaluation, ``optimization`` only.
            optimizer_options: Classical optimizer configuration, ``optimization``
                only.
            options: Backend or run options, forwarded as given.
            use_mitigation: Whether to apply error mitigation, ``optimization`` only.
            use_compression: Whether to apply state compression, ``optimization``
                only.
            compression_options: Compression parameters, ``optimization`` only.
            loss_expression: Loss formula, required for ``pretraining``.
            observables: Named observables referenced by ``loss_expression``,
                required for ``pretraining``.
            max_time: Optional pretraining wall-clock budget in seconds.
            seed: Optional pretraining random seed.
      examples:
        - circuit_id: circ-123
          device_id: fake_kyiv
          experiment_id: exp-123
          mode: optimization
          observable:
            - - ZZ
              - XX
            - - 1
              - 0.5
          optimizer_options:
            maxiter: 50
            type: nft
          shots: 4096
        - circuit_id: circ-123
          experiment_id: exp-123
          loss_expression: (energy + 1.0) ** 2
          mode: pretraining
          observables:
            energy:
              - - ZZ
              - - 1
          seed: 7
    ContextVariationalJobModel:
      properties:
        job_id:
          type: string
          title: Job Id
        mode:
          type: string
          title: Mode
        context:
          type: string
          title: Context
      type: object
      required:
        - job_id
        - mode
        - context
      title: ContextVariationalJobModel
      description: |-
        Represent context returned after a variational submission.

        Attributes:
            job_id: Created job identifier.
            mode: Variational mode that was submitted.
            context: Submission summary and next polling step.
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    APIKeyQuery:
      type: apiKey
      in: query
      name: HAIQU_API_KEY
    APIKeyHeader:
      type: apiKey
      in: header
      name: authorization

````