-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathapplication.py
1898 lines (1698 loc) · 75 KB
/
application.py
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
# Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
import sys
import asyncio
import traceback
import concurrent.futures
import warnings
from typing import Optional, Dict, Generator, List, IO, Iterable, Callable, Tuple, Union
from concurrent.futures import ThreadPoolExecutor, Future, as_completed
from queue import Queue, Empty
import threading
from requests import Session
from requests.models import Response
from requests.exceptions import ConnectionError, HTTPError, JSONDecodeError
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
from tenacity import (
retry,
wait_exponential,
wait_random_exponential,
stop_after_attempt,
retry_if_result,
retry_if_exception,
retry_if_exception_type,
retry_any,
RetryCallState,
)
from time import sleep
from urllib.parse import quote
import random
import time
from vespa.exceptions import VespaError
from vespa.io import VespaQueryResponse, VespaResponse, VespaVisitResponse
from vespa.package import ApplicationPackage
import httpx
import vespa
import gzip
from requests.models import PreparedRequest
from io import BytesIO
import logging
logging.getLogger("urllib3").setLevel(logging.ERROR)
VESPA_CLOUD_SECRET_TOKEN: str = "VESPA_CLOUD_SECRET_TOKEN"
def raise_for_status(
response: Response, raise_on_not_found: Optional[bool] = False
) -> None:
"""
Raises an appropriate error if necessary.
If the response contains an error message, VespaError is raised along with HTTPError to provide more details.
:param response: Response object from Vespa API.
:param raise_on_not_found: If True, raise HTTPError if status_code is 404.
:raises HTTPError: If status_code is between 400 and 599.
:raises VespaError: If the response JSON contains an error message.
"""
try:
response.raise_for_status()
except HTTPError as http_error:
try:
response_json = response.json()
if response.status_code == 404 and not raise_on_not_found:
return
except JSONDecodeError:
raise http_error
errors = response_json.get("root", {}).get("errors", [])
error_message = response_json.get("message", None)
if errors:
raise VespaError(errors) from http_error
if error_message:
raise VespaError(error_message) from http_error
raise HTTPError(http_error) from http_error
class Vespa(object):
def __init__(
self,
url: str,
port: Optional[int] = None,
deployment_message: Optional[List[str]] = None,
cert: Optional[str] = None,
key: Optional[str] = None,
vespa_cloud_secret_token: Optional[str] = None,
output_file: IO = sys.stdout,
application_package: Optional[ApplicationPackage] = None,
) -> None:
"""
Establish a connection with an existing Vespa application.
:param url: Vespa endpoint URL.
:param port: Vespa endpoint port.
:param deployment_message: Message returned by Vespa engine after deployment. Used internally by deploy methods.
:param cert: Path to data plane certificate and key file in case the 'key' parameter is none. If 'key' is not None, this
should be the path of the certificate file. Typically generated by Vespa-cli with 'vespa auth cert'
:param key: Path to the data plane key file. Typically generated by Vespa-cli with 'vespa auth cert'
:param vespa_cloud_secret_token: Vespa Cloud data plane secret token.
:param output_file: Output file to write output messages.
:param application_package: Application package definition used to deploy the application.
>>> Vespa(url = "https://cord19.vespa.ai") # doctest: +SKIP
>>> Vespa(url = "http://localhost", port = 8080)
Vespa(http://localhost, 8080)
>>> Vespa(url="https://token-endpoint..z.vespa-app.cloud", vespa_cloud_secret_token="vespa_cloud_secret_token") # doctest: +SKIP
>>> Vespa(url = "https://mtls-endpoint..z.vespa-app.cloud", cert = "/path/to/cert.pem", key = "/path/to/key.pem") # doctest: +SKIP
"""
self.output_file = output_file
self.url = url
self.port = port
self.deployment_message = deployment_message
self.cert = cert
self.key = key
self.vespa_cloud_secret_token = vespa_cloud_secret_token
self._application_package = application_package
self.pyvespa_version = vespa.__version__
self.base_headers = {"User-Agent": f"pyvespa/{self.pyvespa_version}"}
if port is None:
self.end_point = self.url
else:
self.end_point = str(url).rstrip("/") + ":" + str(port)
self.search_end_point = self.end_point + "/search/"
if self.vespa_cloud_secret_token is not None:
self.auth_method = "token"
self.base_headers.update(
{"Authorization": f"Bearer {self.vespa_cloud_secret_token}"}
)
else:
self.auth_method = "mtls"
def asyncio(
self,
connections: Optional[int] = 1,
total_timeout: Optional[int] = None,
timeout: Union[httpx.Timeout, int] = httpx.Timeout(5),
**kwargs,
) -> "VespaAsync":
"""
Access Vespa asynchronous connection layer.
Should be used as a context manager.
Example usage::
async with app.asyncio() as async_app:
response = await async_app.query(body=body)
# passing kwargs
limits = httpx.Limits(max_keepalive_connections=5, max_connections=5, keepalive_expiry=15)
timeout = httpx.Timeout(connect=3, read=4, write=2, pool=5)
async with app.asyncio(connections=5, timeout=timeout, limits=limits) as async_app:
response = await async_app.query(body=body)
See :class:`VespaAsync` for more details on the parameters.
:param connections: Number of maximum_keepalive_connections.
:param total_timeout: Deprecated. Will be ignored. Use timeout instead.
:param timeout: httpx.Timeout object. See https://www.python-httpx.org/advanced/timeouts/. Defaults to 5 seconds.
:param kwargs: Additional arguments to be passed to the httpx.AsyncClient.
:return: Instance of Vespa asynchronous layer.
"""
return VespaAsync(
app=self,
connections=connections,
total_timeout=total_timeout,
timeout=timeout,
**kwargs,
)
def syncio(
self,
connections: Optional[int] = 8,
compress: Union[str, bool] = "auto",
) -> "VespaSync":
"""
Access Vespa synchronous connection layer.
Should be used as a context manager.
Example usage::
with app.syncio() as sync_app:
response = sync_app.query(body=body)
See :class:`VespaSync` for more details.
:param connections: Number of allowed concurrent connections
:param total_timeout: Total timeout in secs.
:param compress (Union[str, bool], optional): Whether to compress the request body. Defaults to "auto", which will compress if the body is larger than 1024 bytes.
:return: Instance of Vespa asynchronous layer.
"""
return VespaSync(
app=self,
pool_connections=connections,
pool_maxsize=connections,
compress=compress,
)
@staticmethod
def _run_coroutine_new_event_loop(loop, coro):
asyncio.set_event_loop(loop)
return loop.run_until_complete(coro)
@staticmethod
def _check_for_running_loop_and_run_coroutine(coro):
try:
_ = asyncio.get_running_loop()
new_loop = asyncio.new_event_loop()
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(
Vespa._run_coroutine_new_event_loop, new_loop, coro
)
return future.result()
except RuntimeError:
return asyncio.run(coro)
def http(self, pool_maxsize: int = 10):
return VespaSync(
app=self, pool_maxsize=pool_maxsize, pool_connections=pool_maxsize
)
def __repr__(self) -> str:
if self.port:
return "Vespa({}, {})".format(self.url, self.port)
else:
return "Vespa({})".format(self.url)
def _infer_schema_name(self):
if not self._application_package:
raise ValueError(
"Application Package not available. Not possible to infer schema name."
)
try:
schema = self._application_package.schema
except AssertionError:
raise ValueError(
"Application has more than one schema. Not possible to infer schema name."
)
if not schema:
raise ValueError(
"Application has no schema. Not possible to infer schema name."
)
return schema.name
def wait_for_application_up(self, max_wait: int = 300) -> None:
"""
Wait for application endpoint ready (/ApplicationStatus).
:param max_wait: Seconds to wait for the application endpoint
:raises RuntimeError: If not able to reach endpoint within :max_wait: param or the client fails to authenticate.
:return:
"""
for wait_sec in range(max_wait):
sleep(1)
try:
response = self.get_application_status()
if not response:
continue
if response.status_code == 200:
print("Application is up!", file=self.output_file)
return
except ConnectionError:
pass
if wait_sec % 5 == 0:
print(
f"Waiting for application to come up, {wait_sec}/{max_wait} seconds.",
file=self.output_file,
)
else:
raise RuntimeError(
"Could not connect to endpoint {0} using any of the available auth methods within {1} seconds.".format(
self.end_point, max_wait
)
)
def get_application_status(self) -> Optional[Response]:
"""
Get application status (/ApplicationStatus)
:return:
"""
endpoint = f"{self.end_point}/ApplicationStatus"
with self.syncio() as sync_sess:
response = sync_sess.http_session.get(endpoint)
return response
def get_model_endpoint(self, model_id: Optional[str] = None) -> Optional[Response]:
"""Get stateless model evaluation endpoints."""
with VespaSync(self, pool_connections=1, pool_maxsize=1) as sync_app:
return sync_app.get_model_endpoint(model_id=model_id)
def query(
self, body: Optional[Dict] = None, groupname: str = None, **kwargs
) -> VespaQueryResponse:
"""
Send a query request to the Vespa application.
Send 'body' containing all the request parameters.
:param body: Dict containing request parameters.
:param groupname: The groupname used with streaming search.
:param kwargs: Extra Vespa Query API parameters.
:return: The response from the Vespa application.
"""
# Use one connection as this is a single query
with VespaSync(self, pool_maxsize=1, pool_connections=1) as sync_app:
return sync_app.query(body=body, groupname=groupname, **kwargs)
def feed_data_point(
self,
schema: str,
data_id: str,
fields: Dict,
namespace: str = None,
groupname: str = None,
compress: Union[str, bool] = "auto",
**kwargs,
) -> VespaResponse:
"""
Feed a data point to a Vespa app. Will create a new VespaSync with
connection overhead.
Example usage::
app = Vespa(url="localhost", port=8080)
data_id = "1",
fields = {
"field1": "value1",
}
with VespaSync(app) as sync_app:
response = sync_app.feed_data_point(
schema="schema_name",
data_id=data_id,
fields=fields
)
print(response)
:param schema: The schema that we are sending data to.
:param data_id: Unique id associated with this data point.
:param fields: Dict containing all the fields required by the `schema`.
:param namespace: The namespace that we are sending data to.
:param groupname: The groupname that we are sending data
:param compress (Union[str, bool], optional): Whether to compress the request body. Defaults to "auto", which will compress if the body is larger than 1024 bytes.
:return: VespaResponse of the HTTP POST request.
"""
if not namespace:
namespace = schema
# Use low low connection settings to avoid too much overhead for a
# single data point
with VespaSync(
app=self, pool_connections=1, pool_maxsize=1, compress=compress
) as sync_app:
return sync_app.feed_data_point(
schema=schema,
data_id=data_id,
fields=fields,
namespace=namespace,
groupname=groupname,
**kwargs,
)
def feed_iterable(
self,
iter: Iterable[Dict],
schema: Optional[str] = None,
namespace: Optional[str] = None,
callback: Optional[Callable[[VespaResponse, str], None]] = None,
operation_type: Optional[str] = "feed",
max_queue_size: int = 1000,
max_workers: int = 8,
max_connections: int = 16,
compress: Union[str, bool] = "auto",
**kwargs,
):
"""
Feed data from an Iterable of Dict with the keys 'id' and 'fields' to be used in the :func:`feed_data_point`.
Uses a queue to feed data in parallel with a thread pool. The result of each operation is forwarded
to the user provided callback function that can process the returned `VespaResponse`.
Example usage::
app = Vespa(url="localhost", port=8080)
data = [
{"id": "1", "fields": {"field1": "value1"}},
{"id": "2", "fields": {"field1": "value2"}},
]
def callback(response, id):
print(f"Response for id {id}: {response.status_code}")
app.feed_iterable(data, schema="schema_name", callback=callback)
:param iter: An iterable of Dict containing the keys 'id' and 'fields' to be used in the :func:`feed_data_point`. Note that this 'id' is only the last part of the full document id, that will be generated automatically by pyvespa.
:param schema: The Vespa schema name that we are sending data to.
:param namespace: The Vespa document id namespace. If no namespace is provided the schema is used.
:param callback: A callback function to be called on each result. Signature `callback(response:VespaResponse, id:str)`
:param operation_type: The operation to perform. Default to `feed`. Valid are `feed`, `update` or `delete`.
:param max_queue_size: The maximum size of the blocking queue and max in-flight operations.
:param max_workers: The maximum number of workers in the threadpool executor.
:param max_connections: The maximum number of persisted connections to the Vespa endpoint.
:param compress (Union[str, bool], optional): Whether to compress the request body. Defaults to "auto", which will compress if the body is larger than 1024 bytes.
:param kwargs: Additional parameters are passed to the respective operation type specific :func:`_data_point`.
"""
if operation_type not in ["feed", "update", "delete"]:
raise ValueError(
"Invalid operation type. Valid are `feed`, `update` or `delete`."
)
if namespace is None:
namespace = schema
if not schema:
try:
schema = self._infer_schema_name()
except ValueError:
raise ValueError(
"Not possible to infer schema name. Specify schema parameter."
)
def _consumer(
queue: Queue,
executor: ThreadPoolExecutor,
sync_session: VespaSync,
max_in_flight=2 * max_queue_size,
):
in_flight = 0 # Single threaded consumer
futures: List[Future] = []
while True:
try:
doc = queue.get(timeout=5)
except Empty:
continue # producer has not produced anything
if doc is None: # producer is done
queue.task_done()
break # Break and wait for all futures to complete
completed_futures = [future for future in futures if future.done()]
for future in completed_futures:
futures.remove(future)
in_flight -= 1
_handle_result_callback(future, callback=callback)
while in_flight >= max_in_flight:
# Check for completed tasks and reduce in-flight tasks
for future in futures:
if future.done():
futures.remove(future)
in_flight -= 1
_handle_result_callback(future, callback=callback)
sleep(0.01) # wait a bit for more futures to complete
# we can submit a new doc to Vespa
future: Future = executor.submit(_submit, doc, sync_session)
futures.append(future)
in_flight += 1
queue.task_done() # signal that we have consumed the doc from queue
# make sure callback is called for all pending operations before
# exiting the consumer thread
for future in futures:
_handle_result_callback(future, callback)
def _submit(
doc: dict, sync_session: VespaSync
) -> Tuple[str, Union[VespaResponse, Exception]]:
id = doc.get("id", None)
if id is None:
return id, VespaResponse(
status_code=499,
json={"id": id, "message": "Missing id in input dict"},
url="n/a",
operation_type=operation_type,
)
fields = doc.get("fields", None)
if fields is None and operation_type != "delete":
return id, VespaResponse(
status_code=499,
json={"id": id, "message": "Missing fields in input dict"},
url="n/a",
operation_type=operation_type,
)
groupname = doc.get("groupname", None)
try:
if operation_type == "feed":
response: VespaResponse = sync_session.feed_data_point(
schema=schema,
namespace=namespace,
groupname=groupname,
data_id=id,
fields=fields,
**kwargs,
)
return (id, response)
elif operation_type == "update":
response: VespaResponse = sync_session.update_data(
schema=schema,
namespace=namespace,
groupname=groupname,
data_id=id,
fields=fields,
**kwargs,
)
return (id, response)
elif operation_type == "delete":
response: VespaResponse = sync_session.delete_data(
schema=schema,
namespace=namespace,
data_id=id,
groupname=groupname,
**kwargs,
)
return (id, response)
except Exception as e:
return (id, e)
def _handle_result_callback(
future: Future, callback: Optional[Callable[[VespaResponse, str], None]]
):
id, response = future.result()
if isinstance(response, Exception):
response = VespaResponse(
status_code=599,
json={
"Exception": str(response),
"id": id,
"message": "Exception during feed_data_point",
},
url="n/a",
operation_type=operation_type,
)
if callback is not None:
try:
callback(response, id)
except Exception as e:
print(f"Exception in user callback for id {id}", file=sys.stderr)
traceback.print_exception(
type(e), e, e.__traceback__, file=sys.stderr
)
with VespaSync(
app=self,
pool_maxsize=max_connections,
pool_connections=max_connections,
compress=compress,
) as session:
queue = Queue(maxsize=max_queue_size)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
consumer_thread = threading.Thread(
target=_consumer, args=(queue, executor, session, max_queue_size)
)
consumer_thread.start()
for doc in iter:
queue.put(doc, block=True)
queue.put(None, block=True)
queue.join()
consumer_thread.join()
def feed_async_iterable(
self,
iter: Iterable[Dict],
schema: Optional[str] = None,
namespace: Optional[str] = None,
callback: Optional[Callable[[VespaResponse, str], None]] = None,
operation_type: Optional[str] = "feed",
max_queue_size: int = 1000,
max_workers: int = 64,
max_connections: int = 1,
**kwargs,
):
"""
Feed data asynchronously using httpx.AsyncClient with HTTP/2. Feed from an Iterable of Dict with the keys 'id' and 'fields' to be used in the :func:`feed_data_point`.
The result of each operation is forwarded to the user provided callback function that can process the returned `VespaResponse`.
Prefer using this method over :func:`feed_iterable` when the operation is I/O bound from the client side.
Example usage::
app = Vespa(url="localhost", port=8080)
data = [
{"id": "1", "fields": {"field1": "value1"}},
{"id": "2", "fields": {"field1": "value2"}},
]
async def callback(response, id):
print(f"Response for id {id}: {response.status_code}")
app.feed_async_iterable(data, schema="schema_name", callback=callback)
:param iter: An iterable of Dict containing the keys 'id' and 'fields' to be used in the :func:`feed_data_point`. Note that this 'id' is only the last part of the full document id, that will be generated automatically by pyvespa.
:param schema: The Vespa schema name that we are sending data to.
:param namespace: The Vespa document id namespace. If no namespace is provided the schema is used.
:param callback: A callback function to be called on each result. Signature `callback(response:VespaResponse, id:str)`
:param operation_type: The operation to perform. Default to `feed`. Valid are `feed`, `update` or `delete`.
:param max_queue_size: The maximum number of tasks waiting to be processed. Useful to limit memory usage. Default is 1000.
:param max_workers: Maximum number of concurrent requests to have in-flight, bound by an asyncio.Semaphore, that needs to be acquired by a submit task. Increase if the server is scaled to handle more requests.
:param max_connections: The maximum number of connections passed to httpx.AsyncClient to the Vespa endpoint. As HTTP/2 is used, only one connection is needed.
:param kwargs: Additional parameters are passed to the respective operation type specific :func:`_data_point`.
"""
if operation_type not in ["feed", "update", "delete"]:
raise ValueError(
"Invalid operation type. Valid are `feed`, `update` or `delete`."
)
if namespace is None:
namespace = schema
if not schema:
try:
schema = self._infer_schema_name()
except ValueError:
raise ValueError(
"Not possible to infer schema name. Specify schema parameter."
)
async def handle_result(task: asyncio.Task, id: str):
# Wrapper around the task to handle exceptions and call the user callback
try:
response = await task
except Exception as e:
response = VespaResponse(
status_code=599,
json={
"Exception": str(e),
"id": id,
"message": "Exception during feed_data_point",
},
url="n/a",
operation_type=operation_type,
)
if callback is not None:
try:
callback(response, id)
except Exception as e:
print(f"Exception in user callback for id {id}", file=sys.stderr)
traceback.print_exception(
type(e), e, e.__traceback__, file=sys.stderr
)
# Wrapping in async function to be able to use asyncio.run, and avoid that the feed_async_iterable have to be async
async def run():
async with self.asyncio(connections=max_connections) as async_session:
semaphore = asyncio.Semaphore(max_workers)
tasks = []
for doc in iter:
id = doc.get("id")
fields = doc.get("fields")
groupname = doc.get("groupname")
if id is None:
response = VespaResponse(
status_code=499,
json={"id": id, "message": "Missing id in input dict"},
url="n/a",
operation_type=operation_type,
)
if callback is not None:
callback(response, id)
continue
if fields is None and operation_type != "delete":
response = VespaResponse(
status_code=499,
json={"id": id, "message": "Missing fields in input dict"},
url="n/a",
operation_type=operation_type,
)
if callback is not None:
callback(response, id)
continue
async with semaphore:
if operation_type == "feed":
task = async_session.feed_data_point(
schema=schema,
namespace=namespace,
groupname=groupname,
data_id=id,
fields=fields,
**kwargs,
)
elif operation_type == "update":
task = async_session.update_data(
schema=schema,
namespace=namespace,
groupname=groupname,
data_id=id,
fields=fields,
**kwargs,
)
elif operation_type == "delete":
task = async_session.delete_data(
schema=schema,
namespace=namespace,
data_id=id,
groupname=groupname,
**kwargs,
)
tasks.append(handle_result(asyncio.create_task(task), id))
# Control the number of in-flight tasks
if len(tasks) >= max_queue_size:
await asyncio.gather(*tasks)
tasks = []
if tasks:
await asyncio.gather(*tasks)
asyncio.run(run())
return
async def query_many_async(
self,
queries: Iterable[Dict],
num_connections: int = 1,
max_concurrent: int = 100,
client_kwargs: Dict = {},
**query_kwargs,
) -> List[VespaQueryResponse]:
"""
Execute many queries asynchronously using httpx.AsyncClient.
Number of concurrent requests is controlled by the max_concurrent parameter.
Each query will be retried up to 3 times using an exponential backoff strategy.
:param queries: Iterable of query bodies (dictionaries) to be sent.
:param num_connections: Number of connections to be used in the asynchronous client (uses http2). Defaults to 1.
:param max_concurrent: Maximum concurrent requests to be sent. Defaults to 100. Be careful with increasing too much.
:param client_kwargs: Additional arguments to be passed to the httpx.AsyncClient.
:param query_kwargs: Additional arguments to be passed to the query method.
:return: List of VespaQueryResponse objects.
"""
results = []
# Use the asynchronous client from VespaAsync (created via self.asyncio).
async with self.asyncio(connections=num_connections, **client_kwargs) as client:
sem = asyncio.Semaphore(max_concurrent)
async def query_wrapper(query_body: Dict) -> VespaQueryResponse:
async with sem:
try:
response = await client.query(query_body, **query_kwargs)
return response
except HTTPError as e:
return VespaQueryResponse(
json=str(e),
status_code=e.response.status_code,
url=e.request.url,
request_body=query_body,
)
tasks = [query_wrapper(q) for q in queries]
results = await asyncio.gather(*tasks)
return results
def query_many(
self,
queries: Iterable[Dict],
num_connections: int = 1,
max_concurrent: int = 100,
client_kwargs: Dict = {},
**query_kwargs,
) -> List[VespaQueryResponse]:
"""
Execute many queries asynchronously using httpx.AsyncClient.
This method is a wrapper around the query_many_async method that uses the asyncio event loop to run the coroutine.
Number of concurrent requests is controlled by the max_concurrent parameter.
Each query will be retried up to 3 times using an exponential backoff strategy.
:param queries: Iterable of query bodies (dictionaries) to be sent.
:param num_connections: Number of connections to be used in the asynchronous client (uses http2). Defaults to 1.
:param max_concurrent: Maximum concurrent requests to be sent. Defaults to 100. Be careful with increasing too much.
:param client_kwargs: Additional arguments to be passed to the httpx.AsyncClient.
:param query_kwargs: Additional arguments to be passed to the query method.
:return: List of VespaQueryResponse objects.
"""
return self._check_for_running_loop_and_run_coroutine(
self.query_many_async(
queries=queries,
num_connections=num_connections,
max_concurrent=max_concurrent,
client_kwargs=client_kwargs,
**query_kwargs,
)
)
def delete_data(
self,
schema: str,
data_id: str,
namespace: str = None,
groupname: str = None,
**kwargs,
) -> VespaResponse:
"""
Delete a data point from a Vespa app.
Example usage::
app = Vespa(url="localhost", port=8080)
response = app.delete_data(schema="schema_name", data_id="1")
print(response)
:param schema: The schema that we are deleting data from.
:param data_id: Unique id associated with this data point.
:param namespace: The namespace that we are deleting data from. If no namespace is provided the schema is used.
:param groupname: The groupname that we are deleting data from.
:param kwargs: Additional arguments to be passed to the HTTP DELETE request https://docs.vespa.ai/en/reference/document-v1-api-reference.html#request-parameters
:return: Response of the HTTP DELETE request.
"""
with VespaSync(self, pool_connections=1, pool_maxsize=1) as sync_app:
return sync_app.delete_data(
schema=schema,
data_id=data_id,
namespace=namespace,
groupname=groupname,
**kwargs,
)
def delete_all_docs(
self,
content_cluster_name: str,
schema: str,
namespace: str = None,
slices: int = 1,
**kwargs,
) -> Response:
"""
Delete all documents associated with the schema. This might block for a long time as
it requires sending multiple delete requests to complete.
:param content_cluster_name: Name of content cluster to GET from, or visit.
:param schema: The schema that we are deleting data from.
:param namespace: The namespace that we are deleting data from. If no namespace is provided the schema is used.
:param slices: Number of slices to use for parallel delete requests. Defaults to 1.
:param kwargs: Additional arguments to be passed to the HTTP DELETE request https://docs.vespa.ai/en/reference/document-v1-api-reference.html#request-parameters
:return: Response of the HTTP DELETE request.
"""
with VespaSync(self, pool_connections=slices, pool_maxsize=slices) as sync_app:
return sync_app.delete_all_docs(
content_cluster_name=content_cluster_name,
namespace=namespace,
schema=schema,
slices=slices,
**kwargs,
)
def visit(
self,
content_cluster_name: str,
schema: Optional[str] = None,
namespace: Optional[str] = None,
slices: int = 1,
selection: str = "true",
wanted_document_count: int = 500,
slice_id: int = -1,
**kwargs,
) -> Generator[Generator[VespaVisitResponse, None, None], None, None]:
"""
Visit all documents associated with the schema and matching the selection.
Will run each slice on a seperate thread, for each slice yields the
response for each page.
Example usage::
for slice in app.visit(schema="schema_name", slices=2):
for response in slice:
print(response.json)
:param content_cluster_name: Name of content cluster to GET from.
:param schema: The schema that we are visiting data from.
:param namespace: The namespace that we are visiting data from.
:param slices: Number of slices to use for parallel GET.
:param selection: Selection expression to filter documents.
:param wanted_document_count: Best effort number of documents to retrieve for each request. May contain less if there are not enough documents left.
:param slice_id: Slice id to use for the visit. If -1, all slices will be used.
:param kwargs: Additional HTTP request parameters (https://docs.vespa.ai/en/reference/document-v1-api-reference.html#request-parameters)
:return: A generator of slices, each containing a generator of responses.
:raises HTTPError: if one occurred
"""
with VespaSync(self, pool_connections=slices, pool_maxsize=slices) as sync_app:
return sync_app.visit(
content_cluster_name=content_cluster_name,
namespace=namespace,
schema=schema,
slices=slices,
selection=selection,
wanted_document_count=wanted_document_count,
slice_id=slice_id,
**kwargs,
)
def get_data(
self,
schema: str,
data_id: str,
namespace: str = None,
groupname: str = None,
raise_on_not_found: Optional[bool] = False,
**kwargs,
) -> VespaResponse:
"""
Get a data point from a Vespa app.
:param data_id: Unique id associated with this data point.
:param schema: The schema that we are getting data from. Will attempt to infer schema name if not provided.
:param data_id: Unique id associated with this data point.
:param namespace: The namespace that we are getting data from. If no namespace is provided the schema is used.
:param groupname: The groupname that we are getting data from.
:param raise_on_not_found: Raise an exception if the data_id is not found. Default is False.
:param kwargs: Additional arguments to be passed to the HTTP GET request https://docs.vespa.ai/en/reference/document-v1-api-reference.html#request-parameters
:return: Response of the HTTP GET request.
"""
with VespaSync(self, pool_connections=1, pool_maxsize=1) as sync_app:
return sync_app.get_data(
schema=schema,
data_id=data_id,
namespace=namespace,
groupname=groupname,
raise_on_not_found=raise_on_not_found,
**kwargs,
)
def update_data(
self,
schema: str,
data_id: str,
fields: Dict,
create: bool = False,
namespace: str = None,
groupname: str = None,
compress: Union[str, bool] = "auto",
**kwargs,
) -> VespaResponse:
"""
Update a data point in a Vespa app.
Example usage::
vespa = Vespa(url="localhost", port=8080)
fields = {"mystringfield": "value1", "myintfield": 42}
response = vespa.update_data(schema="schema_name", data_id="id1", fields=fields)
# or, with partial update, setting auto_assign=False
fields = {"myintfield": {"increment": 1}}
response = vespa.update_data(schema="schema_name", data_id="id1", fields=fields, auto_assign=False)
print(response.json)
:param schema: The schema that we are updating data.
:param data_id: Unique id associated with this data point.
:param fields: Dict containing all the fields you want to update.
:param create: If true, updates to non-existent documents will create an empty document to update
:param auto_assign: Assumes `fields`-parameter is an assignment operation. (https://docs.vespa.ai/en/reference/document-json-format.html#assign). If set to false, the fields parameter should be a dictionary including the update operation.
:param namespace: The namespace that we are updating data. If no namespace is provided the schema is used.
:param groupname: The groupname that we are updating data.
:param compress (Union[str, bool], optional): Whether to compress the request body. Defaults to "auto", which will compress if the body is larger than 1024 bytes.
:param kwargs: Additional arguments to be passed to the HTTP PUT request. https://docs.vespa.ai/en/reference/document-v1-api-reference.html#request-parameters
:return: Response of the HTTP PUT request.
"""
with VespaSync(
self, pool_connections=1, pool_maxsize=1, compress=compress
) as sync_app:
return sync_app.update_data(
schema=schema,
data_id=data_id,
fields=fields,
create=create,
namespace=namespace,
groupname=groupname,
**kwargs,
)
@property
def application_package(self):
"""Get application package definition, if available."""
if not self._application_package:
raise ValueError("Application package not available.")
else:
return self._application_package
def get_model_from_application_package(self, model_name: str):
"""Get model definition from application package, if available."""
app_package = self.application_package
model = app_package.get_model(model_id=model_name)
return model
def predict(self, x, model_id, function_name="output_0"):
"""
Obtain a stateless model evaluation.
:param x: Input where the format depends on the task that the model is serving.
:param model_id: The id of the model used to serve the prediction.