Skip to content

Protocol & Types

protocol

codex_ai.core.protocol

Core types and contracts for the LLM abstraction layer.

PromptResult — frozen DTO returned by every prompt builder. LLMProviderProtocol — adapter contract for LLM backends (OpenAI, Gemini, etc.). 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 LLM provider's answer() method.

Attributes:

Name Type Description
messages list[LLMMessage]

Provider-specific message list (OpenAI ChatCompletionMessageParam format or Gemini contents). Each provider interprets this field as needed.

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
65
class PromptResult(BaseDTO):
    """
    Frozen DTO produced by a prompt builder.

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

    Attributes:
        messages: Provider-specific message list (OpenAI ChatCompletionMessageParam format
                  or Gemini contents). Each provider interprets this field as needed.
        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

LLMProviderProtocol

Bases: Protocol

Adapter contract for LLM backends.

Implement this protocol to add a new provider (OpenAI, Gemini, Anthropic, etc.).

Example
class MockProvider:
    async def answer(self, prompt: PromptResult, **kw: Any) -> str:
        return "mocked response"
Source code in src/codex_ai/core/protocol.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
@runtime_checkable
class LLMProviderProtocol(Protocol):
    """
    Adapter contract for LLM backends.

    Implement this protocol to add a new provider (OpenAI, Gemini, Anthropic, etc.).

    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 prompt to the LLM 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 LLM.
        """
        ...
Functions
answer(prompt, **kw) async

Send prompt to the LLM 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 LLM.

Source code in src/codex_ai/core/protocol.py
83
84
85
86
87
88
89
90
91
92
93
94
async def answer(self, prompt: PromptResult, **kw: Any) -> str:
    """
    Send prompt to the LLM 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 LLM.
    """
    ...

TextGenerationProvider

Bases: Protocol

Optional adapter contract for direct provider text generation.

Source code in src/codex_ai/core/protocol.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
@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
103
104
105
106
107
108
109
110
111
112
113
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
@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
122
123
124
125
126
127
128
129
130
131
132
133
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@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,
        **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"}``.
            **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, **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
**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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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,
    **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"}``.
        **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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
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)``.
    """
    ...