Skip to content

Protocol & Types

protocol

codex_ai.core.protocol

Core types and contracts for legacy text routing and direct provider helpers.

PromptResult — frozen DTO returned by every prompt builder. LLMProviderProtocol — legacy text compatibility contract for answer(). TextGenerationProvider — optional adapter contract for direct text generation. JsonGenerationProvider — optional adapter contract for direct JSON generation. ImageGenerationProvider — optional adapter contract for binary image generation. ImagenGenerationProvider — optional adapter contract for Imagen image generation. PromptBuilder — type alias for async builder functions registered via LLMRouter.

Classes

LLMMessage

Bases: BaseDTO

Strict contract for single message exchanged with LLM.

Source code in src/codex_ai/core/protocol.py
29
30
31
32
33
34
35
class LLMMessage(BaseDTO):
    """
    Strict contract for single message exchanged with LLM.
    """

    role: Literal["user", "assistant", "system"]
    content: str

PromptResult

Bases: BaseDTO

Frozen DTO produced by a prompt builder.

Passed directly to the provider's legacy text answer() method.

Attributes:

Name Type Description
messages list[LLMMessage]

Ordered text message list consumed by compatibility adapters.

system str

Optional system/developer instruction (top-level string, used by Gemini and OpenAI o-series models that accept a dedicated system field).

Example
result = PromptResult(
    messages=[LLMMessage(role="user", content="Hello!")],
    system="You are a helpful assistant.",
)
Source code in src/codex_ai/core/protocol.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class PromptResult(BaseDTO):
    """
    Frozen DTO produced by a prompt builder.

    Passed directly to the provider's legacy text ``answer()`` method.

    Attributes:
        messages: Ordered text message list consumed by compatibility adapters.
        system: Optional system/developer instruction (top-level string, used by Gemini
                and OpenAI o-series models that accept a dedicated system field).

    Example:
        ```python
        result = PromptResult(
            messages=[LLMMessage(role="user", content="Hello!")],
            system="You are a helpful assistant.",
        )
        ```
    """

    model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)

    messages: list[LLMMessage]
    system: str = ""
    model: str | None = None
    temperature: float | None = None
    max_tokens: int | None = None

ImageInput

Bases: BaseDTO

Binary image input used as a reference or edit source for image generation.

Attributes:

Name Type Description
data bytes

Raw image bytes.

mime_type str

Image MIME type, for example "image/png" or "image/jpeg".

Source code in src/codex_ai/core/protocol.py
67
68
69
70
71
72
73
74
75
76
77
78
79
class ImageInput(BaseDTO):
    """
    Binary image input used as a reference or edit source for image generation.

    Attributes:
        data: Raw image bytes.
        mime_type: Image MIME type, for example ``"image/png"`` or ``"image/jpeg"``.
    """

    model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)

    data: bytes
    mime_type: str

LLMProviderProtocol

Bases: Protocol

Legacy text adapter contract.

New Gemini integrations should prefer direct provider methods such as generate_text(), generate_json(), and generate_image_bytes(). This protocol remains for router/dispatcher text compatibility.

Example
class MockProvider:
    async def answer(self, prompt: PromptResult, **kw: Any) -> str:
        return "mocked response"
Source code in src/codex_ai/core/protocol.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
@runtime_checkable
class LLMProviderProtocol(Protocol):
    """
    Legacy text adapter contract.

    New Gemini integrations should prefer direct provider methods such as
    ``generate_text()``, ``generate_json()``, and ``generate_image_bytes()``.
    This protocol remains for router/dispatcher text compatibility.

    Example:
        ```python
        class MockProvider:
            async def answer(self, prompt: PromptResult, **kw: Any) -> str:
                return "mocked response"
        ```
    """

    async def answer(self, prompt: PromptResult, **kw: Any) -> str:
        """
        Send a legacy text prompt and return the response text.

        Args:
            prompt: Frozen DTO with messages and system instruction.
            **kw: Extra provider-specific kwargs (temperature, max_tokens, etc.).

        Returns:
            Response text from the provider.
        """
        ...
Functions
answer(prompt, **kw) async

