Skip to content

API Reference

Complete reference documentation for all Open Quantum SDK classes, methods, and data models.

Core SDK

SchedulerClient

SchedulerClient

Bases: BaseClient

Client for the OpenQuantum Scheduler API.

Handles the full job lifecycle: uploading circuit files, preparing quotes, submitting jobs, polling for completion, and downloading results.

The high-level submit_job() method wraps the entire flow in a single call. Lower-level methods (upload_job_input, prepare_job, wait_for_preparation, choose_plan_and_priority, create_job, wait_for_job) are available when the caller needs to stop between the quote and the spend.

Example

from openquantum_sdk.auth import ClientCredentials, ClientCredentialsAuth from openquantum_sdk.clients import SchedulerClient, JobSubmissionConfig auth = ClientCredentialsAuth( ... creds=ClientCredentials(client_id="s_...", client_secret="...") ... ) scheduler = SchedulerClient(auth=auth) config = JobSubmissionConfig( ... backend_class_id="ionq:aria-1", ... name="My Job", ... job_subcategory_id="phys:oth", ... shots=1024, ... ) job = scheduler.submit_job(config, file_path="circuit.qasm")

submit_job

Submit a job end-to-end: upload, prepare, approve, create, and poll.

This is the recommended way to run a circuit. It handles the full lifecycle automatically:

  1. Upload the circuit file.
  2. Prepare the job and fetch a pricing quote.
  3. Select (or auto-select) the execution plan and queue priority.
  4. Approve the quote and create the job.
  5. Poll until the job completes (or times out).

Provide exactly one of file_content or file_path.

Returns:

Type Description
JobRead

A JobRead for the completed job, including the

JobRead

output_data_url for downloading results.

Raises:

Type Description
RuntimeError

If preparation fails, the user declines the quote, or the job fails or is canceled.

TimeoutError

If the job does not complete within config.job_timeout_seconds.

Example

config = JobSubmissionConfig( ... backend_class_id="ionq:aria-1", ... name="Bell State", ... job_subcategory_id="phys:oth", ... shots=1024, ... ) job = scheduler.submit_job(config, file_path="bell.qasm") output = scheduler.download_job_output(job)

upload_job_input

Upload a circuit file and return the upload ID.

Provide exactly one of file_content or file_path.

Returns:

Type Description
str

The upload endpoint ID used to reference this file in subsequent

str

preparation and submission calls.

Raises:

Type Description
ValueError

If both or neither of file_content and file_path are provided.

TypeError

If file_content is a str instead of bytes.

prepare_job

Submit a job preparation request.

Preparation validates the circuit, calculates pricing, and returns a preparation ID that can be polled via get_preparation_result().

Returns:

Type Description
JobPreparationResponse

A JobPreparationResponse containing the preparation id.

get_preparation_result

Get the status and pricing quote for a job preparation.

Poll this method until the returned status is "Completed" or "Failed". On completion, the quote field contains the available execution plans and queue priorities with pricing.

Returns:

Type Description
JobPreparationResultResponse

A JobPreparationResultResponse with status, quote, and

JobPreparationResultResponse

circuit metadata.

create_job

Create and submit a job from a completed preparation.

This deducts credits and places the job in the execution queue. Organization is taken from the preparation; organization_id on JobCreate is optional.

Returns:

Type Description
JobRead

A JobRead with the new job's ID and initial status.

get_job

Get the current status of a job.

Returns:

Type Description
JobRead

A JobRead with the job's current status and metadata.

cancel_job

Cancel a queued or running job.

list_jobs

List jobs for an organization.

Returns:

Type Description
PaginatedJobs

A PaginatedJobs containing the job list and pagination

PaginatedJobs

metadata.

download_job_output

Download and parse the output of a completed job.

Returns:

Type Description
Any

The parsed JSON result from the job output.

Raises:

Type Description
RuntimeError

If the job has no output_data_url (e.g., not completed yet or produced no output).

ValueError

If the output cannot be parsed as JSON.

download_job_calibration

Download and parse the calibration snapshot tagged on a job.

Calibration is optional: only present if reported.

Returns:

Type Description
Any

Parsed JSON calibration payload.

Raises:

Type Description
RuntimeError

If the job has no calibration_data_url.

ValueError

If the body cannot be parsed as JSON.

wait_for_preparation

Poll a preparation until it completes or fails.

A Failed preparation raises RuntimeError. A timeout raises TimeoutError. Not-found responses (the preparation row is not visible yet) are retried until the timeout.

wait_for_job

Poll a job until it reaches a terminal status or times out.

Terminal statuses are Completed, Failed, and Canceled (see :data:TERMINAL_JOB_STATUSES).

Returns:

Type Description
JobRead

The latest JobRead. On a soft timeout this is non-terminal.

choose_plan_and_priority

Choose a plan and priority from a completed preparation.

See :func:select_plan_and_priority for the selection rules. prefer_public=True ranks Public plans first when the plan is "auto" (the MCP spend policy). The default keeps cheapest-wins.

Plan selection

openquantum_sdk.clients.select_plan_and_priority(quote, execution_plan='auto', queue_priority='auto', *, prefer_public=False)

Pick an execution plan and queue priority from a preparation quote.

"auto" minimizes total cost (base price + priority increase), then base price. Friendly names ("public", "private", "standard", "priority", "instant"), ExecutionPlanType / QueuePriorityType members, and raw UUIDs select that option exactly.

prefer_public only affects execution_plan="auto": Public plans are ranked ahead of Private ones, then the cheapest pair inside that group wins. The MCP server sets this so Spark credits can apply. The default (False) keeps the historical cheapest-plan behavior used by submit_job.

Raises:

Type Description
ValueError

If the quote is empty or the requested plan/priority is not in it.

OpenQuantumClient

Framework-agnostic session used by PennyLane, Cirq, Qrisp, and the MCP server. from_env() resolves environment credentials and the playbook URL variables and does not autoload a saved account.

