Skip to content

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

feat(images): rebuild types with provider_id + model-level defaults + typed context

xf gongfb5913565c1c
diff --git a/cubepi/providers/images/types.py b/cubepi/providers/images/types.py
index f692223..355ff0f 100644
--- a/cubepi/providers/images/types.py
+++ b/cubepi/providers/images/types.py
@@ -1,4 +1,105 @@
-"""Image generation types — placeholder during the 0.7 redesign.
+from __future__ import annotations
-The real types are added back in Task 2 of the implementation plan.
-"""
+import asyncio
+from typing import Any, Literal
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from cubepi.providers.base import (
+ ImageContent,
+ OnPayloadCallback,
+ OnResponseCallback,
+ ProviderResponse,
+ TextContent,
+)
+from cubepi.types import JsonObject
+
+# Re-exported so the ``OnResponseCallback`` forward reference to
+# ``ProviderResponse`` can be resolved when pydantic builds ``ImagesOptions``
+# under ``from __future__ import annotations``.
+__all__ = [
+ "AssistantImages",
+ "ImagesContext",
+ "ImagesCost",
+ "ImagesModel",
+ "ImagesOptions",
+ "ProviderResponse",
+]
+
+
+class ImagesCost(BaseModel):
+ """Image-generation pricing (per-image is dominant; per-megapixel for Imagen-like models)."""
+
+ per_image: float = 0
+ per_megapixel: float = 0
+
+
+class ImagesModel(BaseModel):
+ """Image-generation model spec, with model-level defaults applied when the
+ matching ``ImagesContext`` field is not set."""
+
+ id: str
+ provider_id: str = ""
+ api: str = ""
+
+ default_size: str | None = None
+ default_n: int | None = None
+ default_quality: Literal["low", "medium", "high"] | None = None
+ default_output_format: Literal["png", "jpeg", "webp"] | None = None
+
+ cost: ImagesCost | None = None
+ max_input_images: int | None = None
+
+
+class ImagesContext(BaseModel):
+ """Per-call request payload.
+
+ ``size`` / ``n`` / ``quality`` / ``output_format`` override the matching
+ ``ImagesModel.default_*``. ``seed`` / ``negative_prompt`` / ``steps`` /
+ ``guidance`` are only written to the wire payload when the provider's
+ ``ImagesCapabilityDescriptor`` declares support; otherwise they are
+ dropped with a one-time warning. ``extra`` carries truly backend-specific
+ fields that the descriptor does not model (e.g. Doubao's ``watermark``).
+ """
+
+ prompt: str
+ input_images: list[ImageContent] = Field(default_factory=list)
+
+ size: str | None = None
+ n: int | None = None
+ quality: Literal["low", "medium", "high"] | None = None
+ output_format: Literal["png", "jpeg", "webp"] | None = None
+
+ seed: int | None = None
+ negative_prompt: str | None = None
+ steps: int | None = None
+ guidance: float | None = None
+
+ extra: dict[str, Any] = Field(default_factory=dict)
+
+
+class ImagesOptions(BaseModel):
+ """Per-call cross-cutting options (analog of chat's ``StreamOptions``)."""
+
+ model_config = ConfigDict(arbitrary_types_allowed=True)
+
+ signal: asyncio.Event | None = None
+ on_payload: OnPayloadCallback | None = None
+ on_response: OnResponseCallback | None = None
+
+
+class AssistantImages(BaseModel):
+ """Response from a successful or aborted image generation call.
+
+ Failures raise ``cubepi.errors.ProviderError`` subclasses; they never
+ appear as a ``stop_reason``. ``stop_reason="aborted"`` is produced when
+ ``ImagesOptions.signal`` fires mid-call.
+ """
+
+ api: str
+ provider_id: str
+ model: str
+ output: list[ImageContent | TextContent] = Field(default_factory=list)
+ stop_reason: Literal["stop", "aborted"] = "stop"
+ response_id: str | None = None
+ metadata: JsonObject = Field(default_factory=dict)
diff --git a/tests/providers/images/test_types.py b/tests/providers/images/test_types.py
new file mode 100644
index 0000000..7dbc325
--- /dev/null
+++ b/tests/providers/images/test_types.py
@@ -0,0 +1,132 @@
+import asyncio
+from typing import get_args
+
+import pytest
+from pydantic import ValidationError
+
+from cubepi.providers.base import ImageContent
+from cubepi.providers.images.types import (
+ AssistantImages,
+ ImagesContext,
+ ImagesCost,
+ ImagesModel,
+ ImagesOptions,
+)
+
+
+def test_images_model_required_field_id():
+ with pytest.raises(ValidationError):
+ ImagesModel() # type: ignore[call-arg]
+
+
+def test_images_model_provider_id_renamed():
+ m = ImagesModel(id="gpt-image-1", provider_id="openai", api="openai-images")
+ assert m.provider_id == "openai"
+ assert m.api == "openai-images"
+ assert not hasattr(m, "provider"), "old `provider` field must be gone"
+
+
+def test_images_model_default_fields():
+ m = ImagesModel(
+ id="gpt-image-1",
+ provider_id="openai",
+ default_size="1024x1024",
+ default_n=2,
+ default_quality="high",
+ default_output_format="png",
+ )
+ assert m.default_size == "1024x1024"
+ assert m.default_n == 2
+ assert m.default_quality == "high"
+ assert m.default_output_format == "png"
+
+
+def test_images_model_defaults_are_optional_none():
+ m = ImagesModel(id="gpt-image-1", provider_id="openai")
+ assert m.default_size is None
+ assert m.default_n is None
+ assert m.default_quality is None
+ assert m.default_output_format is None
+ assert m.cost is None
+ assert m.max_input_images is None
+
+
+def test_images_cost_fields():
+ cost = ImagesCost(per_image=0.04, per_megapixel=0.0)
+ assert cost.per_image == 0.04
+ assert cost.per_megapixel == 0.0
+
+
+def test_images_context_typed_fields():
+ ctx = ImagesContext(
+ prompt="A robot",
+ size="1024x1024",
+ n=2,
+ quality="high",
+ output_format="png",
+ seed=42,
+ negative_prompt="blurry",
+ steps=20,
+ guidance=7.5,
+ extra={"watermark": False},
+ )
+ assert ctx.prompt == "A robot"
+ assert ctx.size == "1024x1024"
+ assert ctx.n == 2
+ assert ctx.quality == "high"
+ assert ctx.output_format == "png"
+ assert ctx.seed == 42
+ assert ctx.negative_prompt == "blurry"
+ assert ctx.steps == 20
+ assert ctx.guidance == 7.5
+ assert ctx.extra == {"watermark": False}
+
+
+def test_images_context_input_images_accepts_image_content():
+ ctx = ImagesContext(
+ prompt="edit",
+ input_images=[ImageContent(source="b64", media_type="image/png")],
+ )
+ assert len(ctx.input_images) == 1
+
+
+def test_images_context_quality_literal_rejects_unknown():
+ with pytest.raises(ValidationError):
+ ImagesContext(prompt="x", quality="ultra") # type: ignore[arg-type]
+
+
+def test_images_options_default_construction():
+ opts = ImagesOptions()
+ assert opts.signal is None
+ assert opts.on_payload is None
+ assert opts.on_response is None
+
+
+def test_images_options_accepts_event_and_callbacks():
+ ev = asyncio.Event()
+ opts = ImagesOptions(
+ signal=ev, on_payload=lambda p, m: None, on_response=lambda r, m: None
+ )
+ assert opts.signal is ev
+ assert opts.on_payload is not None
+ assert opts.on_response is not None
+
+
+def test_assistant_images_stop_reason_literal():
+ allowed = set(get_args(AssistantImages.model_fields["stop_reason"].annotation))
+ assert allowed == {"stop", "aborted"}, "error stop_reason is removed in 0.7"
+
+
+def test_assistant_images_no_error_message_field():
+ assert "error_message" not in AssistantImages.model_fields
+
+
+def test_assistant_images_provider_id_renamed():
+ out = AssistantImages(
+ api="openai-images",
+ provider_id="openai",
+ model="gpt-image-1",
+ output=[],
+ )
+ assert out.provider_id == "openai"
+ assert not hasattr(out, "provider"), "old `provider` field must be gone"