fix(image): use standalone Codex Images API (#6177)
* fix(image): use standalone Codex Images API * docs(image): keep Codex setup focused on user actions
This commit is contained in:
1 parent
73af08efab
commit
bdfc8f7bd4
4 files changed
+126
-383
No files matched your search
@@ -42,14 +42,12 @@ class FakeResponse:
|
||||
payload: dict[str, Any],
|
||||
status_code: int = 200,
|
||||
content: bytes = b"",
|
||||
sse_lines: list[str] | None = None,
|
||||
) -> None:
|
||||
self._payload = payload
|
||||
self.status_code = status_code
|
||||
self.text = str(payload)
|
||||
self.content = content
|
||||
self.request = httpx.Request("POST", "https://openrouter.ai/api/v1/chat/completions")
|
||||
self._sse_lines = sse_lines
|
||||
|
||||
def json(self) -> dict[str, Any]:
|
||||
return self._payload
|
||||
@@ -59,15 +57,6 @@ class FakeResponse:
|
||||
response = httpx.Response(self.status_code, request=self.request, text=self.text)
|
||||
raise httpx.HTTPStatusError("failed", request=self.request, response=response)
|
||||
|
||||
async def aiter_lines(self):
|
||||
if self._sse_lines is not None:
|
||||
for line in self._sse_lines:
|
||||
yield line
|
||||
return
|
||||
# Fallback: treat response text as SSE lines
|
||||
for line in self.text.split("\n"):
|
||||
yield line
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, response: FakeResponse) -> None:
|
||||
@@ -85,23 +74,6 @@ class FakeClient:
|
||||
return self.get_response
|
||||
|
||||
|
||||
class CodexStreamingCompleteThenErrorResponse(FakeResponse):
|
||||
async def aiter_lines(self):
|
||||
yield 'data: {"type":"response.output_item.added","item":{"id":"ig_1","type":"image_generation_call","status":"in_progress"}}'
|
||||
yield ""
|
||||
yield (
|
||||
f'data: {{"type":"response.output_item.done","item":{{"id":"ig_1",'
|
||||
f'"type":"image_generation_call","result":"{PNG_DATA_URL}","status":"completed"}}}}'
|
||||
)
|
||||
yield ""
|
||||
yield 'data: {"type":"response.completed","response":{"status":"completed"}}'
|
||||
yield ""
|
||||
raise httpx.RemoteProtocolError(
|
||||
"peer closed connection without sending complete message body "
|
||||
"(incomplete chunked read)"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def generated_image_downloads(monkeypatch) -> list[tuple[str, str | None]]:
|
||||
"""Keep provider response parsing tests independent from outbound HTTP."""
|
||||
@@ -1238,82 +1210,61 @@ async def test_custom_generate_http_error() -> None:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_codex_payload_and_response(monkeypatch) -> None:
|
||||
@pytest.fixture
|
||||
def codex_oauth(monkeypatch):
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
|
||||
@dataclass
|
||||
class FakeToken:
|
||||
account_id: str = "acct-123"
|
||||
access: str = "oauth-token"
|
||||
calls: list[dict[str, Any]] = []
|
||||
|
||||
async def fake_to_thread(fn, *args, **kwargs):
|
||||
return fn(*args, **kwargs)
|
||||
def get_token(**kwargs):
|
||||
calls.append(kwargs)
|
||||
return SimpleNamespace(account_id="acct-123", access="oauth-token")
|
||||
|
||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
||||
fake_oauth = SimpleNamespace(get_token=lambda: FakeToken())
|
||||
monkeypatch.setitem(sys.modules, "oauth_cli_kit", fake_oauth)
|
||||
monkeypatch.setitem(sys.modules, "oauth_cli_kit", SimpleNamespace(get_token=get_token))
|
||||
return calls
|
||||
|
||||
sse_lines = [
|
||||
'data: {"type":"response.output_item.added","item":{"id":"ig_1","type":"image_generation_call","status":"in_progress"}}',
|
||||
"",
|
||||
f'data: {{"type":"response.output_item.done","item":{{"id":"ig_1","type":"image_generation_call","result":"{PNG_DATA_URL}","status":"completed"}}}}',
|
||||
"",
|
||||
'data: [DONE]',
|
||||
"",
|
||||
]
|
||||
fake = FakeClient(FakeResponse({}, sse_lines=sse_lines))
|
||||
client = CodexImageGenerationClient(
|
||||
api_key=None,
|
||||
api_base="https://chatgpt.com/backend-api",
|
||||
extra_headers={"X-Test": "1"},
|
||||
client=fake, # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
response = await client.generate(
|
||||
prompt="draw a cat",
|
||||
model="gpt-5.4",
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("base", [
|
||||
"https://chatgpt.com/backend-api",
|
||||
"https://chatgpt.com/backend-api/codex/",
|
||||
])
|
||||
async def test_codex_payload_and_response(codex_oauth, base: str) -> None:
|
||||
import json
|
||||
|
||||
requests: list[httpx.Request] = []
|
||||
payload = {"created": 1778832973, "data": [{"b64_json": PNG_DATA_URL.split(",")[1]}]}
|
||||
|
||||
def handle(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request)
|
||||
return httpx.Response(200, json=payload)
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as http:
|
||||
client = CodexImageGenerationClient(
|
||||
api_key=None, api_base=base, extra_headers={"X-Test": "1"}, client=http,
|
||||
)
|
||||
response = await client.generate(prompt="draw a cat", model=client.model_options[0])
|
||||
|
||||
assert response.images == [PNG_DATA_URL]
|
||||
assert response.content == ""
|
||||
call = fake.calls[0]
|
||||
assert call["url"] == "https://chatgpt.com/backend-api/codex/responses"
|
||||
assert call["headers"]["Authorization"] == "Bearer oauth-token"
|
||||
assert call["headers"]["chatgpt-account-id"] == "acct-123"
|
||||
assert call["headers"]["OpenAI-Beta"] == "responses=experimental"
|
||||
assert call["headers"]["X-Test"] == "1"
|
||||
body = call["json"]
|
||||
assert body["model"] == "gpt-5.4"
|
||||
assert body["instructions"] == "Generate an image based on the user's request."
|
||||
assert body["input"] == [{"role": "user", "content": "draw a cat"}]
|
||||
assert body["tools"] == [{"type": "image_generation"}]
|
||||
assert body["tool_choice"] == "auto"
|
||||
assert body["store"] is False
|
||||
assert body["stream"] is True
|
||||
assert response.raw == payload
|
||||
request = requests[0]
|
||||
assert str(request.url) == "https://chatgpt.com/backend-api/codex/images/generations"
|
||||
assert request.headers["Authorization"] == "Bearer oauth-token"
|
||||
assert request.headers["chatgpt-account-id"] == "acct-123"
|
||||
assert request.headers["X-Test"] == "1"
|
||||
assert json.loads(request.content) == {
|
||||
"model": "gpt-image-2", "prompt": "draw a cat",
|
||||
"background": "opaque", "quality": "auto", "size": "auto",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_codex_proxy_applies_to_oauth_and_http(monkeypatch) -> None:
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
|
||||
async def test_codex_proxy_applies_to_oauth_and_http(monkeypatch, codex_oauth) -> None:
|
||||
proxy = "http://127.0.0.1:23458"
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
async def fake_to_thread(fn, *args, **kwargs):
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
def fake_get_token(*, proxy=None):
|
||||
captured["token_proxy"] = proxy
|
||||
return SimpleNamespace(account_id="acct-123", access="oauth-token")
|
||||
|
||||
fake_oauth = SimpleNamespace(get_token=fake_get_token)
|
||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
||||
monkeypatch.setitem(sys.modules, "oauth_cli_kit", fake_oauth)
|
||||
|
||||
class FakeAsyncClient:
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
captured["client_kwargs"] = kwargs
|
||||
@@ -1326,90 +1277,46 @@ async def test_codex_proxy_applies_to_oauth_and_http(monkeypatch) -> None:
|
||||
|
||||
async def post(self, url: str, **kwargs: Any) -> FakeResponse:
|
||||
captured["request"] = {"url": url, **kwargs}
|
||||
return FakeResponse(
|
||||
{},
|
||||
sse_lines=[
|
||||
f'data: {{"type":"response.output_item.done","item":{{"type":"image_generation_call","result":"{PNG_DATA_URL}"}}}}',
|
||||
"",
|
||||
"data: [DONE]",
|
||||
"",
|
||||
],
|
||||
)
|
||||
return FakeResponse({"data": [{"b64_json": PNG_DATA_URL.split(",")[1]}]})
|
||||
|
||||
monkeypatch.setattr(
|
||||
"nanobot.providers.image_generation.httpx.AsyncClient",
|
||||
FakeAsyncClient,
|
||||
)
|
||||
monkeypatch.setattr("nanobot.providers.image_generation.httpx.AsyncClient", FakeAsyncClient)
|
||||
client = CodexImageGenerationClient(api_key=None, proxy=proxy)
|
||||
|
||||
response = await client.generate(prompt="draw", model="gpt-5.4")
|
||||
|
||||
response = await client.generate(prompt="draw", model="gpt-image-2")
|
||||
assert response.images == [PNG_DATA_URL]
|
||||
assert captured["token_proxy"] == proxy
|
||||
assert codex_oauth == [{"proxy": proxy}]
|
||||
assert captured["client_kwargs"]["proxy"] == proxy
|
||||
assert captured["client_kwargs"]["trust_env"] is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_codex_stops_reading_after_completed_event(monkeypatch) -> None:
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
|
||||
@dataclass
|
||||
class FakeToken:
|
||||
account_id: str = "acct-123"
|
||||
access: str = "oauth-token"
|
||||
|
||||
async def fake_to_thread(fn, *args, **kwargs):
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
||||
fake_oauth = SimpleNamespace(get_token=lambda: FakeToken())
|
||||
monkeypatch.setitem(sys.modules, "oauth_cli_kit", fake_oauth)
|
||||
|
||||
fake = FakeClient(CodexStreamingCompleteThenErrorResponse({}, sse_lines=[]))
|
||||
@pytest.mark.parametrize("prefix", ["openai-codex", "openai_codex"])
|
||||
async def test_codex_edit_reference_images_and_options(codex_oauth, tmp_path, prefix) -> None:
|
||||
reference = tmp_path / "reference.png"
|
||||
reference.write_bytes(PNG_BYTES)
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": PNG_DATA_URL.split(",")[1]}]}))
|
||||
client = CodexImageGenerationClient(
|
||||
api_key=None, client=fake # type: ignore[arg-type]
|
||||
api_key=None, extra_body={"quality": "high", "background": None},
|
||||
client=fake, # type: ignore[arg-type]
|
||||
)
|
||||
response = await client.generate(
|
||||
prompt="add a hat", model=f"{prefix}/gpt-image-2",
|
||||
reference_images=[str(reference)], aspect_ratio="16:9",
|
||||
)
|
||||
|
||||
response = await client.generate(prompt="draw a cat", model="gpt-5.4")
|
||||
|
||||
assert response.images == [PNG_DATA_URL]
|
||||
assert response.content == ""
|
||||
assert fake.calls[0]["url"] == "https://chatgpt.com/backend-api/codex/images/edits"
|
||||
assert fake.calls[0]["json"] == {
|
||||
"model": "gpt-image-2", "prompt": "add a hat", "quality": "high",
|
||||
"size": "1536x1024",
|
||||
"images": [{"image_url": "data:image/png;base64," + base64.b64encode(PNG_BYTES).decode()}],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_codex_strips_model_prefix(monkeypatch) -> None:
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
|
||||
@dataclass
|
||||
class FakeToken:
|
||||
account_id: str = "acct-123"
|
||||
access: str = "oauth-token"
|
||||
|
||||
async def fake_to_thread(fn, *args, **kwargs):
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
||||
fake_oauth = SimpleNamespace(get_token=lambda: FakeToken())
|
||||
monkeypatch.setitem(sys.modules, "oauth_cli_kit", fake_oauth)
|
||||
|
||||
fake = FakeClient(FakeResponse({}, sse_lines=[
|
||||
f'data: {{"type":"response.output_item.done","item":{{"type":"image_generation_call","result":"{PNG_DATA_URL}"}}}}',
|
||||
"",
|
||||
'data: [DONE]',
|
||||
"",
|
||||
]))
|
||||
client = CodexImageGenerationClient(
|
||||
api_key=None, client=fake # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
await client.generate(prompt="draw", model="openai-codex/gpt-5.4")
|
||||
|
||||
assert fake.calls[0]["json"]["model"] == "gpt-5.4"
|
||||
async def test_codex_explicit_size(codex_oauth) -> None:
|
||||
fake = FakeClient(FakeResponse({"data": [{"b64_json": PNG_DATA_URL.split(",")[1]}]}))
|
||||
client = CodexImageGenerationClient(api_key=None, client=fake) # type: ignore[arg-type]
|
||||
await client.generate(prompt="draw", model="gpt-image-2", image_size="2048x1152")
|
||||
assert fake.calls[0]["json"]["size"] == "2048x1152"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -1418,115 +1325,25 @@ async def test_codex_requires_oauth(monkeypatch) -> None:
|
||||
raise RuntimeError("no token")
|
||||
|
||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
||||
|
||||
client = CodexImageGenerationClient(api_key=None)
|
||||
|
||||
with pytest.raises(ImageGenerationError, match="OAuth token"):
|
||||
await client.generate(prompt="draw", model="gpt-5.4")
|
||||
await client.generate(prompt="draw", model="gpt-image-2")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_codex_no_images_raises(monkeypatch) -> None:
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
|
||||
@dataclass
|
||||
class FakeToken:
|
||||
account_id: str = "acct-123"
|
||||
access: str = "oauth-token"
|
||||
|
||||
async def fake_to_thread(fn, *args, **kwargs):
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
||||
fake_oauth = SimpleNamespace(get_token=lambda: FakeToken())
|
||||
monkeypatch.setitem(sys.modules, "oauth_cli_kit", fake_oauth)
|
||||
|
||||
fake = FakeClient(FakeResponse({}, sse_lines=[
|
||||
'data: {"type":"response.completed","response":{"status":"completed"}}',
|
||||
"",
|
||||
'data: [DONE]',
|
||||
"",
|
||||
]))
|
||||
client = CodexImageGenerationClient(
|
||||
api_key=None, client=fake # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
async def test_codex_no_images_raises(codex_oauth) -> None:
|
||||
fake = FakeClient(FakeResponse({"data": []}))
|
||||
client = CodexImageGenerationClient(api_key=None, client=fake) # type: ignore[arg-type]
|
||||
with pytest.raises(ImageGenerationError, match="returned no images"):
|
||||
await client.generate(prompt="draw", model="gpt-5.4")
|
||||
await client.generate(prompt="draw", model="gpt-image-2")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_codex_extracts_text_content(monkeypatch) -> None:
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
|
||||
@dataclass
|
||||
class FakeToken:
|
||||
account_id: str = "acct-123"
|
||||
access: str = "oauth-token"
|
||||
|
||||
async def fake_to_thread(fn, *args, **kwargs):
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
||||
fake_oauth = SimpleNamespace(get_token=lambda: FakeToken())
|
||||
monkeypatch.setitem(sys.modules, "oauth_cli_kit", fake_oauth)
|
||||
|
||||
fake = FakeClient(FakeResponse({}, sse_lines=[
|
||||
'data: {"type":"response.output_text.delta","delta":"Here "}',
|
||||
"",
|
||||
'data: {"type":"response.output_text.delta","delta":"is your cat image."}',
|
||||
"",
|
||||
f'data: {{"type":"response.output_item.done","item":{{"type":"image_generation_call","result":"{PNG_DATA_URL}"}}}}',
|
||||
"",
|
||||
'data: [DONE]',
|
||||
"",
|
||||
]))
|
||||
client = CodexImageGenerationClient(
|
||||
api_key=None, client=fake # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
response = await client.generate(prompt="draw a cat", model="gpt-5.4")
|
||||
|
||||
assert response.images == [PNG_DATA_URL]
|
||||
assert response.content == "Here is your cat image."
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_codex_json_result_format(monkeypatch) -> None:
|
||||
"""image_generation_call result can be a dict with image_url key."""
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from types import SimpleNamespace
|
||||
|
||||
@dataclass
|
||||
class FakeToken:
|
||||
account_id: str = "acct-123"
|
||||
access: str = "oauth-token"
|
||||
|
||||
async def fake_to_thread(fn, *args, **kwargs):
|
||||
return fn(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
||||
fake_oauth = SimpleNamespace(get_token=lambda: FakeToken())
|
||||
monkeypatch.setitem(sys.modules, "oauth_cli_kit", fake_oauth)
|
||||
|
||||
fake = FakeClient(FakeResponse({}, sse_lines=[
|
||||
f'data: {{"type":"response.output_item.done","item":{{"type":"image_generation_call","result":{{"image_url":"{PNG_DATA_URL}"}}}}}}',
|
||||
"",
|
||||
'data: [DONE]',
|
||||
"",
|
||||
]))
|
||||
client = CodexImageGenerationClient(
|
||||
api_key=None, client=fake # type: ignore[arg-type]
|
||||
)
|
||||
|
||||
response = await client.generate(prompt="draw", model="gpt-5.4")
|
||||
|
||||
assert response.images == [PNG_DATA_URL]
|
||||
async def test_codex_http_error(codex_oauth) -> None:
|
||||
fake = FakeClient(FakeResponse({"error": {"message": "image quota exceeded"}}, status_code=429))
|
||||
client = CodexImageGenerationClient(api_key=None, client=fake) # type: ignore[arg-type]
|
||||
with pytest.raises(ImageGenerationError, match="HTTP 429.*image quota exceeded"):
|
||||
await client.generate(prompt="draw", model="gpt-image-2")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -140,7 +140,7 @@ def test_image_generation_tool_passes_provider_proxy_to_client(
|
||||
config=ImageGenerationToolConfig(
|
||||
enabled=True,
|
||||
provider="openai_codex",
|
||||
model="openai-codex/gpt-5.4",
|
||||
model="openai-codex/gpt-image-2",
|
||||
),
|
||||
provider_configs={"openai_codex": ProviderConfig(proxy=proxy)},
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user