openquantum_sdk.session.OpenQuantumClient

Authenticated session holding a management + scheduler client pair.

Authentication is resolved in this order:

  1. An explicit token or creds argument.
  2. A saved account on disk (autoloaded when neither is given and auto_load is true). Set OPENQUANTUM_NO_AUTOLOAD=1 or auto_load=False to disable. OPENQUANTUM_ACCOUNT_NAME selects the account (default "default").

Environment-variable credential resolution (OPENQUANTUM_TOKEN etc.) is intentionally not performed in __init__. Callers that want env credentials and service URLs without a saved-account autoload should use :meth:from_env. This keeps autoload and explicit-env behavior separable.

Use as a context manager to close HTTP sessions on exit.

from_env(*, token=None, creds=None, client_id=None, client_secret=None, sdk_key_path=None, keycloak_base=None, realm=None, scheduler_url=None, management_url=None, require=True, **kwargs) classmethod

Build a client from arguments and environment variables.

Does not autoload a saved account. Credential resolution uses :func:openquantum_sdk.credentials.resolve_env_credentials. Service URLs fall back to OPENQUANTUM_SCHEDULER_URL / OPENQUANTUM_MANAGEMENT_URL / OPENQUANTUM_KEYCLOAK_BASE / OPENQUANTUM_KEYCLOAK_REALM, then the production defaults.

When require is true (the default) and no credential resolves, raises :class:~openquantum_sdk.exceptions.AuthenticationError. Pass an already-resolved creds or token to skip env lookup.

organizations()

List organizations the authenticated user belongs to.

backends(*, name=None, online=None, device_type=None, vendor_id=None, min_num_qubits=None, limit=50)

List available backend classes with optional client-side filtering.

Returns a list of dicts with id, name, description, type, provider_id, short_code, queue_depth, accepting_jobs, and status.

login(*, token=None, creds=None, save=False, name='default', filename=None, **kwargs) classmethod

Authenticate and return a client, optionally saving the credentials.

close()

Close the underlying HTTP sessions.

ManagementClient

ManagementClient

Bases: BaseClient

Client for the OpenQuantum Management API.

Provides backend discovery, provider listing, and organization lookup. The management API is read-only and does not require an organization context.

Example

from openquantum_sdk.auth import ClientCredentials, ClientCredentialsAuth auth = ClientCredentialsAuth( ... creds=ClientCredentials(client_id="s_...", client_secret="...") ... ) mgmt = ManagementClient(auth=auth) backends = mgmt.list_backend_classes()

list_backend_classes

List available backend classes (QPUs and simulators).

Returns:

Type Description
PaginatedBackendClasses

A PaginatedBackendClasses containing the backend list and

PaginatedBackendClasses

pagination metadata. Each BackendClassRead includes the

PaginatedBackendClasses

backend's name, type, status, queue depth, and short_code.

list_providers

List quantum hardware providers on the platform.

Returns:

Type Description
PaginatedProviders

A PaginatedProviders containing the provider list and

PaginatedProviders

pagination metadata.

list_user_organizations

List organizations the authenticated user belongs to.

Returns:

Type Description
PaginatedOrganizations

A PaginatedOrganizations containing the organizations list

PaginatedOrganizations

and pagination metadata.

JobSubmissionConfig

openquantum_sdk.clients.JobSubmissionConfig dataclass

Configuration for submitting a job via SchedulerClient.submit_job().

This dataclass bundles every option needed to upload a circuit, prepare a quote, and submit the job in a single call.

Parameters:

Name Type Description Default
backend_class_id str

Backend class ID or short_code (e.g., "ionq:aria-1").

required
name str

Human-readable name for the job (visible in the portal).

required
job_subcategory_id str

Job subcategory ID or short_code (e.g., "phys:oth").

required
shots Optional[int]

Optional measurement shot count (legacy). Prefer configuration_data["shots"]. Omit when the backend does not use shots. When set, the SDK dual-writes into configuration_data if missing.

None
organization_id Optional[str]

Organization UUID. Optional if the user belongs to exactly one organization — the SDK resolves it automatically.

None
configuration_data Optional[Dict[str, Any]]

Optional backend-specific configuration dictionary.

None
execution_plan Union[str, ExecutionPlanType, AutoChoice]

"auto" selects the cheapest available plan. Also accepts "public" / "private", an ExecutionPlanType value, or a plan UUID.

'auto'
queue_priority Union[str, QueuePriorityType, AutoChoice]

"auto" selects the cheapest priority. Also accepts "standard" / "priority" / "instant", a QueuePriorityType value, or a priority UUID.

'auto'
auto_approve_quote bool

If True (default), the pricing quote is approved automatically. Set to False to display the quote and prompt for confirmation before submitting.

True
verbose bool

If True, print step-by-step progress messages during submission. Useful in notebooks and CLI scripts.

False
job_timeout_seconds int

Maximum seconds to wait for the job to complete. Defaults to 86 400 (1 day).

86400
submitted_with Optional[str]

Client/surface that submitted this preparation (e.g. "sdk", "qiskit", "cli"). Defaults to "sdk".

'sdk'
input_format Optional[str]

Circuit input language family (e.g. "qasm"). Defaults to "qasm". OpenQASM 2/3 both use "qasm". Use the format advertised by the backend's supported_formats for non-QASM payloads.

None
Example

config = JobSubmissionConfig( ... backend_class_id="ionq:aria-1", ... name="Bell State", ... job_subcategory_id="phys:oth", ... shots=1024, ... ) job = scheduler.submit_job(config, file_path="circuit.qasm")

Authentication

openquantum_sdk.auth.ClientCredentialsAuth

Keycloak client-credentials OAuth2 helper with thread-safe token caching.

Manages the full token lifecycle: initial fetch, automatic refresh when the token is within leeway_seconds of expiry, and forced refresh on 401 retries. All token operations are thread-safe.

