wenjin272 commented on code in PR #373:
URL: https://github.com/apache/flink-agents/pull/373#discussion_r2605548763
##########
plan/src/main/java/org/apache/flink/agents/plan/serializer/ResourceProviderJsonDeserializer.java:
##########
@@ -105,6 +114,17 @@ private PythonSerializableResourceProvider
deserializePythonSerializableResource
private JavaResourceProvider deserializeJavaResourceProvider(JsonNode
node) {
String name = node.get("name").asText();
String type = node.get("type").asText();
+ if (node.has("clazz")) {
+ String clazz = node.get("clazz").asText();
+
+ JsonNode kwargsNode = node.get("kwargs");
+ Map<String, Object> kwargs = new HashMap<>();
+ if (kwargsNode != null && kwargsNode.isObject()) {
+ ObjectMapper mapper = new ObjectMapper();
+ kwargs = mapper.convertValue(kwargsNode, Map.class);
+ }
+ return new JavaResourceProvider(name,
ResourceType.fromValue(type), clazz, kwargs);
Review Comment:
IIUC, because `JavaResourceProvider` created in python contains field
`clazz` and `kwargs` rather than `descriptor`, so here we should deserialize
`clazz` and `kwargs` from json, and reconstruct `Descriptor` in
`JavaResourceProvider` in java according these.
Due to `ResourceDescriptor` is only a data class, could we refactor the
`JavaResourceProvider` in python, to make it serialize `descriptor` also? Then,
the `JavaResourceProvider` serialization and deserialization behavior can be
same.
The `PythonResourceProvider` may also can be refactored in this way.
##########
runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapter.java:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.runtime.python.utils;
+
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.AgentPlan;
+import org.apache.flink.agents.plan.resourceprovider.PythonResourceProvider;
+import org.apache.flink.agents.plan.resourceprovider.ResourceProvider;
+import pemja.core.PythonInterpreter;
+
+import javax.naming.OperationNotSupportedException;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/** Adapter for managing Java resources and facilitating Python-Java
interoperability. */
+public class JavaResourceAdapter {
+ private final Map<ResourceType, Map<String, ResourceProvider>>
resourceProviders;
+
+ private final transient PythonInterpreter interpreter;
+
+ /** Cache for instantiated resources. */
+ private final transient Map<ResourceType, Map<String, Resource>>
resourceCache;
+
+ public JavaResourceAdapter(AgentPlan agentPlan, PythonInterpreter
interpreter) {
+ this.resourceProviders = agentPlan.getResourceProviders();
+ this.interpreter = interpreter;
+ this.resourceCache = new ConcurrentHashMap<>();
+ }
+
+ /**
+ * Retrieves a Java resource by name and type value.
+ *
+ * @param name the name of the resource to retrieve
+ * @param typeValue the type value of the resource
+ * @return the resource
+ * @throws Exception if the resource cannot be retrieved
+ */
+ public Resource getResource(String name, String typeValue) throws
Exception {
Review Comment:
This method is never used in java side, but will be called in python side.
Should add description.
##########
python/flink_agents/plan/resource_provider.py:
##########
@@ -159,20 +159,61 @@ def provide(self, get_resource: Callable, config:
AgentConfiguration) -> Resourc
return self.resource
-# TODO: implementation
class JavaResourceProvider(ResourceProvider):
"""Represent Resource Provider declared by Java.
Currently, this class only used for deserializing Java agent plan json
"""
+ clazz: str
+ kwargs: Dict[str, Any]
+ _j_resource_adapter: Any = None
+
+ @staticmethod
+ def get(name: str, descriptor: ResourceDescriptor) ->
"JavaResourceProvider":
+ """Create JavaResourceProvider instance."""
+ wrapper_clazz = descriptor.clazz
+ kwargs = {}
+ kwargs.update(descriptor.arguments)
+
+ clazz = kwargs.pop("java_class_name", "")
+ if not clazz or len(clazz) <1:
+ err_msg = f"java_class_name are not set for
{wrapper_clazz.__name__}"
+ raise KeyError(err_msg)
+
+ return JavaResourceProvider(
+ name=name,
+ type=wrapper_clazz.resource_type(),
+ clazz=clazz,
+ kwargs=kwargs,
+ )
+
def provide(self, get_resource: Callable, config: AgentConfiguration) ->
Resource:
"""Create resource in runtime."""
- err_msg = (
- "Currently, flink-agents doesn't support create resource "
- "by JavaResourceProvider in python."
+ if not self._j_resource_adapter:
+ err_msg = "java resource adapter is not set"
+ raise RuntimeError(err_msg)
+
+ j_resource = self._j_resource_adapter.getResource(self.name,
self.type.value)
+
+ from flink_agents.runtime.java.java_chat_model import (
+ JavaChatModelConnectionImpl,
+ JavaChatModelSetupImpl,
)
- raise NotImplementedError(err_msg)
+
+ JAVA_RESOURCE_MAPPING: dict[ResourceType, Type[Resource]] = {
Review Comment:
`JAVA_RESOURCE_MAPPING` is independent of this function and class, can be
moved outside.
##########
runtime/src/main/java/org/apache/flink/agents/runtime/python/utils/JavaResourceAdapter.java:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.runtime.python.utils;
+
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.AgentPlan;
+import org.apache.flink.agents.plan.resourceprovider.PythonResourceProvider;
+import org.apache.flink.agents.plan.resourceprovider.ResourceProvider;
+import pemja.core.PythonInterpreter;
+
+import javax.naming.OperationNotSupportedException;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+/** Adapter for managing Java resources and facilitating Python-Java
interoperability. */
+public class JavaResourceAdapter {
+ private final Map<ResourceType, Map<String, ResourceProvider>>
resourceProviders;
+
+ private final transient PythonInterpreter interpreter;
+
+ /** Cache for instantiated resources. */
+ private final transient Map<ResourceType, Map<String, Resource>>
resourceCache;
+
+ public JavaResourceAdapter(AgentPlan agentPlan, PythonInterpreter
interpreter) {
+ this.resourceProviders = agentPlan.getResourceProviders();
+ this.interpreter = interpreter;
+ this.resourceCache = new ConcurrentHashMap<>();
+ }
+
+ /**
+ * Retrieves a Java resource by name and type value.
+ *
+ * @param name the name of the resource to retrieve
+ * @param typeValue the type value of the resource
+ * @return the resource
+ * @throws Exception if the resource cannot be retrieved
+ */
+ public Resource getResource(String name, String typeValue) throws
Exception {
+ return getResource(name, ResourceType.fromValue(typeValue));
+ }
+
+ /**
+ * Retrieves a Java resource by name and type.
+ *
+ * @param name the name of the resource to retrieve
+ * @param type the type of the resource
+ * @return the resource
+ * @throws Exception if the resource cannot be retrieved
+ */
+ public Resource getResource(String name, ResourceType type) throws
Exception {
+ if (resourceCache.containsKey(type) &&
resourceCache.get(type).containsKey(name)) {
+ return resourceCache.get(type).get(name);
+ }
+
+ if (!resourceProviders.containsKey(type)
+ || !resourceProviders.get(type).containsKey(name)) {
+ throw new IllegalArgumentException("Resource not found: " + name +
" of type " + type);
+ }
+
+ ResourceProvider provider = resourceProviders.get(type).get(name);
+ if (provider instanceof PythonResourceProvider) {
+ // TODO: Support getting resources from PythonResourceProvider in
JavaResourceAdapter.
+ throw new OperationNotSupportedException("PythonResourceProvider
is not supported.");
+ }
+
+ Resource resource =
+ provider.provide(
+ (String anotherName, ResourceType anotherType) -> {
+ try {
+ return this.getResource(anotherName,
anotherType);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+
+ // Cache the resource
+ resourceCache.computeIfAbsent(type, k -> new
ConcurrentHashMap<>()).put(name, resource);
+
+ return resource;
+ }
+
+ /**
+ * Convert a Python chat message to a Java chat message.
+ *
+ * @param pythonChatMessage the Python chat message
+ * @return the Java chat message
+ */
+ public ChatMessage fromPythonChatMessage(Object pythonChatMessage) {
Review Comment:
same here
--
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]