Send a legacy text prompt and return the response text.

Parameters:

Name Type Description Default
prompt PromptResult

Frozen DTO with messages and system instruction.

required
**kw Any

Extra provider-specific kwargs (temperature, max_tokens, etc.).

{}

Returns:

Type Description
str

Response text from the provider.

Source code in src/codex_ai/core/protocol.py
102
103
104
105
106
107
108
109
110
111
112
113
async def answer(self, prompt: PromptResult, **kw: Any) -> str:
    """
    Send a legacy text prompt and return the response text.

    Args:
        prompt: Frozen DTO with messages and system instruction.
        **kw: Extra provider-specific kwargs (temperature, max_tokens, etc.).

    Returns:
        Response text from the provider.
    """
    ...

TextGenerationProvider

Bases: Protocol

Optional adapter contract for direct provider text generation.

Source code in src/codex_ai/core/protocol.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
@runtime_checkable
class TextGenerationProvider(Protocol):
    """
    Optional adapter contract for direct provider text generation.
    """

    async def generate_text(
        self,
        prompt: PromptResult | str,
        *,
        model: str | None = None,
        **kwargs: Any,
    ) -> str:
        """
        Generate plain text from a prompt DTO or a raw prompt string.
        """
        ...
Functions
generate_text(prompt, *, model=None, **kwargs) async

Generate plain text from a prompt DTO or a raw prompt string.

Source code in src/codex_ai/core/protocol.py
122
123
124
125
126
127
128
129
130
131
132
async def generate_text(
    self,
    prompt: PromptResult | str,
    *,
    model: str | None = None,
    **kwargs: Any,
) -> str:
    """
    Generate plain text from a prompt DTO or a raw prompt string.
    """
    ...

JsonGenerationProvider

Bases: Protocol

Optional adapter contract for provider-native JSON generation.

Source code in src/codex_ai/core/protocol.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
@runtime_checkable
class JsonGenerationProvider(Protocol):
    """
    Optional adapter contract for provider-native JSON generation.
    """

    async def generate_json(
        self,
        prompt: PromptResult | str,
        *,
        schema: type[BaseModel] | None = None,
        model: str | None = None,
        **kwargs: Any,
    ) -> Any:
        """
        Generate JSON and validate it locally when a Pydantic schema is provided.
        """
        ...
Functions
generate_json(prompt, *, schema=None, model=None, **kwargs) async

Generate JSON and validate it locally when a Pydantic schema is provided.

Source code in src/codex_ai/core/protocol.py
141
142
143
144
145
146
147
148
149
150
151
152
async def generate_json(
    self,
    prompt: PromptResult | str,
    *,
    schema: type[BaseModel] | None = None,
    model: str | None = None,
    **kwargs: Any,
) -> Any:
    """
    Generate JSON and validate it locally when a Pydantic schema is provided.
    """
    ...

ImageGenerationProvider

Bases: Protocol

Optional adapter contract for providers that can generate image bytes.

This is intentionally separate from LLMProviderProtocol.answer() because image generation returns binary parts, not text.

Source code in src/codex_ai/core/protocol.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
@runtime_checkable
class ImageGenerationProvider(Protocol):
    """
    Optional adapter contract for providers that can generate image bytes.

    This is intentionally separate from ``LLMProviderProtocol.answer()`` because
    image generation returns binary parts, not text.
    """

    async def generate_image_bytes(
        self,
        prompt: str,
        *,
        model: str | None = None,
        response_mime_type: str = "image/webp",
        image_config: dict[str, Any] | None = None,
        input_images: list[ImageInputLike] | None = None,
        **kwargs: Any,
    ) -> tuple[bytes, str]:
        """
        Generate an image and return raw bytes plus the actual content type.

        Args:
            prompt: Plain image-generation prompt.
            model: Optional image model override.
            response_mime_type: Requested/preferred image MIME type.
            image_config: Optional image generation controls such as
                ``{"aspect_ratio": "1:1", "image_size": "4K"}``.
            input_images: Optional reference/source images for image editing or
                image-conditioned generation.
            **kwargs: Extra provider-specific kwargs.

        Returns:
            Tuple of ``(image_bytes, content_type)``.
        """
        ...
