Skip to content

Overview

Public exception types for gllm-multimodal.

AudioDebugInfo

Bases: _DiagnosticModel

Sanitized properties of an audio stream.

Attributes:

Name Type Description
duration_seconds float | None

Audio duration in seconds.

sample_rate_hz int | None

Audio sampling rate in hertz.

channels int | None

Number of audio channels.

codec str | None

Safe identifier for the audio codec.

anomalies list[DiagnosticAnomaly] | None

Bounded records for numeric details omitted as invalid.

record_audio_anomalies(value) classmethod

Record invalid audio numbers before normalizing them away.

Parameters:

Name Type Description Default
value object

Untrusted audio details.

required

Returns:

Type Description
object

Audio details augmented with bounded numeric anomaly records.

validate_channels(value) classmethod

Keep only positive channel counts within the limit.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
int | None

The channel count when valid, or None otherwise.

validate_codec(value) classmethod

Keep only a safe audio codec identifier.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The safe codec identifier, or None otherwise.

validate_duration(value) classmethod

Keep only finite, positive audio durations within the limit.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
float | None

The duration when it is finite, positive, and within the limit; otherwise, None.

validate_sample_rate(value) classmethod

Keep only supported positive audio sample rates.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
int | None

The sample rate when supported, or None otherwise.

ComponentConfigError(*, component, parameter, next_step, debug_info=None)

Bases: ComponentError, ValueError

Report an invalid or missing option for any multimodal component.

Use this during component setup when a required setting is absent or invalid, before a media operation starts.

Example

A converter is created without a required model name.

from gllm_multimodal.exceptions import ComponentConfigError

error = ComponentConfigError(
    component="Audio transcription",
    parameter="model_name",
    next_step="Configure a supported model name and try again.",
)
print(error.message)
Output:
Audio transcription needs a valid model_name. Configure a supported model name and try again.

Initialize the error with the component, option, and corrective action.

Parameters:

Name Type Description Default
component str

Name of the component with invalid or missing configuration.

required
parameter str

Required option or setting that needs correction.

required
next_step str

Action for supplying or correcting the parameter.

required
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

from_validation_error(error, *, component, subject, default_parameter, debug_info=None) classmethod

Create the error from a pydantic validation failure of the component's configuration.

The error names the first offending field and repeats pydantic's reason in its next step. An unknown option, or a failure that is not tied to one field, is reported against default_parameter.

Example

A processor is configured with a non-positive frame rate.

error = ComponentConfigError.from_validation_error(
    validation_error,
    component="GstFrameSamplingProcessor",
    subject="GstFrameSamplingConfig options",
    default_parameter="config",
)
print(error.message)
Output:
GstFrameSamplingProcessor needs a valid default_target_fps. Check the GstFrameSamplingConfig options: default_target_fps must be greater than 0.

Parameters:

Name Type Description Default
error ValidationError

The pydantic validation failure.

required
component str

Name of the component with invalid configuration.

required
subject str

What the caller should check, named in the next step, such as "GstFrameSamplingConfig options" or "target_fps argument".

required
default_parameter str

Parameter reported when the failure is not tied to a single valid field.

required
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

Returns:

Type Description
Self

The configuration error. The caller raises it from error.

ComponentError(*, debug_info=None, _message=None, message_values=None)

Bases: MultimodalError

Abstract family for component setup, configuration, and availability failures.

Use this family when a processor cannot be configured or a required backend or model cannot be prepared.

Example

Catch setup errors before requesting media processing.

from gllm_multimodal.exceptions import ComponentError, MediaBackendUnavailableError

try:
    raise MediaBackendUnavailableError(backend="FFmpeg")
except ComponentError as error:
    print(error.message)
Output:
The selected FFmpeg backend is unavailable. Check that it is installed, or select another backend.

ComponentModelError(*, model, failure, debug_info=None)

Bases: ComponentError, RuntimeError

Report failure to obtain or prepare model weights during component setup.

Use this when downloading, caching, or verifying model weights fails.

Example

A detector downloads a built-in model, but the received file fails integrity verification.

from textwrap import fill
from gllm_multimodal.exceptions import ComponentModelError

