@@ -108,14 +108,41 @@ def create(provider_name: str, api_key: str | None = None, api_base: str | None
108108 fake_any_llm : Any = pytypes .ModuleType ("any_llm" )
109109 fake_any_llm .AnyLLM = FakeAnyLLMFactory
110110
111- sys .modules .pop ("agents.extensions.models.any_llm_model" , None )
111+ # Importing the submodule fresh replaces both bindings that other code resolves
112+ # it through: the ``sys.modules`` entry and the ``any_llm_model`` attribute on the
113+ # parent package. Route both through ``monkeypatch`` so teardown restores them
114+ # together; otherwise a later ``from agents.extensions.models import any_llm_model``
115+ # would still see the stub-backed module while ``sys.modules`` has the original.
116+ parent_package = importlib .import_module ("agents.extensions.models" )
117+ monkeypatch .delitem (sys .modules , "agents.extensions.models.any_llm_model" , raising = False )
118+ monkeypatch .delattr (parent_package , "any_llm_model" , raising = False )
112119 monkeypatch .setitem (sys .modules , "any_llm" , fake_any_llm )
113120
114121 module = importlib .import_module ("agents.extensions.models.any_llm_model" )
115122 monkeypatch .setattr (module , "AnyLLM" , FakeAnyLLMFactory , raising = True )
116123 return module , create_calls
117124
118125
126+ def test_import_any_llm_module_restores_module_bindings_on_teardown () -> None :
127+ pytest .importorskip (
128+ "any_llm" ,
129+ reason = "`any-llm-sdk` is only available when the optional dependency is installed." ,
130+ )
131+ parent_package = importlib .import_module ("agents.extensions.models" )
132+ original = importlib .import_module ("agents.extensions.models.any_llm_model" )
133+
134+ with pytest .MonkeyPatch .context () as monkeypatch :
135+ module , _ = _import_any_llm_module (
136+ monkeypatch , FakeAnyLLMProvider (supports_responses = False )
137+ )
138+ assert module is not original
139+ assert sys .modules ["agents.extensions.models.any_llm_model" ] is module
140+ assert parent_package .any_llm_model is module
141+
142+ assert sys .modules ["agents.extensions.models.any_llm_model" ] is original
143+ assert parent_package .any_llm_model is original
144+
145+
119146def _chat_completion (text : str ) -> ChatCompletion :
120147 return ChatCompletion (
121148 id = "chatcmpl_123" ,
0 commit comments