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


##########
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:
   Done. Split into `media_model_connection.py`, `media_result.py`, 
`media_job.py`, `async_job_model.py`, and `media_model_setup.py`, with matching 
test modules under `python/flink_agents/api/media/tests/`.



-- 
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