error = ComponentModelError(model="ppocrv6_small", failure="integrity")
print(fill(error.message, width=100))
Output:
The ppocrv6_small model could not be prepared: its weights failed integrity verification. Retry the
download; if it repeats, ask the application owner to verify the model artifact.

Initialize a model preparation error with a specific recovery action.

Parameters:

Name Type Description Default
model str

Safe model identifier, without a directory path.

required
failure str

One of download, cache, lock, size_limit, integrity, or local_file.

required
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

Raises:

Type Description
ValueError

If the identifier or failure category is invalid.

ComponentUnexpectedError(*, error_type, detail, component=None, next_step=None, debug_info=None)

Bases: _UnexpectedErrorMessage, ComponentError

Fallback for unclassified component setup or availability failures.

Use this when startup fails and no specific component error covers the cause. Pass only a safe summary of the original cause.

Example

A backend raises an unfamiliar error while it initializes.

from textwrap import fill
from gllm_multimodal.exceptions import ComponentUnexpectedError

error = ComponentUnexpectedError(
    error_type="RuntimeError",
    detail="the backend could not initialize",
    component="video decoder",
)
print(fill(error.message, width=100))
Output:
The video decoder failed with RuntimeError: the backend could not initialize. Check component
configuration and installation, then contact the application owner if it persists.

DiagnosticAnomaly

Bases: _DiagnosticModel

A bounded explanation for a modality detail omitted during validation.

Attributes:

Name Type Description
field AnomalyField

Name of the modality detail that failed validation.

reason AnomalyReason

Stable reason code describing the validation failure.

observed_value int | float | bool | str | None

Safe primitive value when it is finite and bounded.

validate_field(value) classmethod

Keep only names of numeric modality details.

Parameters:

Name Type Description Default
value object

Untrusted anomaly field name.

required

Returns:

Type Description
str

The allowed field name, or unknown when unsupported.

validate_observed_value(value) classmethod

Keep a safe, bounded primitive anomaly value.

Parameters:

Name Type Description Default
value object

Untrusted observed value.

required

Returns:

Type Description
int | float | bool | str | None

The value when it is a bounded primitive, otherwise None.

validate_reason(value) classmethod

Keep a supported anomaly reason code.

Parameters:

Name Type Description Default
value object

Untrusted anomaly reason.

required

Returns:

Type Description
str

The supported reason, or invalid_type when unsupported.

ImageDebugInfo

Bases: _DiagnosticModel

Sanitized visual properties of an image.

Attributes:

Name Type Description
width int | None

Image width in pixels.

height int | None

Image height in pixels.

anomalies list[DiagnosticAnomaly] | None

Bounded records for dimensions omitted as invalid.

record_dimension_anomalies(value) classmethod

Record invalid dimensions before they are omitted from normalized details.

Parameters:

Name Type Description Default
value object

Untrusted image details.

required

Returns:

Type Description
object

Image details augmented with bounded dimension anomaly records.

validate_dimension(value) classmethod

Keep only positive pixel dimensions within the configured limit.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
int | None

The pixel dimension when valid, or None otherwise.

MediaBackendUnavailableError(*, backend=None, next_step=None, debug_info=None)

Bases: ComponentError, RuntimeError

Report a missing media component needed by the selected backend.

Use this during setup when a selected backend cannot run because its executable or required library is unavailable.

Example

A processor selects FFmpeg, but FFmpeg is not installed.

from gllm_multimodal.exceptions import MediaBackendUnavailableError

error = MediaBackendUnavailableError(backend="FFmpeg")
print(error.message)
Output:
The selected FFmpeg backend is unavailable. Check that it is installed, or select another backend.

Initialize the error with backend context and recovery guidance.

Parameters:

Name Type Description Default
backend str | None

Name of the unavailable backend, if known. Defaults to "media".

None
next_step str | None

Suggested recovery action. Defaults to checking the backend installation or selecting another backend.

None
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

MediaError(*, debug_info=None, _message=None, message_values=None)

Bases: MultimodalError

Abstract family for failures about media content or its source.

Use this family when a file is missing, unreadable, or unsuitable as input.

Example

Catch any media input or source error with one handler.

from gllm_multimodal.exceptions import MediaError, MediaSourceNotFoundError

try:
    raise MediaSourceNotFoundError(source_path="/data/video.mp4")
except MediaError as error:
    print(error.message)
