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


##########
docs/content/docs/development/media_models/_index.md:
##########
@@ -0,0 +1,400 @@
+---
+title: "Media Models"
+weight: 9
+type: docs
+---
+<!--
+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.
+-->
+
+# Media Models
+
+## Overview
+
+Use media models when an Agent needs dedicated media operations—such as
+generating images or videos, transcribing recordings, or synthesizing speech.
+By default, register a shared `MEDIA_MODEL_CONNECTION` for your service
+connection and declare named `MEDIA_MODEL` setups (subclasses of
+`BaseImageGenerationModelSetup`, `BaseVideoGenerationModelSetup`,
+`BaseTranscriptionModelSetup`, or `BaseSpeechSynthesisModelSetup`, such as
+DashScope's `DashScopeImageGenerationModelSetup`) retrieved via
+`ctx.get_resource(name, ResourceType.MEDIA_MODEL)`. Declaring named setups 
keeps
+model selection and default parameters out of Action code, enables YAML
+configuration, and makes models easy to reuse across Actions and share between
+Java and Python.
+
+If your workflow uses conversation-style multimodal messages instead, see
+[Chat with Models]({{< ref "docs/development/calling-llms/chat" >}}). For
+available implementations and provider options, see
+[Built-in Media Model Connections]({{< ref 
"docs/development/media_models/providers" >}}).
+
+## Quick start
+
+### 1. Register a connection
+
+Register a `MEDIA_MODEL_CONNECTION` resource with your chosen connection
+descriptor. The example below uses DashScope; replace it with any 
implementation
+from [Built-in Media Model Connections]({{< ref 
"docs/development/media_models/providers" >}}):
+
+{{< tabs "Register a media model connection" >}}
+{{< tab "Python" >}}
+```python
+from flink_agents.api.resource import ResourceDescriptor, ResourceName, 
ResourceType
+
+agents_env.add_resource(
+    "media",
+    ResourceType.MEDIA_MODEL_CONNECTION,
+    ResourceDescriptor(clazz=ResourceName.MediaModel.DASHSCOPE_CONNECTION),
+)
+```
+{{< /tab >}}
+{{< tab "Java" >}}
+```java
+import org.apache.flink.agents.api.resource.PythonResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceName;
+import org.apache.flink.agents.api.resource.ResourceType;
+
+agentsEnv.addResource(
+        "media",
+        ResourceType.MEDIA_MODEL_CONNECTION,
+        PythonResourceDescriptor.Builder.newBuilder(
+                        ResourceName.MediaModel.Python.DASHSCOPE_CONNECTION)
+                .build());
+```
+{{< /tab >}}
+{{< tab "YAML" >}}
+```yaml
+media_model_connections:
+  - name: media
+    clazz: dashscope
+    type: python
+    request_timeout: 60
+```
+{{< /tab >}}
+{{< /tabs >}}
+
+You can also declare a connection using `@media_model_connection` in Python,
+`@MediaModelConnection` in Java, or the YAML `media_model_connections` section.
+See [Registering Resources]({{< ref 
"docs/development/create-agent/resources#registering-resources" >}})
+and [YAML Resources]({{< ref "docs/development/create-agent/yaml#resources" 
>}}).
+
+### 2. Declare a media model setup and call it
+
+Declare a named, pre-configured `MEDIA_MODEL` setup (for example
+`DashScopeImageGenerationModelSetup` or a custom subclass of
+`BaseImageGenerationModelSetup`, `BaseVideoGenerationModelSetup`,
+`BaseTranscriptionModelSetup`, or `BaseSpeechSynthesisModelSetup`) using
+`@media_model_setup` / `@MediaModelSetup`,
+`add_resource(..., ResourceType.MEDIA_MODEL, ...)` / `addResource(...)`, or 
YAML
+`media_model_setups`. This keeps Action code independent of specific model 
names
+and default parameters:
+
+{{< tabs "Declare a media model setup" >}}
+{{< tab "Python" >}}
+```python
+from flink_agents.api.agents.agent import Agent
+from flink_agents.api.decorators import media_model_setup
+from flink_agents.api.resource import ResourceDescriptor, ResourceName, 
ResourceType
+
+
+class PosterAgent(Agent):
+    @media_model_setup
+    @staticmethod
+    def poster_image() -> ResourceDescriptor:
+        return ResourceDescriptor(
+            clazz=ResourceName.MediaModel.DASHSCOPE_IMAGE_GENERATION_SETUP,
+            connection="media",
+            model="qwen-image-3.0",
+            size="512*512",
+        )
+```
+
+Retrieve the setup inside an Action via `ResourceType.MEDIA_MODEL`:
+
+```python
+image_model = ctx.get_resource("poster_image", ResourceType.MEDIA_MODEL)
+result = image_model.generate("A navy notebook on a white desk.", timeout=180)
+generated_image = result.content[0]
+```
+{{< /tab >}}
+{{< tab "Java" >}}
+```java
+import org.apache.flink.agents.api.agents.Agent;
+import org.apache.flink.agents.api.annotation.MediaModelSetup;
+import org.apache.flink.agents.api.resource.PythonResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceName;
+
+public class PosterAgent extends Agent {
+    @MediaModelSetup
+    public static ResourceDescriptor posterImage() {
+        return PythonResourceDescriptor.Builder.newBuilder(
+                        
ResourceName.MediaModel.Python.DASHSCOPE_IMAGE_GENERATION_SETUP)
+                .addInitialArgument("connection", "media")
+                .addInitialArgument("model", "qwen-image-3.0")
+                .addInitialArgument("size", "512*512")
+                .build();
+    }
+}
+```
+
+Retrieve the setup inside an Action via `ResourceType.MEDIA_MODEL`:
+
+```java
+BaseImageGenerationModelSetup imageModel =
+        (BaseImageGenerationModelSetup) ctx.getResource("posterImage", 
ResourceType.MEDIA_MODEL);
+MediaResult<ImageBlock> result =
+        imageModel.generate(
+                ImageGenerationRequest.of("A navy notebook on a white desk."),
+                Duration.ofMinutes(3));
+ImageBlock generatedImage = result.getContent().get(0);
+```
+{{< /tab >}}
+{{< tab "YAML" >}}
+```yaml
+media_model_setups:
+  - name: poster_image
+    clazz: dashscope_image_generation
+    connection: media
+    model: qwen-image-3.0
+    size: "512*512"
+```
+
+Retrieve the setup inside an Action with
+`ctx.get_resource("poster_image", ResourceType.MEDIA_MODEL)` (Java:
+`ctx.getResource("poster_image", ResourceType.MEDIA_MODEL)`). Omitted `type:`
+defaults to `python`; set `type: java` with a Java setup class name in
+Java-loaded YAML.
+{{< /tab >}}
+{{< /tabs >}}
+
+Media model setups require both `connection` and `model`. Concrete
+integration setups (such as DashScope setups) declare common typed parameters
+directly alongside optional `additional_kwargs` for provider-specific
+extensions (and `BaseSpeechSynthesisModelSetup` adds optional `voice`). Setups
+share their connection's lifetime, detach without closing the shared connection
+when closed, and preserve `AsyncJobModel` support whenever the setup is
+asynchronous.
+
+Each call returns a `MediaResult` containing typed output blocks in `content`
+(`getContent()`), along with optional `expires_at_ms`, `usage`, `request_id`,
+and `metadata`.
+
+## Capabilities
+
+Flink Agents currently includes the capabilities below and may expand this set
+over time. Supported capabilities, media sources (URL or Base64),
+provider-specific setup classes, YAML aliases, and model options depend on the
+connection; see
+[Built-in Media Model Connections]({{< ref 
"docs/development/media_models/providers" >}}).
+
+| Capability | Base setup class | Method | Inputs | Result `content` |
+|---|---|---|---|---|
+| Image generation and editing | `BaseImageGenerationModelSetup` | 
`generate(...)` | Prompt and optional reference `ImageBlock`s | `ImageBlock`s |
+| Video generation | `BaseVideoGenerationModelSetup` | `generate(...)` | 
Prompt, ordered media blocks, or both | `VideoBlock`s |
+| Transcription | `BaseTranscriptionModelSetup` | `transcribe(...)` | 
`AudioBlock` or `VideoBlock` | `TextBlock`s |
+| Speech synthesis | `BaseSpeechSynthesisModelSetup` | `synthesize(...)` | 
Text and optional `voice` | `AudioBlock`s |
+
+See [Multimodal Messages]({{< ref 
"docs/development/calling-llms/chat#message-content-blocks" >}})
+for creating `ImageBlock`, `AudioBlock`, `VideoBlock`, and `DocumentBlock`
+inputs.
+
+### Synchronous and asynchronous execution
+
+Depending on the implementation and capability, a setup executes either
+synchronously or through an asynchronous cloud job (see
+[Built-in Media Model Connections]({{< ref 
"docs/development/media_models/providers" >}})
+for each implementation's execution mode):
+
+- **Synchronous capabilities** (such as speech synthesis on DashScope) complete
+  within a single request and return `MediaResult` directly.
+- **Asynchronous capabilities** (such as image generation, video generation,
+  and file transcription on DashScope) run as provider-side jobs and implement
+  `AsyncJobModel`. Calling `generate()` or `transcribe()` directly submits the
+  job and polls until completion; for recovery-safe execution, manual polling,
+  or cancellation, use `AsyncJobModel` directly as shown in
+  [Asynchronous jobs and recovery](#asynchronous-jobs-and-recovery).
+
+### Parameters
+
+Parameters are configured at three levels, with narrower levels overriding
+broader defaults:
+
+- **Connection level (`MEDIA_MODEL_CONNECTION` descriptor)**: Connection and
+  client settings shared across capabilities—for example `api_key`, `region`,
+  `base_url`, and `request_timeout`.
+- **Model setup level (`MEDIA_MODEL` setup)**:
+  Defaults reused across calls to that model—for example explicit typed
+  parameters such as `size="512*512"`, `voice="Cherry"`, plus optional
+  `additional_kwargs` for provider-specific extensions.
+- **Per-call level (`generate()`, `transcribe()`, `synthesize()`)**:
+  Request-specific overrides—for example `model_parameters` (such as `size` or
+  `n`), `voice`, and `timeout` (`timeout=30` in Python or
+  `Duration.ofSeconds(30)` in Java).
+
+Per-call `timeout` overrides the connection's `request_timeout` for synchronous
+calls, or sets the positive polling budget (such as `timeout=180` or
+`Duration.ofMinutes(3)`) for asynchronous calls. `model_parameters` and
+`additional_kwargs` are not mutated during execution; callers should not mutate
+nested container values while a request is in flight.
+
+## Asynchronous jobs and recovery
+
+For asynchronous capabilities that implement `AsyncJobModel`, you can split
+submission and completion with `submit()`, `fetch()`, `wait()`, and `cancel()`
+so a long-running job survives recovery or can be polled and canceled directly:
+
+{{< tabs "Resume asynchronous media jobs" >}}
+{{< tab "Python" >}}
+```python
+from flink_agents.api.media import AsyncJobModel
+from flink_agents.api.resource import ResourceType
+
+image_model = ctx.get_resource("poster_image", ResourceType.MEDIA_MODEL)
+if isinstance(image_model, AsyncJobModel):
+    job = await ctx.durable_execute_async(image_model.submit, "A navy notebook 
on a white desk.")
+    result = await ctx.durable_execute_async(
+        image_model.wait,
+        job,
+        timeout=180,
+        poll_interval=2,
+    )
+    generated_image = result.content[0]
+```
+{{< /tab >}}
+{{< tab "Java" >}}
+```java
+import org.apache.flink.agents.api.chat.messages.ImageBlock;
+import org.apache.flink.agents.api.context.DurableCallable;
+import org.apache.flink.agents.api.media.AsyncJobModel;
+import org.apache.flink.agents.api.media.BaseImageGenerationModelSetup;
+import org.apache.flink.agents.api.media.ImageGenerationRequest;
+import org.apache.flink.agents.api.media.MediaJob;
+import org.apache.flink.agents.api.media.MediaResult;
+import org.apache.flink.agents.api.resource.ResourceType;
+
+import java.time.Duration;
+
+BaseImageGenerationModelSetup imageModel =
+        (BaseImageGenerationModelSetup) ctx.getResource("posterImage", 
ResourceType.MEDIA_MODEL);
+if (imageModel instanceof AsyncJobModel) {
+    @SuppressWarnings("unchecked")
+    AsyncJobModel<ImageGenerationRequest, MediaResult<ImageBlock>> asyncModel =
+            (AsyncJobModel<ImageGenerationRequest, MediaResult<ImageBlock>>) 
imageModel;
+    MediaJob job =
+            ctx.durableExecuteAsync(
+                            new DurableCallable<MediaJob>() {
+                                @Override
+                                public String getId() {
+                                    return "poster-image:submit";
+                                }
+
+                                @Override
+                                public Class<MediaJob> getResultClass() {
+                                    return MediaJob.class;
+                                }
+
+                                @Override
+                                public MediaJob call() {
+                                    return asyncModel.submit(
+                                            ImageGenerationRequest.of(
+                                                    "A navy notebook on a 
white desk."));
+                                }
+                            })
+                    .await();
+    MediaResult<ImageBlock> result =
+            ctx.durableExecuteAsync(
+                            new DurableCallable<MediaResult<ImageBlock>>() {
+                                @Override
+                                public String getId() {
+                                    return "poster-image:wait";
+                                }
+
+                                @SuppressWarnings("unchecked")
+                                @Override
+                                public Class<MediaResult<ImageBlock>> 
getResultClass() {
+                                    return (Class<MediaResult<ImageBlock>>)
+                                            (Class<?>) MediaResult.class;
+                                }
+
+                                @Override
+                                public MediaResult<ImageBlock> call() {
+                                    return asyncModel.wait(
+                                            job, Duration.ofMinutes(3), 
Duration.ofSeconds(2));
+                                }
+                            })
+                    .await();
+    ImageBlock generatedImage = result.getContent().get(0);
+}
+```
+{{< /tab >}}
+{{< /tabs >}}
+
+`MediaJob` is serializable, so persisting the handle from `submit()` lets
+recovery resume with `fetch(job)` or `wait(job)` (callers are responsible for
+routing each job handle back to a matching setup). `fetch()` returns a
+`MediaJobState` carrying `status`, `result` (when `SUCCEEDED`), and any
+`error_code` or `error_message`. `wait()` defaults to a 30-minute polling
+budget (`1800` s) and a `5`-second `poll_interval`; pass `timeout=None` (Java:
+`null`) for unlimited polling, or a strictly positive duration.
+
+If a job ends as `FAILED`, `CANCELED`, or `UNKNOWN`, `wait()` raises
+`MediaJobError` (Java: `MediaJobException`). If the polling budget elapses
+first, it raises `MediaJobTimeoutError` (Java: `MediaJobTimeoutException`)—the
+provider-side job is not canceled, so you can resume waiting or cancel it with
+the attached `job` handle. On Java, interrupting a wait interrupts the delay
+between polls immediately and throws a cancellation exception without canceling
+the remote job; any active in-flight provider request finishes before 
returning,
+and canceling remotely requires an explicit `cancel(job)` call (similarly, an
+interrupted `submit()` with no persisted `MediaJob` may already have created a
+remote job and will resubmit on recovery).
+
+## Lifecycle and cross-language use
+
+- **Lifecycle**: Flink Agents opens and closes registered
+  `MEDIA_MODEL_CONNECTION` and `MEDIA_MODEL` resources automatically.
+  Connection-backed setups share their connection's lifetime; closing a
+  `MEDIA_MODEL` setup clears its connection reference without closing the
+  shared connection. For standalone Python scripts, call `open()` on the
+  connection and setups before use and `close()` in a `finally` block.
+- **Cross-language**: Java Agents can use both Python `MEDIA_MODEL_CONNECTION`
+  and Python `MEDIA_MODEL` setups (extending `BaseSpeechSynthesisModelSetup`,
+  `BaseTranscriptionModelSetup`, `BaseImageGenerationModelSetup`, or
+  `BaseVideoGenerationModelSetup`)—including built-in DashScope setups via YAML
+  (`type: python` default) or descriptors, as well as custom Python setups. On
+  `open()`, a Python setup invokes Python's `open()` directly and resolves any
+  configured `connection` from the host's scoped `ResourceContext`. See
+  [Cross-Language Resources]({{< ref 
"docs/development/create-agent/resources#cross-language-resources" >}}).
+
+## Custom connections and setups

Review Comment:
   Done. Split the custom section into `Implement a connection`, `Implement a 
model setup`, and `Support asynchronous jobs (optional)`, keeping the 
experimental API warning at the top.



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