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
@@ -96,6 +96,26 @@ OpenRouter uses a chat-completions style image response. Configure:
|
|||||||
|
|
||||||
Use a model that supports image generation and image editing if you want reference-image edits.
|
Use a model that supports image generation and image editing if you want reference-image edits.
|
||||||
|
|
||||||
|
### OpenAI Codex
|
||||||
|
|
||||||
|
Log in with `nanobot provider login openai-codex`, then select **OpenAI Codex** and `gpt-image-2` under **Settings → Image**. Image generation uses your Codex subscription.
|
||||||
|
|
||||||
|
For manual configuration:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"tools": {
|
||||||
|
"imageGeneration": {
|
||||||
|
"enabled": true,
|
||||||
|
"provider": "openai_codex",
|
||||||
|
"model": "gpt-image-2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use Codex to generate images from text or edit existing images with reference images.
|
||||||
|
|
||||||
### Custom (OpenAI-compatible)
|
### Custom (OpenAI-compatible)
|
||||||
|
|
||||||
The `custom` image provider fits services that implement the synchronous OpenAI Images API:
|
The `custom` image provider fits services that implement the synchronous OpenAI Images API:
|
||||||
|
|||||||
@@ -1371,13 +1371,13 @@ class CustomImageGenerationClient(ImageGenerationProvider):
|
|||||||
class CodexImageGenerationClient(ImageGenerationProvider):
|
class CodexImageGenerationClient(ImageGenerationProvider):
|
||||||
"""OpenAI image generation via Codex subscription OAuth.
|
"""OpenAI image generation via Codex subscription OAuth.
|
||||||
|
|
||||||
Uses the Codex Responses API with the ``image_generation`` tool
|
Uses the standalone Codex Images API, matching the official Codex
|
||||||
(the same mechanism ChatGPT uses internally). No API key required —
|
image-generation extension. The Codex OAuth token from ``oauth_cli_kit``
|
||||||
the Codex OAuth token from ``oauth_cli_kit`` is used instead.
|
authenticates requests without an API key.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
provider_name = "openai_codex"
|
provider_name = "openai_codex"
|
||||||
model_options = ("gpt-5.4",)
|
model_options = ("gpt-image-2",)
|
||||||
missing_key_message = (
|
missing_key_message = (
|
||||||
"Codex OAuth token is unavailable. "
|
"Codex OAuth token is unavailable. "
|
||||||
"Log in with Codex subscription first."
|
"Log in with Codex subscription first."
|
||||||
@@ -1417,63 +1417,56 @@ class CodexImageGenerationClient(ImageGenerationProvider):
|
|||||||
if not token or not token.access:
|
if not token or not token.access:
|
||||||
raise ImageGenerationError(self.missing_key_message)
|
raise ImageGenerationError(self.missing_key_message)
|
||||||
|
|
||||||
logger.info(
|
|
||||||
"Using Codex OAuth token for image generation (account: {})",
|
|
||||||
token.account_id,
|
|
||||||
)
|
|
||||||
|
|
||||||
if reference_images:
|
|
||||||
logger.warning(
|
|
||||||
"Codex image generation does not support reference images; "
|
|
||||||
"ignoring {} reference image(s)",
|
|
||||||
len(reference_images),
|
|
||||||
)
|
|
||||||
|
|
||||||
headers: dict[str, str] = {
|
headers: dict[str, str] = {
|
||||||
"Authorization": f"Bearer {token.access}",
|
"Authorization": f"Bearer {token.access}",
|
||||||
"chatgpt-account-id": str(token.account_id),
|
"chatgpt-account-id": str(token.account_id),
|
||||||
"OpenAI-Beta": "responses=experimental",
|
|
||||||
"originator": "nanobot",
|
"originator": "nanobot",
|
||||||
"User-Agent": "nanobot (python)",
|
"User-Agent": "nanobot (python)",
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
**self.extra_headers,
|
**self.extra_headers,
|
||||||
}
|
}
|
||||||
|
clean_model = self._codex_model(model)
|
||||||
body: dict[str, Any] = {
|
body: dict[str, Any] = {
|
||||||
"model": self._codex_model(model),
|
"model": clean_model,
|
||||||
"instructions": "Generate an image based on the user's request.",
|
"prompt": prompt,
|
||||||
"input": [{"role": "user", "content": prompt}],
|
"background": "opaque",
|
||||||
"tools": [{"type": "image_generation"}],
|
"quality": "auto",
|
||||||
"tool_choice": "auto",
|
"size": (
|
||||||
"stream": True,
|
_openai_size(clean_model, aspect_ratio, image_size)
|
||||||
"store": False,
|
if aspect_ratio or image_size else "auto"
|
||||||
|
),
|
||||||
}
|
}
|
||||||
body.update(self.extra_body)
|
body.update(self.extra_body)
|
||||||
|
body = {key: value for key, value in body.items() if value is not None}
|
||||||
|
endpoint = "generations"
|
||||||
|
if reference_images:
|
||||||
|
endpoint = "edits"
|
||||||
|
body["images"] = [
|
||||||
|
{"image_url": image_path_to_data_url(path)} for path in reference_images
|
||||||
|
]
|
||||||
|
|
||||||
logger.info("Codex Responses API request: POST {}/codex/responses body={}",
|
base = self.api_base
|
||||||
self.api_base, {k: v for k, v in body.items() if k != "input"})
|
if not base.endswith("/codex"):
|
||||||
|
base = f"{base}/codex"
|
||||||
response = await self._http_post(
|
response = await self._http_post(
|
||||||
f"{self.api_base}/codex/responses",
|
f"{base}/images/{endpoint}",
|
||||||
headers=headers,
|
headers=headers,
|
||||||
body=body,
|
body=body,
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response.raise_for_status()
|
response.raise_for_status()
|
||||||
except httpx.HTTPStatusError as exc:
|
except httpx.HTTPStatusError as exc:
|
||||||
detail = response.text[:1000]
|
detail = response.text[:1000]
|
||||||
logger.error("Codex Responses API error ({}): {}", response.status_code, detail)
|
|
||||||
raise ImageGenerationError(
|
raise ImageGenerationError(
|
||||||
f"Codex image generation failed (HTTP {response.status_code}): {detail}"
|
f"Codex image generation failed (HTTP {response.status_code}): {detail}"
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
images, content_text = await _parse_codex_sse_images(response)
|
payload = _as_json_object(response.json())
|
||||||
|
if payload is None:
|
||||||
raw = {"status": "completed"}
|
raise ImageGenerationError("Codex image generation returned an invalid JSON response")
|
||||||
self._require_images(images, raw)
|
images = await _openai_images_from_payload(payload, proxy=self.proxy)
|
||||||
|
self._require_images(images, payload)
|
||||||
return GeneratedImageResponse(images=images, content=content_text, raw=raw)
|
return GeneratedImageResponse(images=images, content="", raw=payload)
|
||||||
|
|
||||||
|
|
||||||
def _openai_size(
|
def _openai_size(
|
||||||
@@ -1572,93 +1565,6 @@ async def _openai_images_from_payload(
|
|||||||
return images
|
return images
|
||||||
|
|
||||||
|
|
||||||
async def _parse_codex_sse_images(
|
|
||||||
response: httpx.Response,
|
|
||||||
) -> tuple[list[str], str]:
|
|
||||||
"""Parse a Codex Responses API SSE stream for image generation output.
|
|
||||||
|
|
||||||
Returns ``(images, content_text)``.
|
|
||||||
"""
|
|
||||||
import json as _json
|
|
||||||
|
|
||||||
images: list[str] = []
|
|
||||||
text_parts: list[str] = []
|
|
||||||
|
|
||||||
buffer: list[str] = []
|
|
||||||
async for line_bytes in response.aiter_lines():
|
|
||||||
line = line_bytes.strip()
|
|
||||||
if line == "":
|
|
||||||
if buffer:
|
|
||||||
data_lines: list[str] = []
|
|
||||||
for bl in buffer:
|
|
||||||
if bl.startswith("data:"):
|
|
||||||
data_lines.append(bl[5:].strip())
|
|
||||||
buffer.clear()
|
|
||||||
if data_lines:
|
|
||||||
raw = "".join(data_lines)
|
|
||||||
if raw == "[DONE]":
|
|
||||||
break
|
|
||||||
try:
|
|
||||||
event = _as_json_object(_json.loads(raw))
|
|
||||||
except Exception:
|
|
||||||
continue
|
|
||||||
if event is None:
|
|
||||||
continue
|
|
||||||
ev_type = event.get("type", "")
|
|
||||||
if ev_type in ("error", "response.failed"):
|
|
||||||
logger.error("Codex SSE failure: {}", raw[:2000])
|
|
||||||
_collect_images_from_sse_event(event, images)
|
|
||||||
_collect_text_from_sse_event(event, text_parts)
|
|
||||||
if ev_type == "response.completed":
|
|
||||||
break
|
|
||||||
continue
|
|
||||||
buffer.append(line)
|
|
||||||
|
|
||||||
# flush remaining
|
|
||||||
if buffer:
|
|
||||||
data_lines = [bl[5:].strip() for bl in buffer if bl.startswith("data:")]
|
|
||||||
raw = "".join(data_lines)
|
|
||||||
if raw and raw != "[DONE]":
|
|
||||||
try:
|
|
||||||
event = _as_json_object(_json.loads(raw))
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
if event is not None:
|
|
||||||
_collect_images_from_sse_event(event, images)
|
|
||||||
_collect_text_from_sse_event(event, text_parts)
|
|
||||||
|
|
||||||
return images, "".join(text_parts).strip()
|
|
||||||
|
|
||||||
|
|
||||||
def _collect_images_from_sse_event(event: dict[str, Any], images: list[str]) -> None:
|
|
||||||
if event.get("type") != "response.output_item.done":
|
|
||||||
return
|
|
||||||
item = _as_json_object(event.get("item")) or {}
|
|
||||||
if item.get("type") != "image_generation_call":
|
|
||||||
return
|
|
||||||
result = item.get("result")
|
|
||||||
if isinstance(result, str):
|
|
||||||
if result.startswith("data:image/"):
|
|
||||||
images.append(result)
|
|
||||||
else:
|
|
||||||
images.append(_b64_image_data_url(result))
|
|
||||||
elif (result_object := _as_json_object(result)) is not None:
|
|
||||||
image_url = result_object.get("image_url") or result_object.get("image") or ""
|
|
||||||
if isinstance(image_url, str):
|
|
||||||
if image_url.startswith("data:image/"):
|
|
||||||
images.append(image_url)
|
|
||||||
else:
|
|
||||||
images.append(_b64_image_data_url(image_url))
|
|
||||||
|
|
||||||
|
|
||||||
def _collect_text_from_sse_event(event: dict[str, Any], text_parts: list[str]) -> None:
|
|
||||||
if event.get("type") == "response.output_text.delta":
|
|
||||||
delta = event.get("delta")
|
|
||||||
if isinstance(delta, str) and delta:
|
|
||||||
text_parts.append(delta)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
# StepFun (阶跃星辰) image generation
|
# StepFun (阶跃星辰) image generation
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -42,14 +42,12 @@ class FakeResponse:
|
|||||||
payload: dict[str, Any],
|
payload: dict[str, Any],
|
||||||
status_code: int = 200,
|
status_code: int = 200,
|
||||||
content: bytes = b"",
|
content: bytes = b"",
|
||||||
sse_lines: list[str] | None = None,
|
|
||||||
) -> None:
|
) -> None:
|
||||||
self._payload = payload
|
self._payload = payload
|
||||||
self.status_code = status_code
|
self.status_code = status_code
|
||||||
self.text = str(payload)
|
self.text = str(payload)
|
||||||
self.content = content
|
self.content = content
|
||||||
self.request = httpx.Request("POST", "https://openrouter.ai/api/v1/chat/completions")
|
self.request = httpx.Request("POST", "https://openrouter.ai/api/v1/chat/completions")
|
||||||
self._sse_lines = sse_lines
|
|
||||||
|
|
||||||
def json(self) -> dict[str, Any]:
|
def json(self) -> dict[str, Any]:
|
||||||
return self._payload
|
return self._payload
|
||||||
@@ -59,15 +57,6 @@ class FakeResponse:
|
|||||||
response = httpx.Response(self.status_code, request=self.request, text=self.text)
|
response = httpx.Response(self.status_code, request=self.request, text=self.text)
|
||||||
raise httpx.HTTPStatusError("failed", request=self.request, response=response)
|
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:
|
class FakeClient:
|
||||||
def __init__(self, response: FakeResponse) -> None:
|
def __init__(self, response: FakeResponse) -> None:
|
||||||
@@ -85,23 +74,6 @@ class FakeClient:
|
|||||||
return self.get_response
|
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)
|
@pytest.fixture(autouse=True)
|
||||||
def generated_image_downloads(monkeypatch) -> list[tuple[str, str | None]]:
|
def generated_image_downloads(monkeypatch) -> list[tuple[str, str | None]]:
|
||||||
"""Keep provider response parsing tests independent from outbound HTTP."""
|
"""Keep provider response parsing tests independent from outbound HTTP."""
|
||||||
@@ -1238,82 +1210,61 @@ async def test_custom_generate_http_error() -> None:
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.fixture
|
||||||
async def test_codex_payload_and_response(monkeypatch) -> None:
|
def codex_oauth(monkeypatch):
|
||||||
import sys
|
import sys
|
||||||
from dataclasses import dataclass
|
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
|
|
||||||
@dataclass
|
calls: list[dict[str, Any]] = []
|
||||||
class FakeToken:
|
|
||||||
account_id: str = "acct-123"
|
|
||||||
access: str = "oauth-token"
|
|
||||||
|
|
||||||
async def fake_to_thread(fn, *args, **kwargs):
|
def get_token(**kwargs):
|
||||||
return fn(*args, **kwargs)
|
calls.append(kwargs)
|
||||||
|
return SimpleNamespace(account_id="acct-123", access="oauth-token")
|
||||||
|
|
||||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
monkeypatch.setitem(sys.modules, "oauth_cli_kit", SimpleNamespace(get_token=get_token))
|
||||||
fake_oauth = SimpleNamespace(get_token=lambda: FakeToken())
|
return calls
|
||||||
monkeypatch.setitem(sys.modules, "oauth_cli_kit", fake_oauth)
|
|
||||||
|
|
||||||
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(
|
@pytest.mark.asyncio
|
||||||
prompt="draw a cat",
|
@pytest.mark.parametrize("base", [
|
||||||
model="gpt-5.4",
|
"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.images == [PNG_DATA_URL]
|
||||||
assert response.content == ""
|
assert response.content == ""
|
||||||
call = fake.calls[0]
|
assert response.raw == payload
|
||||||
assert call["url"] == "https://chatgpt.com/backend-api/codex/responses"
|
request = requests[0]
|
||||||
assert call["headers"]["Authorization"] == "Bearer oauth-token"
|
assert str(request.url) == "https://chatgpt.com/backend-api/codex/images/generations"
|
||||||
assert call["headers"]["chatgpt-account-id"] == "acct-123"
|
assert request.headers["Authorization"] == "Bearer oauth-token"
|
||||||
assert call["headers"]["OpenAI-Beta"] == "responses=experimental"
|
assert request.headers["chatgpt-account-id"] == "acct-123"
|
||||||
assert call["headers"]["X-Test"] == "1"
|
assert request.headers["X-Test"] == "1"
|
||||||
body = call["json"]
|
assert json.loads(request.content) == {
|
||||||
assert body["model"] == "gpt-5.4"
|
"model": "gpt-image-2", "prompt": "draw a cat",
|
||||||
assert body["instructions"] == "Generate an image based on the user's request."
|
"background": "opaque", "quality": "auto", "size": "auto",
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_codex_proxy_applies_to_oauth_and_http(monkeypatch) -> None:
|
async def test_codex_proxy_applies_to_oauth_and_http(monkeypatch, codex_oauth) -> None:
|
||||||
import sys
|
|
||||||
from types import SimpleNamespace
|
|
||||||
|
|
||||||
proxy = "http://127.0.0.1:23458"
|
proxy = "http://127.0.0.1:23458"
|
||||||
captured: dict[str, Any] = {}
|
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:
|
class FakeAsyncClient:
|
||||||
def __init__(self, **kwargs: Any) -> None:
|
def __init__(self, **kwargs: Any) -> None:
|
||||||
captured["client_kwargs"] = kwargs
|
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:
|
async def post(self, url: str, **kwargs: Any) -> FakeResponse:
|
||||||
captured["request"] = {"url": url, **kwargs}
|
captured["request"] = {"url": url, **kwargs}
|
||||||
return FakeResponse(
|
return FakeResponse({"data": [{"b64_json": PNG_DATA_URL.split(",")[1]}]})
|
||||||
{},
|
|
||||||
sse_lines=[
|
|
||||||
f'data: {{"type":"response.output_item.done","item":{{"type":"image_generation_call","result":"{PNG_DATA_URL}"}}}}',
|
|
||||||
"",
|
|
||||||
"data: [DONE]",
|
|
||||||
"",
|
|
||||||
],
|
|
||||||
)
|
|
||||||
|
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr("nanobot.providers.image_generation.httpx.AsyncClient", FakeAsyncClient)
|
||||||
"nanobot.providers.image_generation.httpx.AsyncClient",
|
|
||||||
FakeAsyncClient,
|
|
||||||
)
|
|
||||||
client = CodexImageGenerationClient(api_key=None, proxy=proxy)
|
client = CodexImageGenerationClient(api_key=None, proxy=proxy)
|
||||||
|
response = await client.generate(prompt="draw", model="gpt-image-2")
|
||||||
response = await client.generate(prompt="draw", model="gpt-5.4")
|
|
||||||
|
|
||||||
assert response.images == [PNG_DATA_URL]
|
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"]["proxy"] == proxy
|
||||||
assert captured["client_kwargs"]["trust_env"] is False
|
assert captured["client_kwargs"]["trust_env"] is False
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_codex_stops_reading_after_completed_event(monkeypatch) -> None:
|
@pytest.mark.parametrize("prefix", ["openai-codex", "openai_codex"])
|
||||||
import sys
|
async def test_codex_edit_reference_images_and_options(codex_oauth, tmp_path, prefix) -> None:
|
||||||
from dataclasses import dataclass
|
reference = tmp_path / "reference.png"
|
||||||
from types import SimpleNamespace
|
reference.write_bytes(PNG_BYTES)
|
||||||
|
fake = FakeClient(FakeResponse({"data": [{"b64_json": PNG_DATA_URL.split(",")[1]}]}))
|
||||||
@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=[]))
|
|
||||||
client = CodexImageGenerationClient(
|
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.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
|
@pytest.mark.asyncio
|
||||||
async def test_codex_strips_model_prefix(monkeypatch) -> None:
|
async def test_codex_explicit_size(codex_oauth) -> None:
|
||||||
import sys
|
fake = FakeClient(FakeResponse({"data": [{"b64_json": PNG_DATA_URL.split(",")[1]}]}))
|
||||||
from dataclasses import dataclass
|
client = CodexImageGenerationClient(api_key=None, client=fake) # type: ignore[arg-type]
|
||||||
from types import SimpleNamespace
|
await client.generate(prompt="draw", model="gpt-image-2", image_size="2048x1152")
|
||||||
|
assert fake.calls[0]["json"]["size"] == "2048x1152"
|
||||||
@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"
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
@@ -1418,115 +1325,25 @@ async def test_codex_requires_oauth(monkeypatch) -> None:
|
|||||||
raise RuntimeError("no token")
|
raise RuntimeError("no token")
|
||||||
|
|
||||||
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
monkeypatch.setattr("asyncio.to_thread", fake_to_thread)
|
||||||
|
|
||||||
client = CodexImageGenerationClient(api_key=None)
|
client = CodexImageGenerationClient(api_key=None)
|
||||||
|
|
||||||
with pytest.raises(ImageGenerationError, match="OAuth token"):
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_codex_no_images_raises(monkeypatch) -> None:
|
async def test_codex_no_images_raises(codex_oauth) -> None:
|
||||||
import sys
|
fake = FakeClient(FakeResponse({"data": []}))
|
||||||
from dataclasses import dataclass
|
client = CodexImageGenerationClient(api_key=None, client=fake) # type: ignore[arg-type]
|
||||||
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]
|
|
||||||
)
|
|
||||||
|
|
||||||
with pytest.raises(ImageGenerationError, match="returned no images"):
|
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
|
@pytest.mark.asyncio
|
||||||
async def test_codex_extracts_text_content(monkeypatch) -> None:
|
async def test_codex_http_error(codex_oauth) -> None:
|
||||||
import sys
|
fake = FakeClient(FakeResponse({"error": {"message": "image quota exceeded"}}, status_code=429))
|
||||||
from dataclasses import dataclass
|
client = CodexImageGenerationClient(api_key=None, client=fake) # type: ignore[arg-type]
|
||||||
from types import SimpleNamespace
|
with pytest.raises(ImageGenerationError, match="HTTP 429.*image quota exceeded"):
|
||||||
|
await client.generate(prompt="draw", model="gpt-image-2")
|
||||||
@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]
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -140,7 +140,7 @@ def test_image_generation_tool_passes_provider_proxy_to_client(
|
|||||||
config=ImageGenerationToolConfig(
|
config=ImageGenerationToolConfig(
|
||||||
enabled=True,
|
enabled=True,
|
||||||
provider="openai_codex",
|
provider="openai_codex",
|
||||||
model="openai-codex/gpt-5.4",
|
model="openai-codex/gpt-image-2",
|
||||||
),
|
),
|
||||||
provider_configs={"openai_codex": ProviderConfig(proxy=proxy)},
|
provider_configs={"openai_codex": ProviderConfig(proxy=proxy)},
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in new issue
Block a user