Output:
We could not find /data/video.mp4. Check that it exists and is available to this application.

MediaInputInvalidError(*, valid_input=None, debug_info=None)

Bases: MediaError, ValueError

Report input that cannot be resolved as a supported media source.

Use this when the input itself cannot be accepted or parsed; use MediaInputUnsupportedError when its media type is known but disallowed by an operation's allowlist.

Example

A call expects bytes or a URL, but receives an unrelated object.

from gllm_multimodal.exceptions import MediaInputInvalidError

error = MediaInputInvalidError(valid_input="Provide media bytes or an HTTP URL.")
print(error.message)
Output:
No media could be loaded from the supplied input. Provide media bytes or an HTTP URL.

Initialize the error with the accepted input forms for this call.

Parameters:

Name Type Description Default
valid_input str | None

Description of accepted input forms. Defaults to guidance for supplying bytes, base64 data, a local path, or a URL.

None
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

MediaInputUnsupportedError(*, mime_type=None, supported_mime_types=(), input_kind=None, supported_input_kinds=(), debug_info=None)

Bases: MediaError, ValueError

Report valid media or a valid source form an operation does not support.

When an allowlist is supplied, the safe message and serializer include its normalized MIME patterns or supported input forms so callers can choose an accepted input. A media type is represented by its MIME type, such as image/png.

Example

A frame extractor accepts video files, but receives a PNG image.

from textwrap import fill
from gllm_multimodal.exceptions import MediaInputUnsupportedError

error = MediaInputUnsupportedError(
    mime_type="image/png",
    supported_mime_types=("video/mp4",),
)
print(fill(error.message, width=100))
Output:
The input is valid, but this operation does not support media type (MIME type image/png). Use one of
these media types: video/mp4.

Initialize an unsupported media type or source form error.

Parameters:

Name Type Description Default
mime_type str | None

Detected or declared media type, represented as a MIME type, that the operation rejected.

None
supported_mime_types tuple[str, ...] | list[str]

Accepted media types represented as MIME types or wildcard patterns, included in the error message.

()
input_kind str | None

Rejected input form, such as "url" or "path".

None
supported_input_kinds tuple[str, ...] | list[str]

Input forms accepted by the operation, such as ("bytes",).

()
debug_info DebugInfo | None

Optional diagnostic fields to sanitize and retain.

None

Raises:

Type Description
ValueError

If neither a MIME type nor an input kind is supplied, or if a supplied value is malformed or unsupported.

to_safe_dict(*, include_debug_info=False)

Return safe fields and accepted media types or input forms.

Parameters:

Name Type Description Default
include_debug_info bool

Include sanitized diagnostic context.

False

Returns:

Type Description
dict[str, Any]

Public error fields, optional diagnostics, and optional accepted

dict[str, Any]

media types or input forms.

MediaOperationConfigError(*, component, parameter, next_step, debug_info=None)

Bases: MediaOperationError, ValueError

Report invalid or incomplete options for a media operation.

Use this when one processing call lacks a required option, such as frame timestamps, while the processor itself is configured and available.

Example

A frame extraction request omits its timestamps.

from gllm_multimodal.exceptions import MediaOperationConfigError

error = MediaOperationConfigError(
    component="Frame extraction",
    parameter="timestamps",
    next_step="Pass process_config.timestamps or call set_timestamps().",
)
print(error.message)
Output:
Frame extraction requires timestamps. Pass process_config.timestamps or call set_timestamps().

Initialize a configuration error with context and recovery guidance.

Parameters:

Name Type Description Default
component str

Name of the media operation that needs configuration.

required
parameter str

Required option or setting that is missing or invalid.

required
next_step str

Action for supplying or correcting the parameter.

required
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

from_validation_error(error, *, component, subject, default_parameter, debug_info=None) classmethod

Create the error from a pydantic validation failure of one call's options.

The error names the first offending field and repeats pydantic's reason in its next step. An unknown option, or a failure that is not tied to one field, is reported against default_parameter.

Example

A frame sampling call passes a non-positive frame rate.

error = MediaOperationConfigError.from_validation_error(
    validation_error,
    component="Frame sampling",
    subject="process_config options",
    default_parameter="process_config",
)
print(error.message)
Output:
Frame sampling requires target_fps. Check the process_config options: target_fps must be greater than 0.

Parameters:

Name Type Description Default
error ValidationError

The pydantic validation failure.

required
component str

Name of the media operation whose options are invalid.

required
subject str

What the caller should check, named in the next step, such as "process_config options".

required
default_parameter str

Parameter reported when the failure is not tied to a single valid field.

required
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

Returns:

Type Description
Self

The configuration error. The caller raises it from error.

MediaOperationConfigTypeError(*, component, parameter, next_step, debug_info=None)

Bases: MediaOperationConfigError, TypeError

Report an invalid config type while preserving TypeError compatibility.

This concrete compatibility error is raised when callers pass an unsupported process_config object. It has its own code so it can be raised directly.

MediaOperationError(*, debug_info=None, _message=None, message_values=None)

Bases: MultimodalError

Abstract family for failures while an operation processes accepted input.

Use this family when decoding, extracting, or converting accepted media fails.

Example

Handle a processing failure after an input has been accepted.

from gllm_multimodal.exceptions import MediaOperationError, MediaOperationTimeoutError

try:
    raise MediaOperationTimeoutError(
        task="frame extraction",
        reason="decoding exceeded 30 seconds",
        next_step="Try a shorter video.",
    )
except MediaOperationError as error:
    print(error.message)
Output:
The frame extraction operation failed due to timeout: decoding exceeded 30 seconds. Try a shorter video.

MediaOperationFailedError(*, task=None, reason=None, next_step=None, debug_info=None)

Bases: MediaOperationError, RuntimeError

Report a failed media operation, including file inspection or content reading.

Use this when an accepted input cannot be processed and the cause can be summarized safely for the caller.

Example

Frame extraction fails because the decoder produces no frames.

from gllm_multimodal.exceptions import MediaOperationFailedError

error = MediaOperationFailedError(
    task="frame extraction",
    reason="the decoder produced no frames",
    next_step="Check the video file and try again.",
)
print(error.message)
Output:
The frame extraction operation failed: the decoder produced no frames. Check the video file and try again.

Initialize an operation failure with optional task guidance.

Parameters:

Name Type Description Default
task str | None

Operation name included in the message. Defaults to "media".

None
reason str | None

Safe summary of why the operation failed. Defaults to "the cause is unknown".

None
next_step str | None

Suggested recovery action. Defaults to checking the input and processing options, then trying again.

None
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

MediaOperationTimeoutError(*, task, reason, next_step, debug_info=None)

Bases: MediaOperationError, TimeoutError

Report an operation that failed because it exceeded its time limit.

Use this when an operation starts successfully but runs past its deadline.

Example

A frame extraction job reaches its processing timeout.

from gllm_multimodal.exceptions import MediaOperationTimeoutError

error = MediaOperationTimeoutError(
    task="frame extraction",
    reason="decoding exceeded 30 seconds",
    next_step="Try a shorter video.",
)
print(error.message)
Output:
The frame extraction operation failed due to timeout: decoding exceeded 30 seconds. Try a shorter video.

Initialize a timeout with its task, cause, and recovery action.

Parameters:

Name Type Description Default
task str

Operation that exceeded its time limit.

required
reason str

Safe explanation of what timed out.

required
next_step str

Action the caller can take to recover.

required
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

MediaProfileDebugInfo

Bases: _DiagnosticModel

Shared and modality-specific sanitized facts for one batch item.

Attributes:

Name Type Description
item_index int | None

Zero-based position of the item in the input batch.

mime_type str | None

Normalized MIME type detected for the item.

mime_type_source MimeTypeSource | None

Whether the MIME type was detected or declared.

modality MediaModality | None

Item modality, or mixed when multiple modalities apply.

size_bytes int | None

Number of bytes in the item.

container_format str | None

Safe identifier for the media container.

image ImageDebugInfo | None

Image dimensions, when available.

audio AudioDebugInfo | None

Audio stream facts, when available.

video VideoDebugInfo | None

Video stream facts, when available.

anomalies list[DiagnosticAnomaly] | None

Bounded records for profile values omitted as invalid.

omit_orphan_mime_source(value) classmethod

Drop MIME provenance when its associated MIME value is invalid.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
object

The input mapping with orphan MIME provenance removed when needed.

record_profile_anomalies(value) classmethod

Record invalid profile indexes and sizes before they are omitted.

Parameters:

Name Type Description Default
value object

Untrusted batch profile details.

required

Returns:

Type Description
object

Profile details augmented with bounded numeric anomaly records.

validate_container_format(value) classmethod

Keep a safe media container identifier.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The safe container identifier, or None otherwise.

validate_item_index(value) classmethod

Keep only non-negative, bounded batch indexes.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
int | None

The batch index when valid, or None otherwise.

validate_mime_source(value) classmethod

Keep MIME provenance only when the MIME type is valid.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The supported MIME provenance label, or None otherwise.

validate_mime_type(value) classmethod

Normalize and validate a MIME type.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The normalized MIME type, or None when invalid.

validate_modality(value) classmethod

Keep supported media modality labels.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
MediaModality | None

The supported modality label, or None otherwise.

validate_size(value) classmethod

Keep non-negative byte counts within the core debug-info limit.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
int | None

The byte count when valid, or None otherwise.

MediaProfilingError(*, debug_info=None, _message=None, message_values=None)

Bases: MediaError, ValueError

Report that non-empty bytes could not be identified as a media format.

Use this when inspecting nonempty bytes cannot determine the media format.

Example

Reject bytes that a media format detector cannot identify.

from textwrap import fill
from gllm_multimodal.exceptions import MediaProfilingError

error = MediaProfilingError()
print(fill(error.message, width=100))
Output:
We could not identify a media format from the supplied bytes. Provide the bytes of a supported media
file or try a different file.

MediaResultOperationError(*, task=None, next_step=None, debug_info=None)

Bases: MediaOperationError, ValueError

Report a missing or invalid result from an otherwise completed operation.

Use this when a backend reports success but omits data that the caller needs.

Example

A segmentation operation returns no segment metadata.

from gllm_multimodal.exceptions import MediaResultOperationError

error = MediaResultOperationError(
    task="segmentation",
    next_step="Check that the backend returns segment metadata.",
)
print(error.message)
Output:
The segmentation result is missing or has an unexpected format. Check that the backend returns segment metadata.

Initialize an invalid result error with optional task guidance.

Parameters:

Name Type Description Default
task str | None

Operation name included in the message. Defaults to "media operation".

None
next_step str | None

Suggested recovery action. Defaults to checking the selected service or backend output, then trying again.

None
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

from_validation_error(error, *, task, subject, default_parameter, debug_info=None) classmethod

Create the error from a pydantic validation failure of an operation's result.

The error names the first offending field and repeats pydantic's reason in its next step. A failure that is not tied to one field is reported against default_parameter. The rejected value is never included.

Example

A captioner returns a segment without a start time.

error = MediaResultOperationError.from_validation_error(
    validation_error,
    task="video caption",
    subject="video captioner segment 0",
    default_parameter="segment",
)
print(error.message)
Output:
The video caption result is missing or has an unexpected format. Check the video captioner segment 0: start_time: Field required.

Parameters:

Name Type Description Default
error ValidationError

The pydantic validation failure.

required
task str

Operation name included in the message.

required
subject str

What the caller should check, named in the next step, such as "video captioner segment 0".

required
default_parameter str

Parameter reported when the failure is not tied to a single valid field.

required
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

Returns:

Type Description
Self

The result error. The caller raises it from error.

MediaSourceAccessDeniedError(*, source_path=None, next_step=None, debug_info=None)

Bases: _SourcePathMessage, MediaError, PermissionError

Report that the current process lacks access to a media source.

Use this when file permissions or source credentials prevent a read.

Example

The application cannot read a protected media file.

from gllm_multimodal.exceptions import MediaSourceAccessDeniedError

error = MediaSourceAccessDeniedError(source_path="/data/private.mp4")
print(error.message)
Output:
We could not access /data/private.mp4. Check the application's permissions.

MediaSourceNotFoundError(*, source_path=None, next_step=None, debug_info=None)

Bases: _SourcePathMessage, MediaError, FileNotFoundError

Report a media source that the requested read could not locate.

Use this when a local file path or remote source no longer exists.

Example

A local media file is missing when the read begins.

from gllm_multimodal.exceptions import MediaSourceNotFoundError

error = MediaSourceNotFoundError(source_path="/data/video.mp4")
print(error.message)
Output:
We could not find /data/video.mp4. Check that it exists and is available to this application.

MediaSourceReadError(*, source_path=None, next_step=None, debug_info=None)

Bases: _SourcePathMessage, MediaError, OSError

Report a source read failure outside the specific source error cases.

Use this when a source exists and is accessible but cannot be read due to another file or connection failure.

Example

The connection closes while downloading a media file.

from textwrap import fill
from gllm_multimodal.exceptions import MediaSourceReadError

error = MediaSourceReadError(source_path="https://example.com/video.mp4")
print(fill(error.message, width=100))
Output:
We could not read https://example.com/video.mp4. Check the source address, credentials, and
connection, then try again.

MediaSourceReadTimeoutError(*, source_path=None, next_step=None, debug_info=None)

Bases: _SourcePathMessage, MediaError, TimeoutError

Report a source read that exceeded its time limit.

Use this when reading a remote or local source takes longer than allowed.

Example

A remote media source does not respond before the read deadline.

from gllm_multimodal.exceptions import MediaSourceReadTimeoutError

error = MediaSourceReadTimeoutError(source_path="https://example.com/video.mp4")
print(error.message)
Output:
Reading https://example.com/video.mp4 timed out. Retry later if repeating the read is safe.

MediaTrackMissingError(*, track, debug_info=None)

Bases: MediaError, ValueError

Report media that lacks a track required by the selected operation.

Use this only after the media has loaded and its audio or video tracks have been inspected. A failed inspection is an operation failure instead.

Example

Frame streaming needs a video track, but the supplied file has only audio.

from textwrap import fill
from gllm_multimodal.exceptions import MediaTrackMissingError

error = MediaTrackMissingError(track="video")
print(fill(error.message, width=100))
Output:
This media has no readable video track. Provide media with a readable video track or choose an
operation that does not require one.

Initialize the error for a required audio or video track.

Parameters:

Name Type Description Default
track str

Required track type, either "audio" or "video".

required
debug_info DebugInfo | None

Optional diagnostic context, sanitized before storage.

None

Raises:

Type Description
ValueError

If track is not audio or video.

MediaUnexpectedError(*, error_type, detail, component=None, next_step=None, debug_info=None)

Bases: _UnexpectedErrorMessage, MediaError

Fallback for unclassified failures about media input or its source.

Use this when a media source fails in a way that no specific media error describes. Pass only a safe summary of the original cause.

Example

Reading a media source raises an unfamiliar transport error.

from textwrap import fill
from gllm_multimodal.exceptions import MediaUnexpectedError

error = MediaUnexpectedError(
    error_type="TransportError",
    detail="the source connection closed unexpectedly",
)
print(fill(error.message, width=100))
Output:
The media input failed with TransportError: the source connection closed unexpectedly. Check the
media input and processing options. If the issue persists, contact the application owner.

MediaUnexpectedOperationError(*, error_type, detail, component=None, next_step=None, debug_info=None)

Bases: _UnexpectedErrorMessage, MediaOperationError

Fallback for unclassified failures while performing a media operation.

Example

Use this when a media operation fails for an unclassified reason and you want to include the cause and affected component in the error.

from textwrap import fill
from gllm_multimodal.exceptions import MediaUnexpectedOperationError

error = MediaUnexpectedOperationError(
    error_type="RuntimeError",
    detail="decoder returned no frames",
    component="frame extraction",
)
print(fill(error.message, width=100))
Output:
The frame extraction operation failed with RuntimeError: decoder returned no frames. Check the media
input and processing options. If the issue persists, contact the application owner.

MultimodalDebugInfo

Bases: _DiagnosticModel

Validated multimodal diagnostics built on core's dictionary contract.

This runtime model preserves the fields defined by core DebugInfo and adds multimodal context. Call the sanitize method for untrusted partial data; it returns a plain dictionary for assignment to BaseError.debug_info. Unsupported fields are ignored, malformed optional values are omitted or replaced with their safe fallback, and text fields are redacted and length-limited before serialization. Media-specific values are grouped into image, audio, and video models; batch items use the MediaProfileDebugInfo model.

Attributes:

Name Type Description
class_name str

Normalized exception class name. Required by core.

error_type str | None

Type name of the caught error, when available.

original_message str | None

Sanitized message from the caught error.

traceback str | None

Sanitized traceback from the caught error.

operation str

Operation category or concrete class-qualified method.

stage StageName

Processing stage where the error occurred.

modality MediaModality

Media modality associated with the operation.

source_kind SourceKind

Kind of input source supplied to the operation.

component str | None

Safe label for the component involved.

encoder str | None

Safe label for the media encoder involved.

parameter str | None

Safe label for the parameter involved.

mime_type str | None

Detected or declared MIME type.

mime_type_source MimeTypeSource | None

Whether the MIME type was detected or declared.

size_bytes int | None

Size of the media payload.

status_code int | None

HTTP status code from a provider response.

request_id str | None

Identifier of the request, such as a provider request ID, when it is short and plain.

service_status str | None

Status label reported by an external service, such as FAILED.

backend MediaBackend | None

Media backend used by the operation.

input_kind InputKind | None

Input representation such as bytes, URL, or path.

container_format str | None

Media container identifier.

image ImageDebugInfo | None

Sanitized image-specific details.

audio AudioDebugInfo | None

Sanitized audio-specific details.

video VideoDebugInfo | None

Sanitized video-specific details. Each modality detail may include anomalies for bounded observations omitted during field validation.

media_profiles list[MediaProfileDebugInfo] | None

Sanitized profiles for items in a batch.

media_profiles_truncated bool | None

Whether profiles were omitted due to limits.

Notes

Operation may be a known category or a validated class-qualified method name. Stage, modality, and source kind use their corresponding schema aliases and fall back to unknown for unsupported values.

bound_media_profiles(value) classmethod

Cap profile lists and mark truncation during direct model validation.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
object

The input mapping with its profile list capped and truncation state updated.

omit_orphan_mime_source(value) classmethod

Drop MIME provenance unless a valid MIME type is available.

Parameters:

Name Type Description Default
value object

Untrusted multimodal diagnostics.

required

Returns:

Type Description
object

The diagnostics with orphan MIME provenance removed.

sanitize(error_class_name, supplied, *, safe_message) classmethod

Validate untrusted diagnostic details and return core's dict format.

Parameters:

Name Type Description Default
error_class_name str

Class name of the normalized exception.

required
supplied Mapping[str, object] | MultimodalDebugInfo | None

Partial core or multimodal diagnostic mapping or model.

required
safe_message str

Safe public error message used as a fallback.

required

Returns:

Type Description
DebugInfo

A plain dictionary containing validated core and multimodal fields.

validate_backend(value) classmethod

Keep supported backend labels.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
MediaBackend | None

The supported backend label, or None otherwise.

validate_container_format(value) classmethod

Keep safe media container identifiers.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The safe container identifier, or None otherwise.

validate_error_type(value, info) classmethod

Keep error type labels bounded to identifier syntax.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required
info ValidationInfo

Previously validated fields, including the normalized exception class name.

required

Returns:

Type Description
str | None

The bounded error type identifier, or None when invalid.

validate_input_kind(value) classmethod

Keep supported input representation labels.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The supported input kind, or None otherwise.

validate_label(value) classmethod

Keep short safe labels for component and parameter names.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The safe component or parameter label, or None otherwise.

validate_mime_source(value) classmethod

Keep MIME provenance labels from the supported set.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The supported MIME provenance label, or None otherwise.

validate_mime_type(value) classmethod

Normalize and validate MIME type syntax and length.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The normalized MIME type, or None when invalid.

validate_operation(value) classmethod

Keep known operation categories and safe class-qualified methods.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str

The supported operation label, or the unknown marker.

validate_original_message(value, info) classmethod

Redact and bound the original diagnostic message.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required
info ValidationInfo

Validation context containing the safe fallback message and prior fields.

required

Returns:

Type Description
str | None

The redacted and bounded message, or None when absent or invalid.

validate_request_id(value) classmethod

Keep request identifiers that are short, plain, and unchanged by redaction.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The request identifier when valid, or None otherwise.

validate_root_modality(value) classmethod

Keep supported media modality labels.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
MediaModality

The supported modality label, or the unknown marker.

