agents icon indicating copy to clipboard operation
agents copied to clipboard

Responses HTTP stream that ends before response.completed is treated as a successful reply

Open HYYAlex opened this issue 1 week ago • 0 comments

Bug Description

On the HTTP (SSE) transport of the Responses engine, a stream whose body ends before any terminal event (response.completed, response.failed or response.incomplete) finishes normally. The caller gets the partial text and no error, so a reply that was cut off mid-stream (an upstream or proxy closing the body early, for example) looks the same as a complete one.

The WebSocket transport in the same function already handles this: after the event loop it checks self._response_completed and raises APIConnectionError, marked non-retryable if text already reached the caller. The HTTP branch has no such check and just returns when async for event in stream runs out.

This affects openai.responses.LLM(use_websocket=False), openai.responses.LLM with a custom client (which forces HTTP), and inference.responses.LLM, whose default is HTTP.

finished normally, text = 'Setting the temperature to'

Expected Behavior

Same as the WebSocket transport: if the stream ends without a terminal event, raise APIConnectionError. Keep it retryable when nothing has been sent to the caller yet, and non-retryable once text has been streamed, so a retry doesn't repeat it.

Reproduction Steps

# Fully offline: an httpx MockTransport returns an SSE body that stops after a text delta.
# Save as repro.py and run: python repro.py
import asyncio
import json

import httpx2 as httpx  # the HTTP client package the openai SDK depends on
import openai

from livekit.agents import llm
from livekit.plugins.openai.responses import LLM

RESPONSE = {"id": "resp_1", "created_at": 0, "model": "gpt-4.1", "object": "response",
            "output": [], "parallel_tool_calls": False, "tool_choice": "auto", "tools": []}
# The body ends after a text delta: no response.completed / failed / incomplete
EVENTS = [
    {"type": "response.created", "sequence_number": 0,
     "response": {**RESPONSE, "status": "in_progress"}},
    {"type": "response.output_text.delta", "sequence_number": 1, "item_id": "msg_1",
     "output_index": 0, "content_index": 0, "delta": "Setting the temperature to", "logprobs": []},
]


def handler(request: httpx.Request) -> httpx.Response:
    body = "".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n" for e in EVENTS)
    return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body)


async def main() -> None:
    http_client = httpx.AsyncClient(transport=httpx.MockTransport(handler))
    client = openai.AsyncOpenAI(api_key="unused", base_url="https://offline.invalid/v1",
                                http_client=http_client)
    model = LLM(model="gpt-4.1", client=client, use_websocket=False)
    ctx = llm.ChatContext()
    ctx.add_message(role="user", content="Set the room temperature to 21 degrees.")
    text = ""
    try:
        async with model.chat(chat_ctx=ctx) as stream:
            async for chunk in stream:
                if chunk.delta and chunk.delta.content:
                    text += chunk.delta.content
        print("finished normally, text =", repr(text))
    except Exception as e:
        print("raised", repr(e), "after text =", repr(text))
    await model.aclose()


asyncio.run(main())

# Output on main (8dc939027):
#   finished normally, text = 'Setting the temperature to'
# Expected: an APIConnectionError (retryable=False, since text was already streamed).
# Adding a response.completed event to EVENTS is the control: it finishes normally either way.

Operating System

macOS 26.6 (arm64)

Models Used

OpenAI Responses over HTTP (livekit.plugins.openai.responses.LLM, gpt-4.1 in the repro); inference.responses.LLM uses the same code path by default

Package Versions

livekit-agents: main @ 8dc9390276a8d50ea10eec8cf7a7e836cac30f65 (1.8.13)
livekit-plugins-openai: same checkout
livekit==1.2.1
openai==3.51.0
Python 3.12.16

Session/Room/Call IDs

No response

Proposed Solution

# In ResponsesLLMStream._run_impl, HTTP branch, mirror the WebSocket check after the loop.
# The existing `except (APIConnectionError, ...)` clause then clears `retryable` if text
# was already sent.
async with stream:
    async for event in stream:
        ...

if not self._response_completed:
    # the body ended without response.completed/failed/incomplete
    raise APIConnectionError(retryable=True)

Additional Context

Relevant code on main:

  • WebSocket branch: checks _response_completed after the loop and raises.
  • HTTP branch: returns as soon as the SSE iterator is exhausted.
  • _response_completed is only set in _handle_response_completed; response.failed and response.incomplete raise, so after the loop it is false only when no terminal event arrived.

This is about the iterator ending cleanly (EOF). A connection error raised by the HTTP library is already turned into APIConnectionError by the existing except Exception clause.

Related but different: #7013 is the WebSocket transport not exiting after it did receive response.incomplete.

I'm happy to send a PR with the fix and a regression test.

AI disclosure: I used an AI assistant to help investigate this and draft the report. I ran the reproduction myself and checked the output.

Screenshots and Recordings

No response

HYYAlex avatar Nov 20 '26 14:11 HYYAlex