The token endpoint is constructed as: {keycloak_base}/realms/{realm}/protocol/openid-connect/token

token_endpoint property

The full Keycloak token endpoint URL for this realm.

__init__(creds, keycloak_base='https://id.openquantum.com', realm='platform', scope=None, leeway_seconds=30, session=None)

Initialize the auth helper.

Parameters:

Name Type Description Default
creds ClientCredentials

Client credentials containing the client ID and secret.

required
keycloak_base str

Base URL of the Keycloak server. Defaults to "https://id.openquantum.com".

'https://id.openquantum.com'
realm str

Keycloak realm name. Defaults to "platform".

'platform'
scope Optional[str]

Optional OAuth2 scope to request.

None
leeway_seconds int

Seconds before token expiry to trigger a proactive refresh. Defaults to 30.

30
session Optional[Session]

Optional requests.Session to use for token requests. A new session is created if not provided.

None

apply_auth_header(headers)

Add a Bearer authorization header using the current access token.

Does not mutate the input dict; returns a new dict with the Authorization header added.

Parameters:

Name Type Description Default
headers Dict[str, str]

Existing headers to augment.

required

Returns:

Type Description
Dict[str, str]

A new headers dict containing all entries from headers plus

Dict[str, str]

the Authorization: Bearer <token> header.

get_access_token(force=False)

Return a valid access token, refreshing if needed.

Uses double-checked locking to ensure only one thread fetches a new token at a time.

Parameters:

Name Type Description Default
force bool

If True, forces a token refresh regardless of expiry status. Defaults to False.

False

Returns:

Type Description
str

A valid OAuth2 access token string.

Raises:

Type Description
RuntimeError

If the Keycloak response is missing an access token.

HTTPError

If the token request fails.

openquantum_sdk.auth.ClientCredentials dataclass

SDK key credentials for machine-to-machine authentication.

Attributes:

Name Type Description
client_id str

The OAuth2 client ID (SDK key ID).

client_secret str

The OAuth2 client secret (SDK key secret).

Models

openquantum_sdk.models.APIError

Bases: OpenQuantumError

Exception raised when the Open Quantum API returns an error response.

Wraps an ErrorResponse and produces a human-readable message that includes the status code, error messages, and request ID.

Attributes:

Name Type Description
error_response

The parsed ErrorResponse from the API.

Exceptions

The shared exception hierarchy raised across the SDK and all framework plugins. Catch OpenQuantumError to handle any Open Quantum failure uniformly.

openquantum_sdk.exceptions

Exception hierarchy for the Open Quantum SDK and its framework plugins.

Everything the SDK or a plugin raises derives from :class:OpenQuantumError, so except OpenQuantumError catches any Open Quantum failure regardless of which framework surface produced it. Below the root are a small set of semantic errors, caught by the kind of failure rather than by framework:

  • :class:AuthenticationError -- missing or invalid credentials.
  • :class:CircuitValidationError -- the circuit cannot be serialized or is not accepted by the target backend (unsupported gate, missing measurement, bad structure).
  • :class:JobError -- a submitted job failed, was cancelled, or returned a result the client could not interpret.

APIError (raised for HTTP-level API responses) is reparented onto this root in :mod:openquantum_sdk.models, so it too is an OpenQuantumError.

Simple argument validation (an empty backend, a bad export_format) stays a plain :class:ValueError, matching normal Python convention.

AuthenticationError

Bases: OpenQuantumError

Raised when credentials are missing or cannot authenticate the client.

CircuitValidationError

Bases: OpenQuantumError

Raised when a circuit cannot be serialized or is rejected by the backend.

JobError

Bases: OpenQuantumError

Raised when a job fails, is cancelled, or returns an unreadable result.

OpenQuantumError

Bases: Exception

Base class for every error raised by the Open Quantum SDK and plugins.

Qiskit Plugin

QASM export

Public helper. Import export_circuit_to_qasm from openquantum_sdk_qiskit, not from the private _qasm module.

openquantum_sdk_qiskit.export_circuit_to_qasm(circuit, fmt, *, backend=None)

Export a circuit to QASM, optionally validating against a backend first.

If backend is provided and has a validate_circuit method, it will be called before export. This provides early, capability-aware rejection (custom gates, shot limits when combined with higher-level callers, etc.).

OpenQuantumService

openquantum_sdk_qiskit.oq_service.OpenQuantumService

Bases: OpenQuantumClient

Entry point for the OpenQuantum Qiskit plugin.

Inherits authentication, saved-account management, and backend/organization discovery from OpenQuantumClient, and adds the Qiskit-specific factories: building a Qiskit Target or BackendV2 for a device, and creating Sampler / Estimator primitives that submit jobs to the OpenQuantum platform.

The service can be instantiated directly with a token or creds, loaded from a saved account on disk, or created via the convenience :meth:login classmethod. When neither token nor creds is supplied the constructor attempts to auto-load the saved account named by OPENQUANTUM_ACCOUNT_NAME (default "default"). If that account is missing or cannot be loaded, it falls back to :func:openquantum_sdk.credentials.resolve_env_credentials (OPENQUANTUM_TOKEN, an SDK key file, or OPENQUANTUM_CLIENT_ID + OPENQUANTUM_CLIENT_SECRET). Set OPENQUANTUM_NO_AUTOLOAD=1 or auto_load=False to skip the saved account and use only those environment credentials.

Use as a context manager to close HTTP sessions on exit.

Example
from openquantum_sdk_qiskit import OpenQuantumService

service = OpenQuantumService(token="oq_tok_...")
backends = service.backends(online=True)
backend = service.return_backend("rigetti:ankaa-3")
sampler = service.create_sampler(backend=backend, job_subcategory_id="oth:oth")
service.close()

Attributes:

Name Type Description
management

The underlying ManagementClient used for backend discovery.

scheduler

