wenjin272 commented on code in PR #1382: URL: https://github.com/apache/flink-agents/pull/1382#discussion_r4693556359
########## plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonMediaModelSetup.java: ########## @@ -0,0 +1,548 @@ +/* + * 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.DataContentBlock; +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.AsyncJobPolling; +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.PythonResourceDescriptor; +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 org.apache.flink.agents.api.utils.StringValidationUtils; +import org.apache.flink.agents.plan.exceptions.UncapturableException; +import pemja.core.object.PyObject; + +import javax.annotation.Nullable; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; + +/** + * 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 PythonMediaModelSetup() {} + + /** Inspect the Python media model setup and return a matching typed Java wrapper. */ + public static BaseMediaModelSetup create( + PythonResourceAdapter adapter, + PyObject resource, + ResourceDescriptor descriptor, + @Nullable ResourceContext resourceContext) { + Objects.requireNonNull(descriptor, "descriptor"); + 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; + final String connectionName; + final String model; + @Nullable final String voice; + try { + connectionName = + StringValidationUtils.requireNonBlank(metadata.get("connection"), "connection"); + model = StringValidationUtils.requireNonBlank(metadata.get("model"), "model"); + voice = + "speech_synthesis".equals(task) + ? StringValidationUtils.optionalNonBlank(metadata.get("voice"), "voice") + : null; + } catch (IllegalArgumentException e) { + throw new IllegalStateException("Invalid MediaModel inspection result from Python", e); + } + ResourceDescriptor effectiveDescriptor = + descriptorWithInspectedMetadata(descriptor, connectionName, model, voice); + Handle handle = new Handle(adapter, resource, task, effectiveDescriptor, 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"); + } + } + + private static ResourceDescriptor descriptorWithInspectedMetadata( + ResourceDescriptor descriptor, + String connectionName, + String model, + @Nullable String voice) { + Map<String, Object> mergedArgs = + descriptor.getInitialArguments() != null + ? new HashMap<>(descriptor.getInitialArguments()) + : new HashMap<>(); + mergedArgs.put("connection", connectionName); + mergedArgs.put("model", model); + if (voice != null) { + mergedArgs.put("voice", voice); + } else { + mergedArgs.remove("voice"); + } + if (descriptor instanceof PythonResourceDescriptor) { + return new PythonResourceDescriptor( + descriptor.getModule(), descriptor.getClazz(), mergedArgs); + } + return new ResourceDescriptor(descriptor.getModule(), descriptor.getClazz(), mergedArgs); + } + + static final class Handle { + private final PythonResourceAdapter adapter; + private final PyObject resource; + private final String task; + private final ResourceDescriptor descriptor; + @Nullable private final ResourceContext resourceContext; + private volatile boolean closed; + + private Handle( + PythonResourceAdapter adapter, + PyObject resource, + String task, + ResourceDescriptor descriptor, + @Nullable ResourceContext resourceContext) { + this.adapter = adapter; + this.resource = resource; + this.task = task; + this.descriptor = descriptor; + this.resourceContext = resourceContext; + } + + private void open() { + adapter.callMethod(resource, "open", Map.of()); Review Comment: The Python setup can resolve its connection from the wrong resource scope here. A child agent inherits the root Python adapter, which injects the root resource context, while the child context held by this wrapper is not propagated to the Python resource. I reproduced both cases through the native bridge: a child-only connection fails with `Resource not found`, and a child override resolves to the root connection instead. Could we propagate the owning resource context when initializing the Python resource and add coverage for both cases? This should be handled in the shared resource initialization path. ########## python/flink_agents/integrations/media_models/tests/test_dashscope_video_generation.py: ########## @@ -0,0 +1,346 @@ +################################################################################ +# 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. +################################################################################# +from collections.abc import Callable +from pathlib import Path +from types import SimpleNamespace +from typing import Any + +import httpx +import pytest + +from flink_agents.api.chat_message import ( + AudioBlock, + DocumentBlock, + ImageBlock, + TextBlock, + UnsupportedContentBlockError, + VideoBlock, +) +from flink_agents.api.media import ( + BaseVideoGenerationModelSetup, + MediaJobStatus, + MediaResult, +) +from flink_agents.integrations.media_models.dashscope_media_model import ( + DashScopeVideoGenerationModelSetup, +) + +_IMAGE = "https://example.test/frame.png" +_VIDEO = "https://oss.example/out.mp4?Expires=1700000000" + + [email protected] +def model_factory( + setup_factory: Callable[..., BaseVideoGenerationModelSetup], +) -> Callable[..., BaseVideoGenerationModelSetup]: + def create(**overrides: Any) -> BaseVideoGenerationModelSetup: + values: dict[str, Any] = {"model": "custom-video-deployment"} + values.update(overrides) + return setup_factory(DashScopeVideoGenerationModelSetup, **values) + + return create + + +def test_text_submission_forwards_model_and_parameters( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, +) -> None: + model = model_factory(resolution="720P", duration=3) + model._client().videos.jobs = sdk_jobs + + job = model.submit("a cat", model_parameters={"duration": 5}) + + assert job.job_id == "job-1" + assert job.expires_at_ms == job.submitted_at_ms + 24 * 60 * 60 * 1000 + assert sdk_jobs.created == [ + { + "model": "custom-video-deployment", + "prompt": "a cat", + "media": None, + "parameters": {"resolution": "720P", "duration": 5}, + } + ] + assert model.model_kwargs == { + "model": "custom-video-deployment", + "resolution": "720P", + "duration": 3, + } + + [email protected]( + ("call_parameters", "role"), + [ + (None, "reference_image"), + ({"video_media_roles": ("first_frame",)}, "first_frame"), + ], +) +def test_media_roles_use_configuration_or_call_override( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + call_parameters: dict[str, Any] | None, + role: str, +) -> None: + model = model_factory( + video_media_roles=["reference_image"], additional_kwargs={"format": "mp4"} + ) + model._client().videos.jobs = sdk_jobs + + model.submit( + media=[ImageBlock.from_url("image/png", _IMAGE)], + model_parameters=call_parameters, + ) + + assert sdk_jobs.created[0]["prompt"] is None + assert sdk_jobs.created[0]["media"] == [{"type": role, "url": _IMAGE}] + assert sdk_jobs.created[0]["parameters"] == {"format": "mp4"} + assert model.video_media_roles == ["reference_image"] + assert model.additional_kwargs == {"format": "mp4"} + + +def test_mixed_media_preserves_sources_order_and_roles( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + audio = "https://example.test/drive.mp3" + clip = "https://example.test/clip.mp4" + document = "oss://dashscope-instant/demo/notes.pdf" + page = "https://example.test/article" + + model.submit( + "Animate these references.", + media=[ + ImageBlock.from_url("image/png", _IMAGE), + ImageBlock.from_base64("image/png", "YQ=="), + AudioBlock.from_url("audio/mpeg", audio), + AudioBlock.from_base64("audio/mpeg", "YQ=="), + VideoBlock.from_url("video/mp4", clip), + DocumentBlock.from_url("application/pdf", document), + DocumentBlock.from_url("text/html", page), + ], + model_parameters={ + "video_media_roles": [ + "reference_image", + "reference_image", + "driving_audio", + "driving_audio", + "first_clip", + "file", + "custom-provider-role", + ] + }, + ) + + assert sdk_jobs.created == [ + { + "model": "custom-video-deployment", + "prompt": "Animate these references.", + "media": [ + {"type": "reference_image", "url": _IMAGE}, + {"type": "reference_image", "url": "data:image/png;base64,YQ=="}, + {"type": "driving_audio", "url": audio}, + {"type": "driving_audio", "url": "data:audio/mpeg;base64,YQ=="}, + {"type": "first_clip", "url": clip}, + {"type": "file", "url": document}, + {"type": "custom-provider-role", "url": page}, + ], + "parameters": None, + } + ] + + +def test_empty_request_is_rejected_before_submission( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + + with pytest.raises(ValueError, match="requires a prompt or at least one media"): + model.submit() + + assert sdk_jobs.created == [] + + [email protected]( + ("prompt", "media"), + [ + (None, None), + ("Animate this.", [TextBlock(text="Not a media input.")]), + ("Animate this.", ImageBlock.from_url("image/png", _IMAGE)), + ], +) +def test_submit_rejects_invalid_inputs_before_request( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + prompt: Any, + media: Any, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + + with pytest.raises(TypeError): + model.submit( + prompt, + media=media, + model_parameters={"video_media_roles": ["reference_image"]}, + ) + + assert sdk_jobs.created == [] + + [email protected]( + ("roles", "message"), + [ + (None, "video_media_roles is required"), + (["first_frame", "last_frame"], "one entry for each media block"), + ], +) +def test_media_requires_one_role_per_block( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + roles: list[str] | None, + message: str, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + media = [ImageBlock.from_url("image/png", _IMAGE)] + + with pytest.raises(ValueError, match=message): + model.submit(media=media, model_parameters={"video_media_roles": roles}) + + assert sdk_jobs.created == [] + + [email protected]( + "roles", + ["first_frame", {"first_frame"}, {"first_frame": "reference_image"}, [1], [""]], +) +def test_roles_require_an_ordered_sequence_of_nonempty_strings( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + roles: Any, +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + + with pytest.raises(TypeError, match="video_media_roles"): + model.submit( + media=[ImageBlock.from_url("image/png", _IMAGE)], + model_parameters={"video_media_roles": roles}, + ) + + assert sdk_jobs.created == [] + + +def test_fetch_reads_the_video_result( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + sdk_jobs: SimpleNamespace, + task_responses: Callable[..., list[dict[str, Any]]], +) -> None: + model = model_factory() + model._client().videos.jobs = sdk_jobs + calls = task_responses( + model, + httpx.Response( + 200, + json={ + "request_id": "req-1", + "usage": {"duration": 5}, + "output": {"task_status": "SUCCEEDED", "video_url": _VIDEO}, + }, + ), + ) + job = model.submit("a cat") + + state = model.fetch(job) + + assert [(call["method"], call["path"]) for call in calls] == [ + ("GET", "/tasks/job-1") + ] + assert state.status is MediaJobStatus.SUCCEEDED + assert isinstance(state.result, MediaResult[VideoBlock]) + restored = type(state).model_validate_json(state.model_dump_json()) + assert isinstance(restored.result, MediaResult[VideoBlock]) + assert len(state.result.content) == 1 + block = state.result.content[0] + assert isinstance(block, VideoBlock) + assert block.media_type == "video/mp4" + assert block.source.url == _VIDEO + assert state.result.expires_at_ms == 1_700_000_000_000 + assert state.result.usage == {"duration": 5} + assert state.result.request_id == "req-1" + + +def test_submit_rejects_local_file_and_file_uri_before_sdk_upload( + model_factory: Callable[..., BaseVideoGenerationModelSetup], + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + local_file = tmp_path / "secret.png" + local_file.write_bytes(b"secret") + + def forbid_call(*_args: Any, **_kwargs: Any) -> Any: + msg = "SDK upload or HTTP transport must not run for disallowed schemes" + raise AssertionError(msg) + + model = model_factory() + monkeypatch.setattr("dashscope.resources.videos.upload_media_value", forbid_call) + monkeypatch.setattr(model._client().transport, "request", forbid_call) + monkeypatch.setattr(model._client().transport, "request_api", forbid_call) Review Comment: This patch fails with `AttributeError` on DashScope 2.0.4, which our dependency range allows, because its transport has no `request_api` attribute. Could we make this patch conditional or use `raising=False`? The test currently fails before reaching the input validation assertions. ########## plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonMediaModelSetup.java: ########## @@ -0,0 +1,548 @@ +/* + * 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.DataContentBlock; +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.AsyncJobPolling; +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.PythonResourceDescriptor; +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 org.apache.flink.agents.api.utils.StringValidationUtils; +import org.apache.flink.agents.plan.exceptions.UncapturableException; +import pemja.core.object.PyObject; + +import javax.annotation.Nullable; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; + +/** + * 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 PythonMediaModelSetup() {} + + /** Inspect the Python media model setup and return a matching typed Java wrapper. */ + public static BaseMediaModelSetup create( + PythonResourceAdapter adapter, + PyObject resource, + ResourceDescriptor descriptor, + @Nullable ResourceContext resourceContext) { + Objects.requireNonNull(descriptor, "descriptor"); + Object inspection = adapter.invoke("python_java_utils.inspect_media_model", resource); + if (!(inspection instanceof Map)) { Review Comment: Could we cast the result of `inspect_media_model` directly to `Map<?, ?>`? This is a fixed internal bridge contract, so the intermediate `Object` variable and `instanceof Map` check seem unnecessary. ########## plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonMediaModelSetup.java: ########## @@ -0,0 +1,548 @@ +/* + * 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.DataContentBlock; +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.AsyncJobPolling; +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.PythonResourceDescriptor; +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 org.apache.flink.agents.api.utils.StringValidationUtils; +import org.apache.flink.agents.plan.exceptions.UncapturableException; +import pemja.core.object.PyObject; + +import javax.annotation.Nullable; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; + +/** + * 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 PythonMediaModelSetup() {} + + /** Inspect the Python media model setup and return a matching typed Java wrapper. */ + public static BaseMediaModelSetup create( + PythonResourceAdapter adapter, + PyObject resource, + ResourceDescriptor descriptor, + @Nullable ResourceContext resourceContext) { + Objects.requireNonNull(descriptor, "descriptor"); + 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"); Review Comment: Could we define constants for the metadata keys, task identifiers, and Python entry-point names in this file? These strings form the bridge protocol, and named constants would make that contract clearer and avoid repeated literals, following the existing Chat bridge convention. ########## api/src/main/java/org/apache/flink/agents/api/yaml/Aliases.java: ########## @@ -177,6 +177,35 @@ public final class Aliases { vsPython.put("mem0", ResourceName.VectorStore.Python.MEM0_VECTOR_STORE); ca.put(ResourceType.VECTOR_STORE, buildLangBuckets(vsJava, vsPython)); + // MEDIA_MODEL + Map<String, String> mediaPython = new HashMap<>(); + mediaPython.put( + "dashscope_speech_synthesis", Review Comment: Could we shorten the media YAML aliases to `dashscope_tts`, `dashscope_asr`, `dashscope_image`, and `dashscope_video`? These still distinguish the four tasks without repeating the full class names. Since these aliases are new in this PR, we can replace the longer names directly and update both loaders, docs, and tests consistently. ########## plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/PythonResourceProvider.java: ########## @@ -96,6 +108,10 @@ public Resource provide(ResourceContext resourceContext) throws Exception { PyObject pyResource = pythonResourceAdapter.initPythonResource(pyModule, pyClazz, kwargs); try { + if (getType() == ResourceType.MEDIA_MODEL) { Review Comment: Could we replace `RESOURCE_TYPE_TO_CLASS` with a factory registry, using constructor references for ordinary wrappers and `PythonMediaModelSetup::create` for media models? A small private functional interface would let `provide()` use one creation path without a `MEDIA_MODEL`-specific branch. ########## 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 Review Comment: Could we keep the Overview focused on the supported media tasks and their use cases: image generation/editing, video generation, transcription, and speech synthesis? The ResourceType names, Setup classes, registration patterns, and `get_resource()` usage are already covered below and can be removed from this section. ########## 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 Review Comment: Could we remove the numbered headings and use annotation-based registration in the main Java/Python examples, consistent with the other resource guides? Please keep the YAML examples and introduce `add_resource()` / `addResource()` separately as an option for registering shared resources through the execution environment. ########## docs/content/docs/development/create-agent/yaml.md: ########## @@ -303,6 +303,50 @@ mcp_servers: endpoint: http://127.0.0.1:8000/mcp ``` +Media model connections register shared connection settings under Review Comment: Could we keep this page focused on the common YAML declaration rules? Please retain the new resource sections in the supported-resource list, the connection-reference entry, alias tables, and cross-language support notes. The detailed Media/Rerank examples and API, environment-variable, and lifecycle explanations can stay in their dedicated guides rather than being duplicated here. ########## 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: Could we split this section into three subsections to make the responsibilities clearer? - **Implement a connection**: shared configuration, SDK client, and `open()` / `close()`. - **Implement a model setup**: extend the appropriate task-specific base class and implement its operation using the connection. - **Support asynchronous jobs (optional)**: implement `AsyncJobModel`, reuse the default `wait()`, and explain how the task operation builds on these methods. The experimental API warning can stay at the start of the section. ########## 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 Review Comment: Could we shorten this introduction? The examples already show the setup classes and registration syntax, so there is no need to enumerate them all here. For example: “Declare a media model setup with a connection, model name, and default parameters, then retrieve it by name in an Action.” ########## 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 Review Comment: Could we rename this section to **“Asynchronous jobs”** and focus on `submit()`, `wait()`, `fetch()`, and `cancel()`, using direct calls in the examples? The durable execution wrappers make the media job API look coupled to runtime execution APIs and add complexity to a section intended to explain basic usage. ########## docs/content/docs/development/rerank_models/_index.md: ########## @@ -0,0 +1,200 @@ +--- +title: "Rerank Models" +weight: 10 +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. +--> + +# Rerank Models + +## Overview + +Use a rerank model to score and order candidate documents by relevance to a +query—for example, refining results retrieved from a +[vector store]({{< ref "docs/development/vector-search/vector_stores" >}}) or +ranking mixed text, image, and video candidates directly. + +Register a `RERANK_MODEL` resource for the model you want to call, then pass a +query and candidate list to `rerank()` inside an Action. See +[Built-in Rerank Model Providers]({{< ref "docs/development/rerank_models/providers" >}}) +for available implementations and provider options. + +## Quick start + +### 1. Register a rerank model Review Comment: Could we simplify the Rerank guide and align its structure with the other resource guides? - Use `@rerank_model` / `@RerankModel` for the main registration examples, keeping the YAML example. Introduce `add_resource()` / `addResource()` separately as a way to register shared resources through the execution environment. - Remove the numbered headings and use **“Register a rerank model”** and **“Use the rerank model”**. - Move the input and result descriptions next to the usage examples. Keep provider-specific options in the provider parameter table, with only a brief explanation of per-call overrides here. - Remove **“Lifecycle and cross-language use”**. These are general Resource concepts, and the Java example already demonstrates cross-language usage. ########## plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonMediaModelSetup.java: ########## @@ -0,0 +1,548 @@ +/* + * 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.DataContentBlock; +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.AsyncJobPolling; +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.PythonResourceDescriptor; +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 org.apache.flink.agents.api.utils.StringValidationUtils; +import org.apache.flink.agents.plan.exceptions.UncapturableException; +import pemja.core.object.PyObject; + +import javax.annotation.Nullable; + +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.function.Function; + +/** + * 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 PythonMediaModelSetup() {} + + /** Inspect the Python media model setup and return a matching typed Java wrapper. */ + public static BaseMediaModelSetup create( + PythonResourceAdapter adapter, + PyObject resource, + ResourceDescriptor descriptor, + @Nullable ResourceContext resourceContext) { + Objects.requireNonNull(descriptor, "descriptor"); + 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; + final String connectionName; + final String model; + @Nullable final String voice; + try { + connectionName = + StringValidationUtils.requireNonBlank(metadata.get("connection"), "connection"); + model = StringValidationUtils.requireNonBlank(metadata.get("model"), "model"); + voice = + "speech_synthesis".equals(task) + ? StringValidationUtils.optionalNonBlank(metadata.get("voice"), "voice") + : null; + } catch (IllegalArgumentException e) { + throw new IllegalStateException("Invalid MediaModel inspection result from Python", e); + } + ResourceDescriptor effectiveDescriptor = + descriptorWithInspectedMetadata(descriptor, connectionName, model, voice); + Handle handle = new Handle(adapter, resource, task, effectiveDescriptor, 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"); + } + } + + private static ResourceDescriptor descriptorWithInspectedMetadata( + ResourceDescriptor descriptor, + String connectionName, + String model, + @Nullable String voice) { + Map<String, Object> mergedArgs = + descriptor.getInitialArguments() != null + ? new HashMap<>(descriptor.getInitialArguments()) + : new HashMap<>(); + mergedArgs.put("connection", connectionName); + mergedArgs.put("model", model); + if (voice != null) { + mergedArgs.put("voice", voice); + } else { + mergedArgs.remove("voice"); + } + if (descriptor instanceof PythonResourceDescriptor) { + return new PythonResourceDescriptor( + descriptor.getModule(), descriptor.getClazz(), mergedArgs); + } + return new ResourceDescriptor(descriptor.getModule(), descriptor.getClazz(), mergedArgs); + } + + static final class Handle { Review Comment: Could we merge `Handle` and `PythonMediaBridge` into one stateful bridge object? Currently, calls go from the wrapper to `Handle`, then to `PythonMediaBridge`, and back to `Handle` for the Python invocation. A single bridge could own the Python object and adapter, manage lifecycle, and handle request/result conversion and invocation, leaving the task-specific wrappers as thin delegates. ########## 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 Review Comment: Could we simplify and reorganize the “Capabilities” section? - Rename it to **“Supported Media Models”**. - Use **“Media task”**, **“API”**, **“Input”**, and **“Result content”** as the table columns. Remove **“Base setup class”**; those classes can be introduced in the custom implementation section. Briefly explain that the APIs return `MediaResult`. - Move **“Synchronous and asynchronous execution”** into **“Asynchronous jobs”**, clarifying that direct `generate()` / `transcribe()` calls wait for completion, while `submit()` returns a job handle. - Remove the separate **“Parameters”** subsection. Explain per-call overrides briefly after the Setup examples, distinguish polling timeouts from HTTP request timeouts in the async section, and keep provider-specific parameters and defaults in the provider tables. ########## 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 Review Comment: Could we remove the **“Lifecycle and cross-language use”** section? Resource lifecycle management and cross-language usage are general Resource concepts and do not need to be repeated in the Media Models guide. -- 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]
