Skip to content

Commit 5dd6ec2

Browse files
committed
close AsyncOpenAI client after agent run to prevent CLOSE_WAIT CPU spin
1 parent 816f53c commit 5dd6ec2

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

src/seclab_taskflow_agent/agent.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,7 @@ def _ToolsToFinalOutputFunction(
200200
else:
201201
model_impl = OpenAIChatCompletionsModel(model=model, openai_client=client)
202202

203+
self._openai_client = client
203204
self.agent = Agent(
204205
name=name,
205206
instructions=instructions,
@@ -211,6 +212,11 @@ def _ToolsToFinalOutputFunction(
211212
hooks=agent_hooks or TaskAgentHooks(),
212213
)
213214

215+
async def close(self) -> None:
216+
"""Close the underlying AsyncOpenAI client and its httpx connection pool."""
217+
if self._openai_client is not None:
218+
await self._openai_client.close()
219+
214220
async def run(self, prompt: str, max_turns: int = DEFAULT_MAX_TURNS) -> result.RunResult:
215221
"""Run the agent to completion and return the result."""
216222
return await Runner.run(starting_agent=self.agent, input=prompt, max_turns=max_turns, hooks=self.run_hooks)

src/seclab_taskflow_agent/runner.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -372,6 +372,7 @@ async def deploy_task_agents(
372372
server_prompts=server_prompts,
373373
important_guidelines=important_guidelines,
374374
)
375+
agent0 = None
375376
agent0 = TaskAgent(
376377
name=primary_name,
377378
instructions=prompt_with_handoff_instructions(system_prompt) if handoffs else system_prompt,
@@ -460,6 +461,10 @@ async def _run_streamed() -> None:
460461
return complete
461462

462463
finally:
464+
# Close the AsyncOpenAI client to release httpx connection pool.
465+
# Dead CLOSE_WAIT sockets in the pool cause kqueue CPU spin if left open.
466+
if agent0 is not None:
467+
await agent0.close()
463468
start_cleanup.set()
464469
cleanup_attempts_left = len(entries)
465470
while cleanup_attempts_left and entries:

0 commit comments

Comments
 (0)