The underlying SchedulerClient used for job submission.

__init__(*, token=None, creds=None, keycloak_base=DEFAULT_KEYCLOAK_BASE, realm=DEFAULT_REALM, scheduler_url=DEFAULT_SCHEDULER_URL, management_url=DEFAULT_MANAGEMENT_URL, auto_load=True, account_name=None, accounts_file=None)

return_backend(name, *, config=None, export_format='qasm3', verbose=None, job_timeout_seconds=None)

Create an OpenQuantumBackend (Qiskit BackendV2) for name.

The returned backend works with Qiskit's transpiler and can submit circuits via its :meth:~OpenQuantumBackend.run method.

Parameters:

Name Type Description Default
name str

Backend identifier (id, short_code, or name).

required
config Optional[Dict[str, Any]]

Optional platform submission metadata. backend_class_id defaults to name; job_subcategory_id belongs on job creation. May include organization_id, name, execution_plan, queue_priority, configuration_data, verbose, and job_timeout_seconds.

None
export_format str

"qasm2" or "qasm3" (default).

'qasm3'
verbose Optional[bool]

Print submission progress and the credit cost. Defaults to False. Overrides config["verbose"].

None
job_timeout_seconds Optional[int]

Maximum seconds to wait for a job to complete. Defaults to 86400. Overrides config["job_timeout_seconds"].

None

Raises:

Type Description
ValueError

If capabilities for the named backend cannot be found.

return_target(name)

Build a Qiskit Target for the named backend.

The Target describes the backend's native gate set, qubit count, and coupling map, and is used by the Qiskit transpiler.

Parameters:

Name Type Description Default
name str

Backend identifier (id, short_code, or name).

required

Raises:

Type Description
ValueError

If capabilities for the named backend cannot be found.

create_sampler(*, backend, organization_id=None, job_subcategory_id='oth:oth', name=None, configuration_data=None, execution_plan='auto', queue_priority='auto', export_format='qasm3', verbose=None, job_timeout_seconds=None)

Create an :class:OQSampler (Qiskit SamplerV2) backed by OpenQuantum.

Parameters:

Name Type Description Default
backend 'BackendV2'

A Qiskit BackendV2 (typically from :meth:return_backend) used for transpilation and target validation. Its name supplies the target backend class.

required
organization_id Optional[str]

Billing organization UUID. Optional.

None
job_subcategory_id str

Workload subcategory (default "oth:oth").

'oth:oth'
name Optional[str]

Job name prefix.

None
configuration_data Optional[Dict[str, Any]]

Provider-specific configuration passthrough.

None
execution_plan str

"auto" (default), "public", or "private".

'auto'
queue_priority str

"auto" (default), "standard", "priority", or "instant".

'auto'
export_format str

"qasm2" or "qasm3" (default).

'qasm3'
verbose Optional[bool]

Print submission progress and the credit cost. When omitted, the backend's flag is used (False if the backend has none).

None
job_timeout_seconds Optional[int]

Maximum seconds to wait for a job to complete. When omitted, the backend's timeout is used (86400 if the backend has none).

None

Raises:

Type Description
ImportError

If Qiskit is not installed.

ValueError

If backend_class_id cannot be determined.

create_estimator(*, backend, organization_id=None, job_subcategory_id='oth:oth', name=None, configuration_data=None, execution_plan='auto', queue_priority='auto', export_format='qasm3', verbose=None, job_timeout_seconds=None)

Create an :class:OQEstimator (Qiskit EstimatorV2) backed by OpenQuantum.

Arguments mirror :meth:create_sampler.

Raises:

Type Description
ImportError

If Qiskit is not installed.

ValueError

If backend_class_id cannot be determined.

OpenQuantumBackend

openquantum_sdk_qiskit.oq_backend.OpenQuantumBackend

Bases: BackendV2

Qiskit BackendV2 implementation for the OpenQuantum platform.

Wraps the OpenQuantum scheduler so that circuits can be submitted and results retrieved through the standard Qiskit backend interface. The backend's Target (native gate set, coupling map, qubit count) is derived from a capabilities dictionary that is either supplied explicitly or resolved from built-in data.

This backend is typically obtained via :meth:OpenQuantumService.return_backend rather than constructed directly.

Example
backend = service.return_backend("rigetti:ankaa-3")

__init__(name, *, capabilities=None, scheduler=None, config=None, export_format='qasm3', configuration_schema=None, verbose=None, job_timeout_seconds=None, **kwargs)

Initialise the backend.

Parameters:

Name Type Description Default
name str

Backend identifier used for capabilities lookup and as the Qiskit backend name.

required
capabilities Optional[Dict[str, Any]]

Hardware capabilities dictionary describing qubit count, native gates, and topology. When None, built-in capabilities are selected by matching name against known backends (e.g. "rigetti:ankaa-3", "ionq:aria-1").

None
scheduler Optional[SchedulerClient]

A :class:~openquantum_sdk.clients.SchedulerClient instance used to submit jobs. Required if the backend will be used for execution (via :meth:run).

None
config Optional[Dict[str, Any]]

Optional platform submission metadata for the backend. backend_class_id defaults to the name. job_subcategory_id and other per-job fields are best supplied at actual job creation time rather than here (they can still be provided for convenience with direct .run() usage or as overrides). May include organization_id, name, configuration_data, execution_plan, queue_priority.

None
export_format str

Circuit serialisation format -- "qasm2" or "qasm3" (default).

'qasm3'
configuration_schema Optional[Dict[str, Any]]

BackendClass.configuration_schema from the platform API. Property defaults become Qiskit backend.options; run() kwargs matching those properties are sent as job configuration_data.

None
verbose Optional[bool]

Print submission progress and the credit cost. Defaults to False (same as :class:~openquantum_sdk.clients.JobSubmissionConfig). A config["verbose"] entry is used when this argument is omitted.

None
job_timeout_seconds Optional[int]

