-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathserverless_client.py
More file actions
1277 lines (1099 loc) · 50.4 KB
/
Copy pathserverless_client.py
File metadata and controls
1277 lines (1099 loc) · 50.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This code is a Qiskit project.
#
# (C) Copyright IBM 2022.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""
================================================
Provider (:mod:`qiskit_serverless.core.client`)
================================================
.. currentmodule:: qiskit_serverless.core.client
Qiskit Serverless provider
===========================
.. autosummary::
:toctree: ../stubs/
ServerlessClient
"""
# pylint: disable=duplicate-code,too-many-lines
import json
import os.path
import os
import re
import tarfile
import warnings
from pathlib import Path
from urllib.parse import urlparse
from dataclasses import asdict
from typing import Optional, List, Dict, Any, Union
from collections.abc import Callable
import requests
from opentelemetry import trace
from qiskit.providers.backend import BackendV2 as Backend
from qiskit.providers.exceptions import QiskitBackendNotFoundError
from qiskit_ibm_runtime import QiskitRuntimeService, IBMBackend
from qiskit_ibm_runtime.accounts.exceptions import InvalidAccountError
from qiskit_serverless.core.constants import (
REQUESTS_TIMEOUT,
ENV_GATEWAY_PROVIDER_HOST,
ENV_GATEWAY_PROVIDER_VERSION,
ENV_GATEWAY_PROVIDER_TOKEN,
GATEWAY_PROVIDER_VERSION_DEFAULT,
IBM_SERVERLESS_HOST_URL,
MAX_ARTIFACT_FILE_SIZE_MB,
USAGE_LOW_THRESHOLD_SECONDS,
USAGE_ZERO_EPSILON_SECONDS,
)
from qiskit_serverless.core.client import BaseClient
from qiskit_serverless.core.decorators import trace_decorator_factory
from qiskit_serverless.core.enums import Channel
from qiskit_serverless.core.files import GatewayFilesClient
from qiskit_serverless.core.job import (
Job,
Configuration,
_map_status_to_serverless,
)
from qiskit_serverless.core.job_event import JobEvent
from qiskit_serverless.core.function import (
QiskitFunction,
RunService,
RunnableQiskitFunction,
)
from qiskit_serverless.exception import QiskitServerlessException
from qiskit_serverless.utils.http import get_headers
from qiskit_serverless.utils.json import (
safe_json_request_as_dict,
safe_json_request_as_list,
safe_json_request,
raise_for_non_ok_response,
)
from qiskit_serverless.utils.formatting import format_provider_name_and_title
from qiskit_serverless.serializers.program_serializers import (
QiskitObjectsEncoder,
QiskitObjectsDecoder,
)
_trace_job = trace_decorator_factory("job")
_trace_functions = trace_decorator_factory("function")
class ServerlessClient(BaseClient): # pylint: disable=too-many-public-methods
"""
A client for connecting to a specified host.
Example:
>>> client = ServerlessClient(
>>> host="<HOST>",
>>> token="<TOKEN>",
>>> instance="<CRN>",
>>> )
"""
def __init__( # pylint: disable=too-many-positional-arguments
self,
host: Optional[str] = None,
token: Optional[str] = None,
instance: Optional[str] = None,
channel: Optional[str] = None,
):
"""
Initializes the ServerlessClient instance.
Args:
host: host of gateway. If None, it uses the ENV_GATEWAY_PROVIDER_HOST env var
token: authorization token
instance: IBM Cloud CRN
channel: identifies the method to use to authenticate the user
"""
host = host or os.environ.get(ENV_GATEWAY_PROVIDER_HOST)
if host is None:
raise QiskitServerlessException("Please provide `host` of gateway.")
host = host.rstrip("/")
version = os.environ.get(ENV_GATEWAY_PROVIDER_VERSION)
if version is None:
version = GATEWAY_PROVIDER_VERSION_DEFAULT
token = token or os.environ.get(ENV_GATEWAY_PROVIDER_TOKEN)
if token is None:
raise QiskitServerlessException("Authentication credentials must be provided in form of `token`.")
channel = channel or Channel.IBM_QUANTUM_PLATFORM.value
try:
channel_enum = Channel(channel)
except ValueError as error:
raise ValueError(
"Your channel value is not correct. Use one of the available channels: "
f"{Channel.LOCAL.value}, "
f"{Channel.IBM_CLOUD.value}, {Channel.IBM_QUANTUM_PLATFORM.value}"
) from error
if channel_enum is Channel.IBM_CLOUD and instance is None:
raise QiskitServerlessException("Authentication with IBM Cloud requires to pass the CRN as an instance.")
if channel_enum is Channel.IBM_QUANTUM_PLATFORM and instance is None:
raise QiskitServerlessException(
"Authentication with IBM Quantum Platform requires to pass the CRN as an instance."
)
super().__init__(host, token, instance, channel)
self.version = version
self._verify_credentials()
self._files_client = GatewayFilesClient(self.host, self.token, self.version, self.instance, self.channel)
@classmethod
def from_dict(cls, dictionary: dict):
# Remove 'name' if present for backward compatibility with serialized clients
data = {k: v for k, v in dictionary.items() if k != "name"}
return ServerlessClient(**data)
def _verify_credentials(self):
"""Verify against the API that the credentials are correct."""
try:
safe_json_request(
request=lambda: requests.get(
url=f"{self.host}/api/v1/programs/",
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
except QiskitServerlessException as reason:
raise QiskitServerlessException(f"Credentials couldn't be verified: {reason}") from reason
def dependencies_versions(self):
"""Get the list of available dependencies and its versions for creating functions"""
return safe_json_request_as_list(
request=lambda: requests.get(
url=f"{self.host}/api/{self.version}/dependencies-versions/",
headers=get_headers(token=self.token, instance=self.instance),
timeout=REQUESTS_TIMEOUT,
)
)
####################
####### JOBS #######
####################
@_trace_job("list")
def jobs(self, function: Optional[QiskitFunction] = None, **kwargs) -> List[Job]:
"""Retrieve a list of jobs with optional filtering.
Args:
function (QiskitFunction): The function that created the jobs we want to retrieve.
limit (int, optional): Maximum number of jobs to return. Defaults to 10.
offset (int, optional): Number of jobs to skip. Defaults to 0.
status (str, optional): Filter by job status.
created_after (str, optional): Filter jobs created after this timestamp.
**kwargs: Additional query parameters.
Returns:
List[Job]: List of Job objects matching the criteria.
"""
limit = kwargs.get("limit", 10)
kwargs["limit"] = limit
offset = kwargs.get("offset", 0)
kwargs["offset"] = offset
status = kwargs.get("status", None)
if status:
status, _ = _map_status_to_serverless(status)
kwargs["status"] = status
created_after = kwargs.get("created_after", None)
kwargs["created_after"] = created_after
if function:
kwargs["function"] = function.title
kwargs["provider"] = function.provider
response_data = safe_json_request_as_dict(
request=lambda: requests.get(
f"{self.host}/api/{self.version}/jobs/",
params=kwargs,
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
return [
Job(
job.get("id"),
job_service=self,
raw_data=job,
compute_profile=job.get("compute_profile"),
)
for job in response_data.get("results", [])
]
@_trace_job("provider_list")
def provider_jobs(self, function: Optional[QiskitFunction], **kwargs) -> List[Job]:
"""Retrieve jobs for a specific provider and function.
Args:
function (QiskitFunction): Function object.
limit (int, optional): Maximum number of jobs to return. Defaults to 10.
offset (int, optional): Number of jobs to skip. Defaults to 0.
status (str, optional): Filter by job status.
created_after (str, optional): Filter jobs created after this timestamp.
**kwargs: Additional query parameters.
Returns:
List[Job]: List of Job objects for the specified provider and function.
Raises:
QiskitServerlessException: If the function doesn't have an associated provider.
"""
if not function.provider:
raise QiskitServerlessException("`function` doesn't have a provider.")
limit = kwargs.get("limit", 10)
kwargs["limit"] = limit
offset = kwargs.get("offset", 0)
kwargs["offset"] = offset
status = kwargs.get("status", None)
if status:
status, _ = _map_status_to_serverless(status)
kwargs["status"] = status
created_after = kwargs.get("created_after", None)
kwargs["created_after"] = created_after
if function:
kwargs["function"] = function.title
kwargs["provider"] = function.provider
response_data = safe_json_request_as_dict(
request=lambda: requests.get(
f"{self.host}/api/{self.version}/jobs/provider/",
params=kwargs,
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
return [
Job(
job.get("id"),
job_service=self,
raw_data=job,
compute_profile=job.get("compute_profile"),
)
for job in response_data.get("results", [])
]
@_trace_job("get")
def job(self, job_id: str) -> Optional[Job]:
url = f"{self.host}/api/{self.version}/jobs/{job_id}/"
response_data = safe_json_request_as_dict(
request=lambda: requests.get(
url,
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
params={"with_result": "false"},
timeout=REQUESTS_TIMEOUT,
)
)
job = None
job_id = response_data.get("id")
if job_id is not None:
job = Job(
job_id=job_id,
job_service=self,
compute_profile=response_data.get("compute_profile"),
)
return job
def run(
self,
program: Union[QiskitFunction, str],
arguments: Optional[Dict[str, Any]] = None,
config: Optional[Configuration] = None,
provider: Optional[str] = None,
*,
compute_profile: Optional[str] = None,
function_size: Optional[str] = None,
) -> Job:
if compute_profile is not None:
warnings.warn(
"'compute_profile' is deprecated; use 'function_size' instead.",
DeprecationWarning,
stacklevel=2,
)
if isinstance(program, QiskitFunction):
title = program.title
provider = program.provider
else:
title = str(program)
tracer = trace.get_tracer("client.tracer")
with tracer.start_as_current_span("job.run") as span:
span.set_attribute("function", title)
span.set_attribute("provider", provider)
span.set_attribute("arguments", str(arguments))
url = f"{self.host}/api/{self.version}/programs/run/"
data = {
"title": title,
"provider": provider,
"compute_profile": compute_profile,
"function_size": function_size,
"arguments": json.dumps(arguments or {}, cls=QiskitObjectsEncoder),
} # type: Dict[str, Any]
if config:
data["config"] = asdict(config)
else:
data["config"] = asdict(Configuration())
response_data = safe_json_request_as_dict(
request=lambda: requests.post(
url=url,
json=data,
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
job_id = response_data.get("id")
span.set_attribute("job.id", job_id)
return Job(
job_id,
job_service=self,
compute_profile=response_data.get("compute_profile"),
)
def get_job_data(self, job_id: str) -> Optional[dict]:
return (
safe_json_request_as_dict(
request=lambda: requests.get(
f"{self.host}/api/{self.version}/jobs/{job_id}/",
params={"with_result": "false"},
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
or None
)
@_trace_job
def status(self, job_id: str):
default_status = "Unknown"
response_data = safe_json_request_as_dict(
request=lambda: requests.get(
f"{self.host}/api/{self.version}/jobs/{job_id}/",
params={"with_result": "false"},
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
status = response_data.get("status", default_status)
sub_status = response_data.get("sub_status")
if status == Job.RUNNING and sub_status is not None:
return sub_status
return status
@_trace_job
def stop(self, job_id: str, service: Optional[QiskitRuntimeService] = None):
if not service:
try:
service = QiskitRuntimeService(channel=self.channel, instance=self.instance, token=self.token)
except InvalidAccountError:
warnings.warn(
"No QiskitRuntimeService can be associated to the given token and instance. "
"Continuing without a QiskitRuntimeService."
)
service = None
data: dict[str, Any] = {
"service": json.dumps(service, cls=QiskitObjectsEncoder),
}
response_data = safe_json_request_as_dict(
request=lambda: requests.post(
f"{self.host}/api/{self.version}/jobs/{job_id}/stop/",
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
json=data,
)
)
return response_data.get("message")
@_trace_job
def result(self, job_id: str) -> Dict[str, Any]:
gateway_url = f"{self.host}/api/{self.version}/jobs/{job_id}/result/"
response = requests.get(
gateway_url,
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
if response.status_code == 204:
return {}
# Any non-OK response (from the gateway, COS, or an intermediary such as
# Cloudflare returning a block page) is surfaced with its status and body
# instead of being fed to the JSON parser as a cryptic decoding error.
raise_for_non_ok_response(response)
# Not all redirects go to COS — HTTP→HTTPS redirects stay on the same host.
# Checking the hostname detects only redirects to an external host (COS/MinIO).
redirected_to_cos = urlparse(response.url).hostname != urlparse(gateway_url).hostname
if redirected_to_cos:
return json.loads(response.text, cls=QiskitObjectsDecoder)
return json.loads(response.json().get("result", "{}") or "{}", cls=QiskitObjectsDecoder)
@_trace_job
def logs(self, job_id: str):
gateway_url = f"{self.host}/api/{self.version}/jobs/{job_id}/logs/"
response = requests.get(
gateway_url,
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
if response.status_code == 204:
return "No logs yet."
# Any non-OK response (from the gateway, COS, or an intermediary such as
# Cloudflare returning a block page) is surfaced with its status and body
# instead of being fed to the JSON parser as a cryptic decoding error.
raise_for_non_ok_response(response)
# Not all redirects go to COS — HTTP→HTTPS redirects stay on the same host.
# Checking the hostname detects only redirects to an external host (COS/MinIO).
redirected_to_cos = urlparse(response.url).hostname != urlparse(gateway_url).hostname
if redirected_to_cos:
return response.text
return safe_json_request_as_dict(request=lambda: response).get("logs")
@_trace_job
def provider_logs(self, job_id: str):
gateway_url = f"{self.host}/api/{self.version}/jobs/{job_id}/provider-logs/"
response = requests.get(
gateway_url,
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
if response.status_code == 204:
return "No logs yet."
# Any non-OK response (from the gateway, COS, or an intermediary such as
# Cloudflare returning a block page) is surfaced with its status and body
# instead of being fed to the JSON parser as a cryptic decoding error.
raise_for_non_ok_response(response)
# Not all redirects go to COS — HTTP→HTTPS redirects stay on the same host.
# Checking the hostname detects only redirects to an external host (COS/MinIO).
redirected_to_cos = urlparse(response.url).hostname != urlparse(gateway_url).hostname
if redirected_to_cos:
return response.text
return safe_json_request_as_dict(request=lambda: response).get("logs")
@_trace_job
def runtime_jobs(self, job_id: str, runtime_session: Optional[str] = None) -> list[str]:
"""Retrieve Qiskit IBM Runtime job ids that correspond to a
given serverless job_id execution and, optionally, filtered by session id."""
response_data = safe_json_request_as_dict(
request=lambda: requests.get(
f"{self.host}/api/{self.version}/jobs/{job_id}/runtime_jobs/",
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
if runtime_session:
return [
job.get("runtime_job")
for job in response_data.get("runtime_jobs", [])
if job.get("runtime_session") == runtime_session
]
return [job.get("runtime_job") for job in response_data.get("runtime_jobs", [])]
@_trace_job
def runtime_sessions(self, job_id: str):
"""Retrieve Qiskit IBM Runtime session ids that correspond to a
given serverless job_id execution."""
response_data = safe_json_request_as_dict(
request=lambda: requests.get(
f"{self.host}/api/{self.version}/jobs/{job_id}/runtime_jobs/",
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
runtime_jobs = response_data.get("runtime_jobs", [])
out_sessions = sorted({job["runtime_session"] for job in runtime_jobs if job.get("runtime_session")})
return out_sessions
def filtered_logs(self, job_id: str, **kwargs):
all_logs = self.logs(job_id=job_id)
included = ""
include = kwargs.get("include")
if include is not None:
for line in all_logs.split("\n"):
if re.search(include, line) is not None:
included = included + line + "\n"
else:
included = all_logs
excluded = ""
exclude = kwargs.get("exclude")
if exclude is not None:
for line in included.split("\n"):
if line != "" and re.search(exclude, line) is None:
excluded = excluded + line + "\n"
else:
excluded = included
return excluded
def events(self, job_id: str, **kwargs) -> list[JobEvent]:
"""Returns events of the job.
Args:
job_id: The job id
"""
response_data = safe_json_request_as_list(
request=lambda: requests.get(
f"{self.host}/api/{self.version}/jobs/{job_id}/events/",
params=kwargs,
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
return [JobEvent.from_json(event) for event in response_data]
#########################
####### Functions #######
#########################
def upload(self, program: QiskitFunction) -> Optional[RunnableQiskitFunction]:
tracer = trace.get_tracer("client.tracer")
with tracer.start_as_current_span("function.upload") as span:
span.set_attribute("function", program.title)
url = f"{self.host}/api/{self.version}/programs/upload/"
if program.image:
# upload function with custom image
function_uploaded = _upload_with_docker_image(
program=program,
url=url,
token=self.token,
span=span,
client=self,
instance=self.instance,
channel=self.channel,
)
elif program.entrypoint:
# upload function with artifact
function_uploaded = _upload_with_artifact(
program=program,
url=url,
token=self.token,
span=span,
client=self,
instance=self.instance,
channel=self.channel,
)
else:
raise QiskitServerlessException("Function must either have `entrypoint` or `image` specified.")
return function_uploaded
@_trace_functions("list")
def functions(self, provider: Optional[str] = None, **kwargs) -> List[RunnableQiskitFunction]:
"""Returns list of available functions.
Args:
provider: if given, only functions belonging to this provider are returned,
e.g. ``functions(provider="q-ctrl")``.
"""
params = dict(kwargs)
if provider:
params["provider"] = provider
response_data = safe_json_request_as_list(
request=lambda: requests.get(
f"{self.host}/api/{self.version}/programs",
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
params=params,
timeout=REQUESTS_TIMEOUT,
)
)
for program_data in response_data:
program_data["client"] = self
return [RunnableQiskitFunction.from_json(program_data) for program_data in response_data]
@_trace_functions("get_by_title")
def function(self, title: str, provider: Optional[str] = None) -> Optional[RunnableQiskitFunction]:
"""Returns program based on parameters."""
provider, title = format_provider_name_and_title(request_provider=provider, title=title)
response_data = safe_json_request_as_dict(
request=lambda: requests.get(
f"{self.host}/api/{self.version}/programs/get_by_title/{title}",
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
params={"provider": provider},
timeout=REQUESTS_TIMEOUT,
)
)
response_data["client"] = self
the_function = RunnableQiskitFunction.from_json(response_data)
return the_function
def validate_arguments(
self,
title: str,
arguments: Optional[Dict[str, Any]] = None,
provider: Optional[str] = None,
) -> dict:
"""Validate arguments against a function's schema without creating a job.
Args:
title: function title, optionally in "provider/title" format
arguments: arguments dict to validate
provider: optional provider name
Returns:
dict: response from the gateway, e.g. {"valid": True}
Raises:
QiskitServerlessException: if arguments are invalid or function not found.
"""
provider_name, function_title = format_provider_name_and_title(request_provider=provider, title=title)
response = safe_json_request_as_dict(
request=lambda: requests.post(
f"{self.host}/api/{self.version}/programs/validate_arguments/",
json={
"title": function_title,
"arguments": json.dumps(arguments or {}, cls=QiskitObjectsEncoder),
"provider": provider_name,
},
headers=get_headers(token=self.token, instance=self.instance, channel=self.channel),
timeout=REQUESTS_TIMEOUT,
)
)
return response
#####################
####### FILES #######
#####################
def files(self, function: QiskitFunction) -> List[str]:
"""Returns the list of files available for the user in the Qiskit Function folder."""
return self._files_client.list(function)
def provider_files(self, function: QiskitFunction) -> List[str]:
"""Returns the list of files available for the provider in the Qiskit Function folder."""
return self._files_client.provider_list(function)
def file_download(
self,
file: str,
function: QiskitFunction,
target_name: Optional[str] = None,
download_location: str = "./",
):
"""Download a file available to the user for the specific Qiskit Function."""
return self._files_client.download(file, download_location, function, target_name)
def provider_file_download(
self,
file: str,
function: QiskitFunction,
target_name: Optional[str] = None,
download_location: str = "./",
):
"""Download a file available to the provider for the specific Qiskit Function."""
return self._files_client.provider_download(file, download_location, function, target_name)
def file_delete(self, file: str, function: QiskitFunction):
"""Deletes a file available to the user for the specific Qiskit Function."""
return self._files_client.delete(file, function)
def provider_file_delete(self, file: str, function: QiskitFunction):
"""Deletes a file available to the provider for the specific Qiskit Function."""
return self._files_client.provider_delete(file, function)
def file_upload(self, file: str, function: QiskitFunction):
"""Uploads a file in the specific user's Qiskit Function folder."""
return self._files_client.upload(file, function)
def provider_file_upload(self, file: str, function: QiskitFunction):
"""Uploads a file in the specific provider's Qiskit Function folder."""
return self._files_client.provider_upload(file, function)
class IBMServerlessClient(ServerlessClient):
"""
A client for connecting to the IBM serverless host.
Credentials can be saved to disk by calling the `save_account()` method::
from qiskit_serverless import IBMServerlessClient
IBMServerlessClient.save_account(token=<INSERT_IBM_QUANTUM_TOKEN>, instance=<INSERT_CRN>)
Once the credentials are saved, you can simply instantiate the client with no
constructor args, as shown below.
from qiskit_serverless import IBMServerlessClient
client = IBMServerlessClient()
Instead of saving credentials to disk, you can also set the environment variable
ENV_GATEWAY_PROVIDER_TOKEN and then instantiate the client as below::
from qiskit_serverless import IBMServerlessClient
client = IBMServerlessClient()
You can also enable an account just for the current session by instantiating the
provider with the API token::
from qiskit_serverless import IBMServerlessClient
client = IBMServerlessClient(token=<INSERT_IBM_QUANTUM_TOKEN>, instance=<INSERT_CRN>)
"""
def __init__(
self,
token: Optional[str] = None,
name: Optional[str] = None,
instance: Optional[str] = None,
channel: Optional[str] = None,
*,
host: Optional[str] = None,
):
"""
Initialize a client with access to an IBMQ-provided remote cluster.
If a ``token`` is used to initialize an instance, the ``name`` argument
will be ignored.
If only a ``name`` is provided, the token for the named account will
be retrieved from the user's local IBM Quantum account config file.
If neither argument is provided, the token will be searched for in the
environment variables and also in the local IBM Quantum account config
file using the default account name.
Args:
host: host of gateway. Optional. It uses IBM_SERVERLESS_HOST_URL env var or IBM host
token: IBM quantum token
name: Name of the account to load
instance: IBM Cloud CRN
channel: identifies the method to use to authenticate the user
"""
channel = channel or Channel.IBM_QUANTUM_PLATFORM.value # For backwards compatibility
# Initialize QiskitRuntimeService
self._service = QiskitRuntimeService(channel=channel, token=token, name=name, instance=instance)
self.account = self._service._account
# Per-instance cache keyed by backend name; populated lazily by backends() or _get_backend().
# Instance-level (not class-level) to avoid cross-client leakage.
self._backends_cache: Dict[str, Any] = {}
super().__init__(
channel=self.account.channel,
token=self.account.token,
instance=self.account.instance,
host=host if host else IBM_SERVERLESS_HOST_URL,
)
@staticmethod
def save_account(
token: Optional[str] = None,
name: Optional[str] = None,
overwrite: Optional[bool] = False,
instance: Optional[str] = None,
channel: Optional[str] = None,
) -> None:
"""
Save the account to disk for future use.
Args:
token: IBM Quantum API token
name: Name of the account to save
overwrite: ``True`` if the existing account is to be overwritten
instance: IBM Cloud CRN
channel: identifies the method to use to authenticate the user
"""
try:
QiskitRuntimeService.save_account(
token=token,
name=name,
overwrite=overwrite,
instance=instance,
channel=channel,
)
except InvalidAccountError as ex:
raise QiskitServerlessException(f"Invalid format in account inputs - {ex}") from ex
def usage(self) -> dict[str, Any]:
"""Return runtime usage information for the active instance.
Exposes the underlying :meth:`QiskitRuntimeService.usage` method to retrieve
the instance's runtime quota information, including ``usage_remaining_seconds``
and ``usage_limit_reached``.
Returns:
A dictionary containing usage information as reported by the runtime service.
Raises:
QiskitServerlessException: If the usage information cannot be retrieved.
"""
try:
return self._service.usage()
except Exception as exc: # pylint: disable=broad-except
raise QiskitServerlessException(
f"Failed to retrieve usage information for instance '{self.instance}': {exc}"
) from exc
def backends( # pylint: disable=too-many-positional-arguments
self,
refresh_cache: bool = False,
name: str | None = None,
min_num_qubits: int | None = None,
filters: Callable[[IBMBackend], bool] | None = None,
**kwargs: Any,
) -> list[IBMBackend]:
"""Return backends accessible through this instance.
Exposes the underlying :meth:`QiskitRuntimeService.backends` method with
per-instance caching. Results are cached after the first call; use
``refresh_cache=True`` to force a refresh.
Args:
refresh_cache: If ``True``, refresh the cache by fetching backends from the service.
name: Backend name to filter by.
min_num_qubits: Minimum number of qubits the backend must have.
filters: More complex filters, such as lambda functions.
For example::
client.backends(filters=lambda b: b.max_shots > 50000)
client.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 backends with at least 127 qubits
client.backends(min_num_qubits=127)
For the full list of backend attributes, see the `IBMBackend class documentation
<https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service#backends>`_
Returns:
List of available backends that match the filter criteria.
Raises:
QiskitServerlessException: If the backend listing call fails.
"""
if not refresh_cache and self._backends_cache:
# cache is available and refresh flag is false
return list(self._backends_cache.values())
try:
backend_list = self._service.backends(
name=name,
min_num_qubits=min_num_qubits,
filters=filters,
**kwargs,
)
except Exception as exc:
raise QiskitServerlessException(
f"Failed to retrieve backends for instance '{self.instance}': {exc}"
) from exc
# deleting cached backends as they could have unavailable backends and update with new accessible backends
self._backends_cache = {}
for backend in backend_list:
self._backends_cache[backend.name] = backend
return backend_list
def backend(self, name: str, **kwargs: Any) -> Backend:
"""Fetch a single backend by name and update the cache.
Exposes the underlying :meth:`QiskitRuntimeService.backend` method to perform
a targeted backend lookup. This is more efficient than listing all backends
and validates that the caller has access to the requested backend. The cache
is updated on every call to reflect current access permissions.
Args:
name: Name of the backend (e.g., ``"ibm_torino"``).
**kwargs: Simple filters that require a specific value for an attribute in
backend configuration or status.
For the full list of backend attributes, see the `IBMBackend class documentation
<https://quantum.cloud.ibm.com/docs/api/qiskit-ibm-runtime/qiskit-runtime-service#backend>`_
Returns:
Backend matching the specified name.
Raises:
QiskitServerlessException: If the backend is not found or is inaccessible.
"""
try:
backend = self._service.backend(name=name, **kwargs)
except QiskitBackendNotFoundError as exc:
raise QiskitServerlessException(
f"Backend '{name}' is not available or you do not have access to it "
f"with instance '{self.instance}'. "
f"Call client.backends() to list accessible backends."
) from exc
except Exception as exc:
raise QiskitServerlessException(f"Failed to retrieve backend '{name}': {exc}") from exc
self._backends_cache[name] = backend
return backend
def least_busy(
self,
min_num_qubits: int | None = None,
filters: Callable[[IBMBackend], bool] | None = None,
**kwargs: Any,
) -> IBMBackend:
"""Return the least busy backend matching the specified criteria.
Exposes the underlying :meth:`QiskitRuntimeService.least_busy` method to find
the backend with the fewest pending jobs. The result is cached in the instance.
Args:
min_num_qubits: Minimum number of qubits the backend must have.
filters: Filters can be defined as for the :meth:`backends` method.
Example::
client.least_busy(min_num_qubits=5, operational=True)
**kwargs: Additional filters for backend configuration or status attributes.
Returns:
The backend with the fewest number of pending jobs that matches the criteria.
Raises:
QiskitServerlessException: If no backend matches the criteria or the call fails.
"""
try:
backend = self._service.least_busy(
min_num_qubits=min_num_qubits,
filters=filters,
**kwargs,
)
except QiskitBackendNotFoundError as exc:
raise QiskitServerlessException(
f"No available backend matches the criteria with instance '{self.instance}'. "
f"Call client.backends() to list accessible backends."
) from exc
except Exception as exc:
raise QiskitServerlessException(f"Failed to retrieve backend: {exc}") from exc
self._backends_cache[backend.name] = backend
return backend