Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(images): address P1 response_format default + P2 cancel propagation + first-agent docs

xf gonge377e396850a
diff --git a/cubepi/providers/images/base.py b/cubepi/providers/images/base.py
index a3b7596..f2a35c8 100644
--- a/cubepi/providers/images/base.py
+++ b/cubepi/providers/images/base.py
@@ -171,8 +171,11 @@ class BaseImagesProvider:
if of is not None and cap.output_format_field is not None:
payload[cap.output_format_field] = of
- # response_format — always written, controlled entirely by capability
- payload[cap.response_format_field] = cap.response_format_value
+ # response_format — written only when the capability opts in
+ # (None default avoids 400s on OpenAI GPT image models, which
+ # reject the field and return base64 by default).
+ if cap.response_format_field is not None:
+ payload[cap.response_format_field] = cap.response_format_value
# supports_* gating
if context.seed is not None and cap.supports_seed:
diff --git a/cubepi/providers/images/capability.py b/cubepi/providers/images/capability.py
index dbe40b4..6c73dae 100644
--- a/cubepi/providers/images/capability.py
+++ b/cubepi/providers/images/capability.py
@@ -45,7 +45,11 @@ class ImagesCapabilityDescriptor(BaseModel):
guidance_field: str = "guidance_scale"
output_format_field: str | None = "output_format"
- response_format_field: str = "response_format"
+ # response_format is opt-in: OpenAI's GPT image models reject
+ # `response_format` and return base64 by default. Older OpenAI image
+ # endpoints (dall-e-3), SiliconFlow, Together, and similar backends
+ # that accept the field can set this to "response_format" explicitly.
+ response_format_field: str | None = None
response_format_value: Literal["b64_json", "url"] = "b64_json"
supports_edit: bool = True
diff --git a/cubepi/providers/images/openai_images.py b/cubepi/providers/images/openai_images.py
index ea0a55e..a062d5b 100644
--- a/cubepi/providers/images/openai_images.py
+++ b/cubepi/providers/images/openai_images.py
@@ -38,6 +38,17 @@ _OUTPUT_FORMAT_MEDIA_TYPE = {
}
+class _SignalAborted(Exception):
+ """Internal sentinel raised by ``_run_with_signal`` when
+ ``ImagesOptions.signal`` triggers an abort.
+
+ Distinct from :class:`asyncio.CancelledError` so that external
+ cancellation (``task.cancel()``, ``asyncio.wait_for``, parent task
+ teardown) propagates cleanly instead of being silently swallowed
+ into ``AssistantImages(stop_reason="aborted")``.
+ """
+
+
class OpenAIImagesProvider(BaseImagesProvider):
"""OpenAI-shape image provider.
@@ -121,11 +132,11 @@ class OpenAIImagesProvider(BaseImagesProvider):
return self._parse_response(sdk_resp, model, context, cap)
- except asyncio.CancelledError as cancel:
+ except _SignalAborted:
# Signal-triggered abort: return as AssistantImages, do not re-raise.
- # The CancelledError is recorded so subscribe_response observers
- # can distinguish abort from successful completion.
- exc = cancel
+ # A synthetic CancelledError is surfaced to response observers so
+ # tracing can distinguish abort from successful completion.
+ exc = asyncio.CancelledError("aborted via ImagesOptions.signal")
return AssistantImages(
api=model.api,
provider_id=model.provider_id,
@@ -133,6 +144,12 @@ class OpenAIImagesProvider(BaseImagesProvider):
output=[],
stop_reason="aborted",
)
+ except asyncio.CancelledError as cancel:
+ # External cancellation (task.cancel(), asyncio.wait_for(),
+ # parent teardown). Record it for response observers, then
+ # re-raise so callers see the cancellation they asked for.
+ exc = cancel
+ raise
except Exception as raw: # noqa: BLE001
exc = raw
classify_and_raise(raw, model=model)
@@ -154,8 +171,9 @@ class OpenAIImagesProvider(BaseImagesProvider):
) -> Any:
"""Run ``sdk_call(**payload)`` while listening to ``signal``.
- If ``signal`` fires first, the SDK task is cancelled and
- ``asyncio.CancelledError`` propagates upward.
+ Raises :class:`_SignalAborted` if ``signal`` fires first.
+ Lets :class:`asyncio.CancelledError` from external cancellation
+ propagate unchanged so callers can detect it.
"""
if signal is None:
return await sdk_call(**payload)
@@ -169,7 +187,7 @@ class OpenAIImagesProvider(BaseImagesProvider):
)
if signal_task in done and not sdk_task.done():
sdk_task.cancel()
- raise asyncio.CancelledError
+ raise _SignalAborted
signal_task.cancel()
return sdk_task.result()
finally:
diff --git a/tests/providers/images/test_capability.py b/tests/providers/images/test_capability.py
index cff61b8..73dae7f 100644
--- a/tests/providers/images/test_capability.py
+++ b/tests/providers/images/test_capability.py
@@ -13,7 +13,9 @@ def test_default_descriptor_is_openai_shape():
assert d.supports_steps is False
assert d.supports_guidance is False
assert d.output_format_field == "output_format"
- assert d.response_format_field == "response_format"
+ # response_format defaults to OFF so OpenAI gpt-image-1 — which rejects
+ # the field — works without an explicit override.
+ assert d.response_format_field is None
assert d.response_format_value == "b64_json"
assert d.supports_edit is True
assert d.input_images_field == "image"
diff --git a/tests/providers/images/test_capability_payload_mapping.py b/tests/providers/images/test_capability_payload_mapping.py
index df48f97..cd8cf54 100644
--- a/tests/providers/images/test_capability_payload_mapping.py
+++ b/tests/providers/images/test_capability_payload_mapping.py
@@ -26,9 +26,35 @@ def test_baseline_payload_has_model_and_prompt():
payload = p._build_payload(_model(), ImagesContext(prompt="A robot"))
assert payload["model"] == "m"
assert payload["prompt"] == "A robot"
+ # response_format is opt-in via the capability descriptor; the default
+ # OpenAI-shape descriptor leaves it off so gpt-image-1 doesn't 400.
+ assert "response_format" not in payload
+
+
+def test_response_format_opt_in_when_field_set():
+ p = _Stub(
+ provider_id="p",
+ capability=ImagesCapabilityDescriptor(
+ response_format_field="response_format",
+ ),
+ )
+ payload = p._build_payload(_model(), ImagesContext(prompt="x"))
assert payload["response_format"] == "b64_json"
+def test_response_format_renamed_when_field_overridden():
+ p = _Stub(
+ provider_id="p",
+ capability=ImagesCapabilityDescriptor(
+ response_format_field="resp_fmt",
+ response_format_value="url",
+ ),
+ )
+ payload = p._build_payload(_model(), ImagesContext(prompt="x"))
+ assert payload["resp_fmt"] == "url"
+ assert "response_format" not in payload
+
+
def test_size_spec_size_string():
p = _Stub(provider_id="p")
payload = p._build_payload(_model(), ImagesContext(prompt="x", size="1024x1024"))
diff --git a/tests/providers/images/test_openai_images.py b/tests/providers/images/test_openai_images.py
index fef4629..eccf445 100644
--- a/tests/providers/images/test_openai_images.py
+++ b/tests/providers/images/test_openai_images.py
@@ -90,7 +90,9 @@ async def test_happy_path_writes_canonical_openai_fields():
assert kw["size"] == "1024x1024"
assert kw["n"] == 2
assert kw["quality"] == "high"
- assert kw["response_format"] == "b64_json"
+ # response_format is NOT sent by default — OpenAI's GPT image models
+ # reject the field and return base64 anyway.
+ assert "response_format" not in kw
assert out.stop_reason == "stop"
assert out.output[0].type == "image"
@@ -336,3 +338,32 @@ async def test_media_type_uses_model_default_output_format():
model = p.model("gpt-image-1", default_output_format="webp")
out = await p.generate_images(model, ImagesContext(prompt="x"))
assert out.output[0].media_type == "image/webp"
+
+
+async def test_external_cancel_propagates_not_swallowed():
+ """task.cancel() on the caller must propagate as CancelledError, not
+ be silently converted into AssistantImages(stop_reason='aborted').
+ Only ImagesOptions.signal triggers the aborted path."""
+ p = _provider(sleep=0.5)
+ model = p.model("gpt-image-1")
+
+ task = asyncio.create_task(p.generate_images(model, ImagesContext(prompt="x")))
+ await asyncio.sleep(0.05)
+ task.cancel()
+
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_wait_for_timeout_propagates_cancellation():
+ """asyncio.wait_for cancellation on the caller must propagate as a
+ timeout, not be swallowed into stop_reason='aborted'."""
+ p = _provider(sleep=0.5)
+ model = p.model("gpt-image-1")
+
+ with pytest.raises(asyncio.TimeoutError):
+ await asyncio.wait_for(
+ p.generate_images(model, ImagesContext(prompt="x")), timeout=0.05
+ )
diff --git a/website/docs/guides/agents/first-agent.md b/website/docs/guides/agents/first-agent.md
index c0c9bc0..58bdc25 100644
--- a/website/docs/guides/agents/first-agent.md
+++ b/website/docs/guides/agents/first-agent.md
@@ -11,28 +11,28 @@ you'll want next: streaming UI, error handling, and a cancel button.
## Step 1 — set up the provider and model
-The provider is the connection to the LLM API; the `Model` describes
-which model you want to invoke and a few capabilities.
+The provider is the connection to the LLM API; `provider.model("id", ...)`
+binds a model id to that provider and produces the value `Agent(model=...)`
+expects.
```python
import os
-from cubepi import Model
from cubepi.providers.anthropic import AnthropicProvider
provider = AnthropicProvider(provider_id="anthropic", api_key=os.environ["ANTHROPIC_API_KEY"])
-model = Model(
- id="claude-sonnet-4-5-20250929",
- provider="anthropic",
- max_tokens=4096, # response cap
+model = provider.model(
+ "claude-sonnet-4-5-20250929",
+ max_tokens=4096, # response cap
context_window=200_000, # hard model limit; defaults are usually fine
temperature=0.7,
)
```
-The `provider` field on `Model` is a string label (e.g. `"anthropic"`,
-`"openai"`). It's used by the framework to clamp thinking levels and
-tag responses — keep it stable, it doesn't have to match the
-provider's internal name.
+`provider_id` lives on the provider constructor and is propagated into the
+bound model automatically — used by the framework to clamp thinking levels
+and tag responses. Building a `Model` by hand and passing both
+`provider=` and `model=` to `Agent` is the 0.6 idiom and no longer works
+in 0.7.
## Step 2 — declare a tool