Maximum seconds to wait for a job to complete. Defaults to 86400 (one day). A config["job_timeout_seconds"] entry is used when this argument is omitted.

None

Raises:

Type Description
ValueError

If export_format is not "qasm2" or "qasm3".

run(circuits, /, *, job_subcategory_id=None, backend_class_id=None, organization_id=None, name=None, configuration_data=None, execution_plan=None, queue_priority=None, **run_options)

Submit one or more circuits to the OpenQuantum platform.

Each circuit is serialised to QASM, submitted to the scheduler, and the results are downloaded synchronously. The method returns immediately with a job-like wrapper around the collected Result.

Job submission metadata (job_subcategory_id, etc.) can be supplied here at the point of job creation, or as defaults via the config passed to the backend constructor.

Parameters:

Name Type Description Default
circuits Iterable[Any]

A single QuantumCircuit or a list of circuits to execute.

required
job_subcategory_id Optional[str]

Workload subcategory for this job. Defaults to "oth:oth" if not provided here or in the backend's config.

None
backend_class_id Optional[str]

Override for the target backend class. Defaults to the value derived at backend construction (usually the name passed to return_backend).

None
organization_id Optional[str]

Override organization for billing.

None
name Optional[str]

Job name prefix for this submission.

None
configuration_data Optional[Dict[str, Any]]

Per-job configuration data.

None
execution_plan, queue_priority

Scheduling overrides for this job.

required
**run_options

Other options including:

  • shots (int) -- Number of measurement shots (default from backend options, fallback 100).
  • memory (bool) -- Include per-shot hex memory in results (default True).
  • export_format (str) -- Override the backend's default serialisation format.
  • verbose (bool) -- Override the backend's progress logging for this run.
  • job_timeout_seconds (int) -- Override the backend's completion timeout for this run.
{}

Returns:

Type Description

A job-like object whose .result() method returns a

Qiskit Result with counts and optional memory for each

submitted circuit.

Raises:

Type Description
RuntimeError

If no scheduler was provided at construction time.

ValueError

If backend_class_id cannot be determined.

OQSampler (SamplerV2)

openquantum_sdk_qiskit.oq_sampler.OQSampler

Bases: BaseSamplerV2

Qiskit SamplerV2 implementation backed by the OpenQuantum platform.

Submits sampling PUBs (Primitive Unified Blocs) to the OpenQuantum scheduler and returns results using Qiskit's primitives containers (DataBin, BitArray, SamplerPubResult, PrimitiveResult).

Typically obtained via :meth:OpenQuantumService.create_sampler rather than constructed directly.

Example
sampler = service.create_sampler(
    backend=backend,
    job_subcategory_id="oth:oth",
)
pub = (circuit, shots)
job = sampler.run([pub])
result = job.result()

__init__(*, backend, options=None, scheduler=None, config=None, export_format='qasm3', verbose=None, job_timeout_seconds=None)

Initialise the sampler.

Parameters:

Name Type Description Default
backend BackendV2

A Qiskit BackendV2 instance used for target validation (e.g. an :class:OpenQuantumBackend).

required
options Optional[dict]

Primitive options dict (currently unused, reserved for future use).

None
scheduler Optional[SchedulerClient]

A :class:~openquantum_sdk.clients.SchedulerClient used to submit jobs. Required for execution.

None
config Optional[Dict[str, Any]]

Platform submission metadata for this sampler (backend_class_id derived from backend when omitted in config; job_subcategory_id etc.). This is the place for job-specific metadata like subcategory.

None
export_format str

Circuit serialisation format -- "qasm2" or "qasm3" (default).

'qasm3'
verbose Optional[bool]

Print submission progress and the credit cost. Defaults to the backend's verbose when that attribute is a bool, otherwise False.

None
job_timeout_seconds Optional[int]

Maximum seconds to wait for a job to complete. Defaults to the backend's timeout when that attribute is an int, otherwise 86400.

None

Raises:

Type Description
ValueError

If export_format is not "qasm2" or "qasm3".

run(pubs, *, shots=None, export_format=None)

Submit sampling PUBs to the OpenQuantum platform.

Each PUB's circuit is serialised, parameter-bound, and submitted to the scheduler. Results are collected and returned as Qiskit SamplerPubResult objects containing BitArray measurement data.

Parameters:

Name Type Description Default
pubs Iterable[SamplerPubLike]

One or more sampler PUBs. Each element can be a SamplerPub or any type accepted by SamplerPub.coerce (e.g. a QuantumCircuit or a (circuit, shots) tuple).

required
shots int | None

Number of measurement shots per PUB. Overrides the shot count embedded in each PUB. Defaults to 100 when None.

None
export_format Optional[str]

Override the sampler's default circuit serialisation format ("qasm2" or "qasm3").

None

Returns:

Type Description
PrimitiveJob[PrimitiveResult[SamplerPubResult]]

A PrimitiveJob whose .result() yields a

PrimitiveJob[PrimitiveResult[SamplerPubResult]]

PrimitiveResult[SamplerPubResult].

Raises:

Type Description
RuntimeError

If no scheduler was provided at construction time.

ValueError

If backend_class_id cannot be determined from the backend (and not supplied in config) or if export_format is invalid.

OQEstimator (EstimatorV2)

openquantum_sdk_qiskit.oq_estimator.OQEstimator

Bases: BaseEstimatorV2

Qiskit EstimatorV2 implementation backed by the OpenQuantum platform.

Computes expectation values of observables by delegating to Qiskit's BackendEstimatorV2 with an :class:OpenQuantumBackend that submits circuits to the OpenQuantum scheduler.

Typically obtained via :meth:OpenQuantumService.create_estimator rather than constructed directly.

Example
estimator = service.create_estimator(
    backend=backend,
    job_subcategory_id="oth:oth",
)
pub = (circuit, observable)
job = estimator.run([pub])
result = job.result()

