wenjin272 commented on code in PR #1382: URL: https://github.com/apache/flink-agents/pull/1382#discussion_r4661231897
########## plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonMediaModelProvider.java: ########## @@ -0,0 +1,521 @@ +/* + * 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 com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +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.BaseMediaModelProvider; +import org.apache.flink.agents.api.media.ImageGenerationModel; +import org.apache.flink.agents.api.media.ImageGenerationRequest; +import org.apache.flink.agents.api.media.MediaJob; +import org.apache.flink.agents.api.media.MediaJobException; +import org.apache.flink.agents.api.media.MediaJobState; +import org.apache.flink.agents.api.media.MediaJobStatus; +import org.apache.flink.agents.api.media.MediaJobTimeoutException; +import org.apache.flink.agents.api.media.MediaResult; +import org.apache.flink.agents.api.media.SpeechSynthesisModel; +import org.apache.flink.agents.api.media.SpeechSynthesisRequest; +import org.apache.flink.agents.api.media.TranscriptionModel; +import org.apache.flink.agents.api.media.TranscriptionRequest; +import org.apache.flink.agents.api.media.VideoGenerationModel; +import org.apache.flink.agents.api.media.VideoGenerationRequest; +import org.apache.flink.agents.api.metrics.FlinkAgentsMetricGroup; +import org.apache.flink.agents.api.resource.ResourceContext; +import org.apache.flink.agents.api.resource.ResourceDescriptor; +import pemja.core.object.PyObject; + +import javax.annotation.Nullable; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.concurrent.CancellationException; +import java.util.function.Function; + +/** Java access to a Python media model provider. */ +public final class PythonMediaModelProvider extends BaseMediaModelProvider + implements PythonResourceWrapper { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private static final Capability<SpeechSynthesisRequest, AudioBlock> SPEECH = + new Capability<>( + AudioBlock.class, + SpeechSynthesisRequest::getText, + SpeechSynthesisRequest::getModelParameters); + private static final Capability<TranscriptionRequest, TextBlock> TRANSCRIPTION = + new Capability<>( + TextBlock.class, + TranscriptionRequest::getAudio, + TranscriptionRequest::getModelParameters); + private static final Capability<ImageGenerationRequest, ImageBlock> IMAGE = + new Capability<>( + ImageBlock.class, + req -> Map.of("prompt", req.getPrompt(), "images", req.getImages()), + ImageGenerationRequest::getModelParameters); + private static final Capability<VideoGenerationRequest, VideoBlock> VIDEO = + new Capability<>( + VideoBlock.class, + req -> Map.of("prompt", req.getPrompt(), "media", req.getMedia()), + VideoGenerationRequest::getModelParameters); + + private final PythonResourceAdapter adapter; + private final PyObject resource; + private volatile boolean closed; + + public PythonMediaModelProvider( + PythonResourceAdapter adapter, + PyObject resource, + ResourceDescriptor descriptor, + ResourceContext resourceContext) { + super(descriptor, resourceContext); + this.adapter = adapter; + this.resource = resource; + } + + @Override + public SpeechSynthesisModel speech(String model, Map<String, Object> modelParameters) { + return wrapSpeech(bind("speech_synthesis", model, bindingOptions(modelParameters))); + } + + @Override + public SpeechSynthesisModel speech( + String model, String voice, Map<String, Object> modelParameters) { + return wrapSpeech( + bind("speech_synthesis", model, speechBindingOptions(voice, modelParameters))); + } + + private static SpeechSynthesisModel wrapSpeech(Binding binding) { + return binding.async + ? new AsyncSpeech(binding) + : (request, timeout) -> binding.generate(request, timeout, SPEECH); + } + + @Override + public TranscriptionModel transcription(String model, Map<String, Object> modelParameters) { + Binding binding = bind("transcription", model, bindingOptions(modelParameters)); + return binding.async + ? new AsyncTranscription(binding) + : (request, timeout) -> binding.generate(request, timeout, TRANSCRIPTION); + } + + @Override + public ImageGenerationModel image(String model, Map<String, Object> modelParameters) { + Binding binding = bind("image_generation", model, bindingOptions(modelParameters)); + return binding.async + ? new AsyncImage(binding) + : (request, timeout) -> binding.generate(request, timeout, IMAGE); + } + + @Override + public VideoGenerationModel video(String model, Map<String, Object> modelParameters) { + Binding binding = bind("video_generation", model, bindingOptions(modelParameters)); + return binding.async + ? new AsyncVideo(binding) + : (request, timeout) -> binding.generate(request, timeout, VIDEO); + } + + private static Map<String, Object> bindingOptions( + @Nullable Map<String, Object> modelParameters) { + return (modelParameters == null || modelParameters.isEmpty()) + ? Map.of() + : Map.of("model_parameters", modelParameters); + } + + private static Map<String, Object> speechBindingOptions( + String voice, @Nullable Map<String, Object> modelParameters) { + Map<String, Object> options = new LinkedHashMap<>(); + options.put("voice", Objects.requireNonNull(voice, "voice")); + if (modelParameters != null && !modelParameters.isEmpty()) { + options.put("model_parameters", modelParameters); + } + return options; + } + + static void validatePositiveDuration(@Nullable Duration duration, String name) { + if (duration != null && (duration.isZero() || duration.isNegative())) { + throw new IllegalArgumentException(name + " must be positive"); + } + } + + static void validateNonNegativeDuration(@Nullable Duration duration, String name) { + if (duration != null && duration.isNegative()) { + throw new IllegalArgumentException(name + " must be non-negative"); + } + } + + private static @Nullable Double toSeconds(@Nullable Duration duration) { + return duration == null + ? null + : duration.getSeconds() + duration.getNano() / 1_000_000_000.0; + } + + private Binding bind(String task, String model, Map<String, Object> options) { + checkOpen(); + String nonNullModel = Objects.requireNonNull(model, "model"); + String optionsJson = json(options); + Object result = + adapter.invoke( + "python_java_utils.validate_media_binding", + resource, + task, + nonNullModel, + optionsJson); + if (!(result instanceof Boolean)) { + throw new IllegalStateException( + "Invalid MediaModelProvider binding validation result from Python"); + } + return new Binding(task, nonNullModel, optionsJson, (Boolean) result); + } + + @Override + public void open() { + checkOpen(); + adapter.callMethod(resource, "open", Map.of()); + } + + @Override + public Object getPythonResource() { + return resource; + } + + @Override + public PythonResourceAdapter getPythonResourceAdapter() { + return adapter; + } + + @Override + public void setMetricGroup(FlinkAgentsMetricGroup metricGroup) { + super.setMetricGroup(metricGroup); + setPythonResourceMetricGroup(metricGroup); + } + + @Override + public void close() throws Exception { + if (closed) { + return; + } + closed = true; + try (resource) { + adapter.callMethod(resource, "close", Map.of()); + } + } + + private void checkOpen() { + if (closed) { + throw new IllegalStateException("Media model provider is closed"); + } + } + + private static final class Capability<Req, T extends DataContentBlock> { + private final Class<T> blockType; + private final Function<Req, Object> payload; + private final Function<Req, Map<String, Object>> modelParameters; + + private Capability( + Class<T> blockType, + Function<Req, Object> payload, + Function<Req, Map<String, Object>> modelParameters) { + this.blockType = blockType; + this.payload = payload; + this.modelParameters = modelParameters; + } + } + + /** Immutable configuration, not a Python object handle or a provider job. */ + private final class Binding { + private final String task; + private final String model; + private final String optionsJson; + private final boolean async; + + private Binding(String task, String model, String optionsJson, boolean async) { + this.task = task; + this.model = model; + this.optionsJson = optionsJson; + this.async = async; + } + + private Object invoke(String operation, Object... arguments) { + checkOpen(); + Object[] all = new Object[4 + arguments.length]; + all[0] = resource; + all[1] = task; + all[2] = model; + all[3] = optionsJson; + System.arraycopy(arguments, 0, all, 4, arguments.length); + return adapter.invoke("python_java_utils." + operation, all); + } + + private <Req, T extends DataContentBlock> MediaResult<T> generate( + Req request, @Nullable Duration timeout, Capability<Req, T> capability) { + checkOpen(); + Objects.requireNonNull(request, "request"); + validatePositiveDuration(timeout, "timeout"); + return read( + invoke( + "call_media_generate", + json(capability.payload.apply(request)), + toSeconds(timeout), + json(capability.modelParameters.apply(request))), + resultType(capability.blockType)); + } + + private <Req> MediaJob submit(Req request, Capability<Req, ?> capability) { + checkOpen(); + Objects.requireNonNull(request, "request"); + return read( + invoke( + "call_media_submit", + json(capability.payload.apply(request)), + json(capability.modelParameters.apply(request))), + MAPPER.constructType(MediaJob.class)); + } + + private <T extends DataContentBlock> MediaJobState<MediaResult<T>> fetch( + MediaJob job, Class<T> blockType) { + checkOpen(); + Objects.requireNonNull(job, "job"); + return read( + invoke("call_media_fetch", json(job)), + MAPPER.getTypeFactory() + .constructParametricType(MediaJobState.class, resultType(blockType))); + } + + private <T extends DataContentBlock> MediaResult<T> wait( + MediaJob job, + @Nullable Duration timeout, + Duration pollInterval, + Class<T> blockType) { + checkOpen(); + Objects.requireNonNull(job, "job"); + validateNonNegativeDuration(timeout, "timeout"); + validatePositiveDuration( + Objects.requireNonNull(pollInterval, "pollInterval"), "pollInterval"); + return read( + invoke( + "call_media_wait", Review Comment: The entire polling loop currently runs inside a single Pemja invocation. Interrupting the Java worker does not automatically interrupt Python’s `time.sleep()`, and the loop does not check the Java cancellation state. Consequently, task cancellation can leave the worker polling until the wait budget expires, delaying shutdown and recovery. I reproduced this with the current `AsyncJobModel.wait()`: interrupting the Java worker after 200 ms did not stop polling; it exited only when the 2-second budget expired. Could we make this polling cancellation-aware? One option is to poll in the Java wrapper, calling Python `fetch()` once per iteration and using interruptible waits between queries. This should cover both explicit `wait()` and the submit-and-wait paths used by `generate()` / `transcribe()`. Cancellation should stop local waiting without automatically canceling the remote job, and remain distinguishable from a persisted business failure. ########## python/flink_agents/integrations/media_model_providers/dashscope_media_model_provider.py: ########## @@ -0,0 +1,851 @@ +################################################################################ +# 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. +################################################################################# +"""DashScope media resource with model-bound capabilities and a shared client.""" + +import os +import time +from abc import abstractmethod +from copy import deepcopy +from dataclasses import dataclass, replace +from typing import Any, ClassVar, Generic, Mapping, Sequence, TypeVar +from urllib.parse import parse_qs, quote, urlparse + +import dashscope +import httpx +from dashscope.errors import DashScopeError, check_response, response_json +from pydantic import BaseModel, Field, PrivateAttr +from typing_extensions import override + +from flink_agents.api.chat_message import ( + AudioBlock, + DataContentBlock, + DocumentBlock, + ImageBlock, + TextBlock, + UnsupportedContentBlockError, + UrlSource, + VideoBlock, +) +from flink_agents.api.media.media_model import ( + AsyncJobModel, + ImageGenerationModel, + MediaJob, + MediaJobError, + MediaJobState, + MediaJobStatus, + MediaResult, + SpeechSynthesisModel, + TranscriptionModel, + VideoGenerationModel, +) +from flink_agents.api.media.media_model_provider import BaseMediaModelProvider +from flink_agents.integrations.dashscope_utils import ( + create_client, + media_source_url, + usage_counters, + validate_request_timeout, +) + +DEFAULT_REQUEST_TIMEOUT = 60.0 +DEFAULT_REGION = "cn-beijing" +_PROVIDER = "dashscope" +_DAY_MS = 24 * 60 * 60 * 1000 +_PROVIDER_LABEL = "DashScope" +_ROLES_REQUIRED = "video_media_roles is required when media is not empty." +_AUDIO_MEDIA_TYPES = { + "mp3": "audio/mpeg", + "wav": "audio/wav", + "opus": "audio/ogg", + "pcm": "audio/pcm", +} +_DEFAULT_AUDIO_FORMAT = "mp3" +_TASK_STATUS = { + "PENDING": MediaJobStatus.PENDING, + "SUSPENDED": MediaJobStatus.PENDING, + "RUNNING": MediaJobStatus.RUNNING, + "SUCCEEDED": MediaJobStatus.SUCCEEDED, + "FAILED": MediaJobStatus.FAILED, + "CANCELED": MediaJobStatus.CANCELED, +} + + +ResultT = TypeVar("ResultT", bound=MediaResult) + + +class DashScopeMediaModelProvider(BaseMediaModelProvider): + """DashScope media generation, transcription, and speech synthesis. + + Register ``ResourceDescriptor(clazz=ResourceName.MediaModelProvider.DASHSCOPE)`` + and retrieve the provider with ``get_resource``. For example, + ``dashscope.speech(model, voice="Cherry").synthesize("Hello")`` synthesizes + speech. A bound model can also be reused for multiple calls. + + The SDK client is created by ``open()`` before any model requests. An omitted + API key is read from ``DASHSCOPE_API_KEY`` when the resource opens. + ``request_timeout`` bounds each HTTP request. SDK retries and local SDK + configuration-file loading are disabled. + ``workspace`` and ``base_url`` retain SDK environment defaults when omitted. + Closing the resource closes the shared client and ends all bound models' + lifetime. Bound models must not be closed separately. When constructing the + provider directly, call ``open()`` before use and ``close()`` when finished. + + Attributes: + ---------- + api_key : str | None + DashScope API key. Falls back to ``DASHSCOPE_API_KEY``. + workspace : str | None + Bailian workspace id. With ``region``, it selects the workspace + gateway ``https://{workspace}.{region}.maas.aliyuncs.com``. + region : str + Gateway region. Defaults to ``cn-beijing``. + base_url : str | None + Replaces the SDK-derived address when set. The value is the API root, + including its path, and is not given an extra ``/api/v1``. + request_timeout : float + Timeout in seconds for one HTTP request. Defaults to 60. + """ + + api_key: str | None = Field( + default=None, repr=False, description="DashScope API key." + ) + workspace: str | None = Field( + default=None, + description="Bailian workspace id used in the gateway host.", + ) + region: str = Field( + default=DEFAULT_REGION, + description="DashScope gateway region.", + ) + base_url: str | None = Field( + default=None, + description="API root that replaces the SDK-derived address.", + ) + request_timeout: float = Field( + default=DEFAULT_REQUEST_TIMEOUT, + gt=0, + allow_inf_nan=False, + description="Timeout in seconds for one HTTP request.", + ) + _sdk_client: dashscope.Client | None = PrivateAttr(default=None) + _closed: bool = PrivateAttr(default=False) + + def speech( + self, + model: str, + *, + voice: str | None = None, + model_parameters: Mapping[str, Any] | None = None, + ) -> SpeechSynthesisModel: + """Bind a speech model that returns audio without creating a job. + + An explicit voice overrides ``model_parameters["voice"]``. Call-time + parameters override the resulting binding. + """ + bound = dict(model_parameters or {}) + if voice is not None: + bound["voice"] = voice + return _DashScopeSpeechSynthesisModel( + provider=self, + model=model, + model_parameters=bound, + ) + + def transcription( + self, + model: str, + *, + model_parameters: Mapping[str, Any] | None = None, + ) -> TranscriptionModel: + """Bind a file-transcription model with resumable provider jobs.""" + return _DashScopeTranscriptionModel( + provider=self, + model=model, + model_parameters=dict(model_parameters or {}), + ) + + def image( + self, + model: str, + *, + model_parameters: Mapping[str, Any] | None = None, + ) -> ImageGenerationModel: + """Bind an image model using the asynchronous generation protocol.""" + return _DashScopeImageGenerationModel( + provider=self, + model=model, + model_parameters=dict(model_parameters or {}), + ) + + def video( + self, + model: str, + *, + model_parameters: Mapping[str, Any] | None = None, + ) -> VideoGenerationModel: + """Bind a video model with resumable provider jobs.""" + return _DashScopeVideoGenerationModel( + provider=self, + model=model, + model_parameters=dict(model_parameters or {}), + ) + + @override + def open(self) -> None: + """Open the shared client before using any bound model.""" + if self._closed: + msg = "The DashScope resource is closed." + raise RuntimeError(msg) + if self._sdk_client is None: + api_key = self.api_key or os.environ.get("DASHSCOPE_API_KEY") + if not api_key: + msg = "Pass api_key or set DASHSCOPE_API_KEY before opening DashScope." + raise ValueError(msg) + self._sdk_client = create_client( + api_key=api_key, + base_url=self.base_url, + workspace=self.workspace, + region=self.region, + timeout=self.request_timeout, + ) + + @override + def close(self) -> None: + """End the provider lifetime and close its client once, if opened.""" + if not self._closed: + self._closed = True + client = self._sdk_client + self._sdk_client = None + if client is not None: + client.close() + + def _client(self) -> dashscope.Client: + """Return the shared client of an open resource.""" + if self._closed: + msg = "The DashScope resource is closed." + raise RuntimeError(msg) + if self._sdk_client is None: + msg = "The DashScope resource is not open. Call open() before using it." + raise RuntimeError(msg) + return self._sdk_client + + +class _DashScopeModel(BaseModel): + model_parameters: dict[str, Any] = Field( + default_factory=dict, + description="Bailian model parameters overridden by call-time model_parameters.", + ) + _provider: DashScopeMediaModelProvider = PrivateAttr() + + def __init__(self, *, provider: DashScopeMediaModelProvider, **kwargs: Any) -> None: + if provider._closed: + msg = "The DashScope resource is closed." + raise RuntimeError(msg) + super().__init__(**kwargs) + self.model_parameters = deepcopy(self.model_parameters) + self._provider = provider + + def _client(self) -> dashscope.Client: + return self._provider._client() + + +class _DashScopeSpeechSynthesisModel(_DashScopeModel, SpeechSynthesisModel): + def synthesize( + self, + text: str, + *, + voice: str | None = None, + model_parameters: Mapping[str, Any] | None = None, + timeout: float | None = None, + ) -> MediaResult[AudioBlock]: + """Synthesize text. The SDK call is a single HTTP POST. + + ``timeout`` is the timeout for that request. None uses + the provider's ``request_timeout``. + """ + parameters = {**self.model_parameters, **(model_parameters or {})} + if voice is not None: + parameters["voice"] = voice + resolved_voice = parameters.pop("voice", None) + if not isinstance(resolved_voice, str) or not resolved_voice: + msg = "Speech synthesis requires a voice." + raise ValueError(msg) + audio_format = parameters.pop("format", None) + sample_rate = parameters.pop("sample_rate", None) + language_type = parameters.pop("language_type", None) + if not isinstance(text, str): + msg = "Speech synthesis requires a string." + raise TypeError(msg) + if not text: + msg = "Speech synthesis requires non-empty text." + raise ValueError(msg) + timeout = validate_request_timeout(timeout) + synthesized = self._client().audio.tts.http.synthesize( + text, + model=self.model, + voice=resolved_voice, + format=audio_format, + sample_rate=sample_rate, + language_type=language_type, + parameters=parameters or None, Review Comment: TTS controls such as `rate`, `volume`, `language_hints`, and `instruction` belong in `input`, but are currently serialized into `parameters`. Could we pass them through the SDK’s `extra_input` and verify the HTTP body in a test? -- 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]
