joeyutong commented on code in PR #1382: URL: https://github.com/apache/flink-agents/pull/1382#discussion_r4677730410
########## 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: Done. Removed `getProviderType()` / `bindProvider()` in Java and `_provider_type` / `_expected_provider_type()` / `_validate_provider_instance()` in Python; `BaseMediaModelSetup` now resolves `connection` directly via `resourceContext` / `get_resource` with `ResourceType.MEDIA_MODEL_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() { + 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: Done. Removed `ownsProviderBinding` in Java and `_owns_provider_binding` in Python; `close()` clears the setup's connection reference without closing the shared connection. ########## 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: Done. Removed `model_parameters` from `BaseMediaModelSetup` and exposed common task parameters directly on each `DashScope*ModelSetup` alongside `additional_kwargs` (precedence: call-time `model_parameters` > `additional_kwargs` > explicit setup fields), aligned across Java, Python, YAML, and schemas. -- 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]