__init__(*, backend, options=None, scheduler=None, config=None, export_format='qasm3', verbose=None, job_timeout_seconds=None)

Initialise the estimator.

Internally creates a shallow copy of the supplied backend and injects the scheduler and config into it, then wraps it with Qiskit's BackendEstimatorV2 to handle observable decomposition and expectation-value computation.

The backend proxy's run method is patched to fully transpile measurement-basis circuits into the device native gate set before submission (see module-level note on BackendEstimatorV2).

Parameters:

Name Type Description Default
backend BackendV2

A Qiskit BackendV2 instance (typically an :class:OpenQuantumBackend) used for circuit execution.

required
options Optional[dict]

Options forwarded to the underlying BackendEstimatorV2 (e.g. {"default_precision": 0.01}).

None
scheduler Optional[SchedulerClient]

A :class:~openquantum_sdk.clients.SchedulerClient injected into the backend copy for job submission.

None
config Optional[Dict[str, Any]]

Platform submission metadata (derived backend_class_id from the backend + job_subcategory_id etc.). Merged into a proxy for execution. job_subcategory_id belongs at creation time, not on the backend object.

None
export_format str

Circuit serialisation format -- "qasm3" (default) or "qasm2".

'qasm3'
verbose Optional[bool]

Print submission progress and the credit cost on the jobs this estimator submits. When omitted, the backend's own verbose flag is kept. False by default on a backend that does not set one.

None
job_timeout_seconds Optional[int]

Maximum seconds to wait for each job. When omitted, the backend's timeout is kept (86400).

None

run(pubs, *, precision=None)

Estimate expectation values for one or more PUBs.

Delegates to the internal BackendEstimatorV2 which decomposes observables, executes the required circuits on the OpenQuantum backend, and combines shot results into expectation-value estimates.

Parameters:

Name Type Description Default
pubs Iterable[EstimatorPubLike]

One or more estimator PUBs. Each element can be an EstimatorPub or any type accepted by EstimatorPub.coerce (e.g. a (circuit, observable) tuple).

required
precision float | None

Target precision for the expectation-value estimates. When None, the estimator's default precision is used.

None

Returns:

Type Description
PrimitiveJob[PrimitiveResult[PubResult]]

A PrimitiveJob whose .result() yields a

PrimitiveJob[PrimitiveResult[PubResult]]

PrimitiveResult[PubResult] containing expectation

PrimitiveJob[PrimitiveResult[PubResult]]

values and standard errors.

PennyLane Plugin

Device

pennylane_openquantum.device.OpenQuantumDevice

Bases: Device

PennyLane device for the OpenQuantum quantum computing platform.

Authenticates via one of three methods (checked in order): 1. A pre-built OpenQuantumClient passed as client. 2. A bearer token (e.g. from OPENQUANTUM_TOKEN). 3. client_id + client_secret for the OAuth2 client-credentials flow (env vars OPENQUANTUM_CLIENT_ID / OPENQUANTUM_CLIENT_SECRET).

Parameters:

Name Type Description Default
wires int | list[int]

Number of qubits or iterable of wire labels.

required
shots int | None

Number of measurement shots (required).

None
backend str

Backend class ID or short_code (e.g. "ionq:aria-1").

''
auto_confirm bool

If True, skip the interactive cost confirmation prompt and execute immediately. Credits used are still printed to stdout. Default is False (prompt before spending credits). In Jupyter notebooks, the prompt is replaced with a 5-second warning since input() can hang.

False
client OpenQuantumClient | None

Pre-built OpenQuantumClient instance.

None
token str | None

Bearer token for the API. Falls back to OPENQUANTUM_TOKEN.

None
client_id str | None

OAuth2 client ID. Falls back to OPENQUANTUM_CLIENT_ID.

None
client_secret str | None

OAuth2 client secret. Falls back to OPENQUANTUM_CLIENT_SECRET.

None
organization_id str | None

Organization UUID. Falls back to OPENQUANTUM_ORGANIZATION_ID.

None
scheduler_url str | None

Scheduler API base URL.

None
management_url str | None

Management API base URL.

None
keycloak_base str | None

Keycloak base URL for OAuth2.

None
realm str | None

Keycloak realm name.

None
job_subcategory_id str

Job subcategory ID or short_code.

'oth:oth'
execution_plan str

"auto" (default) or an ExecutionPlanType value.

'auto'
queue_priority str

"auto" (default) or a QueuePriorityType value.

'auto'
verbose bool

Print submission progress and the credit cost. Defaults to False, matching the other Open Quantum plugins and JobSubmissionConfig. The spend-confirmation prompt is controlled by auto_confirm, not by this flag. When a prompt is shown, the cost line is printed either way.

False
job_timeout_seconds int

Maximum time to wait for job completion.

86400

__init__(wires, shots=None, backend='', *, auto_confirm=False, client=None, token=None, client_id=None, client_secret=None, organization_id=None, scheduler_url=None, management_url=None, keycloak_base=None, realm=None, job_subcategory_id='oth:oth', execution_plan='auto', queue_priority='auto', configuration_data=None, verbose=False, job_timeout_seconds=86400)

execute(circuits, execution_config=ExecutionConfig())

Execute one or more circuits on the OpenQuantum platform.

Before submitting: - Checks the target backend status and queue depth. - If the backend is offline or not accepting jobs, shows online alternatives and prompts for confirmation. - Prints a live updating status line during job execution.

Parameters:

Name Type Description Default
circuits QuantumScript | list[QuantumScript]

A single tape or list of tapes to execute.

required
execution_config ExecutionConfig

Execution configuration.

ExecutionConfig()

Returns:

Type Description
Union[tuple, list[tuple]]

Results for each circuit.

Raises:

Type Description
RuntimeError

If the user declines or a job fails.

preprocess(execution_config=ExecutionConfig())

Build the preprocessing transform program.

QASM Serializer

