1- import os
1+ import threading
2+ from typing import Dict , Optional , Any
23
34from agentex import AsyncAgentex
4- from agentex .lib .environment_variables import refreshed_environment_variables , EnvironmentVariables
5+ from agentex .lib .environment_variables import EnvironmentVariables , refreshed_environment_variables
56
7+ _client : Optional ["AsyncAgentex" ] = None
8+ _cached_headers : Dict [str , str ] = {}
9+ _init_kwargs : Dict [str , Any ] = {}
10+ _lock = threading .RLock ()
611
7- def create_async_agentex_client (** kwargs ):
12+
13+ def _build_headers () -> Dict [str , str ]:
814 EnvironmentVariables .refresh ()
9- agent_id = refreshed_environment_variables .AGENT_ID
10- default_headers = {
11- "x-agent-identity" : agent_id
12- }
13- return AsyncAgentex (default_headers = default_headers , ** kwargs )
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 {}
18+
19+
20+ def create_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
26+
27+ new_headers = _build_headers ()
28+
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
36+
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
0 commit comments