QiskitRuntimeService
QiskitRuntimeService(channel=None, token=None, url=None, filename=None, name=None, instance=None, proxies=None, verify=None, channel_strategy=None)
Class for interacting with the Qiskit Runtime service.
Qiskit Runtime is a new architecture offered by IBM Quantum that streamlines computations requiring many iterations. These experiments will execute significantly faster within its improved hybrid quantum/classical process.
A sample workflow of using the runtime service:
from qiskit_ibm_runtime import QiskitRuntimeService, Session, Sampler, Estimator, Options
from qiskit.test.reference_circuits import ReferenceCircuits
from qiskit.circuit.library import RealAmplitudes
from qiskit.quantum_info import SparsePauliOp
# Initialize account.
service = QiskitRuntimeService()
# Set options, which can be overwritten at job level.
options = Options(optimization_level=1)
# Prepare inputs.
bell = ReferenceCircuits.bell()
psi = RealAmplitudes(num_qubits=2, reps=2)
H1 = SparsePauliOp.from_list([("II", 1), ("IZ", 2), ("XI", 3)])
theta = [0, 1, 1, 2, 3, 5]
with Session(service=service, backend="ibmq_qasm_simulator") as session:
# Submit a request to the Sampler primitive within the session.
sampler = Sampler(session=session, options=options)
job = sampler.run(circuits=bell)
print(f"Sampler results: {job.result()}")
# Submit a request to the Estimator primitive within the session.
estimator = Estimator(session=session, options=options)
job = estimator.run(
circuits=[psi], observables=[H1], parameter_values=[theta]
)
print(f"Estimator results: {job.result()}")
The example above uses the dedicated Sampler
and Estimator
classes. You can also use the run()
method directly to invoke a Qiskit Runtime program.
If the program has any interim results, you can use the callback
parameter of the run()
method to stream the interim results. Alternatively, you can use the RuntimeJob.stream_results()
method to stream the results at a later time, but before the job finishes.
The run()
method returns a RuntimeJob
object. You can use its methods to perform tasks like checking job status, getting job result, and canceling job.
QiskitRuntimeService constructor
An account is selected in the following order:
- Account with the input name, if specified.
- Default account for the channel type, if channel is specified but token is not.
- Account defined by the input channel and token, if specified.
- Account defined by the default_channel if defined in filename
- Account defined by the environment variables, if defined.
- Default account for the
ibm_cloud
account, if one is available.- Default account for the
ibm_quantum
account, if one is available.
instance, proxies, and verify can be used to overwrite corresponding values in the loaded account.
Parameters
- channel (
Optional
[Literal
[‘ibm_cloud’, ‘ibm_quantum’]]) – Channel type.ibm_cloud
oribm_quantum
. - token (
Optional
[str
]) – IBM Cloud API key or IBM Quantum API token. - url (
Optional
[str
]) – The API URL. Defaults to https://cloud.ibm.com (opens in a new tab) (ibm_cloud) or https://auth.quantum-computing.ibm.com/api (opens in a new tab) (ibm_quantum). - filename (
Optional
[str
]) – Full path of the file where the account is created. Default: _DEFAULT_ACCOUNT_CONFIG_JSON_FILE - name (
Optional
[str
]) – Name of the account to load. - instance (
Optional
[str
]) – The service instance to use. Foribm_cloud
runtime, this is the Cloud Resource Name (CRN) or the service name. Foribm_quantum
runtime, this is the hub/group/project in that format. - proxies (
Optional
[dict
]) – Proxy configuration. Supported optional keys areurls
(a dictionary mapping protocol or protocol and host to the URL of the proxy, documented at https://docs.python-requests.org/en/latest/api/#requests.Session.proxies (opens in a new tab)),username_ntlm
,password_ntlm
(username and password to enable NTLM user authentication) - verify (
Optional
[bool
]) – Whether to verify the server’s TLS certificate. - channel_strategy (
Optional
[str
]) – Error mitigation strategy.
Returns
An instance of QiskitRuntimeService.
Raises
IBMInputValueError – If an input is invalid.
Attributes
channel
Return the channel type used.
Return type
str
Returns
The channel type used.
global_service
= None
runtime
Return self for compatibility with IBMQ provider.
Returns
self
version
= 1
Methods
active_account
active_account()
Return the IBM Quantum account currently in use for the session.
Return type
Optional
[Dict
[str
, str
]]
Returns
A dictionary with information about the account currently in the session.
backend
backend(name=None, instance=None)
Return a single backend matching the specified filtering.
Parameters
- name (
Optional
[str
]) – Name of the backend. - instance (
Optional
[str
]) – This is only supported foribm_quantum
runtime and is in the hub/group/project format. If an instance is not given, among the providers with access to the backend, a premium provider will be prioritized. For users without access to a premium provider, the default open provider will be used.
Returns
A backend matching the filtering.
Return type
Backend
Raises
QiskitBackendNotFoundError – if no backend could be found.
backends
backends(name=None, min_num_qubits=None, instance=None, filters=None, **kwargs)
Return all backends accessible via this account, subject to optional filtering.
Parameters
-
name (
Optional
[str
]) – Backend name to filter by. -
min_num_qubits (
Optional
[int
]) – Minimum number of qubits the backend has to have. -
instance (
Optional
[str
]) – This is only supported foribm_quantum
runtime and is in the hub/group/project format. -
filters (
Optional
[Callable
[[List
[IBMBackend
]],bool
]]) –More complex filters, such as lambda functions. For example:
QiskitRuntimeService.backends( filters=lambda b: b.max_shots > 50000) QiskitRuntimeService.backends( filters=lambda x: ("rz" in x.basis_gates )
-
**kwargs –
Simple filters that require a specific value for an attribute in backend configuration or status. Examples:
# Get the operational real backends QiskitRuntimeService.backends(simulator=False, operational=True) # Get the backends with at least 127 qubits QiskitRuntimeService.backends(min_num_qubits=127) # Get the backends that support OpenPulse QiskitRuntimeService.backends(open_pulse=True)
For the full list of backend attributes, see the IBMBackend class documentation <providers_models>
Return type
List
[IBMBackend
]
Returns
The list of available backends that match the filter.
Raises
- IBMInputValueError – If an input is invalid.
- QiskitBackendNotFoundError – If the backend is not in any instance.
delete_account
static delete_account(filename=None, name=None, channel=None)
Delete a saved account from disk.
Parameters
- filename (
Optional
[str
]) – Name of file from which to delete the account. - name (
Optional
[str
]) – Name of the saved account to delete. - channel (
Optional
[Literal
[‘ibm_cloud’, ‘ibm_quantum’]]) – Channel type of the default account to delete. Ignored if account name is provided.
Return type
bool
Returns
True if the account was deleted. False if no account was found.
delete_job
delete_job(job_id)
Delete a runtime job.
Note that this operation cannot be reversed.
Parameters
job_id (str
) – ID of the job to delete.
Raises
- RuntimeJobNotFound – If the job doesn’t exist.
- IBMRuntimeError – If the request failed.
Return type
None
delete_program
delete_program(program_id)
Delete a runtime program.
Parameters
program_id (str
) – Program ID.
Raises
- RuntimeProgramNotFound – If the program doesn’t exist.
- IBMRuntimeError – If the request failed.
Return type
None
get_backend
get_backend(name=None, **kwargs)
Return a single backend matching the specified filtering.
Parameters
- name (str) – name of the backend.
- **kwargs – dict used for filtering.
Returns
a backend matching the filtering.
Return type
Backend
Raises
QiskitBackendNotFoundError – if no backend could be found or more than one backend matches the filtering criteria.
instances
instances()
Return the IBM Quantum instances list currently in use for the session.
Return type
List
[str
]
Returns
A list with instances currently in the session.
job
job(job_id)
Retrieve a runtime job.
Parameters
job_id (str
) – Job ID.
Return type
Returns
Runtime job retrieved.
Raises
- RuntimeJobNotFound – If the job doesn’t exist.
- IBMRuntimeError – If the request failed.
jobs
jobs(limit=10, skip=0, backend_name=None, pending=None, program_id=None, instance=None, job_tags=None, session_id=None, created_after=None, created_before=None, descending=True)
Retrieve all runtime jobs, subject to optional filtering.
Parameters
- limit (
Optional
[int
]) – Number of jobs to retrieve.None
means no limit. - skip (
int
) – Starting index for the job retrieval. - backend_name (
Optional
[str
]) – Name of the backend to retrieve jobs from. - pending (
Optional
[bool
]) – Filter by job pending state. IfTrue
, ‘QUEUED’ and ‘RUNNING’ jobs are included. IfFalse
, ‘DONE’, ‘CANCELLED’ and ‘ERROR’ jobs are included. - program_id (
Optional
[str
]) – Filter by Program ID. - instance (
Optional
[str
]) – This is only supported foribm_quantum
runtime and is in the hub/group/project format. - job_tags (
Optional
[List
[str
]]) – Filter by tags assigned to jobs. Matched jobs are associated with all tags. - session_id (
Optional
[str
]) – Job ID of the first job in a runtime session. - created_after (
Optional
[datetime
]) – Filter by the given start date, in local time. This is used to find jobs whose creation dates are after (greater than or equal to) this local date/time. - created_before (
Optional
[datetime
]) – Filter by the given end date, in local time. This is used to find jobs whose creation dates are before (less than or equal to) this local date/time. - descending (
bool
) – IfTrue
, return the jobs in descending order of the job creation date (i.e. newest first) until the limit is reached.
Return type
List
[RuntimeJob
]
Returns
A list of runtime jobs.
Raises
IBMInputValueError – If an input value is invalid.
least_busy
least_busy(min_num_qubits=None, instance=None, filters=None, **kwargs)
Return the least busy available backend.
Parameters
-
min_num_qubits (
Optional
[int
]) – Minimum number of qubits the backend has to have. -
instance (
Optional
[str
]) – This is only supported foribm_quantum
runtime and is in the hub/group/project format. -
filters (
Optional
[Callable
[[List
[IBMBackend
]],bool
]]) –Filters can be defined as for the
backends()
method. An example to get the operational backends with 5 qubits:QiskitRuntimeService.least_busy(n_qubits=5, operational=True)
Return type
Returns
The backend with the fewest number of pending jobs.
Raises
QiskitBackendNotFoundError – If no backend matches the criteria.
pprint_programs
pprint_programs(refresh=False, detailed=False, limit=20, skip=0)
Pretty print information about available runtime programs.
Parameters
- refresh (
bool
) – IfTrue
, re-query the server for the programs. Otherwise return the cached value. - detailed (
bool
) – IfTrue
print all details about available runtime programs. - limit (
int
) – The number of programs returned at a time. Default and maximum value of 20. - skip (
int
) – The number of programs to skip.
Return type
None
program
program(program_id, refresh=False)
Retrieve a runtime program.
Currently only program metadata is returned.
Parameters
- program_id (
str
) – Program ID. - refresh (
bool
) – IfTrue
, re-query the server for the program. Otherwise return the cached value.
Return type
Returns
Runtime program.
Raises
- RuntimeProgramNotFound – If the program does not exist.
- IBMRuntimeError – If the request failed.
programs
programs(refresh=False, limit=20, skip=0)
Return available runtime programs.
Currently only program metadata is returned.
Parameters
- refresh (
bool
) – IfTrue
, re-query the server for the programs. Otherwise return the cached value. - limit (
int
) – The number of programs returned at a time.None
means no limit. - skip (
int
) – The number of programs to skip.
Return type
List
[RuntimeProgram
]
Returns
A list of runtime programs.
run
run(program_id, inputs, options=None, callback=None, result_decoder=None, session_id=None, start_session=False)
Execute the runtime program.
Parameters
-
program_id (
str
) – Program ID. -
inputs (
Union
[Dict
,ParameterNamespace
]) – Program input parameters. These input values are passed to the runtime program. -
options (
Union
[RuntimeOptions
,Dict
,None
]) – Runtime options that control the execution environment. SeeRuntimeOptions
for all available options. -
callback (
Optional
[Callable
]) –Callback function to be invoked for any interim results and final result. The callback function will receive 2 positional parameters:
- Job ID
- Job result.
-
result_decoder (
Union
[Type
[ResultDecoder
],Sequence
[Type
[ResultDecoder
]],None
]) – AResultDecoder
subclass used to decode job results. If more than one decoder is specified, the first is used for interim results and the second final results. If not specified, a program-specific decoder or the defaultResultDecoder
is used. -
session_id (
Optional
[str
]) – Job ID of the first job in a runtime session. -
start_session (
Optional
[bool
]) – Set to True to explicitly start a runtime session. Defaults to False.
Return type
Returns
A RuntimeJob
instance representing the execution.
Raises
- IBMInputValueError – If input is invalid.
- RuntimeProgramNotFound – If the program cannot be found.
- IBMRuntimeError – An error occurred running the program.
save_account
static save_account(token=None, url=None, instance=None, channel=None, filename=None, name=None, proxies=None, verify=None, overwrite=False, channel_strategy=None, set_as_default=None)
Save the account to disk for future use.
Parameters
- token (
Optional
[str
]) – IBM Cloud API key or IBM Quantum API token. - url (
Optional
[str
]) – The API URL. Defaults to https://cloud.ibm.com (opens in a new tab) (ibm_cloud) or https://auth.quantum-computing.ibm.com/api (opens in a new tab) (ibm_quantum). - instance (
Optional
[str
]) – The CRN (ibm_cloud) or hub/group/project (ibm_quantum). - channel (
Optional
[Literal
[‘ibm_cloud’, ‘ibm_quantum’]]) – Channel type. ibm_cloud or ibm_quantum. - filename (
Optional
[str
]) – Full path of the file where the account is saved. - name (
Optional
[str
]) – Name of the account to save. - proxies (
Optional
[dict
]) – Proxy configuration. Supported optional keys areurls
(a dictionary mapping protocol or protocol and host to the URL of the proxy, documented at https://docs.python-requests.org/en/latest/api/#requests.Session.proxies (opens in a new tab)),username_ntlm
,password_ntlm
(username and password to enable NTLM user authentication) - verify (
Optional
[bool
]) – Verify the server’s TLS certificate. - overwrite (
Optional
[bool
]) –True
if the existing account is to be overwritten. - channel_strategy (
Optional
[str
]) – Error mitigation strategy. - set_as_default (
Optional
[bool
]) – IfTrue
, the account is saved in filename, as the default account.
Return type
None
saved_accounts
static saved_accounts(default=None, channel=None, filename=None, name=None)
List the accounts saved on disk.
Parameters
- default (
Optional
[bool
]) – If set to True, only default accounts are returned. - channel (
Optional
[Literal
[‘ibm_cloud’, ‘ibm_quantum’]]) – Channel type. ibm_cloud or ibm_quantum. - filename (
Optional
[str
]) – Name of file whose accounts are returned. - name (
Optional
[str
]) – If set, only accounts with the given name are returned.
Return type
dict
Returns
A dictionary with information about the accounts saved on disk.
Raises
ValueError – If an invalid account is found on disk.
set_program_visibility
set_program_visibility(program_id, public)
Sets a program’s visibility.
Parameters
- program_id (
str
) – Program ID. - public (
bool
) – IfTrue
, make the program visible to all. IfFalse
, make the program visible to just your account.
Raises
- RuntimeProgramNotFound – if program not found (404)
- IBMRuntimeError – if update failed (401, 403)
Return type
None
update_program
update_program(program_id, data=None, metadata=None, name=None, description=None, max_execution_time=None, spec=None)
Update a runtime program.
Program metadata can be specified using the metadata parameter or individual parameters, such as name and description. If the same metadata field is specified in both places, the individual parameter takes precedence.
Parameters
- program_id (
str
) – Program ID. - data (
Optional
[str
]) – Program data or path of the file containing program data to upload. - metadata (
Union
[Dict
,str
,None
]) – Name of the program metadata file or metadata dictionary. - name (
Optional
[str
]) – New program name. - description (
Optional
[str
]) – New program description. - max_execution_time (
Optional
[int
]) – New maximum execution time. - spec (
Optional
[Dict
]) – New specifications for backend characteristics, input parameters, interim results and final result.
Raises
- RuntimeProgramNotFound – If the program doesn’t exist.
- IBMRuntimeError – If the request failed.
Return type
None
upload_program
upload_program(data, metadata=None)
Upload a runtime program.
In addition to program data, the following program metadata is also required:
- name
- max_execution_time
Program metadata can be specified using the metadata parameter or individual parameter (for example, name and description). If the same metadata field is specified in both places, the individual parameter takes precedence. For example, if you specify:
upload_program(metadata={"name": "name1"}, name="name2")
name2
will be used as the program name.
Parameters
-
data (
str
) – Program data or path of the file containing program data to upload. -
metadata (
Union
[Dict
,str
,None
]) –Name of the program metadata file or metadata dictionary. A metadata file needs to be in the JSON format. The
parameters
,return_values
, andinterim_results
should be defined as JSON Schema. Seeprogram/program_metadata_sample.json
for an example. The fields in metadata are explained below.-
name: Name of the program. Required.
-
max_execution_time: Maximum execution time in seconds. Required.
-
description: Program description.
-
is_public: Whether the runtime program should be visible to the public.
The default is
False
. -
spec: Specifications for backend characteristics and input parameters
required to run the program, interim results and final result.
- backend_requirements: Backend requirements.
- parameters: Program input parameters in JSON schema format.
- return_values: Program return values in JSON schema format.
- interim_results: Program interim results in JSON schema format.
-
Return type
str
Returns
Program ID.
Raises
- IBMInputValueError – If required metadata is missing.
- RuntimeDuplicateProgramError – If a program with the same name already exists.
- IBMNotAuthorizedError – If you are not authorized to upload programs.
- IBMRuntimeError – If the upload failed.