pennylane_openquantum.qasm_serializer

PennyLane tape to OpenQASM 2.0 serialization.

This module converts PennyLane quantum tapes into OpenQASM 2.0 program strings. It uses OPERATION_MAP to translate PennyLane gate names (e.g. "PauliX", "CNOT") to their OpenQASM 2.0 gate identifiers (e.g. "x", "cx").

When backend capabilities are provided, gates that the backend supports are emitted directly without inline definitions. Otherwise, gates not known by the backend parser are emitted as inline gate definitions in terms of u1/u2/u3/cx/ccx.

OPERATION_MAP = {'PauliX': 'x', 'PauliY': 'y', 'PauliZ': 'z', 'Hadamard': 'h', 'CNOT': 'cx', 'CZ': 'cz', 'SWAP': 'swap', 'RX': 'rx', 'RY': 'ry', 'RZ': 'rz', 'PhaseShift': 'p', 'S': 's', 'T': 't', 'SX': 'sx', 'Toffoli': 'ccx', 'CSWAP': 'cswap', 'CRX': 'crx', 'CRY': 'cry', 'CRZ': 'crz', 'Identity': 'id'} module-attribute

circuit_to_qasm(tape, num_wires, capabilities=None)

Convert a PennyLane tape to an OpenQASM 2.0 string.

Parameters:

Name Type Description Default
tape QuantumScript

A PennyLane QuantumScript/tape containing operations.

required
num_wires int

The number of qubits in the circuit.

required
capabilities BackendCapabilities | None

Optional backend capabilities. When provided, gates the backend supports are emitted directly without inline definitions, producing cleaner QASM.

None

Returns:

Type Description
str

A valid OpenQASM 2.0 program string.

Raises:

Type Description
ValueError

If an unsupported operation is encountered.

Exceptions

pennylane_openquantum.exceptions

Custom exception classes for the Open Quantum PennyLane plugin.

OpenQuantumCircuitError

Bases: OpenQuantumDeviceError

Raised when circuit serialization or validation fails.

Common causes include unsupported gate operations or invalid circuit structure that cannot be converted to OpenQASM 2.0.

OpenQuantumDeviceError

Bases: OpenQuantumError

Base exception for Open Quantum PennyLane device errors.

Raised for device-level issues such as invalid device configuration. Missing credentials raise :class:openquantum_sdk.exceptions.AuthenticationError instead, matching the other plugins. Subclasses :class:openquantum_sdk.exceptions.OpenQuantumError, so callers can catch any Open Quantum failure uniformly.

Cirq Plugin

OpenQuantumSampler

cirq_openquantum.sampler.OpenQuantumSampler

Bases: Sampler

Cirq sampler that executes circuits on the Open Quantum platform.

Use it anywhere a cirq.Sampler is accepted::

sampler = OpenQuantumSampler(
    backend="qr:gpu-gb10",
    configuration_data={"engine": "amber_quantum_rings"},
)
result = sampler.run(circuit, repetitions=1024)
print(result.histogram(key="m"))

Authentication mirrors the other Open Quantum plugins and is resolved in this order:

  1. A pre-built :class:openquantum_sdk.OpenQuantumClient passed as client (full control over auth, URLs, saved accounts).
  2. A bearer token (falls back to OPENQUANTUM_TOKEN).
  3. client_id + client_secret for the OAuth2 client-credentials flow (fall back to OPENQUANTUM_CLIENT_ID / OPENQUANTUM_CLIENT_SECRET).

Parameters:

Name Type Description Default
backend str

Backend class ID or short_code (e.g. "qr:gpu-gb10").

required
client Optional[Any]

Pre-built OpenQuantumClient instance.

None
token Optional[str]

Bearer token for the API. Falls back to OPENQUANTUM_TOKEN.

None
client_id Optional[str]

OAuth2 client ID. Falls back to OPENQUANTUM_CLIENT_ID.

None
client_secret Optional[str]

OAuth2 client secret. Falls back to OPENQUANTUM_CLIENT_SECRET.

None
organization_id Optional[str]

Organization UUID. Falls back to OPENQUANTUM_ORGANIZATION_ID.

None
scheduler_url Optional[str]

Scheduler API base URL.

None
management_url Optional[str]

Management API base URL.

None
keycloak_base Optional[str]

Keycloak base URL for OAuth2.

None
realm Optional[str]

Keycloak realm name.

None
job_subcategory_id str

Job subcategory ID or short_code (default "oth:oth").

'oth:oth'
execution_plan str

"auto" (default), "public", or "private".

'auto'
queue_priority str

"auto" (default), "standard", "priority", or "instant".

'auto'
export_format str

Circuit serialisation format, "qasm2" or "qasm3" (default). Cirq exports OpenQASM 2.0 natively and OpenQASM 3.0 via to_qasm(version="3.0"); the default is "qasm3" to match the other Open Quantum plugins.

'qasm3'
configuration_data Optional[Dict[str, Any]]

Backend-specific configuration passthrough (e.g. {"engine": "amber_quantum_rings"} for qr:gpu-gb10). shots is injected automatically from the per-run repetitions.

None
reverse_bits bool

Reverse the bit order of returned bitstrings. The platform returns counts little-endian (the first classical bit is the rightmost character, Qiskit-style), while Cirq is big-endian (the first measured qubit is the most-significant bit). The default (True) reverses each bitstring so the mapping is correct; confirmed live with an asymmetric |10> state. Set False only for a backend that returns counts big-endian.

True
verbose bool

Print submission progress and the credit cost to stdout. Defaults to False, matching JobSubmissionConfig and the other plugins. Set True for step-by-step progress in a notebook or script.

False
job_timeout_seconds int

Maximum seconds to wait for a job to complete (default 86400, one day).

86400

backend property

Alias for :attr:backend_class_id (matches the other plugins).

backend_class_id property

The Open Quantum backend class ID or short_code this sampler targets.

