http_client.py
1 # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai> 2 # 3 # SPDX-License-Identifier: Apache-2.0 4 5 from typing import Any, Literal, overload 6 7 import httpx 8 9 10 @overload 11 def init_http_client(http_client_kwargs: dict[str, Any], async_client: Literal[False]) -> httpx.Client: ... 12 @overload 13 def init_http_client( 14 http_client_kwargs: dict[str, Any] | None, async_client: Literal[False] 15 ) -> httpx.Client | None: ... 16 @overload 17 def init_http_client(http_client_kwargs: dict[str, Any], async_client: Literal[True]) -> httpx.AsyncClient: ... 18 @overload 19 def init_http_client( 20 http_client_kwargs: dict[str, Any] | None, async_client: Literal[True] 21 ) -> httpx.AsyncClient | None: ... 22 @overload 23 def init_http_client( 24 http_client_kwargs: dict[str, Any] | None, async_client: bool 25 ) -> httpx.Client | httpx.AsyncClient | None: ... 26 def init_http_client( 27 http_client_kwargs: dict[str, Any] | None = None, async_client: bool = False 28 ) -> httpx.Client | httpx.AsyncClient | None: 29 """ 30 Initialize an httpx client based on the http_client_kwargs. 31 32 :param http_client_kwargs: 33 The kwargs to pass to the httpx client. 34 :param async_client: 35 Whether to initialize an async client. 36 37 :returns: 38 A httpx client or an async httpx client. 39 """ 40 if not http_client_kwargs: 41 return None 42 if not isinstance(http_client_kwargs, dict): 43 raise TypeError("The parameter 'http_client_kwargs' must be a dictionary.") 44 45 # Create a copy to avoid modifying the original dict 46 processed_kwargs = http_client_kwargs.copy() 47 48 # Handle limits parameter - convert dict to httpx.Limits object if needed 49 if "limits" in processed_kwargs and isinstance(processed_kwargs["limits"], dict): 50 limits_dict = processed_kwargs["limits"] 51 processed_kwargs["limits"] = httpx.Limits(**limits_dict) 52 53 if async_client: 54 return httpx.AsyncClient(**processed_kwargs) 55 return httpx.Client(**processed_kwargs)