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, create_job, etc.) are available for fine-grained control.

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.

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.

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 int

Number of measurement shots to execute.

required
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[ExecutionPlanType, AutoChoice]

"auto" selects the cheapest available plan, or pass an ExecutionPlanType value to choose explicitly.

'auto'
queue_priority Union[QueuePriorityType, AutoChoice]

"auto" selects the cheapest priority, or pass a QueuePriorityType value to choose explicitly.

'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
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: Exception

Exception raised when the OpenQuantum 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.

Qiskit Plugin

OpenQuantumService

openquantum_sdk_qiskit.oq_service.OpenQuantumService

Entry point for the OpenQuantum Qiskit plugin.

Handles authentication, backend discovery, and creation of Sampler and 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 class method. When neither token nor creds is supplied the constructor attempts to auto-load the saved account named by the OPENQUANTUM_ACCOUNT_NAME environment variable (default "default"). Set OPENQUANTUM_NO_AUTOLOAD=1 to disable this behaviour.

The service also acts as a context manager -- use with to ensure the underlying HTTP sessions are closed 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.

active_account property

Return a summary of the currently active authentication context.

Returns:

Type Description
Dict[str, Any]

A dictionary with keys management_url, scheduler_url,

Dict[str, Any]

and auth_mode (one of "token",

Dict[str, Any]

"client_credentials", or "unauthenticated").

__init__(*, token=None, creds=None, keycloak_base='https://id.openquantum.com', realm='platform', scheduler_url='https://scheduler.openquantum.com', management_url='https://management.openquantum.com')

Initialise the service with optional authentication.

If neither token nor creds is provided and OPENQUANTUM_NO_AUTOLOAD is not "1", the constructor automatically loads saved credentials from the accounts file.

Parameters:

Name Type Description Default
token Optional[str]

A static bearer token for API authentication.

None
creds Optional[ClientCredentials]

OAuth2 client credentials for machine-to-machine authentication.

None
keycloak_base str

Base URL of the Keycloak identity provider.

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

Keycloak realm name.

'platform'
scheduler_url str

Base URL of the OpenQuantum scheduler API.

'https://scheduler.openquantum.com'
management_url str

Base URL of the OpenQuantum management API.

'https://management.openquantum.com'

Raises:

Type Description
ValueError

If both token and creds are provided.

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

List available backend classes with optional filtering.

Paginates through all backend classes returned by the Management API and applies the requested client-side filters.

Parameters:

Name Type Description Default
name Optional[str]

Case-insensitive substring matched against the backend class name and short_code fields.

None
online Optional[bool]

When True, only return backends whose status is "Online" and accepting_jobs is True.

None
device_type Optional[str]

Filter by device type (e.g. "QPU" or "SIMULATOR").

None
vendor_id Optional[str]

Filter by the backend's provider_id.

None
min_num_qubits Optional[int]

Deprecated -- ignored since SDK v0.2.1.

None
limit int

Page size used when querying the Management API.

50

Returns:

Type Description
List[Dict[str, Any]]

A list of dictionaries, each containing the keys id,

List[Dict[str, Any]]

name, description, type, provider_id,

List[Dict[str, Any]]

short_code, queue_depth, accepting_jobs, and

List[Dict[str, Any]]

status.

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

Create an OpenQuantumBackend (Qiskit BackendV2) for the named backend.

The returned backend can be used with Qiskit's transpiler and can submit circuits directly via its :meth:~OpenQuantumBackend.run method when a config with the required platform identifiers is supplied.

Parameters:

Name Type Description Default
name str

Backend identifier -- may be an id, short_code, or name recognised by the capabilities resolver.

required
config Optional[Dict[str, Any]]

Optional platform submission metadata. When omitted or partial, backend_class_id defaults to the name argument (for convenient direct use of backend.run()). job_subcategory_id is not auto-defaulted here; it belongs on job creation (create_sampler, create_estimator, or passed at .run() time). May also include organization_id, name, execution_plan, queue_priority, and configuration_data for defaults on the backend object.

None
export_format str

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

'qasm3'

Returns:

Name Type Description
An Any

