joeyutong commented on code in PR #1382: URL: https://github.com/apache/flink-agents/pull/1382#discussion_r4677728267
########## api/src/main/java/org/apache/flink/agents/api/media/BaseMediaModelProvider.java: ########## @@ -0,0 +1,112 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.apache.flink.agents.api.media; + +import org.apache.flink.agents.api.resource.Resource; +import org.apache.flink.agents.api.resource.ResourceContext; +import org.apache.flink.agents.api.resource.ResourceDescriptor; +import org.apache.flink.agents.api.resource.ResourceType; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** + * A media model provider that binds capabilities to models and owns their shared client. + * + * <p>Each binding accepts a map of default model parameters. Whether a bound capability runs + * synchronously or exposes resumable provider jobs via {@link AsyncJobModel} is determined by the + * underlying provider implementation. Factory methods should return lightweight capability views + * without independent mutable state so the same {@code (model, modelParameters)} binding can be + * recreated safely; shared state belongs on the provider itself (or in a persisted {@link + * MediaJob}). Cross-language Java-to-Python bridges recreate bindings from immutable configuration + * rather than retaining child Python object handles. The bound model shares this provider's + * lifetime and must not be used after the provider closes. + */ +public abstract class BaseMediaModelProvider extends Resource { Review Comment: Renamed `BaseMediaModelProvider` to `BaseMediaModelConnection` (`ResourceType.MEDIA_MODEL_CONNECTION`), aligned `connection` fields, concrete class/resource names, YAML (`media_model_connections`), schemas, tests, docs, and examples across Java and Python. Also removed the factory methods on `BaseMediaModelConnection` so it matches `BaseChatModelConnection` (setups are declared as named `MEDIA_MODEL` resources). ########## plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonMediaModelSetup.java: ########## @@ -0,0 +1,630 @@ +/* + * 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.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.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.Resource; +import org.apache.flink.agents.api.resource.ResourceContext; +import org.apache.flink.agents.api.resource.ResourceDescriptor; +import org.apache.flink.agents.api.resource.ResourceType; +import pemja.core.object.PyObject; + +import javax.annotation.Nullable; + +import java.time.Duration; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * 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 static final String FALLBACK_MODEL_NAME = "python-media-model"; + + private PythonMediaModelSetup() {} + + /** Inspect the Python media model setup and return a matching typed Java wrapper. */ + public static BaseMediaModelSetup create( + PythonResourceAdapter adapter, + PyObject resource, + @Nullable ResourceDescriptor descriptor, + @Nullable ResourceContext resourceContext) { + 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; + Handle handle = + new Handle( + adapter, + resource, + task, + resolveProviderName(metadata.get("provider"), descriptor), + resolveModelName(metadata.get("model"), descriptor), + "speech_synthesis".equals(task) + ? resolveVoice(metadata.get("voice"), descriptor) + : null, + extractModelParameters(descriptor), + descriptor, + 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"); + } + } + + @Nullable + private static String resolveProviderName( + @Nullable Object inspectedProvider, @Nullable ResourceDescriptor descriptor) { + if (inspectedProvider != null) { + if (!(inspectedProvider instanceof String) || ((String) inspectedProvider).isBlank()) { + throw new IllegalArgumentException( + "Media model setup 'provider' must be a non-blank string when set."); + } + return (String) inspectedProvider; + } + if (descriptor != null && descriptor.getInitialArguments() != null) { + Object rawProvider = descriptor.getInitialArguments().get("provider"); + if (rawProvider != null) { + if (!(rawProvider instanceof String) || ((String) rawProvider).isBlank()) { + throw new IllegalArgumentException( + "Media model setup 'provider' must be a non-blank string when set."); + } + return (String) rawProvider; + } + } + return null; + } + + private static String resolveModelName( + @Nullable Object inspectedModel, @Nullable ResourceDescriptor descriptor) { + if (inspectedModel instanceof String && !((String) inspectedModel).isBlank()) { + return (String) inspectedModel; + } + if (descriptor != null && descriptor.getInitialArguments() != null) { + Object rawModel = descriptor.getInitialArguments().get("model"); + if (rawModel instanceof String && !((String) rawModel).isBlank()) { + return (String) rawModel; + } + } + return FALLBACK_MODEL_NAME; + } + + @Nullable + private static String resolveVoice( + @Nullable Object inspectedVoice, @Nullable ResourceDescriptor descriptor) { + if (inspectedVoice instanceof String && !((String) inspectedVoice).isBlank()) { + return (String) inspectedVoice; + } + if (descriptor != null && descriptor.getInitialArguments() != null) { + Object rawVoice = descriptor.getInitialArguments().get("voice"); + if (rawVoice instanceof String && !((String) rawVoice).isBlank()) { + return (String) rawVoice; + } + } + return null; + } + + @Nullable + private static Map<String, Object> extractModelParameters( + @Nullable ResourceDescriptor descriptor) { + if (descriptor == null || descriptor.getInitialArguments() == null) { + return null; + } + Object rawParams = descriptor.getInitialArguments().get("model_parameters"); + if (!(rawParams instanceof Map)) { + return null; + } + Map<?, ?> rawMap = (Map<?, ?>) rawParams; + Map<String, Object> typed = new LinkedHashMap<>(rawMap.size()); + for (Map.Entry<?, ?> entry : rawMap.entrySet()) { + if (entry.getKey() instanceof String) { + typed.put((String) entry.getKey(), entry.getValue()); + } + } + return typed; + } + + private static final class Handle implements PythonMediaBridge.Target { + private final PythonResourceAdapter adapter; + private final PyObject resource; + private final String task; + @Nullable private final String providerName; + private final String model; + @Nullable private final String voice; + @Nullable private final Map<String, Object> modelParameters; + @Nullable private final ResourceDescriptor descriptor; + @Nullable private final ResourceContext resourceContext; + private volatile boolean closed; + + private Handle( + PythonResourceAdapter adapter, + PyObject resource, + String task, + @Nullable String providerName, + String model, + @Nullable String voice, + @Nullable Map<String, Object> modelParameters, + @Nullable ResourceDescriptor descriptor, + @Nullable ResourceContext resourceContext) { + this.adapter = adapter; + this.resource = resource; + this.task = task; + this.providerName = providerName; + this.model = model; + this.voice = voice; + this.modelParameters = modelParameters; + this.descriptor = descriptor; + this.resourceContext = resourceContext; + } + + private void open() throws Exception { + checkOpen(); + if (providerName != null) { + if (resourceContext == null) { + throw new IllegalStateException( + "ResourceContext is required to resolve media model provider '" + + providerName + + "'."); + } + Resource provider = + resourceContext.getResource( + providerName, ResourceType.MEDIA_MODEL_PROVIDER); + if (!(provider instanceof PythonResourceWrapper)) { + throw new IllegalStateException( + "Media model provider '" + + providerName + + "' referenced by Python media model setup requires a Python MEDIA_MODEL_PROVIDER, got: " + + (provider == null ? "null" : provider.getClass().getName())); + } + adapter.invoke( Review Comment: Done. `PythonMediaModelSetup` now calls Python `open()` directly so the Python setup resolves its connection via `resource_context`, and `open_media_model_setup()` / `_bind_provider()` were removed. -- 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]
