Instrument OpenAI Responses WebSocket mode

AM
16h ago
+1075-20

Closes #1734

logfire.instrument_openai() only wraps HTTP requests, so client.responses.connect() (Responses API WebSocket mode) wasn't recorded at all. This PR instruments it for sync and async clients, whether instrument_openai is called on a client or on a client class. As with HTTP, instrumenting a class only affects that class and its subclasses.

What gets recorded

Each response.create sent over a connection is recorded with the same streaming response from {model} took {duration}s log that streamed HTTP Responses calls produce. It has the same attributes: input and output messages, system instructions, request parameters, response id and model, usage and cost. The request attributes come from a helper shared with the HTTP /responses path, so both stay consistent.

Requests are captured from connection.response.create(...), connection.send(...) (dict or model), and manager.send(...) before the connection opens.

There's no separate request span, unlike HTTP. Over HTTP, the request span only lasts until the headers arrive, and the content goes on the streaming log. Over WebSocket, response.create() only writes to an open socket and returns immediately, so a span there would be empty. The log's duration runs from sending response.create to the final event. Happy to change this if you'd prefer a span per response.

Concurrent responses

One connection can run several responses at once, one per stream_id lane. Requests on the same lane run in order, and server events carry their lane's stream_id. Each event is therefore routed to the oldest pending request on its lane.

Errors

These are logged at error level with error.type:

  • an error event from the server
  • a response.failed event (error.type is the API's error code)
  • an exception raised inside with client.responses.connect() as conn:

If send raises, the request is removed again, so it doesn't take the next response. Requests that aren't recorded (suppressed instrumentation, or inside an OpenAI Agents span) keep their place in their lane, so their responses aren't assigned to later requests.

A connection closed after a response started but before it finished still records what was received. Requests that never received any event are dropped.

Tests

A local websockets server stands in for OpenAI, so no API key or recorded requests are needed. The tests cover:

  • sync and async connections
  • several turns on one connection
  • two lanes running at once with interleaved events
  • a request queued on the manager before connecting, answered with an error
  • an exception or an early close mid-response
  • suppressed instrumentation and OpenAI Agents spans
  • instrumenting the classes instead of a client
  • turning the instrumentation off again