class:OpenQuantumBackend instance.

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. It is used by the Qiskit transpiler to compile circuits for the target hardware.

Parameters:

Name Type Description Default
name str

Backend identifier -- may be an id, short_code, or name recognised by the capabilities resolver.

required

Returns:

Type Description
Any

A qiskit.transpiler.Target instance.

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')

Create an :class:OQSampler (Qiskit SamplerV2) that submits sampling jobs to OpenQuantum.

The returned sampler follows the Qiskit BaseSamplerV2 interface: call :meth:~OQSampler.run with one or more SamplerPub to obtain measurement bit-arrays.

Parameters:

Name Type Description Default
backend 'BackendV2'

A Qiskit BackendV2 instance (typically obtained via :meth:return_backend) used for transpilation and target validation. The backend's name (or its internal backend_class_id) is used as the target backend class.

required
organization_id Optional[str]

UUID of the organisation under which the job is billed. Optional.

None
job_subcategory_id str

Workload subcategory identifier (UUID or short code). Defaults to "oth:oth". This is job metadata and lives only on the primitive/job creation.

'oth:oth'
name Optional[str]

Human-readable name prefix attached to submitted jobs.

None
configuration_data Optional[Dict[str, Any]]

Provider-specific configuration passed through to the scheduler.

None
execution_plan str

"auto" (default) selects the cheapest plan, or pass "public" / "private" explicitly.

'auto'
queue_priority str

"auto" (default) selects the cheapest priority, or pass "standard" / "priority" / "instant" explicitly.

'auto'
export_format str

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

'qasm3'

Returns:

Name Type Description
An

class:OQSampler instance ready to accept run

calls.

Raises:

Type Description
ImportError

If Qiskit is not installed.

ValueError

If backend_class_id cannot be determined from the provided backend.

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')

Create an :class:OQEstimator (Qiskit EstimatorV2) that computes expectation values via OpenQuantum.

The returned estimator follows the Qiskit BaseEstimatorV2 interface: call :meth:~OQEstimator.run with one or more EstimatorPub to obtain expectation-value results.

Parameters:

Name Type Description Default
backend 'BackendV2'

A Qiskit BackendV2 instance (typically obtained via :meth:return_backend) used for transpilation and target validation. The backend's name (or its internal backend_class_id) is used as the target backend class.

required
organization_id Optional[str]

UUID of the organisation under which the job is billed. Optional.

None
job_subcategory_id str

Workload subcategory identifier (UUID or short code). Defaults to "oth:oth". This is job metadata and lives only on the primitive/job creation.

'oth:oth'
name Optional[str]

Human-readable name prefix attached to submitted jobs.

None
configuration_data Optional[Dict[str, Any]]

Provider-specific configuration passed through to the scheduler.

None
execution_plan str

"auto" (default) selects the cheapest plan, or pass "public" / "private" explicitly.

'auto'
queue_priority str

"auto" (default) selects the cheapest priority, or pass "standard" / "priority" / "instant" explicitly.

'auto'
export_format str

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

'qasm3'

Returns:

Name Type Description
An

class:OQEstimator instance ready to accept run

calls.

Raises:

Type Description
ImportError

If Qiskit is not installed.

ValueError

If backend_class_id cannot be determined from the provided backend.

save_account(*, name='default', token=None, creds=None, keycloak_base='https://id.openquantum.com', realm='platform', scheduler_url='https://scheduler.openquantum.com', management_url='https://management.openquantum.com', filename=None, overwrite=True, use_keyring=True) classmethod

Persist account credentials to disk for later reuse.

Credentials are stored in a JSON file at a platform-appropriate configuration directory (see OPENQUANTUM_CONFIG_DIR). Sensitive values (tokens, client secrets) are stored in the system keyring when available; otherwise they are written to the file directly.

Parameters:

Name Type Description Default
name str

Logical account name. Use "default" for the account that is auto-loaded by the constructor.

'default'
token Optional[str]

Static bearer token.

None
creds Optional[ClientCredentials]

OAuth2 client credentials.

None
keycloak_base str

Keycloak identity-provider URL to store.

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

