The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(run-agent): reuse the Anthropic request-local client instead of rebuilding it per call
joaomarcos2162d583b118
diff --git a/run_agent.py b/run_agent.pyindex 86aee2e53ae..b6f655c355a 100644--- a/run_agent.py+++ b/run_agent.py@@ -4385,6 +4385,10 @@ class AIAgent:self._close_cached_request_openai_client(reason="cache_evict")except Exception:pass+ try:+ self._close_cached_request_anthropic_client(reason="cache_evict")+ except Exception:+ passdef close(self) -> None:"""Release all resources held by this agent instance.@@ -4472,6 +4476,10 @@ class AIAgent:self._close_cached_request_openai_client(reason="agent_close")except Exception:pass+ try:+ self._close_cached_request_anthropic_client(reason="agent_close")+ except Exception:+ pass# 6c. Close the Codex app-server session. The runtime already drops# it on turn crash / retirement (agent/codex_runtime.py), but hard@@ -5386,8 +5394,31 @@ class AIAgent:exc,)+ def _request_anthropic_client_cache_ref(self) -> dict:+ # Lazy init — tests build agents via AIAgent.__new__ without __init__.+ cache = getattr(self, "_request_anthropic_client_cache", None)+ if cache is None:+ cache = {"client": None, "key": None, "poisoned": False, "in_use": False}+ self._request_anthropic_client_cache = cache+ return cache++ def _request_anthropic_client_key(self) -> tuple:+ """Cache key covering everything that forces a fresh client: credential+ rotation, base URL / region changes, timeout changes (model switch),+ and the 1M-context beta flag."""+ if getattr(self, "provider", None) == "bedrock":+ region = getattr(self, "_bedrock_region", "us-east-1") or "us-east-1"+ return ("bedrock", region)+ return (+ "direct",+ self._anthropic_api_key,+ getattr(self, "_anthropic_base_url", None),+ get_provider_request_timeout(self.provider, self.model),+ bool(getattr(self, "_oauth_1m_beta_disabled", False)),+ )+def _create_request_anthropic_client(self, *, reason: str) -> Any:- """Build a request-local Anthropic client for one in-flight call.+ """Build (or reuse) a request-local Anthropic client for one in-flight call.The shared ``_anthropic_client`` stays the long-lived primary, but thestale/interrupt watchdog runs on the poll thread and must never call@@ -5399,24 +5430,56 @@ class AIAgent:worker performs the SDK-level close from its own context — the sameownership contract the OpenAI-wire path already uses.+ Also mirrors the OpenAI-wire path's single-slot cache+ (``_create_request_openai_client``): building ``anthropic.Anthropic``+ means a fresh httpx pool and TCP+TLS handshake per call, so the client+ is kept warm across sequential calls whose cache key (credentials,+ base URL/region, timeout, 1M-beta flag) hasn't changed. ``in_use``+ keeps a second concurrent call from sharing one pool's close/abort+ lifecycle — it gets a fresh untracked client instead.+Mirrors ``_rebuild_anthropic_client`` construction (direct + Bedrock,- 1M-beta drop) but returns a fresh client instead of swapping the shared- one.+ 1M-beta drop) but returns a fresh/cached client instead of swapping+ the shared one."""if self.api_mode == "anthropic_messages":self._try_refresh_anthropic_client_credentials()- _drop_1m = bool(getattr(self, "_oauth_1m_beta_disabled", False))- if getattr(self, "provider", None) == "bedrock":+ key = self._request_anthropic_client_key()++ stale = None+ with self._openai_client_lock():+ cache = self._request_anthropic_client_cache_ref()+ cached = cache["client"]+ if cached is not None and not cache["in_use"]:+ if (+ not cache["poisoned"]+ and cache["key"] == key+ and not self._is_openai_client_closed(cached)+ ):+ cache["in_use"] = True+ return cached+ # Key changed (credential rotation, base URL/region, timeout,+ # 1M-beta flip), poisoned by a cross-thread abort, or+ # externally closed — never reuse; discard and rebuild below.+ stale = cached+ cache["client"] = None+ cache["key"] = None+ cache["poisoned"] = False+ if stale is not None:+ # Safe to close from this thread: in_use was False, so no worker+ # thread owns the pool's FDs (same #29507 reasoning as OpenAI).+ self._close_request_anthropic_client(stale, reason=f"reuse_evict:{reason}")++ if key[0] == "bedrock":from agent.anthropic_adapter import build_anthropic_bedrock_client- region = getattr(self, "_bedrock_region", "us-east-1") or "us-east-1"- client = build_anthropic_bedrock_client(region)+ client = build_anthropic_bedrock_client(key[1])else:from agent.anthropic_adapter import build_anthropic_clientclient = build_anthropic_client(self._anthropic_api_key,getattr(self, "_anthropic_base_url", None),timeout=get_provider_request_timeout(self.provider, self.model),- drop_context_1m_beta=_drop_1m,+ drop_context_1m_beta=key[4],)logger.debug("Anthropic request client created (%s, shared=False) provider=%s model=%s",@@ -5424,17 +5487,41 @@ class AIAgent:getattr(self, "provider", None),getattr(self, "model", None),)+ with self._openai_client_lock():+ cache = self._request_anthropic_client_cache_ref()+ if cache["client"] is None:+ cache["client"] = client+ cache["key"] = key+ cache["poisoned"] = False+ cache["in_use"] = True+ # else: a concurrent call holds the slot — hand this client out+ # untracked; _close_request_anthropic_client fully closes+ # untracked clients, preserving the per-request lifecycle.return clientdef _close_request_anthropic_client(self, client: Any, *, reason: str) -> None:- """Owner-thread full close of a request-local Anthropic client.-- Force-closes the pool's TCP sockets first (CLOSE-WAIT hygiene, parity- with ``_close_openai_client``), then does the graceful SDK close. Safe+ """Owner-thread close of a request-local Anthropic client.++ On a clean finish (``reason`` in ``_REQUEST_CLIENT_REUSE_REASONS``)+ the pool is kept warm in the cache slot for the next sequential call,+ mirroring ``_close_request_openai_client``. Any other outcome+ (error / kill / abort / stale-slot eviction) force-closes the pool's+ TCP sockets first (CLOSE-WAIT hygiene, parity with+ ``_close_openai_client``), then does the graceful SDK close. Safebecause the caller owns the connection."""if client is None:return+ with self._openai_client_lock():+ cache = self._request_anthropic_client_cache_ref()+ if cache["client"] is client:+ if reason in self._REQUEST_CLIENT_REUSE_REASONS and not cache["poisoned"]:+ cache["in_use"] = False+ return+ cache["client"] = None+ cache["key"] = None+ cache["poisoned"] = False+ cache["in_use"] = Falsetry:self._force_close_tcp_sockets(client)client.close()@@ -5453,6 +5540,30 @@ class AIAgent:exc,)+ def _close_cached_request_anthropic_client(self, *, reason: str) -> None:+ """Teardown hook: really close the cached per-request Anthropic client."""+ with self._openai_client_lock():+ cache = getattr(self, "_request_anthropic_client_cache", None)+ client = cache["client"] if cache else None+ in_use = bool(cache["in_use"]) if cache else False+ if cache is not None:+ cache["client"] = None+ cache["key"] = None+ cache["poisoned"] = False+ cache["in_use"] = False+ if client is None:+ return+ if in_use:+ # A worker thread has this client checked out for an in-flight+ # request — same #29507 reasoning as the OpenAI teardown hook.+ self._abort_request_anthropic_client(client, reason=f"{reason}_in_flight")+ return+ try:+ self._force_close_tcp_sockets(client)+ client.close()+ except Exception:+ pass+def _abort_request_anthropic_client(self, client: Any, *, reason: str) -> None:"""Cross-thread abort for request-local Anthropic clients.@@ -5464,6 +5575,13 @@ class AIAgent:"""if client is None:return+ # A pool whose sockets were shut down from a stranger thread must+ # never be reused: poison the cache slot so the owner-thread close+ # discards it and the next create builds a fresh client.+ with self._openai_client_lock():+ cache = self._request_anthropic_client_cache_ref()+ if cache["client"] is client:+ cache["poisoned"] = Truetry:shutdown_count = self._force_close_tcp_sockets(client)# Same visibility contract as the OpenAI abort path (#72975):diff --git a/tests/agent/test_anthropic_request_client_reuse.py b/tests/agent/test_anthropic_request_client_reuse.pynew file mode 100644index 00000000000..d5983d62ec3--- /dev/null+++ b/tests/agent/test_anthropic_request_client_reuse.py@@ -0,0 +1,157 @@+"""Per-request Anthropic wire client reuse across sequential LLM calls.++Mirrors ``tests/agent/test_request_client_reuse.py`` (the OpenAI-wire cache)+for the Anthropic request-local client. Before this cache existed,+``_create_request_anthropic_client`` built a fresh ``anthropic.Anthropic``+(and its httpx pool) on every single LLM call and ``_close_request_anthropic_client``+always fully closed it — no reuse across a turn's sequential tool-loop calls,+unlike the OpenAI-wire path.++- identical cache key (credentials, base URL, timeout, 1M-beta flag) → same+ client object handed back (the reuse win);+- key changes (credential rotation, base URL change) → evict + rebuild;+- cross-thread abort poisons the slot → the owner-thread close does a real+ close and the next create rebuilds;+- non-reuse close reasons (error cleanups, stale/interrupt kills) discard —+ only request_complete / stream_request_complete reuse;+- teardown (release_clients / close) really closes the cached client, or+ detaches it to the in-flight worker's own close when checked out.+"""++from unittest.mock import MagicMock, patch++from run_agent import AIAgent+++class _StubClient:+ """Minimal non-Mock client: _is_openai_client_closed reads ``is_closed``."""++ def __init__(self):+ self.is_closed = False++ def close(self):+ self.is_closed = True+++def _make_agent(provider="anthropic", base_url="https://api.anthropic.com", model="claude-sonnet-5"):+ agent = AIAgent.__new__(AIAgent)+ agent.provider = provider+ agent.model = model+ agent.api_mode = "anthropic_messages"+ agent._anthropic_api_key = "sk-ant-test"+ agent._anthropic_base_url = base_url+ agent._oauth_1m_beta_disabled = False+ # Real credential-refresh reaches auth/network state we don't need here;+ # the cache logic under test is agnostic to it.+ agent._try_refresh_anthropic_client_credentials = MagicMock(return_value=False)+ return agent+++class _Harness:+ """Patch the Anthropic client build/socket seams and record calls."""++ def __init__(self, agent):+ self.agent = agent+ self.built = [] # reason+ self._patchers = []++ def __enter__(self):+ def _fake_build(*a, **k):+ self.built.append(k.get("drop_context_1m_beta"))+ return _StubClient()++ self._patchers = [+ patch("agent.anthropic_adapter.build_anthropic_client", side_effect=_fake_build),+ patch.object(self.agent, "_force_close_tcp_sockets", return_value=0),+ ]+ for p in self._patchers:+ p.start()+ return self++ def __exit__(self, *exc):+ for p in self._patchers:+ p.stop()+++def test_reuse_on_identical_key_same_object():+ agent = _make_agent()+ with _Harness(agent) as h:+ a = agent._create_request_anthropic_client(reason="chat_completion_request")+ agent._close_request_anthropic_client(a, reason="request_complete")+ assert not a.is_closed # kept for reuse, not really closed++ b = agent._create_request_anthropic_client(reason="chat_completion_request")+ assert b is a+ assert len(h.built) == 1+++def test_rebuild_on_credential_rotation():+ agent = _make_agent()+ with _Harness(agent):+ a = agent._create_request_anthropic_client(reason="r")+ agent._close_request_anthropic_client(a, reason="request_complete")++ agent._anthropic_api_key = "sk-ant-rotated"+ b = agent._create_request_anthropic_client(reason="r")+ assert b is not a+ assert a.is_closed # stale slot really closed on eviction++ agent._close_request_anthropic_client(b, reason="request_complete")+ c = agent._create_request_anthropic_client(reason="r")+ assert c is b+++def test_non_reuse_reason_discards_client():+ agent = _make_agent()+ with _Harness(agent):+ a = agent._create_request_anthropic_client(reason="r")+ agent._close_request_anthropic_client(a, reason="request_error_cleanup")+ assert a.is_closed++ b = agent._create_request_anthropic_client(reason="r")+ assert b is not a+++def test_cross_thread_abort_poisons_slot():+ agent = _make_agent()+ with _Harness(agent):+ a = agent._create_request_anthropic_client(reason="r")+ agent._abort_request_anthropic_client(a, reason="interrupt")+ # Owner thread's close now sees the poisoned slot and really closes.+ agent._close_request_anthropic_client(a, reason="request_complete")+ assert a.is_closed++ b = agent._create_request_anthropic_client(reason="r")+ assert b is not a+++def test_concurrent_call_gets_untracked_client():+ agent = _make_agent()+ with _Harness(agent):+ a = agent._create_request_anthropic_client(reason="r")+ # Slot still checked out (in_use=True) — a second concurrent call+ # must not share it.+ b = agent._create_request_anthropic_client(reason="r")+ assert b is not a++ # Finishing the untracked one does a real close, not a slot release.+ agent._close_request_anthropic_client(b, reason="request_complete")+ assert b.is_closed+ # The tracked slot is unaffected and still reusable.+ agent._close_request_anthropic_client(a, reason="request_complete")+ c = agent._create_request_anthropic_client(reason="r")+ assert c is a+++def test_agent_close_closes_cached_request_client():+ agent = _make_agent()+ with _Harness(agent):+ a = agent._create_request_anthropic_client(reason="r")+ agent._close_request_anthropic_client(a, reason="request_complete")+ assert not a.is_closed++ agent._close_cached_request_anthropic_client(reason="agent_close")+ assert a.is_closed++ # Idempotent: a second teardown must not error or double-act.+ agent._close_cached_request_anthropic_client(reason="agent_close")