1- import threading
2- from typing import Dict , Optional , Any
1+ import httpx
32
43from agentex import AsyncAgentex
5- from agentex .lib .environment_variables import EnvironmentVariables , refreshed_environment_variables
4+ from agentex .lib .environment_variables import refreshed_environment_variables
5+ from agentex .lib .utils .logging import make_logger
66
7- _client : Optional ["AsyncAgentex" ] = None
8- _cached_headers : Dict [str , str ] = {}
9- _init_kwargs : Dict [str , Any ] = {}
10- _lock = threading .RLock ()
7+ logger = make_logger (__name__ )
118
129
13- def _build_headers () -> Dict [str , str ]:
14- EnvironmentVariables .refresh ()
15- if refreshed_environment_variables and getattr (refreshed_environment_variables , "AGENT_ID" , None ):
16- return {"x-agent-identity" : refreshed_environment_variables .AGENT_ID }
17- return {}
10+ class EnvAuth (httpx .Auth ):
11+ def __init__ (self , header_name = "x-agent-identity" ):
12+ self .header_name = header_name
1813
14+ def auth_flow (self , request ):
15+ # This gets called for every request
1916
20- def get_async_agentex_client (** kwargs ) -> "AsyncAgentex" :
21- """
22- Return a cached AsyncAgentex instance (created synchronously).
23- Each call re-checks env vars and updates client.default_headers if needed.
24- """
25- global _client , _cached_headers , _init_kwargs
17+ agent_id = refreshed_environment_variables .AGENT_ID
18+ if agent_id :
19+ request .headers [self .header_name ] = agent_id
20+ logger .info (f"Adding header { self .header_name } :{ agent_id } " )
21+ yield request
2622
27- new_headers = _build_headers ()
2823
29- with _lock :
30- # First time (or kwargs changed) -> build a new client
31- if _client is None or kwargs != _init_kwargs :
32- _client = AsyncAgentex (default_headers = new_headers .copy (), ** kwargs )
33- _cached_headers = new_headers
34- _init_kwargs = dict (kwargs )
35- return _client
24+ def create_async_agentex_client (** kwargs ) -> AsyncAgentex :
25+ http_client = httpx .AsyncClient (auth = EnvAuth ())
3626
37- # Same client; maybe headers changed
38- if new_headers != _cached_headers :
39- _cached_headers = new_headers
40- _client .default_headers .clear ()
41- _client .default_headers .update (new_headers )
42-
43- return _client
27+ return AsyncAgentex (http_client = http_client , ** kwargs )
0 commit comments