Keycloak realm to store.

'platform'
scheduler_url str

Scheduler API URL to store.

'https://scheduler.openquantum.com'
management_url str

Management API URL to store.

'https://management.openquantum.com'
filename Optional[str]

Override the default accounts file path.

None
overwrite bool

When False, raise if name already exists in the accounts file.

True
use_keyring bool

Attempt to store secrets in the system keyring rather than in the JSON file.

True

Raises:

Type Description
ValueError

If both token and creds are provided, or if overwrite is False and the account already exists.

from_saved_account(*, name='default', filename=None) classmethod

Instantiate a service from a previously saved account.

Reads the named account entry from the accounts file, retrieves secrets from the system keyring when applicable, and returns a fully authenticated :class:OpenQuantumService.

Parameters:

Name Type Description Default
name str

Logical account name to load (default "default").

'default'
filename Optional[str]

Override the default accounts file path.

None

Returns:

Type Description
'OpenQuantumService'

A new :class:OpenQuantumService instance configured with

'OpenQuantumService'

the saved credentials.

Raises:

Type Description
ValueError

If the accounts file does not exist, cannot be parsed, or does not contain the requested account name.

saved_accounts(*, filename=None) classmethod

Return all saved accounts with secrets masked.

Tokens and client secrets are truncated so that only the first and last few characters are visible (e.g. "oq_tok...abcd").

Parameters:

Name Type Description Default
filename Optional[str]

Override the default accounts file path.

None

Returns:

Type Description
Dict[str, Any]

A dictionary keyed by account name. Each value is the

Dict[str, Any]

account entry with sensitive fields masked. Returns an

Dict[str, Any]

empty dictionary if no accounts file exists or if it cannot

Dict[str, Any]

be parsed.

delete_account(*, name='default', filename=None) classmethod

Delete a saved account by name.

Removes the account entry from the JSON file and attempts to delete any associated secrets from the system keyring.

Parameters:

Name Type Description Default
name str

Logical account name to delete.

'default'
filename Optional[str]

Override the default accounts file path.

None

Returns:

Type Description
bool

True if the account was found and deleted, False

bool

otherwise.

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

Authenticate and return a new service, optionally saving credentials.

This is a convenience factory that combines construction and optional :meth:save_account in a single call.

Parameters:

Name Type Description Default
token Optional[str]

Static bearer token.

None
creds Optional[ClientCredentials]

OAuth2 client credentials.

None
save bool

When True, persist the supplied credentials to disk via :meth:save_account.

False
name str

Logical account name used when save=True.

'default'
filename Optional[str]

Override the default accounts file path used when save=True.

None
**kwargs Any

Forwarded to the :class:OpenQuantumService constructor (e.g. keycloak_base, realm, scheduler_url, management_url).

{}

Returns:

Type Description
'OpenQuantumService'

A new :class:OpenQuantumService instance.

close()

Close underlying HTTP sessions.

Call this when the service is no longer needed to free network resources. Also invoked automatically when the service is used as a context manager.

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', **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'

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.
{}

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')

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'

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')

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.

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_shots": 4096}).

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'

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 SchedulerClient passed as scheduler. 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
scheduler SchedulerClient | None

Pre-built SchedulerClient 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

Scheduler API base URL.

'https://scheduler.openquantum.com'
management_url str

Management API base URL.

'https://management.openquantum.com'
keycloak_base str

Keycloak base URL for OAuth2.

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

Keycloak realm name.

'platform'
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'
job_timeout_seconds int

Maximum time to wait for job completion.

86400

__init__(wires, shots=None, backend='', *, auto_confirm=False, scheduler=None, token=None, client_id=None, client_secret=None, organization_id=None, scheduler_url='https://scheduler.openquantum.com', management_url='https://management.openquantum.com', keycloak_base='https://id.openquantum.com', realm='platform', job_subcategory_id='oth:oth', execution_plan='auto', queue_priority='auto', 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 OpenQuantum 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: Exception

Base exception for OpenQuantum PennyLane device errors.

Raised for device-level issues such as authentication failures, missing credentials, or invalid device configuration.