Skip to content

openai: with_azure() closes idle connections after 5s, so most Azure requests open a new connection #8792

Done

Description

@furkan-v

Bug Description

LLM.with_azure(), TTS.with_azure() and STT.with_azure() build an openai.AsyncAzureOpenAI client without an http_client. The client then uses the OpenAI SDK's default connection pool, and httpx closes idle connections in that pool after 5 seconds.

The default constructors, LLM(), TTS() and STT(), pass their own httpx.AsyncClient with keepalive_expiry=120. So the same plugin keeps connections to OpenAI open between turns but not to Azure.

In a voice agent the gap between two LLM requests is usually longer than 5 seconds, because the user is speaking. Almost every Azure request therefore opens a new TCP and TLS connection. We measured this on two Azure OpenAI resources, in Sweden Central and East US 2, with three requests 10 seconds apart:

Client Request 1 Request 2 Request 3
LLM.with_azure() new connection new connection new connection
LLM.with_azure() with a 120 s keep-alive pool new connection reused reused

Each new connection adds a handshake to the turn's latency. During a period when Azure East US 2 dropped about a quarter of new TLS handshakes, opening a connection for every request also exposed every request to that failure.

Expected Behavior

with_azure() keeps idle connections for 120 seconds, the same as the default constructors.

Reproduction Steps

# Save as repro.py and run: python repro.py
# A local HTTP/1.1 server that keeps connections open counts how many connections the client opens.
import asyncio
import contextlib
import time
from types import SimpleNamespace

import httpcore2

from livekit.plugins.openai import LLM


async def main() -> None:
    connections = []

    async def handle(reader, writer):
        connections.append(writer)
        with contextlib.suppress(asyncio.IncompleteReadError):  # the client closed the connection
            while await reader.readuntil(b"\r\n\r\n"):
                body = b'{"object": "list", "data": []}'
                writer.write(b"HTTP/1.1 200 OK\r\ncontent-length: %d\r\n\r\n%s" % (len(body), body))
                await writer.drain()

    server = await asyncio.start_server(handle, "127.0.0.1", 0)
    port = server.sockets[0].getsockname()[1]
    llm = LLM.with_azure(api_key="k", azure_endpoint=f"http://127.0.0.1:{port}", api_version="2025-04-01-preview")

    await llm._client.models.list()
    # Move the pool's clock 10 s forward, a typical pause between two turns.
    httpcore2._async.http11.time = SimpleNamespace(monotonic=lambda: time.monotonic() + 10)
    await llm._client.models.list()

    print("connections opened:", len(connections))  # 2 today, 1 expected
    await llm._client.close()
    server.close()


asyncio.run(main())

Operating System

Linux (production), macOS 26.6 (reproduction)

Models Used

Azure OpenAI gpt-5.4, gpt-4.1 and gpt-4o through openai.LLM.with_azure()

Package Versions

livekit-agents==1.8.11
livekit-plugins-openai==1.8.11
openai==3.46.0
httpx2==2.12.0

The code is the same on main at b9b50f2.

Proposed Solution

timeout = timeout or httpx.Timeout(connect=15.0, read=5.0, write=5.0, pool=5.0)
azure_client = openai.AsyncAzureOpenAI(
    ...,
    timeout=timeout,
    http_client=httpx.AsyncClient(
        timeout=timeout,
        follow_redirects=True,
        limits=httpx.Limits(max_connections=50, max_keepalive_connections=50, keepalive_expiry=120),
    ),
)

The same change applies to LLM.with_azure(), TTS.with_azure() and STT.with_azure(). I'll open a PR with it.

Additional Context

#524 added the keep-alive pool to the default constructors about two weeks after #431 added the Azure constructor, then called create_azure_client(). #611 renamed it to with_azure(). It always passes its own client, so it never got the pool.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions