wenjin272 commented on code in PR #1382:
URL: https://github.com/apache/flink-agents/pull/1382#discussion_r4675189696


##########
api/src/main/java/org/apache/flink/agents/api/media/BaseMediaModelProvider.java:
##########
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.api.media;
+
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceContext;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * A media model provider that binds capabilities to models and owns their 
shared client.
+ *
+ * <p>Each binding accepts a map of default model parameters. Whether a bound 
capability runs
+ * synchronously or exposes resumable provider jobs via {@link AsyncJobModel} 
is determined by the
+ * underlying provider implementation. Factory methods should return 
lightweight capability views
+ * without independent mutable state so the same {@code (model, 
modelParameters)} binding can be
+ * recreated safely; shared state belongs on the provider itself (or in a 
persisted {@link
+ * MediaJob}). Cross-language Java-to-Python bridges recreate bindings from 
immutable configuration
+ * rather than retaining child Python object handles. The bound model shares 
this provider's
+ * lifetime and must not be used after the provider closes.
+ */
+public abstract class BaseMediaModelProvider extends Resource {

Review Comment:
   Could we rename `BaseMediaModelProvider` to `BaseMediaModelConnection` to 
align with `BaseChatModelConnection`? Its responsibilities are connection 
configuration, authentication, and shared SDK client lifecycle. Please align 
the concrete class names, resource types/names, Setup configuration field 
(`provider` to `connection`), and YAML/schema, documentation, and examples 
across both languages. The factory convenience methods can remain.



##########
api/src/main/java/org/apache/flink/agents/api/media/BaseMediaModelSetup.java:
##########
@@ -0,0 +1,251 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.api.media;
+
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceContext;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+
+import javax.annotation.Nullable;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Abstract base class for {@link ResourceType#MEDIA_MODEL} capability setups.
+ *
+ * <p>Concrete task setups extend one of the four task-specific subclasses 
({@link
+ * BaseSpeechSynthesisModelSetup}, {@link BaseTranscriptionModelSetup}, {@link
+ * BaseImageGenerationModelSetup}, or {@link BaseVideoGenerationModelSetup}) 
and optionally
+ * implement {@link AsyncJobModel} when backed by resumable provider jobs. A 
setup can either be
+ * declared via {@link ResourceDescriptor} referencing a {@link 
ResourceType#MEDIA_MODEL_PROVIDER},
+ * returned directly by {@link BaseMediaModelProvider} factory methods, or 
manage its own standalone
+ * client.
+ */
+public abstract class BaseMediaModelSetup extends Resource {
+    @Nullable protected final ResourceDescriptor descriptor;
+    @Nullable private final String providerName;
+    private final String model;
+    private final Map<String, Object> modelParameters;
+    @Nullable private transient BaseMediaModelProvider boundProvider;
+    private transient boolean ownsProviderBinding;
+
+    /**
+     * Construct a media model setup from a resource descriptor.
+     *
+     * <p>Requires a non-blank {@code model} argument; {@code provider} and 
{@code model_parameters}
+     * are optional (validated when set).
+     */
+    protected BaseMediaModelSetup(
+            ResourceDescriptor descriptor, @Nullable ResourceContext 
resourceContext) {
+        super(Objects.requireNonNull(descriptor, "descriptor"), 
resourceContext);
+        this.descriptor = descriptor;
+        Map<String, Object> rawArguments = descriptor.getInitialArguments();
+        Map<String, Object> arguments = rawArguments == null ? Map.of() : 
rawArguments;
+        this.providerName = optionalNonBlankString(arguments, "provider");
+        this.model = requireNonBlankString(arguments, "model");
+        this.modelParameters = extractModelParameters(arguments);
+    }
+
+    /**
+     * Construct a directly configured or provider-bound media model setup 
without a named provider
+     * reference.
+     */
+    protected BaseMediaModelSetup(
+            String model,
+            @Nullable Map<String, Object> modelParameters,
+            @Nullable ResourceDescriptor descriptor,
+            @Nullable ResourceContext resourceContext) {
+        this(null, model, modelParameters, descriptor, resourceContext);
+    }
+
+    /**
+     * Construct a media model setup with an explicit model, optional provider 
name, and model
+     * parameters.
+     */
+    protected BaseMediaModelSetup(
+            @Nullable String providerName,
+            String model,
+            @Nullable Map<String, Object> modelParameters,
+            @Nullable ResourceDescriptor descriptor,
+            @Nullable ResourceContext resourceContext) {
+        super(descriptor, resourceContext);
+        this.descriptor = descriptor;
+        if (providerName != null && providerName.isBlank()) {
+            throw new IllegalArgumentException(
+                    "Media model setup 'provider' must be a non-blank string 
when set.");
+        }
+        this.providerName = providerName;
+        this.model =
+                validateNonBlank(model, "Media model setup 'model' must be a 
non-blank string.");
+        this.modelParameters =
+                modelParameters == null ? Map.of() : 
MediaParameters.copy(modelParameters);
+    }
+
+    @Nullable
+    public String getProviderName() {
+        return providerName;
+    }
+
+    public String getModel() {
+        return model;
+    }
+
+    public Map<String, Object> getModelParameters() {
+        return modelParameters;
+    }
+
+    @Override
+    public ResourceType getResourceType() {
+        return ResourceType.MEDIA_MODEL;
+    }
+
+    /** Expected provider base class enforced when resolving or binding a 
provider. */
+    protected Class<? extends BaseMediaModelProvider> getProviderType() {
+        return BaseMediaModelProvider.class;
+    }
+
+    /** Attach a provider instance directly when constructed from a provider 
factory method. */
+    protected void bindProvider(BaseMediaModelProvider provider) {
+        Objects.requireNonNull(provider, "provider");
+        Class<? extends BaseMediaModelProvider> expectedType = 
getProviderType();
+        if (!expectedType.isInstance(provider)) {
+            throw new IllegalStateException(
+                    getClass().getSimpleName()
+                            + " requires a "
+                            + expectedType.getSimpleName()
+                            + ", got "
+                            + provider.getClass().getName());
+        }
+        this.boundProvider = provider;
+        this.ownsProviderBinding = false;
+    }
+
+    @Override
+    public void open() throws Exception {
+        super.open();
+        if (boundProvider == null && providerName != null) {
+            boundProvider = resolveProvider();
+            ownsProviderBinding = true;
+        }
+    }
+
+    @Override
+    public void close() throws Exception {
+        if (ownsProviderBinding) {

Review Comment:
   Could we follow Chat setup's lifecycle in both languages and remove Java's 
`ownsProviderBinding` and Python's `_owns_provider_binding`? These flags make 
`close()` clear the provider reference for declarative setups but retain it for 
factory-created setups. There does not seem to be a need for different close 
behavior based on how the setup was created; neither should close the shared 
connection.



##########
api/src/main/java/org/apache/flink/agents/api/media/BaseMediaModelSetup.java:
##########
@@ -0,0 +1,251 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.api.media;
+
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceContext;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+
+import javax.annotation.Nullable;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Abstract base class for {@link ResourceType#MEDIA_MODEL} capability setups.
+ *
+ * <p>Concrete task setups extend one of the four task-specific subclasses 
({@link
+ * BaseSpeechSynthesisModelSetup}, {@link BaseTranscriptionModelSetup}, {@link
+ * BaseImageGenerationModelSetup}, or {@link BaseVideoGenerationModelSetup}) 
and optionally
+ * implement {@link AsyncJobModel} when backed by resumable provider jobs. A 
setup can either be
+ * declared via {@link ResourceDescriptor} referencing a {@link 
ResourceType#MEDIA_MODEL_PROVIDER},
+ * returned directly by {@link BaseMediaModelProvider} factory methods, or 
manage its own standalone
+ * client.
+ */
+public abstract class BaseMediaModelSetup extends Resource {
+    @Nullable protected final ResourceDescriptor descriptor;
+    @Nullable private final String providerName;
+    private final String model;
+    private final Map<String, Object> modelParameters;
+    @Nullable private transient BaseMediaModelProvider boundProvider;
+    private transient boolean ownsProviderBinding;
+
+    /**
+     * Construct a media model setup from a resource descriptor.
+     *
+     * <p>Requires a non-blank {@code model} argument; {@code provider} and 
{@code model_parameters}
+     * are optional (validated when set).
+     */
+    protected BaseMediaModelSetup(
+            ResourceDescriptor descriptor, @Nullable ResourceContext 
resourceContext) {
+        super(Objects.requireNonNull(descriptor, "descriptor"), 
resourceContext);
+        this.descriptor = descriptor;
+        Map<String, Object> rawArguments = descriptor.getInitialArguments();
+        Map<String, Object> arguments = rawArguments == null ? Map.of() : 
rawArguments;
+        this.providerName = optionalNonBlankString(arguments, "provider");
+        this.model = requireNonBlankString(arguments, "model");
+        this.modelParameters = extractModelParameters(arguments);
+    }
+
+    /**
+     * Construct a directly configured or provider-bound media model setup 
without a named provider
+     * reference.
+     */
+    protected BaseMediaModelSetup(
+            String model,
+            @Nullable Map<String, Object> modelParameters,
+            @Nullable ResourceDescriptor descriptor,
+            @Nullable ResourceContext resourceContext) {
+        this(null, model, modelParameters, descriptor, resourceContext);
+    }
+
+    /**
+     * Construct a media model setup with an explicit model, optional provider 
name, and model
+     * parameters.
+     */
+    protected BaseMediaModelSetup(
+            @Nullable String providerName,
+            String model,
+            @Nullable Map<String, Object> modelParameters,
+            @Nullable ResourceDescriptor descriptor,
+            @Nullable ResourceContext resourceContext) {
+        super(descriptor, resourceContext);
+        this.descriptor = descriptor;
+        if (providerName != null && providerName.isBlank()) {
+            throw new IllegalArgumentException(
+                    "Media model setup 'provider' must be a non-blank string 
when set.");
+        }
+        this.providerName = providerName;
+        this.model =
+                validateNonBlank(model, "Media model setup 'model' must be a 
non-blank string.");
+        this.modelParameters =
+                modelParameters == null ? Map.of() : 
MediaParameters.copy(modelParameters);
+    }
+
+    @Nullable
+    public String getProviderName() {
+        return providerName;
+    }
+
+    public String getModel() {
+        return model;
+    }
+
+    public Map<String, Object> getModelParameters() {
+        return modelParameters;
+    }
+
+    @Override
+    public ResourceType getResourceType() {
+        return ResourceType.MEDIA_MODEL;
+    }
+
+    /** Expected provider base class enforced when resolving or binding a 
provider. */
+    protected Class<? extends BaseMediaModelProvider> getProviderType() {

Review Comment:
   Could we remove `getProviderType()` and `bindProvider()`? `bindProvider()` 
has no production callers, and `getProviderType()` is only overridden in tests. 
We could follow Chat setup's connection lookup without introducing a separate 
concrete-provider type constraint. On Python, this would also remove 
`_provider_type`, `_expected_provider_type()`, and 
`_validate_provider_instance()`. Required connection-name validation should 
remain independent of the concrete connection type, allowing a directly 
supplied instance for factory-created setups.



##########
plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonMediaModelSetup.java:
##########
@@ -0,0 +1,630 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.plan.resource.python;
+
+import org.apache.flink.agents.api.chat.messages.AudioBlock;
+import org.apache.flink.agents.api.chat.messages.ImageBlock;
+import org.apache.flink.agents.api.chat.messages.TextBlock;
+import org.apache.flink.agents.api.chat.messages.VideoBlock;
+import org.apache.flink.agents.api.media.AsyncJobModel;
+import org.apache.flink.agents.api.media.BaseImageGenerationModelSetup;
+import org.apache.flink.agents.api.media.BaseMediaModelSetup;
+import org.apache.flink.agents.api.media.BaseSpeechSynthesisModelSetup;
+import org.apache.flink.agents.api.media.BaseTranscriptionModelSetup;
+import org.apache.flink.agents.api.media.BaseVideoGenerationModelSetup;
+import org.apache.flink.agents.api.media.ImageGenerationRequest;
+import org.apache.flink.agents.api.media.MediaJob;
+import org.apache.flink.agents.api.media.MediaJobState;
+import org.apache.flink.agents.api.media.MediaResult;
+import org.apache.flink.agents.api.media.SpeechSynthesisRequest;
+import org.apache.flink.agents.api.media.TranscriptionRequest;
+import org.apache.flink.agents.api.media.VideoGenerationRequest;
+import org.apache.flink.agents.api.metrics.FlinkAgentsMetricGroup;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceContext;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import pemja.core.object.PyObject;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Factory creating Java {@link BaseMediaModelSetup} bridges around Python 
{@link
+ * ResourceType#MEDIA_MODEL} setup instances.
+ *
+ * <p>Each created resource extends the task-specific {@code Base*ModelSetup} 
class and implements
+ * {@link AsyncJobModel} if and only if the underlying Python resource 
supports async jobs.
+ */
+public final class PythonMediaModelSetup {
+    private static final String FALLBACK_MODEL_NAME = "python-media-model";
+
+    private PythonMediaModelSetup() {}
+
+    /** Inspect the Python media model setup and return a matching typed Java 
wrapper. */
+    public static BaseMediaModelSetup create(
+            PythonResourceAdapter adapter,
+            PyObject resource,
+            @Nullable ResourceDescriptor descriptor,
+            @Nullable ResourceContext resourceContext) {
+        Object inspection = 
adapter.invoke("python_java_utils.inspect_media_model", resource);
+        if (!(inspection instanceof Map)) {
+            throw new IllegalStateException("Invalid MediaModel inspection 
result from Python");
+        }
+        Map<?, ?> metadata = (Map<?, ?>) inspection;
+        Object taskValue = metadata.get("task");
+        Object asyncValue = metadata.get("async");
+        if (!(taskValue instanceof String) || !(asyncValue instanceof 
Boolean)) {
+            throw new IllegalStateException("Invalid MediaModel inspection 
result from Python");
+        }
+        String task = (String) taskValue;
+        boolean async = (Boolean) asyncValue;
+        Handle handle =
+                new Handle(
+                        adapter,
+                        resource,
+                        task,
+                        resolveProviderName(metadata.get("provider"), 
descriptor),
+                        resolveModelName(metadata.get("model"), descriptor),
+                        "speech_synthesis".equals(task)
+                                ? resolveVoice(metadata.get("voice"), 
descriptor)
+                                : null,
+                        extractModelParameters(descriptor),
+                        descriptor,
+                        resourceContext);
+        switch (task) {
+            case "speech_synthesis":
+                return async ? new AsyncSpeech(handle) : new Speech(handle);
+            case "transcription":
+                return async ? new AsyncTranscription(handle) : new 
Transcription(handle);
+            case "image_generation":
+                return async ? new AsyncImage(handle) : new Image(handle);
+            case "video_generation":
+                return async ? new AsyncVideo(handle) : new Video(handle);
+            default:
+                throw new IllegalStateException("Invalid MediaModel inspection 
result from Python");
+        }
+    }
+
+    @Nullable
+    private static String resolveProviderName(
+            @Nullable Object inspectedProvider, @Nullable ResourceDescriptor 
descriptor) {
+        if (inspectedProvider != null) {
+            if (!(inspectedProvider instanceof String) || ((String) 
inspectedProvider).isBlank()) {
+                throw new IllegalArgumentException(
+                        "Media model setup 'provider' must be a non-blank 
string when set.");
+            }
+            return (String) inspectedProvider;
+        }
+        if (descriptor != null && descriptor.getInitialArguments() != null) {
+            Object rawProvider = 
descriptor.getInitialArguments().get("provider");
+            if (rawProvider != null) {
+                if (!(rawProvider instanceof String) || ((String) 
rawProvider).isBlank()) {
+                    throw new IllegalArgumentException(
+                            "Media model setup 'provider' must be a non-blank 
string when set.");
+                }
+                return (String) rawProvider;
+            }
+        }
+        return null;
+    }
+
+    private static String resolveModelName(
+            @Nullable Object inspectedModel, @Nullable ResourceDescriptor 
descriptor) {
+        if (inspectedModel instanceof String && !((String) 
inspectedModel).isBlank()) {
+            return (String) inspectedModel;
+        }
+        if (descriptor != null && descriptor.getInitialArguments() != null) {
+            Object rawModel = descriptor.getInitialArguments().get("model");
+            if (rawModel instanceof String && !((String) rawModel).isBlank()) {
+                return (String) rawModel;
+            }
+        }
+        return FALLBACK_MODEL_NAME;
+    }
+
+    @Nullable
+    private static String resolveVoice(
+            @Nullable Object inspectedVoice, @Nullable ResourceDescriptor 
descriptor) {
+        if (inspectedVoice instanceof String && !((String) 
inspectedVoice).isBlank()) {
+            return (String) inspectedVoice;
+        }
+        if (descriptor != null && descriptor.getInitialArguments() != null) {
+            Object rawVoice = descriptor.getInitialArguments().get("voice");
+            if (rawVoice instanceof String && !((String) rawVoice).isBlank()) {
+                return (String) rawVoice;
+            }
+        }
+        return null;
+    }
+
+    @Nullable
+    private static Map<String, Object> extractModelParameters(
+            @Nullable ResourceDescriptor descriptor) {
+        if (descriptor == null || descriptor.getInitialArguments() == null) {
+            return null;
+        }
+        Object rawParams = 
descriptor.getInitialArguments().get("model_parameters");
+        if (!(rawParams instanceof Map)) {
+            return null;
+        }
+        Map<?, ?> rawMap = (Map<?, ?>) rawParams;
+        Map<String, Object> typed = new LinkedHashMap<>(rawMap.size());
+        for (Map.Entry<?, ?> entry : rawMap.entrySet()) {
+            if (entry.getKey() instanceof String) {
+                typed.put((String) entry.getKey(), entry.getValue());
+            }
+        }
+        return typed;
+    }
+
+    private static final class Handle implements PythonMediaBridge.Target {
+        private final PythonResourceAdapter adapter;
+        private final PyObject resource;
+        private final String task;
+        @Nullable private final String providerName;
+        private final String model;
+        @Nullable private final String voice;
+        @Nullable private final Map<String, Object> modelParameters;
+        @Nullable private final ResourceDescriptor descriptor;
+        @Nullable private final ResourceContext resourceContext;
+        private volatile boolean closed;
+
+        private Handle(
+                PythonResourceAdapter adapter,
+                PyObject resource,
+                String task,
+                @Nullable String providerName,
+                String model,
+                @Nullable String voice,
+                @Nullable Map<String, Object> modelParameters,
+                @Nullable ResourceDescriptor descriptor,
+                @Nullable ResourceContext resourceContext) {
+            this.adapter = adapter;
+            this.resource = resource;
+            this.task = task;
+            this.providerName = providerName;
+            this.model = model;
+            this.voice = voice;
+            this.modelParameters = modelParameters;
+            this.descriptor = descriptor;
+            this.resourceContext = resourceContext;
+        }
+
+        private void open() throws Exception {
+            checkOpen();
+            if (providerName != null) {
+                if (resourceContext == null) {
+                    throw new IllegalStateException(
+                            "ResourceContext is required to resolve media 
model provider '"
+                                    + providerName
+                                    + "'.");
+                }
+                Resource provider =
+                        resourceContext.getResource(
+                                providerName, 
ResourceType.MEDIA_MODEL_PROVIDER);
+                if (!(provider instanceof PythonResourceWrapper)) {
+                    throw new IllegalStateException(
+                            "Media model provider '"
+                                    + providerName
+                                    + "' referenced by Python media model 
setup requires a Python MEDIA_MODEL_PROVIDER, got: "
+                                    + (provider == null ? "null" : 
provider.getClass().getName()));
+                }
+                adapter.invoke(

Review Comment:
   Could we follow `PythonChatModelSetup` and let the Java wrapper call 
Python's `open()` directly? The Python setup can resolve its connection through 
`resource_context`, preserving the current Agent scope and child-Agent resource 
overrides. This would remove the media-specific `open_media_model_setup()` / 
`_bind_provider()` injection path. Factory-created setups can receive the 
connection instance through their constructor.



##########
python/flink_agents/api/media/media_model.py:
##########
@@ -0,0 +1,668 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+#################################################################################
+import json
+import math
+import time
+from abc import ABC, abstractmethod
+from enum import Enum
+from typing import TYPE_CHECKING, Any, ClassVar, Generic, Mapping, Sequence, 
TypeVar
+
+from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator
+from typing_extensions import override
+
+from flink_agents.api.chat_message import (
+    AudioBlock,
+    DataContentBlock,
+    DocumentBlock,
+    ImageBlock,
+    TextBlock,
+    VideoBlock,
+)
+from flink_agents.api.resource import Resource, ResourceType
+
+if TYPE_CHECKING:
+    from flink_agents.api.media.media_model_provider import 
BaseMediaModelProvider
+
+
+class _MediaTask(str, Enum):
+    """Internal identifiers for job validation and cross-language dispatch."""
+
+    IMAGE_GENERATION = "image_generation"
+    VIDEO_GENERATION = "video_generation"
+    TRANSCRIPTION = "transcription"
+    SPEECH_SYNTHESIS = "speech_synthesis"
+
+
+class MediaJobStatus(str, Enum):
+    """Lifecycle state of a submitted asynchronous provider task."""
+
+    PENDING = "pending"
+    RUNNING = "running"
+    SUCCEEDED = "succeeded"
+    FAILED = "failed"
+    CANCELED = "canceled"
+    # The provider can no longer identify the task, for example because its
+    # retention window has passed.
+    UNKNOWN = "unknown"
+
+
+class MediaJob(BaseModel):
+    """Handle of a submitted asynchronous provider task.
+
+    Frozen and JSON-serializable so it can be persisted as the result of a
+    durable execution and replayed across recovery.
+    """
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    provider: str = Field(description="Provider that owns the task, e.g. 
'dashscope'.")
+    model: str = Field(description="Model the task was submitted to.")
+    task: str = Field(description="Capability identifier recorded when 
submitting.")
+    job_id: str = Field(description="Provider task identifier.")
+    submitted_at_ms: int = Field(description="Local submission time, epoch 
millis.")
+    expires_at_ms: int | None = Field(
+        default=None,
+        description="Time until which the provider can still be queried for 
this task.",
+    )
+
+    @field_validator("task")
+    @classmethod
+    def _validate_task(cls, value: str) -> str:
+        expected = tuple(task.value for task in _MediaTask)
+        if value not in expected:
+            msg = (
+                f"Invalid media task {value!r}; expected one of: {', 
'.join(expected)}."
+            )
+            raise ValueError(msg)
+        return value
+
+
+ContentT = TypeVar("ContentT", bound=DataContentBlock)
+
+
+class MediaResult(BaseModel, Generic[ContentT]):
+    """Output of a finished generation, transcription, or synthesis."""
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    content: list[ContentT] = Field(
+        description="Generated content, in the order returned by the provider."
+    )
+    expires_at_ms: int | None = Field(
+        default=None,
+        description="Time until which result URLs stay valid, when the 
provider says so.",
+    )
+    usage: dict[str, int | float | str] = Field(
+        default_factory=dict,
+        description="Provider usage counters, kept as reported.",
+    )
+    request_id: str | None = Field(
+        default=None, description="Provider request identifier."
+    )
+    metadata: dict[str, Any] = Field(
+        default_factory=dict,
+        description="Structured provider data that does not fit into a content 
block.",
+    )
+
+
+ResultT = TypeVar("ResultT", bound=MediaResult)
+
+
+class MediaJobState(BaseModel, Generic[ResultT]):
+    """One observation of a job, returned by ``fetch``."""
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    job: MediaJob
+    status: MediaJobStatus
+    result: ResultT | None = Field(
+        default=None, description="Present only when the status is SUCCEEDED."
+    )
+    error_code: str | None = Field(
+        default=None, description="Present only when the status is FAILED."
+    )
+    error_message: str | None = None
+
+
+class MediaJobError(Exception):
+    """An operation on a media job failed.
+
+    Attributes:
+        job: The job associated with the error.
+        status: The last observed job status, or UNKNOWN if unavailable.
+        code: Provider error code, when the provider reported one.
+        message: Provider error message, when the provider reported one.
+    """
+
+    def __init__(
+        self,
+        job: MediaJob,
+        status: MediaJobStatus,
+        code: str | None = None,
+        message: str | None = None,
+    ) -> None:
+        """Record the job, its observed status, and any provider error."""
+        self.job = job
+        self.status = status
+        self.code = code
+        self.message = message
+        detail = status.value
+        if code is not None:
+            detail = f"{detail} ({code})"
+        if message is not None:
+            detail = f"{detail}: {message}"
+        super().__init__(f"Media job {job.job_id}: {detail}")
+
+    def __reduce__(self) -> tuple[type[Exception], tuple[Any, ...], dict[str, 
Any]]:
+        """Rebuild the exception with its structured constructor arguments."""
+        return type(self), (self.job, self.status, self.code, self.message), 
vars(self)
+
+
+class MediaJobTimeoutError(MediaJobError):
+    """The polling budget for ``wait`` elapsed before a terminal status was 
observed.
+
+    Attributes:
+        timeout: The polling budget in seconds.
+    """
+
+    def __init__(
+        self,
+        job: MediaJob,
+        timeout: float,
+        status: MediaJobStatus = MediaJobStatus.UNKNOWN,
+    ) -> None:
+        """Record the job, its last observed status, and the polling budget."""
+        self.timeout = timeout
+        super().__init__(job, status, message=f"timed out after {timeout} 
seconds")
+
+    def __reduce__(self) -> tuple[type[Exception], tuple[Any, ...], dict[str, 
Any]]:
+        """Rebuild the timeout with its job, budget, and last observed 
status."""
+        return type(self), (self.job, self.timeout, self.status), vars(self)
+
+
+DEFAULT_WAIT_TIMEOUT = 1800.0
+DEFAULT_POLL_INTERVAL = 5.0
+
+
+class AsyncJobModel(Generic[ResultT], ABC):
+    """A media capability with submitted jobs that can be queried and resumed.
+
+    Setups that back a media capability with cloud jobs implement this
+    interface alongside their ``Base*ModelSetup`` base class and own 
``submit``,
+    single-observation ``fetch``, ``cancel``, and job-ownership validation
+    (``_check_job``). Python convenience methods compose ``_submit_and_wait``,
+    and Java-to-Python bridges compose those same primitives with interruptible
+    polling using ``DEFAULT_WAIT_TIMEOUT`` and ``DEFAULT_POLL_INTERVAL``.
+    Native Java ``AsyncJobModel`` implementations supply three-argument 
``wait``
+    directly. Synchronous setups extend only the task-specific setup base 
class.
+
+    Call ``submit`` and persist its returned job separately when waiting must
+    resume after recovery. None of these methods records durable execution or
+    emits events itself.
+    """
+
+    if TYPE_CHECKING:
+        model: str
+        _task: ClassVar[_MediaTask]
+
+    def _submit_and_wait(
+        self,
+        *args: Any,
+        timeout: float | None = None,
+        **kwargs: Any,
+    ) -> ResultT:
+        """Submit a request and wait for its result.
+
+        Args:
+            *args: The inputs accepted by this media capability.
+            timeout: Polling budget in seconds after submission. None uses
+                ``DEFAULT_WAIT_TIMEOUT``. This does not change HTTP request
+                timeouts.
+            **kwargs: Provider parameters for submission.
+        """
+        budget = DEFAULT_WAIT_TIMEOUT if timeout is None else timeout
+        budget = self._validate_wait_timeout(budget, allow_zero=False)
+        job = self.submit(*args, **kwargs)
+        return self.wait(job, timeout=budget)
+
+    @abstractmethod
+    def submit(self, *args: Any, **kwargs: Any) -> MediaJob:
+        """Submit a request and return its job handle without waiting."""
+
+    @abstractmethod
+    def fetch(self, job: MediaJob) -> MediaJobState[ResultT]:
+        """Query the task status once.
+
+        Retrieve the full result when the status is SUCCEEDED.
+        """
+
+    def wait(
+        self,
+        job: MediaJob,
+        *,
+        timeout: float | None = DEFAULT_WAIT_TIMEOUT,
+        poll_interval: float = DEFAULT_POLL_INTERVAL,
+    ) -> ResultT:
+        """Block until the task reaches a terminal status.
+
+        Waits up to ``poll_interval`` seconds between queries. The polling
+        budget limits when a new query can start. A query already in progress
+        can finish and return its result. On timeout ``MediaJobTimeoutError``
+        is raised and the provider task can continue.
+
+        Args:
+            job: Handle returned by ``submit``.
+            timeout: Polling budget in seconds from the start of this wait.
+                Defaults to ``DEFAULT_WAIT_TIMEOUT`` (1800s). Pass ``None`` for
+                unlimited polling.
+            poll_interval: Positive seconds between status queries. Defaults to
+                ``DEFAULT_POLL_INTERVAL`` (5s).
+
+        Raises:
+            MediaJobError: The task ended as FAILED, CANCELED, or UNKNOWN.
+            MediaJobTimeoutError: The polling budget elapsed with no terminal 
result.
+            TypeError: ``timeout`` or ``poll_interval`` has an invalid type.
+            ValueError: ``timeout`` is negative/non-finite or 
``poll_interval`` is
+                non-positive/non-finite.
+        """
+        started_at = time.monotonic()
+        self._check_job(job)
+        wait_timeout = self._validate_wait_timeout(timeout, allow_zero=True)
+        interval = self._validate_poll_interval(poll_interval)
+        status = MediaJobStatus.UNKNOWN
+        while True:
+            if (
+                wait_timeout is not None
+                and time.monotonic() - started_at >= wait_timeout
+            ):
+                raise MediaJobTimeoutError(job, wait_timeout, status)
+            state = self.fetch(job)
+            status = state.status
+            if status is MediaJobStatus.SUCCEEDED:
+                if state.result is None:
+                    msg = f"Media job {job.job_id} succeeded without a result."
+                    raise MediaJobError(job, status, message=msg)
+                return state.result
+            if status in (
+                MediaJobStatus.FAILED,
+                MediaJobStatus.CANCELED,
+                MediaJobStatus.UNKNOWN,
+            ):
+                raise MediaJobError(job, status, state.error_code, 
state.error_message)
+            delay = interval
+            if wait_timeout is not None:
+                elapsed = time.monotonic() - started_at
+                delay = min(delay, wait_timeout - elapsed)
+            if delay > 0:
+                time.sleep(delay)
+
+    @abstractmethod
+    def cancel(self, job: MediaJob) -> None:
+        """Request cancellation of a task.
+
+        Providers that can only cancel queued tasks raise ``MediaJobError`` for
+        any other status.
+        """
+
+    @staticmethod
+    def _validate_wait_timeout(
+        timeout: float | None, *, allow_zero: bool = True
+    ) -> float | None:
+        """Validate the polling budget for an asynchronous job."""
+        if timeout is None:
+            return None
+        if isinstance(timeout, bool) or not isinstance(timeout, int | float):
+            msg = "The wait timeout must be a finite number or None."
+            raise TypeError(msg)
+        if not math.isfinite(timeout):
+            msg = "The wait timeout must be finite."
+            raise ValueError(msg)
+        if allow_zero:
+            if timeout < 0:
+                msg = "The wait timeout must be non-negative."
+                raise ValueError(msg)
+        elif timeout <= 0:
+            msg = "The wait timeout must be greater than 0."
+            raise ValueError(msg)
+        return timeout
+
+    @staticmethod
+    def _validate_poll_interval(poll_interval: float) -> float:
+        """Validate the positive delay between job status queries."""
+        if isinstance(poll_interval, bool) or not isinstance(
+            poll_interval, int | float
+        ):
+            msg = "The poll interval must be a positive finite number."
+            raise TypeError(msg)
+        if not math.isfinite(poll_interval):
+            msg = "The poll interval must be finite."
+            raise ValueError(msg)
+        if poll_interval <= 0:
+            msg = "The poll interval must be greater than 0."
+            raise ValueError(msg)
+        return poll_interval
+
+    def _check_job(self, job: MediaJob) -> None:
+        """Check the job against this capability's provider, model, and 
task."""
+        expected = self._provider_name()
+        if (
+            job.provider != expected
+            or job.model != self.model
+            or job.task != self._task.value
+        ):
+            msg = (
+                f"Media job {job.job_id} belongs to provider {job.provider!r}, 
"
+                f"model {job.model!r}, task {job.task!r}; this capability is "
+                f"provider {expected!r}, model {self.model!r}, task "
+                f"{self._task.value!r}."
+            )
+            raise ValueError(msg)
+
+    def _provider_name(self) -> str:
+        """Provider identifier stamped on jobs this capability submits.
+
+        Subclasses override this with their own provider name.
+        """
+        return type(self).__name__
+
+
+class BaseMediaModelSetup(Resource, ABC):
+    """Abstract base class for ``ResourceType.MEDIA_MODEL`` capability setups.
+
+    Concrete task setups extend one of the four task-specific subclasses
+    (``BaseSpeechSynthesisModelSetup``, ``BaseTranscriptionModelSetup``,
+    ``BaseImageGenerationModelSetup``, or ``BaseVideoGenerationModelSetup``) 
and
+    additionally implement ``AsyncJobModel`` when backed by resumable provider
+    jobs.
+    """
+
+    model_config = ConfigDict(extra="forbid", arbitrary_types_allowed=True)
+
+    provider: str | None = Field(
+        default=None,
+        description="Registered MEDIA_MODEL_PROVIDER resource name, when 
provider-backed.",
+    )
+    model: str = Field(description="Name of the model to call.")
+    model_parameters: dict[str, Any] = Field(

Review Comment:
   Could we follow the ChatModelSetup convention and expose common model 
parameters directly on each integration-specific Setup, with 
`additional_kwargs` for extra provider parameters? For example, 
`DashScopeImageGenerationModelSetup` could declare `size` and `n` explicitly, 
providing defaults and validation. This would remove the need for the base 
Setup to extract a generic `model_parameters` map. Please keep the Java, 
Python, and YAML configuration APIs aligned.



##########
api/src/main/java/org/apache/flink/agents/api/media/BaseMediaModelSetup.java:
##########
@@ -0,0 +1,251 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.api.media;
+
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceContext;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+
+import javax.annotation.Nullable;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Abstract base class for {@link ResourceType#MEDIA_MODEL} capability setups.
+ *
+ * <p>Concrete task setups extend one of the four task-specific subclasses 
({@link
+ * BaseSpeechSynthesisModelSetup}, {@link BaseTranscriptionModelSetup}, {@link
+ * BaseImageGenerationModelSetup}, or {@link BaseVideoGenerationModelSetup}) 
and optionally
+ * implement {@link AsyncJobModel} when backed by resumable provider jobs. A 
setup can either be
+ * declared via {@link ResourceDescriptor} referencing a {@link 
ResourceType#MEDIA_MODEL_PROVIDER},
+ * returned directly by {@link BaseMediaModelProvider} factory methods, or 
manage its own standalone
+ * client.
+ */
+public abstract class BaseMediaModelSetup extends Resource {
+    @Nullable protected final ResourceDescriptor descriptor;
+    @Nullable private final String providerName;
+    private final String model;
+    private final Map<String, Object> modelParameters;
+    @Nullable private transient BaseMediaModelProvider boundProvider;
+    private transient boolean ownsProviderBinding;
+
+    /**
+     * Construct a media model setup from a resource descriptor.
+     *
+     * <p>Requires a non-blank {@code model} argument; {@code provider} and 
{@code model_parameters}
+     * are optional (validated when set).
+     */
+    protected BaseMediaModelSetup(
+            ResourceDescriptor descriptor, @Nullable ResourceContext 
resourceContext) {
+        super(Objects.requireNonNull(descriptor, "descriptor"), 
resourceContext);
+        this.descriptor = descriptor;
+        Map<String, Object> rawArguments = descriptor.getInitialArguments();
+        Map<String, Object> arguments = rawArguments == null ? Map.of() : 
rawArguments;
+        this.providerName = optionalNonBlankString(arguments, "provider");
+        this.model = requireNonBlankString(arguments, "model");
+        this.modelParameters = extractModelParameters(arguments);
+    }
+
+    /**
+     * Construct a directly configured or provider-bound media model setup 
without a named provider
+     * reference.
+     */
+    protected BaseMediaModelSetup(
+            String model,
+            @Nullable Map<String, Object> modelParameters,
+            @Nullable ResourceDescriptor descriptor,
+            @Nullable ResourceContext resourceContext) {
+        this(null, model, modelParameters, descriptor, resourceContext);
+    }
+
+    /**
+     * Construct a media model setup with an explicit model, optional provider 
name, and model
+     * parameters.
+     */
+    protected BaseMediaModelSetup(
+            @Nullable String providerName,
+            String model,
+            @Nullable Map<String, Object> modelParameters,
+            @Nullable ResourceDescriptor descriptor,
+            @Nullable ResourceContext resourceContext) {
+        super(descriptor, resourceContext);
+        this.descriptor = descriptor;
+        if (providerName != null && providerName.isBlank()) {
+            throw new IllegalArgumentException(
+                    "Media model setup 'provider' must be a non-blank string 
when set.");
+        }
+        this.providerName = providerName;
+        this.model =
+                validateNonBlank(model, "Media model setup 'model' must be a 
non-blank string.");
+        this.modelParameters =
+                modelParameters == null ? Map.of() : 
MediaParameters.copy(modelParameters);
+    }
+
+    @Nullable
+    public String getProviderName() {
+        return providerName;
+    }
+
+    public String getModel() {
+        return model;
+    }
+
+    public Map<String, Object> getModelParameters() {
+        return modelParameters;
+    }
+
+    @Override
+    public ResourceType getResourceType() {
+        return ResourceType.MEDIA_MODEL;
+    }
+
+    /** Expected provider base class enforced when resolving or binding a 
provider. */
+    protected Class<? extends BaseMediaModelProvider> getProviderType() {
+        return BaseMediaModelProvider.class;
+    }
+
+    /** Attach a provider instance directly when constructed from a provider 
factory method. */
+    protected void bindProvider(BaseMediaModelProvider provider) {
+        Objects.requireNonNull(provider, "provider");
+        Class<? extends BaseMediaModelProvider> expectedType = 
getProviderType();
+        if (!expectedType.isInstance(provider)) {
+            throw new IllegalStateException(
+                    getClass().getSimpleName()
+                            + " requires a "
+                            + expectedType.getSimpleName()
+                            + ", got "
+                            + provider.getClass().getName());
+        }
+        this.boundProvider = provider;
+        this.ownsProviderBinding = false;
+    }
+
+    @Override
+    public void open() throws Exception {
+        super.open();
+        if (boundProvider == null && providerName != null) {
+            boundProvider = resolveProvider();
+            ownsProviderBinding = true;
+        }
+    }
+
+    @Override
+    public void close() throws Exception {
+        if (ownsProviderBinding) {
+            boundProvider = null;
+            ownsProviderBinding = false;
+        }
+        super.close();
+    }
+
+    /** Return the attached or opened {@link BaseMediaModelProvider} for this 
setup. */
+    protected BaseMediaModelProvider getProvider() {
+        if (boundProvider == null) {
+            throw new IllegalStateException(
+                    "Media model setup is not open. Call open() before using 
it.");
+        }
+        return boundProvider;
+    }
+
+    /** Resolve the configured {@link ResourceType#MEDIA_MODEL_PROVIDER} from 
context. */
+    protected BaseMediaModelProvider resolveProvider() throws Exception {
+        if (boundProvider != null) {
+            return boundProvider;
+        }
+        if (providerName == null) {
+            throw new IllegalStateException("Media model setup 'provider' is 
not configured.");
+        }
+        if (resourceContext == null) {
+            throw new IllegalStateException(
+                    "ResourceContext is required to resolve media model 
provider '"
+                            + providerName
+                            + "'.");
+        }
+        Resource resource =
+                resourceContext.getResource(providerName, 
ResourceType.MEDIA_MODEL_PROVIDER);
+        Class<? extends BaseMediaModelProvider> expectedType = 
getProviderType();
+        if (!expectedType.isInstance(resource)) {
+            throw new IllegalStateException(
+                    "Resource '"
+                            + providerName
+                            + "' of type MEDIA_MODEL_PROVIDER is not a "
+                            + expectedType.getSimpleName()
+                            + ": "
+                            + (resource == null ? "null" : 
resource.getClass().getName()));
+        }
+        return expectedType.cast(resource);
+    }
+
+    @Nullable
+    protected static String optionalNonBlankString(

Review Comment:
   Could we consolidate the string validation into a shared utility with 
required and optional variants? These checks are not media-specific, and the 
current helpers duplicate the type/blank checks across constructor paths. Also, 
`validateNonBlank()` always receives the same message, so its configurable 
`message` parameter adds no value here; an argument name would be sufficient. 
On Python, we can use the existing Pydantic validation mechanisms and 
consolidate the repeated connection-name checks in `__init__`, the field 
validator, and `_resolve_provider()`.



##########
api/src/main/java/org/apache/flink/agents/api/media/AsyncJobModel.java:
##########
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.api.media;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+
+/**
+ * Orthogonal contract implemented by media capabilities backed by resumable 
provider-side jobs.
+ *
+ * <p>Synchronous setups implement only the task-specific setup base class 
(such as {@link
+ * BaseSpeechSynthesisModelSetup} or {@link BaseImageGenerationModelSetup}) 
and do not implement
+ * this interface.
+ *
+ * <p>When a Python-backed async capability is reached across the 
Java-to-Python bridge, the
+ * provider owns {@link #submit(Object)}, single-observation {@link 
#fetch(MediaJob)}, {@link
+ * #cancel(MediaJob)}, and job-ownership validation, while convenience methods 
compose {@code
+ * submit()} + {@code wait()} and the Java bridge drives interruptible polling 
over those primitives
+ * using {@link #DEFAULT_WAIT_TIMEOUT} and {@link #DEFAULT_POLL_INTERVAL}. 
Native Java {@code
+ * AsyncJobModel} implementations supply three-argument {@link #wait(MediaJob, 
Duration, Duration)}
+ * directly.
+ */
+public interface AsyncJobModel<Req, Res extends MediaResult<?>> {
+    /** Default polling budget used by {@link #wait(MediaJob)}. */
+    Duration DEFAULT_WAIT_TIMEOUT = Duration.ofMinutes(30);
+
+    /** Default interval between job status queries. */
+    Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(5);
+
+    /** Submit a request and return a durable job handle without waiting. */
+    MediaJob submit(Req request);
+
+    /** Query once, retrieving the typed result when the job has succeeded. */
+    MediaJobState<Res> fetch(MediaJob job);
+
+    /** Wait using {@link #DEFAULT_WAIT_TIMEOUT} and {@link 
#DEFAULT_POLL_INTERVAL}. */
+    default Res wait(MediaJob job) {
+        return wait(job, DEFAULT_WAIT_TIMEOUT);
+    }
+
+    /**
+     * Poll until completion using {@link #DEFAULT_POLL_INTERVAL}. Pass {@code 
null} for unlimited
+     * polling.
+     */
+    default Res wait(MediaJob job, @Nullable Duration timeout) {
+        return wait(job, timeout, DEFAULT_POLL_INTERVAL);
+    }
+
+    /**
+     * Poll until completion. Pass {@code null} timeout for unlimited polling. 
The budget limits
+     * when a new query can start; an in-flight query may return after it 
expires.
+     *
+     * @param job durable job handle returned by {@link #submit(Object)}
+     * @param timeout non-negative polling budget, or {@code null} for 
unlimited polling
+     * @param pollInterval positive delay between status queries
+     * @throws MediaJobException if the job ends without a successful result
+     * @throws MediaJobTimeoutException if the polling budget expires; the job 
remains queryable
+     */
+    Res wait(MediaJob job, @Nullable Duration timeout, Duration pollInterval);

Review Comment:
   Could we provide a default implementation of this three-argument `wait()` in 
Java's `AsyncJobModel`, consistent with Python? It could poll through 
`fetch(job)`, avoiding duplicated polling logic in individual implementations. 
Please preserve the existing interruption handling so cancellation stops local 
waiting without automatically canceling the remote job or persisting 
cancellation as a business failure.



##########
api/src/main/java/org/apache/flink/agents/api/media/MediaJob.java:
##########
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.api.media;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import javax.annotation.Nullable;
+
+import java.util.Objects;
+
+/** Handle of a submitted asynchronous media task. */
+public final class MediaJob {
+    private final String provider;

Review Comment:
   Could we simplify `MediaJob` by removing `provider`, `model`, and `task`, 
together with Python's `_check_job()`, the related bridge validation, and 
Java's `MediaTask` enum? These fields currently support matching validation 
rather than request routing. Queries use the job ID, while the selected Setup 
determines the connection and result decoding. We can document that callers are 
responsible for using the appropriate Setup, and update both Java/Python models 
and the bridge serialization accordingly. Setup task metadata used for 
cross-language dispatch should remain.



##########
python/flink_agents/api/media/media_model.py:
##########
@@ -0,0 +1,668 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+#################################################################################
+import json
+import math
+import time
+from abc import ABC, abstractmethod
+from enum import Enum
+from typing import TYPE_CHECKING, Any, ClassVar, Generic, Mapping, Sequence, 
TypeVar
+
+from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator
+from typing_extensions import override
+
+from flink_agents.api.chat_message import (
+    AudioBlock,
+    DataContentBlock,
+    DocumentBlock,
+    ImageBlock,
+    TextBlock,
+    VideoBlock,
+)
+from flink_agents.api.resource import Resource, ResourceType
+
+if TYPE_CHECKING:
+    from flink_agents.api.media.media_model_provider import 
BaseMediaModelProvider
+
+
+class _MediaTask(str, Enum):
+    """Internal identifiers for job validation and cross-language dispatch."""
+
+    IMAGE_GENERATION = "image_generation"
+    VIDEO_GENERATION = "video_generation"
+    TRANSCRIPTION = "transcription"
+    SPEECH_SYNTHESIS = "speech_synthesis"
+
+
+class MediaJobStatus(str, Enum):
+    """Lifecycle state of a submitted asynchronous provider task."""
+
+    PENDING = "pending"
+    RUNNING = "running"
+    SUCCEEDED = "succeeded"
+    FAILED = "failed"
+    CANCELED = "canceled"
+    # The provider can no longer identify the task, for example because its
+    # retention window has passed.
+    UNKNOWN = "unknown"
+
+
+class MediaJob(BaseModel):
+    """Handle of a submitted asynchronous provider task.
+
+    Frozen and JSON-serializable so it can be persisted as the result of a
+    durable execution and replayed across recovery.
+    """
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    provider: str = Field(description="Provider that owns the task, e.g. 
'dashscope'.")
+    model: str = Field(description="Model the task was submitted to.")
+    task: str = Field(description="Capability identifier recorded when 
submitting.")
+    job_id: str = Field(description="Provider task identifier.")
+    submitted_at_ms: int = Field(description="Local submission time, epoch 
millis.")
+    expires_at_ms: int | None = Field(
+        default=None,
+        description="Time until which the provider can still be queried for 
this task.",
+    )
+
+    @field_validator("task")
+    @classmethod
+    def _validate_task(cls, value: str) -> str:
+        expected = tuple(task.value for task in _MediaTask)
+        if value not in expected:
+            msg = (
+                f"Invalid media task {value!r}; expected one of: {', 
'.join(expected)}."
+            )
+            raise ValueError(msg)
+        return value
+
+
+ContentT = TypeVar("ContentT", bound=DataContentBlock)
+
+
+class MediaResult(BaseModel, Generic[ContentT]):
+    """Output of a finished generation, transcription, or synthesis."""
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    content: list[ContentT] = Field(
+        description="Generated content, in the order returned by the provider."
+    )
+    expires_at_ms: int | None = Field(
+        default=None,
+        description="Time until which result URLs stay valid, when the 
provider says so.",
+    )
+    usage: dict[str, int | float | str] = Field(
+        default_factory=dict,
+        description="Provider usage counters, kept as reported.",
+    )
+    request_id: str | None = Field(
+        default=None, description="Provider request identifier."
+    )
+    metadata: dict[str, Any] = Field(
+        default_factory=dict,
+        description="Structured provider data that does not fit into a content 
block.",
+    )
+
+
+ResultT = TypeVar("ResultT", bound=MediaResult)
+
+
+class MediaJobState(BaseModel, Generic[ResultT]):
+    """One observation of a job, returned by ``fetch``."""
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    job: MediaJob
+    status: MediaJobStatus
+    result: ResultT | None = Field(
+        default=None, description="Present only when the status is SUCCEEDED."
+    )
+    error_code: str | None = Field(
+        default=None, description="Present only when the status is FAILED."
+    )
+    error_message: str | None = None
+
+
+class MediaJobError(Exception):
+    """An operation on a media job failed.
+
+    Attributes:
+        job: The job associated with the error.
+        status: The last observed job status, or UNKNOWN if unavailable.
+        code: Provider error code, when the provider reported one.
+        message: Provider error message, when the provider reported one.
+    """
+
+    def __init__(
+        self,
+        job: MediaJob,
+        status: MediaJobStatus,
+        code: str | None = None,
+        message: str | None = None,
+    ) -> None:
+        """Record the job, its observed status, and any provider error."""
+        self.job = job
+        self.status = status
+        self.code = code
+        self.message = message
+        detail = status.value
+        if code is not None:
+            detail = f"{detail} ({code})"
+        if message is not None:
+            detail = f"{detail}: {message}"
+        super().__init__(f"Media job {job.job_id}: {detail}")
+
+    def __reduce__(self) -> tuple[type[Exception], tuple[Any, ...], dict[str, 
Any]]:
+        """Rebuild the exception with its structured constructor arguments."""
+        return type(self), (self.job, self.status, self.code, self.message), 
vars(self)
+
+
+class MediaJobTimeoutError(MediaJobError):
+    """The polling budget for ``wait`` elapsed before a terminal status was 
observed.
+
+    Attributes:
+        timeout: The polling budget in seconds.
+    """
+
+    def __init__(
+        self,
+        job: MediaJob,
+        timeout: float,
+        status: MediaJobStatus = MediaJobStatus.UNKNOWN,
+    ) -> None:
+        """Record the job, its last observed status, and the polling budget."""
+        self.timeout = timeout
+        super().__init__(job, status, message=f"timed out after {timeout} 
seconds")
+
+    def __reduce__(self) -> tuple[type[Exception], tuple[Any, ...], dict[str, 
Any]]:
+        """Rebuild the timeout with its job, budget, and last observed 
status."""
+        return type(self), (self.job, self.timeout, self.status), vars(self)
+
+
+DEFAULT_WAIT_TIMEOUT = 1800.0
+DEFAULT_POLL_INTERVAL = 5.0
+
+
+class AsyncJobModel(Generic[ResultT], ABC):
+    """A media capability with submitted jobs that can be queried and resumed.
+
+    Setups that back a media capability with cloud jobs implement this
+    interface alongside their ``Base*ModelSetup`` base class and own 
``submit``,
+    single-observation ``fetch``, ``cancel``, and job-ownership validation
+    (``_check_job``). Python convenience methods compose ``_submit_and_wait``,
+    and Java-to-Python bridges compose those same primitives with interruptible
+    polling using ``DEFAULT_WAIT_TIMEOUT`` and ``DEFAULT_POLL_INTERVAL``.
+    Native Java ``AsyncJobModel`` implementations supply three-argument 
``wait``
+    directly. Synchronous setups extend only the task-specific setup base 
class.
+
+    Call ``submit`` and persist its returned job separately when waiting must
+    resume after recovery. None of these methods records durable execution or
+    emits events itself.
+    """
+
+    if TYPE_CHECKING:
+        model: str
+        _task: ClassVar[_MediaTask]
+
+    def _submit_and_wait(
+        self,
+        *args: Any,
+        timeout: float | None = None,
+        **kwargs: Any,
+    ) -> ResultT:
+        """Submit a request and wait for its result.
+
+        Args:
+            *args: The inputs accepted by this media capability.
+            timeout: Polling budget in seconds after submission. None uses
+                ``DEFAULT_WAIT_TIMEOUT``. This does not change HTTP request
+                timeouts.
+            **kwargs: Provider parameters for submission.
+        """
+        budget = DEFAULT_WAIT_TIMEOUT if timeout is None else timeout
+        budget = self._validate_wait_timeout(budget, allow_zero=False)
+        job = self.submit(*args, **kwargs)
+        return self.wait(job, timeout=budget)
+
+    @abstractmethod
+    def submit(self, *args: Any, **kwargs: Any) -> MediaJob:
+        """Submit a request and return its job handle without waiting."""
+
+    @abstractmethod
+    def fetch(self, job: MediaJob) -> MediaJobState[ResultT]:
+        """Query the task status once.
+
+        Retrieve the full result when the status is SUCCEEDED.
+        """
+
+    def wait(
+        self,
+        job: MediaJob,
+        *,
+        timeout: float | None = DEFAULT_WAIT_TIMEOUT,
+        poll_interval: float = DEFAULT_POLL_INTERVAL,
+    ) -> ResultT:
+        """Block until the task reaches a terminal status.
+
+        Waits up to ``poll_interval`` seconds between queries. The polling
+        budget limits when a new query can start. A query already in progress
+        can finish and return its result. On timeout ``MediaJobTimeoutError``
+        is raised and the provider task can continue.
+
+        Args:
+            job: Handle returned by ``submit``.
+            timeout: Polling budget in seconds from the start of this wait.
+                Defaults to ``DEFAULT_WAIT_TIMEOUT`` (1800s). Pass ``None`` for
+                unlimited polling.
+            poll_interval: Positive seconds between status queries. Defaults to
+                ``DEFAULT_POLL_INTERVAL`` (5s).
+
+        Raises:
+            MediaJobError: The task ended as FAILED, CANCELED, or UNKNOWN.
+            MediaJobTimeoutError: The polling budget elapsed with no terminal 
result.
+            TypeError: ``timeout`` or ``poll_interval`` has an invalid type.
+            ValueError: ``timeout`` is negative/non-finite or 
``poll_interval`` is
+                non-positive/non-finite.
+        """
+        started_at = time.monotonic()
+        self._check_job(job)
+        wait_timeout = self._validate_wait_timeout(timeout, allow_zero=True)
+        interval = self._validate_poll_interval(poll_interval)
+        status = MediaJobStatus.UNKNOWN
+        while True:
+            if (
+                wait_timeout is not None
+                and time.monotonic() - started_at >= wait_timeout
+            ):
+                raise MediaJobTimeoutError(job, wait_timeout, status)
+            state = self.fetch(job)
+            status = state.status
+            if status is MediaJobStatus.SUCCEEDED:
+                if state.result is None:
+                    msg = f"Media job {job.job_id} succeeded without a result."
+                    raise MediaJobError(job, status, message=msg)
+                return state.result
+            if status in (
+                MediaJobStatus.FAILED,
+                MediaJobStatus.CANCELED,
+                MediaJobStatus.UNKNOWN,
+            ):
+                raise MediaJobError(job, status, state.error_code, 
state.error_message)
+            delay = interval
+            if wait_timeout is not None:
+                elapsed = time.monotonic() - started_at
+                delay = min(delay, wait_timeout - elapsed)
+            if delay > 0:
+                time.sleep(delay)
+
+    @abstractmethod
+    def cancel(self, job: MediaJob) -> None:
+        """Request cancellation of a task.
+
+        Providers that can only cancel queued tasks raise ``MediaJobError`` for
+        any other status.
+        """
+
+    @staticmethod
+    def _validate_wait_timeout(

Review Comment:
   Could we merge `_validate_wait_timeout()` and `_validate_poll_interval()` 
into one helper that validates a positive, finite number, keeping the float 
API? We could consistently reject zero and remove `allow_zero`, leaving `None` 
handling to the callers. Please keep validation before submission in 
`_submit_and_wait()`, as well as in `wait()` for standalone calls, and align 
the Java timeout contract accordingly.



##########
api/src/main/java/org/apache/flink/agents/api/media/MediaParameters.java:
##########
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.api.media;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/** Recursively snapshots nested {@link Map} and {@link List} model parameters 
for immutability. */
+final class MediaParameters {

Review Comment:
   Could we remove `MediaParameters` and the recursive immutable snapshots? We 
can read parameters directly from the request, with callers expected not to 
mutate them during execution. Implementations only need a new map when merging 
defaults or modifying parameters for a call. Please use the same ownership 
contract on the Python side and adjust the documentation and tests rather than 
promise deep immutability.



##########
api/src/main/java/org/apache/flink/agents/api/media/BaseMediaModelSetup.java:
##########
@@ -0,0 +1,251 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.agents.api.media;
+
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceContext;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+
+import javax.annotation.Nullable;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Abstract base class for {@link ResourceType#MEDIA_MODEL} capability setups.
+ *
+ * <p>Concrete task setups extend one of the four task-specific subclasses 
({@link
+ * BaseSpeechSynthesisModelSetup}, {@link BaseTranscriptionModelSetup}, {@link
+ * BaseImageGenerationModelSetup}, or {@link BaseVideoGenerationModelSetup}) 
and optionally
+ * implement {@link AsyncJobModel} when backed by resumable provider jobs. A 
setup can either be
+ * declared via {@link ResourceDescriptor} referencing a {@link 
ResourceType#MEDIA_MODEL_PROVIDER},
+ * returned directly by {@link BaseMediaModelProvider} factory methods, or 
manage its own standalone
+ * client.
+ */
+public abstract class BaseMediaModelSetup extends Resource {
+    @Nullable protected final ResourceDescriptor descriptor;
+    @Nullable private final String providerName;
+    private final String model;
+    private final Map<String, Object> modelParameters;
+    @Nullable private transient BaseMediaModelProvider boundProvider;
+    private transient boolean ownsProviderBinding;
+
+    /**
+     * Construct a media model setup from a resource descriptor.
+     *
+     * <p>Requires a non-blank {@code model} argument; {@code provider} and 
{@code model_parameters}
+     * are optional (validated when set).
+     */
+    protected BaseMediaModelSetup(
+            ResourceDescriptor descriptor, @Nullable ResourceContext 
resourceContext) {
+        super(Objects.requireNonNull(descriptor, "descriptor"), 
resourceContext);
+        this.descriptor = descriptor;
+        Map<String, Object> rawArguments = descriptor.getInitialArguments();
+        Map<String, Object> arguments = rawArguments == null ? Map.of() : 
rawArguments;
+        this.providerName = optionalNonBlankString(arguments, "provider");
+        this.model = requireNonBlankString(arguments, "model");
+        this.modelParameters = extractModelParameters(arguments);
+    }
+
+    /**
+     * Construct a directly configured or provider-bound media model setup 
without a named provider
+     * reference.
+     */
+    protected BaseMediaModelSetup(

Review Comment:
   Could we remove this unused four-argument constructor? All four 
task-specific subclasses call the five-argument constructor with `providerName` 
directly, so this overload has no callers.



##########
python/flink_agents/api/media/media_model.py:
##########
@@ -0,0 +1,668 @@
+################################################################################
+#  Licensed to the Apache Software Foundation (ASF) under one
+#  or more contributor license agreements.  See the NOTICE file
+#  distributed with this work for additional information
+#  regarding copyright ownership.  The ASF licenses this file
+#  to you under the Apache License, Version 2.0 (the
+#  "License"); you may not use this file except in compliance
+#  with the License.  You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+#  Unless required by applicable law or agreed to in writing, software
+#  distributed under the License is distributed on an "AS IS" BASIS,
+#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#  See the License for the specific language governing permissions and
+# limitations under the License.
+#################################################################################
+import json
+import math
+import time
+from abc import ABC, abstractmethod
+from enum import Enum
+from typing import TYPE_CHECKING, Any, ClassVar, Generic, Mapping, Sequence, 
TypeVar
+
+from pydantic import BaseModel, ConfigDict, Field, PrivateAttr, field_validator
+from typing_extensions import override
+
+from flink_agents.api.chat_message import (
+    AudioBlock,
+    DataContentBlock,
+    DocumentBlock,
+    ImageBlock,
+    TextBlock,
+    VideoBlock,
+)
+from flink_agents.api.resource import Resource, ResourceType
+
+if TYPE_CHECKING:
+    from flink_agents.api.media.media_model_provider import 
BaseMediaModelProvider
+
+
+class _MediaTask(str, Enum):
+    """Internal identifiers for job validation and cross-language dispatch."""
+
+    IMAGE_GENERATION = "image_generation"
+    VIDEO_GENERATION = "video_generation"
+    TRANSCRIPTION = "transcription"
+    SPEECH_SYNTHESIS = "speech_synthesis"
+
+
+class MediaJobStatus(str, Enum):
+    """Lifecycle state of a submitted asynchronous provider task."""
+
+    PENDING = "pending"
+    RUNNING = "running"
+    SUCCEEDED = "succeeded"
+    FAILED = "failed"
+    CANCELED = "canceled"
+    # The provider can no longer identify the task, for example because its
+    # retention window has passed.
+    UNKNOWN = "unknown"
+
+
+class MediaJob(BaseModel):
+    """Handle of a submitted asynchronous provider task.
+
+    Frozen and JSON-serializable so it can be persisted as the result of a
+    durable execution and replayed across recovery.
+    """
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    provider: str = Field(description="Provider that owns the task, e.g. 
'dashscope'.")
+    model: str = Field(description="Model the task was submitted to.")
+    task: str = Field(description="Capability identifier recorded when 
submitting.")
+    job_id: str = Field(description="Provider task identifier.")
+    submitted_at_ms: int = Field(description="Local submission time, epoch 
millis.")
+    expires_at_ms: int | None = Field(
+        default=None,
+        description="Time until which the provider can still be queried for 
this task.",
+    )
+
+    @field_validator("task")
+    @classmethod
+    def _validate_task(cls, value: str) -> str:
+        expected = tuple(task.value for task in _MediaTask)
+        if value not in expected:
+            msg = (
+                f"Invalid media task {value!r}; expected one of: {', 
'.join(expected)}."
+            )
+            raise ValueError(msg)
+        return value
+
+
+ContentT = TypeVar("ContentT", bound=DataContentBlock)
+
+
+class MediaResult(BaseModel, Generic[ContentT]):
+    """Output of a finished generation, transcription, or synthesis."""
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    content: list[ContentT] = Field(
+        description="Generated content, in the order returned by the provider."
+    )
+    expires_at_ms: int | None = Field(
+        default=None,
+        description="Time until which result URLs stay valid, when the 
provider says so.",
+    )
+    usage: dict[str, int | float | str] = Field(
+        default_factory=dict,
+        description="Provider usage counters, kept as reported.",
+    )
+    request_id: str | None = Field(
+        default=None, description="Provider request identifier."
+    )
+    metadata: dict[str, Any] = Field(
+        default_factory=dict,
+        description="Structured provider data that does not fit into a content 
block.",
+    )
+
+
+ResultT = TypeVar("ResultT", bound=MediaResult)
+
+
+class MediaJobState(BaseModel, Generic[ResultT]):
+    """One observation of a job, returned by ``fetch``."""
+
+    model_config = ConfigDict(frozen=True, extra="forbid")
+
+    job: MediaJob
+    status: MediaJobStatus
+    result: ResultT | None = Field(
+        default=None, description="Present only when the status is SUCCEEDED."
+    )
+    error_code: str | None = Field(
+        default=None, description="Present only when the status is FAILED."
+    )
+    error_message: str | None = None
+
+
+class MediaJobError(Exception):
+    """An operation on a media job failed.
+
+    Attributes:
+        job: The job associated with the error.
+        status: The last observed job status, or UNKNOWN if unavailable.
+        code: Provider error code, when the provider reported one.
+        message: Provider error message, when the provider reported one.
+    """
+
+    def __init__(
+        self,
+        job: MediaJob,
+        status: MediaJobStatus,
+        code: str | None = None,
+        message: str | None = None,
+    ) -> None:
+        """Record the job, its observed status, and any provider error."""
+        self.job = job
+        self.status = status
+        self.code = code
+        self.message = message
+        detail = status.value
+        if code is not None:
+            detail = f"{detail} ({code})"
+        if message is not None:
+            detail = f"{detail}: {message}"
+        super().__init__(f"Media job {job.job_id}: {detail}")
+
+    def __reduce__(self) -> tuple[type[Exception], tuple[Any, ...], dict[str, 
Any]]:
+        """Rebuild the exception with its structured constructor arguments."""
+        return type(self), (self.job, self.status, self.code, self.message), 
vars(self)
+
+
+class MediaJobTimeoutError(MediaJobError):
+    """The polling budget for ``wait`` elapsed before a terminal status was 
observed.
+
+    Attributes:
+        timeout: The polling budget in seconds.
+    """
+
+    def __init__(
+        self,
+        job: MediaJob,
+        timeout: float,
+        status: MediaJobStatus = MediaJobStatus.UNKNOWN,
+    ) -> None:
+        """Record the job, its last observed status, and the polling budget."""
+        self.timeout = timeout
+        super().__init__(job, status, message=f"timed out after {timeout} 
seconds")
+
+    def __reduce__(self) -> tuple[type[Exception], tuple[Any, ...], dict[str, 
Any]]:
+        """Rebuild the timeout with its job, budget, and last observed 
status."""
+        return type(self), (self.job, self.timeout, self.status), vars(self)
+
+
+DEFAULT_WAIT_TIMEOUT = 1800.0
+DEFAULT_POLL_INTERVAL = 5.0
+
+
+class AsyncJobModel(Generic[ResultT], ABC):

Review Comment:
   Could we split `media_model.py` by responsibility? It currently combines 
result types, job state/errors, async polling, and model setups.
   
   A possible structure:
   
   - `media_result.py`: `MediaResult`
   - `media_job.py`: job handles, status, state, and errors
   - `async_job_model.py`: `AsyncJobModel` and polling logic
   - `media_model_setup.py`: the shared and task-specific Setup classes
   
   The task-specific Setups are small enough to stay together. This would also 
make the separation between async job support and model setups clearer. Please 
update the imports and organize the corresponding tests along the same 
boundaries.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to