run_sweep(program, params, repetitions=1)

Submit a circuit once per parameter resolver and collect results.

Implementing run_sweep gives run, sample, run_async, and run_batch for free (Cirq's Sampler routes them all here).

Parameters:

Name Type Description Default
program AbstractCircuit

The circuit to run. Must contain at least one measurement.

required
params Sweepable

A cirq.Sweepable of parameter resolvers.

required
repetitions int

Shot count per resolver.

1

Returns:

Type Description
Sequence[Result]

One cirq.Result per resolver, in sweep order.

Result Helpers

cirq_openquantum.result.result_from_counts(counts, circuit, params=None, *, reverse_bits=False, qasm=None)

Reconstruct a cirq.ResultDict from a platform counts histogram.

Parameters:

Name Type Description Default
counts Mapping[str, int]

{bitstring: count} as returned by the scheduler.

required
circuit

The resolved cirq.Circuit that was submitted.

required
params

The cirq.ParamResolver used for this circuit (stored on the result so sweeps round-trip their parameters).

None
reverse_bits bool

Reverse each platform bitstring before mapping. The platform returns counts little-endian (classical bit 0 is the rightmost character), so this must be True to map onto ascending classical-bit index. The sampler passes True by default.

False
qasm Optional[str]

The exact OpenQASM submitted for this circuit. When omitted it is regenerated with circuit.to_qasm(); pass the submitted string to guarantee the layout matches what the platform parsed.

None

Returns:

Type Description

A cirq.ResultDict whose measurements[key] is a

(repetitions, num_qubits_in_key) uint8 array.

Qrisp Plugin

OpenQuantumBackend

qrisp_openquantum.backend.OpenQuantumBackend

Bases: Backend

Qrisp backend that executes circuits on the Open Quantum platform.

Pass an instance to any Qrisp execution call, e.g. qv.get_measurement(backend=oq, shots=1024) or qc.run(backend=oq, shots=1024).

Authentication mirrors the other Open Quantum plugins and is resolved in this order:

  1. A pre-built :class:openquantum_sdk_qiskit.OpenQuantumService passed as service (full control over auth, URLs, saved accounts).
  2. A bearer token (falls back to OPENQUANTUM_TOKEN).
  3. client_id + client_secret for the OAuth2 client-credentials flow (fall back to OPENQUANTUM_CLIENT_ID / OPENQUANTUM_CLIENT_SECRET).

Parameters:

Name Type Description Default
backend str

Backend class ID or short_code (e.g. "ionq:aria-1").

required
shots int

Default shot count used when a Qrisp call does not specify one.

1024
service Optional[Any]

Pre-built OpenQuantumService instance.

None
token Optional[str]

Bearer token for the API. Falls back to OPENQUANTUM_TOKEN.

None
client_id Optional[str]

OAuth2 client ID. Falls back to OPENQUANTUM_CLIENT_ID.

None
client_secret Optional[str]

OAuth2 client secret. Falls back to OPENQUANTUM_CLIENT_SECRET.

None
organization_id Optional[str]

Organization UUID. Falls back to OPENQUANTUM_ORGANIZATION_ID.

None
scheduler_url Optional[str]

Scheduler API base URL.

None
management_url Optional[str]

Management API base URL.

None
keycloak_base Optional[str]

Keycloak base URL for OAuth2.

None
realm Optional[str]

Keycloak realm name.

None
job_subcategory_id str

Job subcategory ID or short_code (default "oth:oth").

'oth:oth'
execution_plan str

"auto" (default), "public", or "private".

'auto'
queue_priority str

"auto" (default), "standard", "priority", or "instant".

'auto'
export_format str

Circuit serialisation format, "qasm2" or "qasm3" (default).

'qasm3'
configuration_data Optional[Dict[str, Any]]

Backend-specific configuration passthrough (e.g. {"engine": "amber_quantum_rings"} for qr:gpu-gb10). shots is injected automatically from the per-run shot count.

None
reverse_bits bool

Reverse the bit order of returned bitstrings. The default (False) passes the platform's bit order straight through to Qrisp, which reads the leftmost character as the most-significant bit. Set True only if a backend's counts come back in the opposite order.

False
name Optional[str]

Optional Qrisp backend name (defaults to "openquantum").

None
verbose bool

Print submission progress and the credit cost to stdout. Defaults to False, matching JobSubmissionConfig and the other plugins. Set True for step-by-step progress in a notebook or script.

False
job_timeout_seconds int

Maximum seconds to wait for a job to complete (default 86400, one day).

86400

backend property

Alias for :attr:backend_class_id (matches the other plugins).

backend_class_id property

The Open Quantum backend class ID or short_code targeted by this backend.

run_async(circuits, shots=None)

Submit one or more Qrisp circuits and return a completed job.

Each circuit is converted to a Qiskit circuit, validated against the backend's capabilities, serialised to QASM, and submitted to the platform synchronously.

Parameters:

Name Type Description Default
circuits

A single Qrisp QuantumCircuit or a sequence of them.

required
shots Union[int, List[int], None]

Shot count. An int applies to every circuit; a list[int] sets per-circuit shots; None uses the backend's default.

None

Returns:

Name Type Description
An OpenQuantumJob

class:OpenQuantumJob already in the DONE state.

OpenQuantumJob

qrisp_openquantum.job.OpenQuantumJob

Bases: Job

A completed Open Quantum job wrapping one counts dict per circuit.

Parameters:

Name Type Description Default
backend

The :class:OpenQuantumBackend that produced this job.

required
counts Sequence[dict]

One {bitstring: count} dict per submitted circuit, in input order.

required
job_id str | None

Optional platform job identifier (the id of the last submitted circuit, for reference).

None

cancel()

Jobs are already terminal when returned, so there is nothing to cancel.

result(timeout=None)

Return the measurement results (job is already terminal).

status()

Return the cached (terminal) status.