validate_service_status(value) classmethod

Keep upper-case status labels reported by external services.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The service status label when valid, or None otherwise.

validate_size(value) classmethod

Keep non-negative bounded media sizes.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
int | None

The byte count when valid, or None otherwise.

validate_source_kind(value) classmethod

Keep supported source kind labels.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str

The supported source kind, or the unknown marker.

validate_stage(value) classmethod

Keep supported processing stage labels.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str

The supported stage label, or the unknown marker.

validate_status_code(value) classmethod

Keep valid non-boolean HTTP status codes.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
int | None

The HTTP status code when valid, or None otherwise.

validate_traceback(value) classmethod

Redact and bound an original traceback.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The redacted and bounded traceback, or None when absent or invalid.

MultimodalError(*, debug_info=None, _message=None, message_values=None)

Bases: BaseError

Base class for normalized, user-safe errors raised by this package.

Concrete subclasses define a stable code and complete default message. Lower-level diagnostic text is excluded by default; only allowlisted values are retained in debug_info. to_safe_dict() keeps diagnostics optional so callers can choose a compact user message or a richer debug payload. verbose() formats the sanitized payload for developer logs; str() remains the public message.

For diagnostic context, pass debug_info with operation, stage, modality, and source_kind. Optional fields include mime_type, size_bytes, and bounded media details. Unsupported fields are omitted.

Attributes:

Name Type Description
reference_id

Per-error identifier for correlation by the consuming app.

Example

Catch any error raised by the multimodal package and return its safe message to the caller.

from gllm_multimodal.exceptions import MediaInputInvalidError, MultimodalError

try:
    raise MediaInputInvalidError(valid_input="Provide media bytes.")
except MultimodalError as error:
    print(error.to_safe_dict()["message"])
Output:
No media could be loaded from the supplied input. Provide media bytes.

Initialize the safe public message and bounded diagnostics.

Parameters:

Name Type Description Default
debug_info DebugInfo | None

Candidate diagnostic fields, filtered through the package's sanitizer.

None
_message str | None

Internal override for a more specific safe message.

None
message_values Mapping[str, object] | None

Values for placeholders in default_message. Missing optional fields use optional_message_defaults.

None

Raises:

Type Description
KeyError

If a placeholder has no value or optional default.

ValueError

If a required placeholder has a blank value.

to_safe_dict(*, include_debug_info=False)

Return public error fields, optionally including sanitized diagnostics.

Parameters:

Name Type Description Default
include_debug_info bool

Include allowlisted media and error context for debugging. Defaults to False for a compact user-facing form.

False

Returns:

Type Description
dict[str, Any]

Error code, complete safe message, and reference ID; optionally

dict[str, Any]

includes a freshly sanitized debug_info mapping.

verbose()

Format the public message and sanitized diagnostics for developer logs.

Returns:

Type Description
str

Error class, code, reference ID, message, and allowlisted debug fields.

VideoDebugInfo

Bases: _DiagnosticModel

Sanitized properties of a video stream.

Attributes:

Name Type Description
duration_seconds float | None

Video duration in seconds.

fps float | None

Video frame rate.

width int | None

Video frame width in pixels.

height int | None

Video frame height in pixels.

codec str | None

Safe identifier for the video codec.

anomalies list[DiagnosticAnomaly] | None

Bounded records for numeric details omitted as invalid.

record_video_anomalies(value) classmethod

Record invalid video numbers before normalizing them away.

Parameters:

Name Type Description Default
value object

Untrusted video details.

required

Returns:

Type Description
object

Video details augmented with bounded numeric anomaly records.

validate_codec(value) classmethod

Keep only a safe video codec identifier.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
str | None

The safe codec identifier, or None otherwise.

validate_dimension(value) classmethod

Keep only positive pixel dimensions within the configured limit.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
int | None

The pixel dimension when valid, or None otherwise.

validate_duration(value) classmethod

Keep only finite, positive video durations within the limit.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
float | None

The duration when it is finite, positive, and within the limit; otherwise, None.

validate_frame_rate(value) classmethod

Keep only finite, positive frame rates within the limit.

Parameters:

Name Type Description Default
value object

Untrusted value to validate or normalize.

required

Returns:

Type Description
float | None

The frame rate when valid, or None otherwise.