runapi-ideogram-v3 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,29 @@
1
+ # Build artifacts
2
+ dist/
3
+ build/
4
+ *.egg-info/
5
+ *.egg
6
+
7
+ # Bytecode
8
+ __pycache__/
9
+ *.py[cod]
10
+
11
+ # Virtual environments
12
+ .venv/
13
+ venv/
14
+
15
+ # uv
16
+ uv.lock
17
+
18
+ # Test / type caches
19
+ .pytest_cache/
20
+ .mypy_cache/
21
+ .ruff_cache/
22
+ .coverage
23
+ htmlcov/
24
+
25
+ # IDE / OS
26
+ .idea/
27
+ .vscode/
28
+ *.swp
29
+ .DS_Store
@@ -0,0 +1,90 @@
1
+ Metadata-Version: 2.4
2
+ Name: runapi-ideogram-v3
3
+ Version: 0.1.0
4
+ Summary: Ideogram V3 image generation client for RunAPI
5
+ Project-URL: Homepage, https://runapi.ai/models/ideogram-v3
6
+ Project-URL: Documentation, https://runapi.ai/docs#sdk-ideogram-v3
7
+ Author-email: RunAPI <contact@runapi.ai>
8
+ License-Expression: Apache-2.0
9
+ Keywords: ai,edit-image,ideogram-v3,runapi,sdk,text-to-image
10
+ Requires-Python: >=3.9
11
+ Requires-Dist: runapi-core
12
+ Description-Content-Type: text/markdown
13
+
14
+ # Ideogram V3 Python SDK for RunAPI
15
+
16
+ The Ideogram V3 Python SDK is the language-specific package for Ideogram V3 on
17
+ RunAPI. Use it for text-to-image, edit-image, remix-image, and reframe-image
18
+ flows when your application needs JSON request bodies, task status lookup, and
19
+ consistent RunAPI errors in Python.
20
+
21
+ For model details, use https://runapi.ai/models/ideogram-v3; for API reference,
22
+ use https://runapi.ai/docs#ideogram-v3; for SDK docs, use
23
+ https://runapi.ai/docs#sdk-ideogram-v3.
24
+
25
+ ## Install
26
+
27
+ ```bash
28
+ pip install runapi-ideogram-v3
29
+ ```
30
+
31
+ ## Quick start
32
+
33
+ ```python
34
+ from runapi.ideogram_v3 import IdeogramV3Client
35
+
36
+ client = IdeogramV3Client() # reads RUNAPI_API_KEY, or pass api_key="sk-..."
37
+
38
+ task = client.text_to_image.create(
39
+ model="ideogram-v3-text-to-image",
40
+ prompt="A cinematic lakeside at twilight",
41
+ aspect_ratio="16:9",
42
+ rendering_speed="quality",
43
+ )
44
+ status = client.text_to_image.get(task.id)
45
+
46
+ edit = client.edit_image.create(
47
+ model="ideogram-v3-edit",
48
+ prompt="Replace the sky with aurora",
49
+ source_image_url="https://example.com/source.jpg",
50
+ mask_url="https://example.com/mask.png",
51
+ )
52
+ ```
53
+
54
+ Use `create` to submit a task and return quickly, `get` to fetch the latest task
55
+ state, and `run` to create and poll until completion:
56
+
57
+ ```python
58
+ result = client.text_to_image.run(
59
+ model="ideogram-v3-text-to-image",
60
+ prompt="A serene mountain lake at dawn",
61
+ )
62
+ print(result.images[0].url)
63
+ ```
64
+
65
+ In web request handlers, prefer `create` plus webhook or later `get` polling so a
66
+ worker is not held open.
67
+
68
+ RunAPI-generated file URLs are temporary. Download and store generated images in
69
+ your own durable storage within 7 days; do not treat returned URLs as long-term
70
+ assets.
71
+
72
+ ## Language notes
73
+
74
+ Pass parameters as keyword arguments and catch the `runapi.ideogram_v3` error
75
+ classes when building image jobs or scripts. The available resources are
76
+ `text_to_image`, `edit_image`, `remix_image`, and `reframe_image`. Keep
77
+ `RUNAPI_API_KEY` in the environment or your secret manager; never commit API keys
78
+ or callback secrets.
79
+
80
+ ## Links
81
+
82
+ - Model page: https://runapi.ai/models/ideogram-v3
83
+ - SDK docs: https://runapi.ai/docs#sdk-ideogram-v3
84
+ - Product docs: https://runapi.ai/docs#ideogram-v3
85
+ - Pricing and rate limits: https://runapi.ai/models/ideogram-v3
86
+ - Full catalog: https://runapi.ai/models
87
+
88
+ ## License
89
+
90
+ Licensed under the Apache License, Version 2.0.
@@ -0,0 +1,77 @@
1
+ # Ideogram V3 Python SDK for RunAPI
2
+
3
+ The Ideogram V3 Python SDK is the language-specific package for Ideogram V3 on
4
+ RunAPI. Use it for text-to-image, edit-image, remix-image, and reframe-image
5
+ flows when your application needs JSON request bodies, task status lookup, and
6
+ consistent RunAPI errors in Python.
7
+
8
+ For model details, use https://runapi.ai/models/ideogram-v3; for API reference,
9
+ use https://runapi.ai/docs#ideogram-v3; for SDK docs, use
10
+ https://runapi.ai/docs#sdk-ideogram-v3.
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ pip install runapi-ideogram-v3
16
+ ```
17
+
18
+ ## Quick start
19
+
20
+ ```python
21
+ from runapi.ideogram_v3 import IdeogramV3Client
22
+
23
+ client = IdeogramV3Client() # reads RUNAPI_API_KEY, or pass api_key="sk-..."
24
+
25
+ task = client.text_to_image.create(
26
+ model="ideogram-v3-text-to-image",
27
+ prompt="A cinematic lakeside at twilight",
28
+ aspect_ratio="16:9",
29
+ rendering_speed="quality",
30
+ )
31
+ status = client.text_to_image.get(task.id)
32
+
33
+ edit = client.edit_image.create(
34
+ model="ideogram-v3-edit",
35
+ prompt="Replace the sky with aurora",
36
+ source_image_url="https://example.com/source.jpg",
37
+ mask_url="https://example.com/mask.png",
38
+ )
39
+ ```
40
+
41
+ Use `create` to submit a task and return quickly, `get` to fetch the latest task
42
+ state, and `run` to create and poll until completion:
43
+
44
+ ```python
45
+ result = client.text_to_image.run(
46
+ model="ideogram-v3-text-to-image",
47
+ prompt="A serene mountain lake at dawn",
48
+ )
49
+ print(result.images[0].url)
50
+ ```
51
+
52
+ In web request handlers, prefer `create` plus webhook or later `get` polling so a
53
+ worker is not held open.
54
+
55
+ RunAPI-generated file URLs are temporary. Download and store generated images in
56
+ your own durable storage within 7 days; do not treat returned URLs as long-term
57
+ assets.
58
+
59
+ ## Language notes
60
+
61
+ Pass parameters as keyword arguments and catch the `runapi.ideogram_v3` error
62
+ classes when building image jobs or scripts. The available resources are
63
+ `text_to_image`, `edit_image`, `remix_image`, and `reframe_image`. Keep
64
+ `RUNAPI_API_KEY` in the environment or your secret manager; never commit API keys
65
+ or callback secrets.
66
+
67
+ ## Links
68
+
69
+ - Model page: https://runapi.ai/models/ideogram-v3
70
+ - SDK docs: https://runapi.ai/docs#sdk-ideogram-v3
71
+ - Product docs: https://runapi.ai/docs#ideogram-v3
72
+ - Pricing and rate limits: https://runapi.ai/models/ideogram-v3
73
+ - Full catalog: https://runapi.ai/models
74
+
75
+ ## License
76
+
77
+ Licensed under the Apache License, Version 2.0.
@@ -0,0 +1,30 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "runapi-ideogram-v3"
7
+ version = "0.1.0"
8
+ description = "Ideogram V3 image generation client for RunAPI"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "RunAPI", email = "contact@runapi.ai" }]
13
+ keywords = ["runapi", "ideogram-v3", "text-to-image", "edit-image", "ai", "sdk"]
14
+ dependencies = ["runapi-core"]
15
+
16
+ [project.urls]
17
+ Homepage = "https://runapi.ai/models/ideogram-v3"
18
+ Documentation = "https://runapi.ai/docs#sdk-ideogram-v3"
19
+
20
+ [tool.hatch.build.targets.wheel]
21
+ packages = ["src/runapi"]
22
+
23
+ [tool.uv]
24
+ package = true
25
+
26
+ [tool.uv.sources]
27
+ runapi-core = { path = "../runapi-core", editable = true }
28
+
29
+ [dependency-groups]
30
+ dev = ["pytest>=8"]
@@ -0,0 +1,24 @@
1
+ """Ideogram V3 client for RunAPI."""
2
+
3
+ from runapi.core import (
4
+ AuthenticationError,
5
+ InsufficientCreditsError,
6
+ NotFoundError,
7
+ RateLimitError,
8
+ TaskFailedError,
9
+ TaskTimeoutError,
10
+ ValidationError,
11
+ )
12
+
13
+ from .client import IdeogramV3Client
14
+
15
+ __all__ = [
16
+ "IdeogramV3Client",
17
+ "AuthenticationError",
18
+ "RateLimitError",
19
+ "InsufficientCreditsError",
20
+ "NotFoundError",
21
+ "ValidationError",
22
+ "TaskFailedError",
23
+ "TaskTimeoutError",
24
+ ]
@@ -0,0 +1,19 @@
1
+ """Shared validators for Ideogram V3 resources."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from runapi.core import ValidationError
8
+
9
+ from .types import OUTPUT_COUNTS
10
+
11
+
12
+ def validate_output_count(params: Dict[str, Any]) -> None:
13
+ output_count = params.get("output_count")
14
+ if output_count is None:
15
+ return
16
+ if not isinstance(output_count, bool) and output_count in OUTPUT_COUNTS:
17
+ return
18
+ joined = ", ".join(str(option) for option in OUTPUT_COUNTS)
19
+ raise ValidationError(f"Invalid output_count: {output_count}. Must be one of: {joined}")
@@ -0,0 +1,34 @@
1
+ """Ideogram V3 client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Optional
6
+
7
+ from runapi.core import ClientOptions, HttpClient, resolve_api_key
8
+
9
+ from .resources.edit_image import EditImage
10
+ from .resources.reframe_image import ReframeImage
11
+ from .resources.remix_image import RemixImage
12
+ from .resources.text_to_image import TextToImage
13
+
14
+
15
+ class IdeogramV3Client:
16
+ """Ideogram V3 image generation client.
17
+
18
+ Example::
19
+
20
+ client = IdeogramV3Client(api_key="sk-...")
21
+ result = client.text_to_image.run(
22
+ model="ideogram-v3-text-to-image",
23
+ prompt="A cinematic lakeside at twilight",
24
+ )
25
+ """
26
+
27
+ def __init__(self, api_key: Optional[str] = None, **options: Any) -> None:
28
+ resolved_api_key = resolve_api_key(api_key)
29
+ client_options = ClientOptions(api_key=resolved_api_key, **options)
30
+ http = client_options.http_client or HttpClient(client_options)
31
+ self.text_to_image = TextToImage(http)
32
+ self.edit_image = EditImage(http)
33
+ self.remix_image = RemixImage(http)
34
+ self.reframe_image = ReframeImage(http)
@@ -0,0 +1,6 @@
1
+ from .edit_image import EditImage
2
+ from .reframe_image import ReframeImage
3
+ from .remix_image import RemixImage
4
+ from .text_to_image import TextToImage
5
+
6
+ __all__ = ["TextToImage", "EditImage", "RemixImage", "ReframeImage"]
@@ -0,0 +1,95 @@
1
+ """Ideogram V3 edit-image resource (model: ideogram-v3-edit)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from runapi.core import Resource, ValidationError
8
+
9
+ from .._validators import validate_output_count
10
+ from ..types import (
11
+ CHARACTER_EDIT_MODEL,
12
+ CHARACTER_STYLES,
13
+ EDIT_MODEL,
14
+ RENDERING_SPEEDS,
15
+ CompletedIdeogramResponse,
16
+ IdeogramResponse,
17
+ )
18
+
19
+
20
+ class EditImage(Resource):
21
+ """Inpaint an image with a mask using Ideogram V3 models."""
22
+
23
+ ENDPOINT = "/api/v1/ideogram_v3/edit_image"
24
+ RESPONSE_CLASS = IdeogramResponse
25
+ COMPLETED_RESPONSE_CLASS = CompletedIdeogramResponse
26
+ PROMPT_MAX_LENGTH = 5000
27
+
28
+ def run(self, **params: Any) -> Any:
29
+ """Create an edit-image task and poll until it completes.
30
+
31
+ Args:
32
+ **params: Edit-image parameters (model, prompt, source_image_url, mask_url, ...).
33
+
34
+ Returns:
35
+ The completed (narrowed) response.
36
+ """
37
+ task = self.create(**params)
38
+ return self._poll_until_complete(lambda: self.get(task.id))
39
+
40
+ def create(self, **params: Any) -> Any:
41
+ """Create an edit-image task and return immediately with an ``id``.
42
+
43
+ Args:
44
+ **params: Edit-image parameters (model, prompt, source_image_url, mask_url, ...).
45
+
46
+ Returns:
47
+ The task creation result with an id.
48
+ """
49
+ compacted = self._compact_params(params)
50
+ self._validate_params(compacted)
51
+ return self._request("post", self.ENDPOINT, body=compacted)
52
+
53
+ def get(self, id: str) -> Any:
54
+ """Fetch the current status of an edit-image task.
55
+
56
+ Args:
57
+ id: The task id.
58
+
59
+ Returns:
60
+ The current task status.
61
+ """
62
+ return self._request("get", f"{self.ENDPOINT}/{id}")
63
+
64
+ def _validate_params(self, params: Dict[str, Any]) -> None:
65
+ model = params.get("model")
66
+ if not model:
67
+ raise ValidationError("model is required")
68
+ if model not in (EDIT_MODEL, CHARACTER_EDIT_MODEL):
69
+ raise ValidationError(
70
+ f"Invalid model: {model}. Must be {EDIT_MODEL} or {CHARACTER_EDIT_MODEL}"
71
+ )
72
+
73
+ prompt = params.get("prompt")
74
+ if not (isinstance(prompt, str) and prompt):
75
+ raise ValidationError("prompt is required")
76
+ if len(prompt) > self.PROMPT_MAX_LENGTH:
77
+ raise ValidationError(f"prompt must be at most {self.PROMPT_MAX_LENGTH} characters")
78
+
79
+ if not params.get("source_image_url"):
80
+ raise ValidationError("source_image_url is required")
81
+ if not params.get("mask_url"):
82
+ raise ValidationError("mask_url is required")
83
+
84
+ self._validate_optional(params, "rendering_speed", RENDERING_SPEEDS)
85
+ self._validate_character_fields(params, model)
86
+
87
+ def _validate_character_fields(self, params: Dict[str, Any], model: str) -> None:
88
+ refs = params.get("reference_image_urls")
89
+ if model == CHARACTER_EDIT_MODEL:
90
+ if not (isinstance(refs, list) and refs):
91
+ raise ValidationError("reference_image_urls is required")
92
+ self._validate_optional(params, "style", CHARACTER_STYLES)
93
+ elif refs or params.get("style"):
94
+ raise ValidationError(f"character edit fields are not supported for {model}")
95
+ validate_output_count(params)
@@ -0,0 +1,78 @@
1
+ """Ideogram V3 reframe-image resource (model: ideogram-v3-reframe)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from runapi.core import Resource, ValidationError
8
+
9
+ from .._validators import validate_output_count
10
+ from ..types import (
11
+ ASPECT_RATIOS,
12
+ REFRAME_MODEL,
13
+ RENDERING_SPEEDS,
14
+ STYLES,
15
+ CompletedIdeogramResponse,
16
+ IdeogramResponse,
17
+ )
18
+
19
+
20
+ class ReframeImage(Resource):
21
+ """Reframe a source image to a new aspect ratio with Ideogram V3."""
22
+
23
+ ENDPOINT = "/api/v1/ideogram_v3/reframe_image"
24
+ RESPONSE_CLASS = IdeogramResponse
25
+ COMPLETED_RESPONSE_CLASS = CompletedIdeogramResponse
26
+
27
+ def run(self, **params: Any) -> Any:
28
+ """Create a reframe-image task and poll until it completes.
29
+
30
+ Args:
31
+ **params: Reframe-image parameters (model, source_image_url, aspect_ratio, ...).
32
+
33
+ Returns:
34
+ The completed (narrowed) response.
35
+ """
36
+ task = self.create(**params)
37
+ return self._poll_until_complete(lambda: self.get(task.id))
38
+
39
+ def create(self, **params: Any) -> Any:
40
+ """Create a reframe-image task and return immediately with an ``id``.
41
+
42
+ Args:
43
+ **params: Reframe-image parameters (model, source_image_url, aspect_ratio, ...).
44
+
45
+ Returns:
46
+ The task creation result with an id.
47
+ """
48
+ compacted = self._compact_params(params)
49
+ self._validate_params(compacted)
50
+ return self._request("post", self.ENDPOINT, body=compacted)
51
+
52
+ def get(self, id: str) -> Any:
53
+ """Fetch the current status of a reframe-image task.
54
+
55
+ Args:
56
+ id: The task id.
57
+
58
+ Returns:
59
+ The current task status.
60
+ """
61
+ return self._request("get", f"{self.ENDPOINT}/{id}")
62
+
63
+ def _validate_params(self, params: Dict[str, Any]) -> None:
64
+ model = params.get("model")
65
+ if not model:
66
+ raise ValidationError("model is required")
67
+ if model != REFRAME_MODEL:
68
+ raise ValidationError(f"Invalid model: {model}. Must be {REFRAME_MODEL}")
69
+
70
+ if not params.get("source_image_url"):
71
+ raise ValidationError("source_image_url is required")
72
+ if not params.get("aspect_ratio"):
73
+ raise ValidationError("aspect_ratio is required")
74
+
75
+ self._validate_optional(params, "aspect_ratio", ASPECT_RATIOS)
76
+ self._validate_optional(params, "rendering_speed", RENDERING_SPEEDS)
77
+ self._validate_optional(params, "style", STYLES)
78
+ validate_output_count(params)
@@ -0,0 +1,117 @@
1
+ """Ideogram V3 remix-image resource (model: ideogram-v3-remix)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from runapi.core import Resource, ValidationError
8
+
9
+ from .._validators import validate_output_count
10
+ from ..types import (
11
+ ASPECT_RATIOS,
12
+ CHARACTER_REMIX_MODEL,
13
+ CHARACTER_STYLES,
14
+ REMIX_MODEL,
15
+ RENDERING_SPEEDS,
16
+ STYLES,
17
+ CompletedIdeogramResponse,
18
+ IdeogramResponse,
19
+ )
20
+
21
+
22
+ class RemixImage(Resource):
23
+ """Remix a source image with Ideogram V3 models."""
24
+
25
+ ENDPOINT = "/api/v1/ideogram_v3/remix_image"
26
+ RESPONSE_CLASS = IdeogramResponse
27
+ COMPLETED_RESPONSE_CLASS = CompletedIdeogramResponse
28
+ PROMPT_MAX_LENGTH = 5000
29
+ STRENGTH_MIN = 0.01
30
+ CHARACTER_REMIX_STRENGTH_MIN = 0.1
31
+ STRENGTH_MAX = 1.0
32
+
33
+ def run(self, **params: Any) -> Any:
34
+ """Create a remix-image task and poll until it completes.
35
+
36
+ Args:
37
+ **params: Remix-image parameters (model, prompt, source_image_url, ...).
38
+
39
+ Returns:
40
+ The completed (narrowed) response.
41
+ """
42
+ task = self.create(**params)
43
+ return self._poll_until_complete(lambda: self.get(task.id))
44
+
45
+ def create(self, **params: Any) -> Any:
46
+ """Create a remix-image task and return immediately with an ``id``.
47
+
48
+ Args:
49
+ **params: Remix-image parameters (model, prompt, source_image_url, ...).
50
+
51
+ Returns:
52
+ The task creation result with an id.
53
+ """
54
+ compacted = self._compact_params(params)
55
+ self._validate_params(compacted)
56
+ return self._request("post", self.ENDPOINT, body=compacted)
57
+
58
+ def get(self, id: str) -> Any:
59
+ """Fetch the current status of a remix-image task.
60
+
61
+ Args:
62
+ id: The task id.
63
+
64
+ Returns:
65
+ The current task status.
66
+ """
67
+ return self._request("get", f"{self.ENDPOINT}/{id}")
68
+
69
+ def _validate_params(self, params: Dict[str, Any]) -> None:
70
+ model = params.get("model")
71
+ if not model:
72
+ raise ValidationError("model is required")
73
+ if model not in (REMIX_MODEL, CHARACTER_REMIX_MODEL):
74
+ raise ValidationError(
75
+ f"Invalid model: {model}. Must be {REMIX_MODEL} or {CHARACTER_REMIX_MODEL}"
76
+ )
77
+
78
+ prompt = params.get("prompt")
79
+ if not (isinstance(prompt, str) and prompt):
80
+ raise ValidationError("prompt is required")
81
+ if len(prompt) > self.PROMPT_MAX_LENGTH:
82
+ raise ValidationError(f"prompt must be at most {self.PROMPT_MAX_LENGTH} characters")
83
+
84
+ if not params.get("source_image_url"):
85
+ raise ValidationError("source_image_url is required")
86
+
87
+ self._validate_optional(params, "rendering_speed", RENDERING_SPEEDS)
88
+ style_values = CHARACTER_STYLES if model == CHARACTER_REMIX_MODEL else STYLES
89
+ self._validate_optional(params, "style", style_values)
90
+ self._validate_optional(params, "aspect_ratio", ASPECT_RATIOS)
91
+ self._validate_character_fields(params, model)
92
+ validate_output_count(params)
93
+ self._validate_strength(params, model)
94
+
95
+ def _validate_character_fields(self, params: Dict[str, Any], model: str) -> None:
96
+ refs = params.get("reference_image_urls")
97
+ if model == CHARACTER_REMIX_MODEL:
98
+ if not (isinstance(refs, list) and refs):
99
+ raise ValidationError("reference_image_urls is required")
100
+ elif refs or params.get("style_reference_image_urls") or params.get("reference_mask_urls"):
101
+ raise ValidationError(f"character remix fields are not supported for {model}")
102
+
103
+ def _validate_strength(self, params: Dict[str, Any], model: str) -> None:
104
+ strength = params.get("strength")
105
+ if strength is None:
106
+ return
107
+ minimum = (
108
+ self.CHARACTER_REMIX_STRENGTH_MIN
109
+ if model == CHARACTER_REMIX_MODEL
110
+ else self.STRENGTH_MIN
111
+ )
112
+ try:
113
+ numeric = float(strength)
114
+ except (TypeError, ValueError):
115
+ numeric = None
116
+ if numeric is None or numeric < minimum or numeric > self.STRENGTH_MAX:
117
+ raise ValidationError(f"strength must be between {minimum} and {self.STRENGTH_MAX}")
@@ -0,0 +1,94 @@
1
+ """Ideogram V3 text-to-image resource (model: ideogram-v3-text-to-image)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from runapi.core import Resource, ValidationError
8
+
9
+ from .._validators import validate_output_count
10
+ from ..types import (
11
+ ASPECT_RATIOS,
12
+ CHARACTER_MODEL,
13
+ CHARACTER_STYLES,
14
+ GENERATION_MODEL,
15
+ RENDERING_SPEEDS,
16
+ STYLES,
17
+ CompletedIdeogramResponse,
18
+ IdeogramResponse,
19
+ )
20
+
21
+
22
+ class TextToImage(Resource):
23
+ """Generate images from text prompts with Ideogram V3 models."""
24
+
25
+ ENDPOINT = "/api/v1/ideogram_v3/text_to_image"
26
+ RESPONSE_CLASS = IdeogramResponse
27
+ COMPLETED_RESPONSE_CLASS = CompletedIdeogramResponse
28
+ PROMPT_MAX_LENGTH = 5000
29
+
30
+ def run(self, **params: Any) -> Any:
31
+ """Create a text-to-image task and poll until it completes.
32
+
33
+ Args:
34
+ **params: Text-to-image parameters (model, prompt, ...).
35
+
36
+ Returns:
37
+ The completed (narrowed) response.
38
+ """
39
+ task = self.create(**params)
40
+ return self._poll_until_complete(lambda: self.get(task.id))
41
+
42
+ def create(self, **params: Any) -> Any:
43
+ """Create a text-to-image task and return immediately with an ``id``.
44
+
45
+ Args:
46
+ **params: Text-to-image parameters (model, prompt, ...).
47
+
48
+ Returns:
49
+ The task creation result with an id.
50
+ """
51
+ compacted = self._compact_params(params)
52
+ self._validate_params(compacted)
53
+ return self._request("post", self.ENDPOINT, body=compacted)
54
+
55
+ def get(self, id: str) -> Any:
56
+ """Fetch the current status of a text-to-image task.
57
+
58
+ Args:
59
+ id: The task id.
60
+
61
+ Returns:
62
+ The current task status.
63
+ """
64
+ return self._request("get", f"{self.ENDPOINT}/{id}")
65
+
66
+ def _validate_params(self, params: Dict[str, Any]) -> None:
67
+ model = params.get("model")
68
+ if not model:
69
+ raise ValidationError("model is required")
70
+ if model not in (GENERATION_MODEL, CHARACTER_MODEL):
71
+ raise ValidationError(
72
+ f"Invalid model: {model}. Must be {GENERATION_MODEL} or {CHARACTER_MODEL}"
73
+ )
74
+
75
+ prompt = params.get("prompt")
76
+ if not (isinstance(prompt, str) and prompt):
77
+ raise ValidationError("prompt is required")
78
+ if len(prompt) > self.PROMPT_MAX_LENGTH:
79
+ raise ValidationError(f"prompt must be at most {self.PROMPT_MAX_LENGTH} characters")
80
+
81
+ self._validate_optional(params, "rendering_speed", RENDERING_SPEEDS)
82
+ style_values = CHARACTER_STYLES if model == CHARACTER_MODEL else STYLES
83
+ self._validate_optional(params, "style", style_values)
84
+ self._validate_optional(params, "aspect_ratio", ASPECT_RATIOS)
85
+ self._validate_character_refs(params, model)
86
+ validate_output_count(params)
87
+
88
+ def _validate_character_refs(self, params: Dict[str, Any], model: str) -> None:
89
+ refs = params.get("reference_image_urls")
90
+ if model == CHARACTER_MODEL:
91
+ if not (isinstance(refs, list) and refs):
92
+ raise ValidationError("reference_image_urls is required")
93
+ elif refs:
94
+ raise ValidationError(f"reference_image_urls is not supported for {model}")
@@ -0,0 +1,38 @@
1
+ """Ideogram V3 model constants, enums, and response models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from runapi.core import BaseModel, TaskResponse, optional, required
6
+
7
+ GENERATION_MODEL = "ideogram-v3-text-to-image"
8
+ EDIT_MODEL = "ideogram-v3-edit"
9
+ REMIX_MODEL = "ideogram-v3-remix"
10
+ CHARACTER_MODEL = "ideogram-v3-character"
11
+ CHARACTER_EDIT_MODEL = "ideogram-v3-character-edit"
12
+ CHARACTER_REMIX_MODEL = "ideogram-v3-character-remix"
13
+ REFRAME_MODEL = "ideogram-v3-reframe"
14
+
15
+ RENDERING_SPEEDS = ["turbo", "balanced", "quality"]
16
+ STYLES = ["auto", "general", "realistic", "design"]
17
+ CHARACTER_STYLES = ["auto", "realistic", "fiction"]
18
+ ASPECT_RATIOS = ["1:1", "3:4", "9:16", "4:3", "16:9"]
19
+ OUTPUT_COUNTS = [1, 2, 3, 4]
20
+
21
+
22
+ class Image(BaseModel):
23
+ url = optional(str)
24
+
25
+
26
+ class IdeogramResponse(TaskResponse):
27
+ """Response for an Ideogram V3 image task."""
28
+
29
+ id = required(str)
30
+ status = optional(str, enum=lambda: TaskResponse.Status.ALL)
31
+ images = optional([lambda: Image])
32
+ error = optional(str)
33
+
34
+
35
+ class CompletedIdeogramResponse(IdeogramResponse):
36
+ """Narrowed response from ``run()`` once polling observes ``status: completed``."""
37
+
38
+ images = required([lambda: Image])
@@ -0,0 +1,358 @@
1
+ import pytest
2
+
3
+ from runapi.core import config
4
+ from runapi.core.errors import AuthenticationError, ValidationError
5
+ from runapi.ideogram_v3 import IdeogramV3Client
6
+ from runapi.ideogram_v3.resources.edit_image import EditImage
7
+ from runapi.ideogram_v3.resources.reframe_image import ReframeImage
8
+ from runapi.ideogram_v3.resources.remix_image import RemixImage
9
+ from runapi.ideogram_v3.resources.text_to_image import TextToImage
10
+ from runapi.ideogram_v3.types import CompletedIdeogramResponse, IdeogramResponse
11
+
12
+
13
+ class FakeHttp:
14
+ def __init__(self, *responses):
15
+ self._responses = list(responses)
16
+ self.calls = []
17
+
18
+ def request(self, method, path, body=None, options=None):
19
+ self.calls.append((method, path, body))
20
+ if self._responses:
21
+ return self._responses.pop(0)
22
+ return {"id": "task_1", "status": "pending"}
23
+
24
+
25
+ @pytest.fixture(autouse=True)
26
+ def reset_config(monkeypatch):
27
+ monkeypatch.delenv("RUNAPI_API_KEY", raising=False)
28
+ monkeypatch.setattr(config, "api_key", None)
29
+ yield
30
+
31
+
32
+ # --- auth -----------------------------------------------------------------
33
+
34
+
35
+ def test_accepts_api_key_parameter():
36
+ assert isinstance(IdeogramV3Client(api_key="k", http_client=FakeHttp()), IdeogramV3Client)
37
+
38
+
39
+ def test_falls_back_to_global(monkeypatch):
40
+ monkeypatch.setattr(config, "api_key", "global-key")
41
+ assert isinstance(IdeogramV3Client(http_client=FakeHttp()), IdeogramV3Client)
42
+
43
+
44
+ def test_falls_back_to_env(monkeypatch):
45
+ monkeypatch.setenv("RUNAPI_API_KEY", "env-key")
46
+ assert isinstance(IdeogramV3Client(http_client=FakeHttp()), IdeogramV3Client)
47
+
48
+
49
+ def test_raises_without_api_key():
50
+ with pytest.raises(AuthenticationError, match="API key is required"):
51
+ IdeogramV3Client()
52
+
53
+
54
+ # --- injection / accessors ------------------------------------------------
55
+
56
+
57
+ def test_uses_injected_http_client():
58
+ fake = FakeHttp()
59
+ client = IdeogramV3Client(api_key="k", http_client=fake)
60
+ assert client.text_to_image._http is fake
61
+ assert client.edit_image._http is fake
62
+ assert client.remix_image._http is fake
63
+ assert client.reframe_image._http is fake
64
+
65
+
66
+ def test_exposes_resource_accessors():
67
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
68
+ assert isinstance(client.text_to_image, TextToImage)
69
+ assert isinstance(client.edit_image, EditImage)
70
+ assert isinstance(client.remix_image, RemixImage)
71
+ assert isinstance(client.reframe_image, ReframeImage)
72
+
73
+
74
+ # --- request shapes -------------------------------------------------------
75
+
76
+
77
+ def test_text_to_image_create_posts_compacted_body():
78
+ fake = FakeHttp({"id": "t1", "status": "pending"})
79
+ client = IdeogramV3Client(api_key="k", http_client=fake)
80
+ result = client.text_to_image.create(
81
+ model="ideogram-v3-text-to-image",
82
+ prompt="hello world",
83
+ aspect_ratio="1:1",
84
+ rendering_speed=None,
85
+ )
86
+ assert fake.calls == [
87
+ (
88
+ "post",
89
+ "/api/v1/ideogram_v3/text_to_image",
90
+ {"model": "ideogram-v3-text-to-image", "prompt": "hello world", "aspect_ratio": "1:1"},
91
+ ),
92
+ ]
93
+ assert isinstance(result, IdeogramResponse)
94
+
95
+
96
+ def test_text_to_image_get_fetches_by_id():
97
+ fake = FakeHttp({"id": "t1", "status": "processing"})
98
+ client = IdeogramV3Client(api_key="k", http_client=fake)
99
+ client.text_to_image.get("t1")
100
+ assert fake.calls == [("get", "/api/v1/ideogram_v3/text_to_image/t1", None)]
101
+
102
+
103
+ def test_edit_image_create_posts_body():
104
+ fake = FakeHttp({"id": "t1", "status": "pending"})
105
+ client = IdeogramV3Client(api_key="k", http_client=fake)
106
+ client.edit_image.create(
107
+ model="ideogram-v3-edit",
108
+ prompt="add aurora",
109
+ source_image_url="https://x/a.png",
110
+ mask_url="https://x/m.png",
111
+ )
112
+ assert fake.calls == [
113
+ (
114
+ "post",
115
+ "/api/v1/ideogram_v3/edit_image",
116
+ {
117
+ "model": "ideogram-v3-edit",
118
+ "prompt": "add aurora",
119
+ "source_image_url": "https://x/a.png",
120
+ "mask_url": "https://x/m.png",
121
+ },
122
+ ),
123
+ ]
124
+
125
+
126
+ def test_remix_image_create_posts_body():
127
+ fake = FakeHttp({"id": "t1", "status": "pending"})
128
+ client = IdeogramV3Client(api_key="k", http_client=fake)
129
+ client.remix_image.create(
130
+ model="ideogram-v3-remix",
131
+ prompt="remix it",
132
+ source_image_url="https://x/a.png",
133
+ strength=0.5,
134
+ )
135
+ assert fake.calls == [
136
+ (
137
+ "post",
138
+ "/api/v1/ideogram_v3/remix_image",
139
+ {
140
+ "model": "ideogram-v3-remix",
141
+ "prompt": "remix it",
142
+ "source_image_url": "https://x/a.png",
143
+ "strength": 0.5,
144
+ },
145
+ ),
146
+ ]
147
+
148
+
149
+ def test_remix_image_get_fetches_by_id():
150
+ fake = FakeHttp({"id": "t1", "status": "processing"})
151
+ client = IdeogramV3Client(api_key="k", http_client=fake)
152
+ client.remix_image.get("t1")
153
+ assert fake.calls == [("get", "/api/v1/ideogram_v3/remix_image/t1", None)]
154
+
155
+
156
+ def test_reframe_image_create_posts_body():
157
+ fake = FakeHttp({"id": "t1", "status": "pending"})
158
+ client = IdeogramV3Client(api_key="k", http_client=fake)
159
+ client.reframe_image.create(
160
+ model="ideogram-v3-reframe",
161
+ source_image_url="https://x/a.png",
162
+ aspect_ratio="16:9",
163
+ )
164
+ assert fake.calls == [
165
+ (
166
+ "post",
167
+ "/api/v1/ideogram_v3/reframe_image",
168
+ {
169
+ "model": "ideogram-v3-reframe",
170
+ "source_image_url": "https://x/a.png",
171
+ "aspect_ratio": "16:9",
172
+ },
173
+ ),
174
+ ]
175
+
176
+
177
+ def test_reframe_image_get_fetches_by_id():
178
+ fake = FakeHttp({"id": "t1", "status": "processing"})
179
+ client = IdeogramV3Client(api_key="k", http_client=fake)
180
+ client.reframe_image.get("t1")
181
+ assert fake.calls == [("get", "/api/v1/ideogram_v3/reframe_image/t1", None)]
182
+
183
+
184
+ # --- run() narrowing ------------------------------------------------------
185
+
186
+
187
+ def test_text_to_image_run_narrows_completed_type():
188
+ fake = FakeHttp(
189
+ {"id": "t1", "status": "pending"},
190
+ {"id": "t1", "status": "completed", "images": [{"url": "https://x/y.png"}]},
191
+ )
192
+ client = IdeogramV3Client(api_key="k", http_client=fake)
193
+ result = client.text_to_image.run(
194
+ model="ideogram-v3-text-to-image", prompt="a serene lake"
195
+ )
196
+ assert isinstance(result, CompletedIdeogramResponse)
197
+ assert result.images[0].url == "https://x/y.png"
198
+
199
+
200
+ def test_reframe_image_run_narrows_completed_type():
201
+ fake = FakeHttp(
202
+ {"id": "t1", "status": "pending"},
203
+ {"id": "t1", "status": "completed", "images": [{"url": "https://x/r.png"}]},
204
+ )
205
+ client = IdeogramV3Client(api_key="k", http_client=fake)
206
+ result = client.reframe_image.run(
207
+ model="ideogram-v3-reframe", source_image_url="https://x/a.png", aspect_ratio="16:9"
208
+ )
209
+ assert isinstance(result, CompletedIdeogramResponse)
210
+ assert result.images[0].url == "https://x/r.png"
211
+
212
+
213
+ # --- validation: model + shared --------------------------------------------
214
+
215
+
216
+ def test_text_to_image_rejects_unknown_model():
217
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
218
+ with pytest.raises(ValidationError, match="Invalid model: nope"):
219
+ client.text_to_image.create(model="nope", prompt="hi there")
220
+
221
+
222
+ def test_text_to_image_requires_prompt():
223
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
224
+ with pytest.raises(ValidationError, match="prompt is required"):
225
+ client.text_to_image.create(model="ideogram-v3-text-to-image")
226
+
227
+
228
+ def test_text_to_image_rejects_invalid_style_enum():
229
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
230
+ with pytest.raises(ValidationError, match="Invalid style: bogus"):
231
+ client.text_to_image.create(
232
+ model="ideogram-v3-text-to-image", prompt="hi there", style="bogus"
233
+ )
234
+
235
+
236
+ def test_text_to_image_output_count_enum():
237
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
238
+ with pytest.raises(ValidationError, match="Invalid output_count: 9"):
239
+ client.text_to_image.create(
240
+ model="ideogram-v3-text-to-image", prompt="hi there", output_count=9
241
+ )
242
+
243
+
244
+ def test_character_model_requires_reference_image_urls():
245
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
246
+ with pytest.raises(ValidationError, match="reference_image_urls is required"):
247
+ client.text_to_image.create(model="ideogram-v3-character", prompt="hi there")
248
+
249
+
250
+ def test_text_to_image_rejects_reference_image_urls_for_base_model():
251
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
252
+ with pytest.raises(
253
+ ValidationError, match="reference_image_urls is not supported for ideogram-v3-text-to-image"
254
+ ):
255
+ client.text_to_image.create(
256
+ model="ideogram-v3-text-to-image",
257
+ prompt="hi there",
258
+ reference_image_urls=["https://x/a.png"],
259
+ )
260
+
261
+
262
+ # --- validation: edit ------------------------------------------------------
263
+
264
+
265
+ def test_edit_requires_source_and_mask():
266
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
267
+ with pytest.raises(ValidationError, match="source_image_url is required"):
268
+ client.edit_image.create(model="ideogram-v3-edit", prompt="x")
269
+ with pytest.raises(ValidationError, match="mask_url is required"):
270
+ client.edit_image.create(
271
+ model="ideogram-v3-edit", prompt="x", source_image_url="https://x/a.png"
272
+ )
273
+
274
+
275
+ def test_edit_rejects_character_fields_for_base_model():
276
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
277
+ with pytest.raises(
278
+ ValidationError, match="character edit fields are not supported for ideogram-v3-edit"
279
+ ):
280
+ client.edit_image.create(
281
+ model="ideogram-v3-edit",
282
+ prompt="x",
283
+ source_image_url="https://x/a.png",
284
+ mask_url="https://x/m.png",
285
+ style="auto",
286
+ )
287
+
288
+
289
+ # --- validation: remix -----------------------------------------------------
290
+
291
+
292
+ def test_remix_requires_source_image_url():
293
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
294
+ with pytest.raises(ValidationError, match="source_image_url is required"):
295
+ client.remix_image.create(model="ideogram-v3-remix", prompt="x")
296
+
297
+
298
+ def test_remix_strength_out_of_range():
299
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
300
+ with pytest.raises(ValidationError, match="strength must be between 0.01 and 1.0"):
301
+ client.remix_image.create(
302
+ model="ideogram-v3-remix",
303
+ prompt="x",
304
+ source_image_url="https://x/a.png",
305
+ strength=2,
306
+ )
307
+
308
+
309
+ def test_remix_character_strength_min_differs():
310
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
311
+ with pytest.raises(ValidationError, match="strength must be between 0.1 and 1.0"):
312
+ client.remix_image.create(
313
+ model="ideogram-v3-character-remix",
314
+ prompt="x",
315
+ source_image_url="https://x/a.png",
316
+ reference_image_urls=["https://x/r.png"],
317
+ strength=0.05,
318
+ )
319
+
320
+
321
+ def test_remix_rejects_character_fields_for_base_model():
322
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
323
+ with pytest.raises(
324
+ ValidationError, match="character remix fields are not supported for ideogram-v3-remix"
325
+ ):
326
+ client.remix_image.create(
327
+ model="ideogram-v3-remix",
328
+ prompt="x",
329
+ source_image_url="https://x/a.png",
330
+ reference_image_urls=["https://x/r.png"],
331
+ )
332
+
333
+
334
+ # --- validation: reframe ---------------------------------------------------
335
+
336
+
337
+ def test_reframe_rejects_unknown_model():
338
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
339
+ with pytest.raises(ValidationError, match="Must be ideogram-v3-reframe"):
340
+ client.reframe_image.create(
341
+ model="ideogram-v3-remix", source_image_url="https://x/a.png", aspect_ratio="1:1"
342
+ )
343
+
344
+
345
+ def test_reframe_requires_aspect_ratio():
346
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
347
+ with pytest.raises(ValidationError, match="aspect_ratio is required"):
348
+ client.reframe_image.create(
349
+ model="ideogram-v3-reframe", source_image_url="https://x/a.png"
350
+ )
351
+
352
+
353
+ def test_reframe_rejects_invalid_aspect_ratio_enum():
354
+ client = IdeogramV3Client(api_key="k", http_client=FakeHttp())
355
+ with pytest.raises(ValidationError, match="Invalid aspect_ratio: 21:9"):
356
+ client.reframe_image.create(
357
+ model="ideogram-v3-reframe", source_image_url="https://x/a.png", aspect_ratio="21:9"
358
+ )