Functions
generate_image_bytes(prompt, *, model=None, response_mime_type='image/webp', image_config=None, input_images=None, **kwargs) async

Generate an image and return raw bytes plus the actual content type.

Parameters:

Name Type Description Default
prompt str

Plain image-generation prompt.

required
model str | None

Optional image model override.

None
response_mime_type str

Requested/preferred image MIME type.

'image/webp'
image_config dict[str, Any] | None

Optional image generation controls such as {"aspect_ratio": "1:1", "image_size": "4K"}.

None
input_images list[ImageInputLike] | None

Optional reference/source images for image editing or image-conditioned generation.

None
**kwargs Any

Extra provider-specific kwargs.

{}

Returns:

Type Description
tuple[bytes, str]

Tuple of (image_bytes, content_type).

Source code in src/codex_ai/core/protocol.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
async def generate_image_bytes(
    self,
    prompt: str,
    *,
    model: str | None = None,
    response_mime_type: str = "image/webp",
    image_config: dict[str, Any] | None = None,
    input_images: list[ImageInputLike] | None = None,
    **kwargs: Any,
) -> tuple[bytes, str]:
    """
    Generate an image and return raw bytes plus the actual content type.

    Args:
        prompt: Plain image-generation prompt.
        model: Optional image model override.
        response_mime_type: Requested/preferred image MIME type.
        image_config: Optional image generation controls such as
            ``{"aspect_ratio": "1:1", "image_size": "4K"}``.
        input_images: Optional reference/source images for image editing or
            image-conditioned generation.
        **kwargs: Extra provider-specific kwargs.

    Returns:
        Tuple of ``(image_bytes, content_type)``.
    """
    ...

ImagenGenerationProvider

Bases: Protocol

Optional adapter contract for providers that expose Imagen image generation.

This is separate from ImageGenerationProvider because Gemini image models and Imagen models use different SDK methods and MIME configuration fields.

Source code in src/codex_ai/core/protocol.py
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
@runtime_checkable
class ImagenGenerationProvider(Protocol):
    """
    Optional adapter contract for providers that expose Imagen image generation.

    This is separate from ``ImageGenerationProvider`` because Gemini image models
    and Imagen models use different SDK methods and MIME configuration fields.
    """

    async def generate_imagen_bytes(
        self,
        prompt: str,
        *,
        model: str | None = None,
        response_mime_type: str = "image/jpeg",
        **kwargs: Any,
    ) -> tuple[bytes, str]:
        """
        Generate an Imagen image and return raw bytes plus the actual content type.

        Args:
            prompt: Plain image-generation prompt.
            model: Optional Imagen model override.
            response_mime_type: Requested image MIME type passed to Imagen when supported.
            **kwargs: Extra provider-specific kwargs.

        Returns:
            Tuple of ``(image_bytes, content_type)``.
        """
        ...
Functions
generate_imagen_bytes(prompt, *, model=None, response_mime_type='image/jpeg', **kwargs) async

Generate an Imagen image and return raw bytes plus the actual content type.

Parameters:

Name Type Description Default
prompt str

Plain image-generation prompt.

required
model str | None

Optional Imagen model override.

None
response_mime_type str

Requested image MIME type passed to Imagen when supported.

'image/jpeg'
**kwargs Any

Extra provider-specific kwargs.

{}

Returns:

Type Description
tuple[bytes, str]

Tuple of (image_bytes, content_type).

Source code in src/codex_ai/core/protocol.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
async def generate_imagen_bytes(
    self,
    prompt: str,
    *,
    model: str | None = None,
    response_mime_type: str = "image/jpeg",
    **kwargs: Any,
) -> tuple[bytes, str]:
    """
    Generate an Imagen image and return raw bytes plus the actual content type.

    Args:
        prompt: Plain image-generation prompt.
        model: Optional Imagen model override.
        response_mime_type: Requested image MIME type passed to Imagen when supported.
        **kwargs: Extra provider-specific kwargs.

    Returns:
        Tuple of ``(image_bytes, content_type)``.
    """
    ...