litellm/tests/e2e/llm_translation/test_responses_retrieve_e2e.py
yuneng-jiang 7d50a31eb5
test(e2e): move live-provider legacy tests into tests/e2e (#44120)
* test(e2e): move live-provider legacy tests into tests/e2e

Port legacy tests that exercise real providers into the tests/e2e suites that own them, using the harness (/model/new plus deferred cleanup) and asserting on what the caller receives. Delete legacy tests already covered at equal or stronger strength by e2e, integration or unit tests, and drop the now empty ocr_testing CircleCI job

* test(e2e): address review on the live-provider test move

Assert the SSE error frame a client actually receives when a post_call guardrail blocks a stream, and require a tool call for every requested city before checking the answer. Restore the OCR matrix and its CircleCI job, the Claude Agent SDK streaming test, and test_async_create_batch, since their SDK-level and callback assertions have no equivalent in tests/e2e

* test(e2e): accept both guardrail block shapes on a blocked stream

A post_call block before the first chunk reaches the client as HTTP 400 with either a JSON error body or a single SSE error frame, depending on whether the block surfaced as an exception or an error chunk. Assert the policy message is present and the blocked output is absent in both

* test(realtime): restore direct SDK realtime tests against OpenAI

The e2e realtime tests go through the proxy and the remaining SDK tests either mock the upstream or assert less, so keep the direct litellm._arealtime tests with and without intent, and TestOpenAIRealtime::test_realtime_connection, in place

* test: make realtime and Nova stream checks deterministic

The direct SDK realtime tests now fail on a refused connection instead of skipping. The with-intent test asserts OpenAI rejects the exact intent value sent, which only happens when the intent is forwarded. The Nova /v1/messages stream test asserts stream structure, stop reason and usage instead of model wording

* test(realtime): own intent forwarding with a unit test instead of a live rejection

Assert litellm._arealtime passes the intent query param into the OpenAI realtime websocket URL, which is the behavior LiteLLM owns, and drop the live test that depended on OpenAI's rejection wording
2026-10-02 00:02:18 -07:00

209 lines
8.1 KiB
Python

"""Vendor §9.9: GET /v1/responses/{id} retrieve after store (LIT-4778).
Creates a stored response, retrieves it by id, and pins invalid-id error handling.
"""
from __future__ import annotations
import time
from typing import Final
import openai
import pytest
from e2e_config import POLL_INTERVAL, POLL_TIMEOUT, unique_marker
from e2e_http import NoBody, Success, UnknownApiError, unwrap
from lifecycle import ResourceManager
from models import LiteLLMParamsBody
from openai.types.responses import (
ResponseCreatedEvent,
ResponseInputMessageItem,
ResponseInputText,
ResponseQueuedEvent,
)
from proxy_client import ProxyClient
from pydantic import BaseModel
from sdk_clients import NO_PROXY_CACHE, SdkClients
pytestmark = pytest.mark.e2e
OPENAI_BACKEND: Final = "openai/gpt-5.5"
LONG_TASK: Final = "Write a numbered list counting from 1 to 400, one number per line, with a short word after each."
CANCELLABLE_STATUSES: Final = frozenset({"queued", "in_progress"})
class ResponsesCreateBody(BaseModel):
model: str
input: str
store: bool = True
stream: bool = False
max_output_tokens: int = 64
class ResponsesObject(BaseModel):
id: str
object: str | None = None
status: str | None = None
def _retrieve_response(proxy: ProxyClient, key: str, response_id: str) -> ResponsesObject:
deadline = time.monotonic() + POLL_TIMEOUT
while time.monotonic() < deadline:
result = proxy.transport.get(
f"/v1/responses/{response_id}",
headers=proxy.transport.bearer(key),
params=NoBody(),
response_type=ResponsesObject,
)
match result:
case Success(data=response):
return response
case UnknownApiError(status_code=404):
time.sleep(POLL_INTERVAL)
case other:
raise AssertionError(f"unexpected retrieve result: {other!r}")
raise AssertionError(f"response {response_id!r} was not retrievable within {POLL_TIMEOUT}s")
class TestResponsesRetrieve:
@pytest.mark.skip(
reason="stage red: product gap (LIT-5446), retrieve returns a different id than the stored response (non-idempotent response-id re-encryption)"
)
@pytest.mark.covers("llm.responses.openai.basic.nonstream.works")
def test_store_and_retrieve_by_id(self, proxy: ProxyClient, resources: ResourceManager) -> None:
model = f"e2e-resp-store-{unique_marker()}"
model_id = proxy.create_model(
model,
LiteLLMParamsBody(model="openai/gpt-4o-mini", api_key="os.environ/OPENAI_API_KEY"),
)
resources.defer(lambda: proxy.delete_model(model_id))
key = resources.key()
created = unwrap(
proxy.transport.post(
"/v1/responses",
headers=proxy.transport.bearer(key),
json=ResponsesCreateBody(
model=model,
input=f"Say pong. {unique_marker()}",
store=True,
),
response_type=ResponsesObject,
)
)
assert created.id, f"create returned no id: {created}"
assert created.object == "response"
assert created.status == "completed"
retrieved = _retrieve_response(proxy, key, created.id)
assert retrieved.id == created.id
assert retrieved.object == "response"
assert retrieved.status == "completed"
@pytest.mark.skip(
reason="stage red: product gap (LIT-5447), retrieving an unknown response id returns 400 (model=None) instead of 404"
)
@pytest.mark.covers("llm.responses.openai.input_validation.nonstream.works")
def test_invalid_response_id_returns_error(self, proxy: ProxyClient, resources: ResourceManager) -> None:
key = resources.key()
get_result = proxy.transport.get(
"/v1/responses/resp_00000000000000000000000000000000",
headers=proxy.transport.bearer(key),
params=NoBody(),
response_type=ResponsesObject,
)
match get_result:
case Success():
pytest.fail("invalid response id must not succeed")
case UnknownApiError(status_code=404):
return
case other:
pytest.fail(f"invalid response id expected 404, got {other!r}")
def _register_openai(proxy: ProxyClient, resources: ResourceManager, prefix: str) -> str:
model = f"{prefix}-{unique_marker()}"
model_id = proxy.create_model(model, LiteLLMParamsBody(model=OPENAI_BACKEND, api_key="os.environ/OPENAI_API_KEY"))
resources.defer(lambda: proxy.delete_model(model_id))
return model
def _input_texts(item: object) -> tuple[str, ...]:
if not isinstance(item, ResponseInputMessageItem):
return ()
return tuple(part.text for part in item.content if isinstance(part, ResponseInputText))
@pytest.mark.provider_live
class TestStoredResponseLifecycle:
def test_input_items_list_the_stored_prompt(
self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
model = _register_openai(proxy, resources, "e2e-resp-items")
client = sdk.openai(resources.key())
marker = unique_marker()
created = client.responses.create(
model=model, input=f"Reply with one word. {marker}", store=True, extra_body=NO_PROXY_CACHE
)
items = client.responses.input_items.list(created.id, limit=20, order="desc").data
texts = tuple(text for item in items for text in _input_texts(item))
assert any(marker in text for text in texts), f"input_items did not list the stored prompt: {items!r}"
def test_deleted_response_is_no_longer_retrievable(
self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
model = _register_openai(proxy, resources, "e2e-resp-delete")
client = sdk.openai(resources.key())
created = client.responses.create(
model=model, input=f"Reply with one word. {unique_marker()}", store=True, extra_body=NO_PROXY_CACHE
)
retrieved = client.responses.retrieve(created.id)
assert retrieved.status == "completed", f"stored response not retrievable as completed: {retrieved!r}"
client.responses.delete(created.id)
with pytest.raises(openai.APIStatusError) as gone:
client.responses.retrieve(created.id)
assert 400 <= gone.value.status_code < 500, f"retrieve after delete expected a 4xx: {gone.value!r}"
@pytest.mark.provider_live
class TestBackgroundResponseCancel:
def test_cancel_background_response(
self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
model = _register_openai(proxy, resources, "e2e-resp-cancel")
client = sdk.openai(resources.key())
created = client.responses.create(
model=model, input=f"{LONG_TASK} {unique_marker()}", background=True, extra_body=NO_PROXY_CACHE
)
assert created.status in CANCELLABLE_STATUSES, f"background response was not queued: {created.status}"
cancelled = client.responses.cancel(created.id)
assert cancelled.status == "cancelled", f"cancel did not stop the response: {cancelled.status}"
def test_cancel_background_streaming_response_by_streamed_id(
self, proxy: ProxyClient, resources: ResourceManager, sdk: SdkClients
) -> None:
model = _register_openai(proxy, resources, "e2e-resp-cancel-stream")
client = sdk.openai(resources.key())
stream = client.responses.create(
model=model,
input=f"{LONG_TASK} {unique_marker()}",
background=True,
stream=True,
extra_body=NO_PROXY_CACHE,
)
response_id = next(
(event.response.id for event in stream if isinstance(event, (ResponseCreatedEvent, ResponseQueuedEvent))),
None,
)
stream.close()
assert response_id, "background stream advertised no response id before the first output"
cancelled = client.responses.cancel(response_id)
assert cancelled.status == "cancelled", f"cancel by streamed id did not stop the response: {cancelled.status}"