@@ -238,17 +238,48 @@ async def add_batch_of_requests(
238238 Returns:
239239 Response containing information about the added requests.
240240 """
241- # Prepare requests for API by converting to dictionaries.
242- requests_dict = [
243- request .model_dump (
244- by_alias = True ,
245- exclude = {'id' }, # Exclude ID fields from requests since the API doesn't accept them.
246- )
247- for request in requests
248- ]
241+ # Do not try to add previously added requests to avoid pointless expensive calls to API
242+ new_requests : list [Request ] = []
243+ already_present_requests : list [ProcessedRequest ] = []
244+ for request in requests :
245+ if self ._requests_cache .get (request .id ):
246+ # We are no sure if it was already handled at this point, and it is not worth calling API for it.
247+ already_present_requests .append (
248+ {
249+ 'id' : request .id ,
250+ 'uniqueKey' : request .unique_key ,
251+ 'wasAlreadyPresent' : True ,
252+ 'wasAlreadyHandled' : request .was_already_handled ,
253+ }
254+ )
249255
250- # Send requests to API.
251- response = await self ._api_client .batch_add_requests (requests = requests_dict , forefront = forefront )
256+ else :
257+ new_requests .append (request )
258+
259+ if new_requests :
260+ # Prepare requests for API by converting to dictionaries.
261+ requests_dict = [
262+ request .model_dump (
263+ by_alias = True ,
264+ exclude = {'id' }, # Exclude ID fields from requests since the API doesn't accept them.
265+ )
266+ for request in new_requests
267+ ]
268+
269+ # Send requests to API.
270+ response = await self ._api_client .batch_add_requests (requests = requests_dict , forefront = forefront )
271+ # Add new requests to the cache.
272+ for processed_request_raw in response ['processedRequests' ]:
273+ processed_request = ProcessedRequest .model_validate (processed_request_raw )
274+ self ._cache_request (
275+ unique_key_to_request_id (processed_request .unique_key ),
276+ processed_request ,
277+ forefront = False ,
278+ )
279+ # Add the locally known already present processed requests based on the local cache.
280+ response ['processedRequests' ].extend (already_present_requests )
281+ else :
282+ response = {'unprocessedRequests' : [], 'processedRequests' : already_present_requests }
252283
253284 # Update assumed total count for newly added requests.
254285 api_response = AddRequestsResponse .model_validate (response )
0 commit comments