You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by xt...@apache.org on 2025/09/10 11:10:20 UTC
(flink-agents) branch main updated: [api][java] Introduce ChatModel,Tool and Prompt in Java
This is an automated email from the ASF dual-hosted git repository.
xtsong pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/flink-agents.git
The following commit(s) were added to refs/heads/main by this push:
new 338a20a [api][java] Introduce ChatModel,Tool and Prompt in Java
338a20a is described below
commit 338a20a8ebb3484f529fb6bfb3e237dcd0aa17e4
Author: Adem Amen Thabti <ad...@gmail.com>
AuthorDate: Fri Jul 25 14:14:18 2025 +0100
[api][java] Introduce ChatModel,Tool and Prompt in Java
Co-authored-by: WenjinXie <we...@gmail.com>
---
api/pom.xml | 1 -
.../flink/agents/api/annotation/ChatModel.java | 11 +-
.../api/annotation/{Tool.java => Prompt.java} | 17 +-
.../apache/flink/agents/api/annotation/Tool.java | 13 +-
.../annotation/{ChatModel.java => ToolParam.java} | 44 +++-
.../agents/api/chat/messages/ChatMessage.java | 173 ++++++++++++++
.../agents/api/chat/messages/MessageRole.java | 62 +++++
.../flink/agents/api/chat/model/BaseChatModel.java | 68 ++++++
.../flink/agents/api/event/ToolRequestEvent.java | 61 +++++
.../flink/agents/api/event/ToolResponseEvent.java | 93 ++++++++
.../org/apache/flink/agents/api/prompt/Prompt.java | 196 ++++++++++++++++
.../apache/flink/agents/api/resource/Resource.java | 8 -
.../agents/api/chat/messages/ChatMessageTest.java | 152 ++++++++++++
.../agents/api/chat/model/BaseChatModelTest.java | 241 +++++++++++++++++++
.../apache/flink/agents/api/prompt/PromptTest.java | 260 +++++++++++++++++++++
.../flink/agents/examples/AgentWithResource.java | 127 ++++++++++
.../agents/examples/AgentWithResourceExample.java | 56 +++++
.../org/apache/flink/agents/plan/AgentPlan.java | 117 ++++++----
.../resourceprovider/JavaResourceProvider.java | 46 +++-
.../JavaSerializableResourceProvider.java | 58 ++++-
.../resourceprovider/PythonResourceProvider.java | 5 +-
.../PythonSerializableResourceProvider.java | 5 +-
.../plan/resourceprovider/ResourceProvider.java | 5 +-
.../ResourceProviderJsonDeserializer.java | 44 +++-
.../serializer/ResourceProviderJsonSerializer.java | 46 +++-
.../apache/flink/agents/plan/tools/BaseTool.java | 62 +++++
.../flink/agents/plan/tools/FunctionTool.java | 136 +++++++++++
.../flink/agents/plan/tools/SchemaUtils.java | 89 +++++++
.../flink/agents/plan/tools/ToolMetadata.java | 88 +++++++
.../agents/plan/tools/ToolMetadataFactory.java | 52 +++++
.../flink/agents/plan/tools/ToolParameters.java | 122 ++++++++++
.../flink/agents/plan/tools/ToolResponse.java | 191 +++++++++++++++
.../apache/flink/agents/plan/tools/ToolType.java | 58 +++++
.../serializer/FunctionToolJsonDeserializer.java | 95 ++++++++
.../serializer/FunctionToolJsonSerializer.java | 90 +++++++
.../agents/plan/AgentPlanDeclareChatModelTest.java | 141 +++++++++++
.../agents/plan/AgentPlanDeclareToolFieldTest.java | 202 ++++++++++++++++
.../plan/AgentPlanDeclareToolMethodTest.java | 221 ++++++++++++++++++
.../apache/flink/agents/plan/AgentPlanTest.java | 19 +-
.../flink/agents/plan/FunctionToolPlanTest.java | 124 ++++++++++
.../flink/agents/plan/tools/FunctionToolTest.java | 81 +++++++
41 files changed, 3543 insertions(+), 137 deletions(-)
diff --git a/api/pom.xml b/api/pom.xml
index 07ac54e..184cb9a 100644
--- a/api/pom.xml
+++ b/api/pom.xml
@@ -27,7 +27,6 @@ under the License.
<artifactId>flink-agents-api</artifactId>
<name>Flink Agents : API</name>
-
<dependencies>
<dependency>
<groupId>org.apache.flink</groupId>
diff --git a/api/src/main/java/org/apache/flink/agents/api/annotation/ChatModel.java b/api/src/main/java/org/apache/flink/agents/api/annotation/ChatModel.java
index 564078f..e74d2ef 100644
--- a/api/src/main/java/org/apache/flink/agents/api/annotation/ChatModel.java
+++ b/api/src/main/java/org/apache/flink/agents/api/annotation/ChatModel.java
@@ -29,13 +29,10 @@ import java.lang.annotation.Target;
* <p>Fields annotated with @ChatModel will be scanned during agent plan creation and corresponding
* resource providers will be created to manage the chat model instances.
*/
-@Target(ElementType.FIELD)
+@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ChatModel {
- /**
- * The name of the chat model resource. If not specified, the field name will be used.
- *
- * @return the resource name
- */
- String name() default "";
+ String CHAT_MODEL_CLASS_NAME = "clazz";
+ String CHAT_MODEL_ARGUMENTS = "arguments";
+ String CHAT_MODEL_ARGUMENTS_TYPES = "types";
}
diff --git a/api/src/main/java/org/apache/flink/agents/api/annotation/Tool.java b/api/src/main/java/org/apache/flink/agents/api/annotation/Prompt.java
similarity index 68%
copy from api/src/main/java/org/apache/flink/agents/api/annotation/Tool.java
copy to api/src/main/java/org/apache/flink/agents/api/annotation/Prompt.java
index 50fccc1..156f839 100644
--- a/api/src/main/java/org/apache/flink/agents/api/annotation/Tool.java
+++ b/api/src/main/java/org/apache/flink/agents/api/annotation/Prompt.java
@@ -24,18 +24,11 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
- * Annotation to mark a field as a tool resource that should be managed by the agent plan.
+ * Annotation to mark a field as a prompt resource that should be managed by the agent plan.
*
- * <p>Fields annotated with @Tool will be scanned during agent plan creation and corresponding
- * resource providers will be created to manage the tool instances.
+ * <p>Fields annotated with @Prompt will be scanned during agent plan creation and corresponding
+ * resource providers will be created to manage the prompt instances.
*/
-@Target(ElementType.FIELD)
+@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
-public @interface Tool {
- /**
- * The name of the tool resource. If not specified, the field name will be used.
- *
- * @return the resource name
- */
- String name() default "";
-}
+public @interface Prompt {}
diff --git a/api/src/main/java/org/apache/flink/agents/api/annotation/Tool.java b/api/src/main/java/org/apache/flink/agents/api/annotation/Tool.java
index 50fccc1..6d32d56 100644
--- a/api/src/main/java/org/apache/flink/agents/api/annotation/Tool.java
+++ b/api/src/main/java/org/apache/flink/agents/api/annotation/Tool.java
@@ -24,18 +24,19 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
- * Annotation to mark a field as a tool resource that should be managed by the agent plan.
+ * Annotation to mark a field or method as a tool resource that should be managed by the agent plan.
*
* <p>Fields annotated with @Tool will be scanned during agent plan creation and corresponding
- * resource providers will be created to manage the tool instances.
+ * resource providers will be created to manage the tool instances. Methods annotated with @Tool
+ * must be static and will be wrapped as FunctionTool resources.
*/
-@Target(ElementType.FIELD)
+@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Tool {
/**
- * The name of the tool resource. If not specified, the field name will be used.
+ * The description of the tool. If not provided, the field/method name will be used.
*
- * @return the resource name
+ * @return the description of the tool
*/
- String name() default "";
+ String description() default "";
}
diff --git a/api/src/main/java/org/apache/flink/agents/api/annotation/ChatModel.java b/api/src/main/java/org/apache/flink/agents/api/annotation/ToolParam.java
similarity index 51%
copy from api/src/main/java/org/apache/flink/agents/api/annotation/ChatModel.java
copy to api/src/main/java/org/apache/flink/agents/api/annotation/ToolParam.java
index 564078f..3d7aa97 100644
--- a/api/src/main/java/org/apache/flink/agents/api/annotation/ChatModel.java
+++ b/api/src/main/java/org/apache/flink/agents/api/annotation/ToolParam.java
@@ -1,4 +1,5 @@
/*
+ *
* 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
@@ -7,35 +8,56 @@
* "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
+ * 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.annotation;
+import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
-/**
- * Annotation to mark a field as a chat model resource that should be managed by the agent plan.
- *
- * <p>Fields annotated with @ChatModel will be scanned during agent plan creation and corresponding
- * resource providers will be created to manage the chat model instances.
- */
-@Target(ElementType.FIELD)
+@Target({ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
-public @interface ChatModel {
+@Documented
+public @interface ToolParam {
+
+ /**
+ * Whether the tool argument is required.
+ *
+ * @return true if the argument is required, false otherwise.
+ */
+ boolean required() default true;
+
/**
- * The name of the chat model resource. If not specified, the field name will be used.
+ * The name of the tool argument.
*
- * @return the resource name
+ * @return a string representing the name of the argument, which can be used to identify it in
+ * the tool's context.
*/
String name() default "";
+
+ /**
+ * The description of the tool argument.
+ *
+ * @return a string describing the argument, which can be used to provide context or usage
+ * information.
+ */
+ String description() default "";
+
+ /**
+ * The default value of the tool argument. If not provided, the argument is considered required.
+ *
+ * @return a string representing the default value of the argument.
+ */
+ String defaultValue() default "";
}
diff --git a/api/src/main/java/org/apache/flink/agents/api/chat/messages/ChatMessage.java b/api/src/main/java/org/apache/flink/agents/api/chat/messages/ChatMessage.java
new file mode 100644
index 0000000..b00d802
--- /dev/null
+++ b/api/src/main/java/org/apache/flink/agents/api/chat/messages/ChatMessage.java
@@ -0,0 +1,173 @@
+/*
+ * 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.chat.messages;
+
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * Chat message class that represents all message types (user, system, assistant, tool) with
+ * different roles
+ */
+public class ChatMessage {
+
+ /** The key for the message type in the metadata. */
+ public static final String MESSAGE_TYPE = "messageType";
+
+ private MessageRole role;
+ private String content;
+ private List<Map<String, Object>> toolCalls;
+ private Map<String, Object> extraArgs;
+
+ /** Default constructor with SYSTEM role */
+ public ChatMessage() {
+ this.role = MessageRole.SYSTEM;
+ this.content = "";
+ this.toolCalls = new ArrayList<>();
+ this.extraArgs = new HashMap<>();
+ }
+
+ /** Constructor with role and content */
+ public ChatMessage(MessageRole role, String content) {
+ this.role = role != null ? role : MessageRole.SYSTEM;
+ this.content = content != null ? content : "";
+ this.toolCalls = new ArrayList<>();
+ this.extraArgs = new HashMap<>();
+ this.extraArgs.put(MESSAGE_TYPE, this.role);
+ }
+
+ /** Full constructor */
+ public ChatMessage(
+ MessageRole role,
+ String content,
+ List<Map<String, Object>> toolCalls,
+ Map<String, Object> extraArgs) {
+ this.role = role != null ? role : MessageRole.SYSTEM;
+ this.content = content != null ? content : "";
+ this.toolCalls = toolCalls != null ? toolCalls : new ArrayList<>();
+ this.extraArgs = extraArgs != null ? new HashMap<>(extraArgs) : new HashMap<>();
+ this.extraArgs.put(MESSAGE_TYPE, this.role);
+ }
+
+ /** Constructor with resource */
+ public ChatMessage(MessageRole role, Resource resource, Map<String, Object> extraArgs) {
+ if (resource == null) throw new IllegalArgumentException("resource must not be null");
+ // TODO handle resource content properly
+ this.role = role != null ? role : MessageRole.SYSTEM;
+ this.toolCalls = new ArrayList<>();
+ this.extraArgs = extraArgs != null ? new HashMap<>(extraArgs) : new HashMap<>();
+ this.extraArgs.put(MESSAGE_TYPE, this.role);
+ }
+
+ public MessageRole getRole() {
+ return role;
+ }
+
+ public void setRole(MessageRole role) {
+ this.role = role;
+ this.extraArgs.put(MESSAGE_TYPE, this.role);
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ public void setContent(String content) {
+ this.content = content;
+ }
+
+ public List<Map<String, Object>> getToolCalls() {
+ return toolCalls;
+ }
+
+ public void setToolCalls(List<Map<String, Object>> toolCalls) {
+ this.toolCalls = toolCalls;
+ }
+
+ public Map<String, Object> getExtraArgs() {
+ return extraArgs;
+ }
+
+ public void setExtraArgs(Map<String, Object> extraArgs) {
+ this.extraArgs = extraArgs != null ? extraArgs : new HashMap<>();
+ this.extraArgs.put(MESSAGE_TYPE, this.role);
+ }
+
+ @JsonIgnore
+ public String getText() {
+ return this.content;
+ }
+
+ public Map<String, Object> getMetadata() {
+ return this.extraArgs;
+ }
+
+ @JsonIgnore
+ public MessageRole getMessageType() {
+ return this.role;
+ }
+
+ // Static factory methods for convenience
+ public static ChatMessage user(String content) {
+ return new ChatMessage(MessageRole.USER, content);
+ }
+
+ public static ChatMessage system(String content) {
+ return new ChatMessage(MessageRole.SYSTEM, content);
+ }
+
+ public static ChatMessage assistant(String content) {
+ return new ChatMessage(MessageRole.ASSISTANT, content);
+ }
+
+ public static ChatMessage assistant(String content, List<Map<String, Object>> toolCalls) {
+ return new ChatMessage(MessageRole.ASSISTANT, content, toolCalls, new HashMap<>());
+ }
+
+ public static ChatMessage tool(String content) {
+ return new ChatMessage(MessageRole.TOOL, content);
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (!(o instanceof ChatMessage)) return false;
+ ChatMessage that = (ChatMessage) o;
+ return Objects.equals(role, that.role)
+ && Objects.equals(content, that.content)
+ && Objects.equals(toolCalls, that.toolCalls)
+ && Objects.equals(extraArgs, that.extraArgs);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(role, content, toolCalls, extraArgs);
+ }
+
+ @Override
+ public String toString() {
+ return role.getValue() + ": " + content;
+ }
+}
diff --git a/api/src/main/java/org/apache/flink/agents/api/chat/messages/MessageRole.java b/api/src/main/java/org/apache/flink/agents/api/chat/messages/MessageRole.java
new file mode 100644
index 0000000..b992b9a
--- /dev/null
+++ b/api/src/main/java/org/apache/flink/agents/api/chat/messages/MessageRole.java
@@ -0,0 +1,62 @@
+/*
+ * 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.chat.messages;
+
+/**
+ * Enumeration of message roles in a chat conversation. Each role represents a different participant
+ * type in the conversation.
+ */
+public enum MessageRole {
+
+ /** A message from an end-user or developer. */
+ USER("user"),
+
+ /** A message generated by the AI assistant in response to user input. */
+ ASSISTANT("assistant"),
+
+ /** A system message containing high-level instructions for the conversation. */
+ SYSTEM("system"),
+
+ /** A message containing tool or function call results. */
+ TOOL("tool");
+
+ private final String value;
+
+ MessageRole(String value) {
+ this.value = value;
+ }
+
+ public static MessageRole fromValue(String value) {
+ for (MessageRole messageRole : MessageRole.values()) {
+ if (messageRole.getValue().equals(value)) {
+ return messageRole;
+ }
+ }
+ throw new IllegalArgumentException("Invalid MessageRole value: " + value);
+ }
+
+ public String getValue() {
+ return this.value;
+ }
+
+ @Override
+ public String toString() {
+ return this.value;
+ }
+}
diff --git a/api/src/main/java/org/apache/flink/agents/api/chat/model/BaseChatModel.java b/api/src/main/java/org/apache/flink/agents/api/chat/model/BaseChatModel.java
new file mode 100644
index 0000000..5227063
--- /dev/null
+++ b/api/src/main/java/org/apache/flink/agents/api/chat/model/BaseChatModel.java
@@ -0,0 +1,68 @@
+/*
+ * 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.chat.model;
+
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceType;
+
+import java.util.List;
+import java.util.function.BiFunction;
+
+public abstract class BaseChatModel extends Resource {
+ protected final BiFunction<String, ResourceType, Resource> getResource;
+ protected String promptName;
+ protected List<String> toolNames;
+
+ public BaseChatModel(BiFunction<String, ResourceType, Resource> getResource) {
+ this(getResource, null, null);
+ }
+
+ public BaseChatModel(
+ BiFunction<String, ResourceType, Resource> getResource, String promptName) {
+ this(getResource, promptName, null);
+ }
+
+ public BaseChatModel(
+ BiFunction<String, ResourceType, Resource> getResource, List<String> toolNames) {
+ this(getResource, null, toolNames);
+ }
+
+ public BaseChatModel(
+ BiFunction<String, ResourceType, Resource> getResource,
+ String promptName,
+ List<String> toolNames) {
+ this.getResource = getResource;
+ this.promptName = promptName;
+ this.toolNames = toolNames;
+ }
+
+ /**
+ * Process a chat request and return a chat response.
+ *
+ * @param messages the input chat messages
+ * @return the chat response containing model outputs
+ */
+ public abstract ChatMessage chat(List<ChatMessage> messages);
+
+ @Override
+ public ResourceType getResourceType() {
+ return ResourceType.CHAT_MODEL;
+ }
+}
diff --git a/api/src/main/java/org/apache/flink/agents/api/event/ToolRequestEvent.java b/api/src/main/java/org/apache/flink/agents/api/event/ToolRequestEvent.java
new file mode 100644
index 0000000..e39db7f
--- /dev/null
+++ b/api/src/main/java/org/apache/flink/agents/api/event/ToolRequestEvent.java
@@ -0,0 +1,61 @@
+/*
+ * 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.event;
+
+import java.util.Map;
+import java.util.Objects;
+
+/** Event representing a tool call request */
+public class ToolRequestEvent {
+
+ private final String tool;
+ private final Map<String, Object> kwargs;
+ private final long timestamp;
+
+ public ToolRequestEvent(String tool, Map<String, Object> kwargs) {
+ this.tool = Objects.requireNonNull(tool, "tool name cannot be null");
+ this.kwargs = Objects.requireNonNull(kwargs, "kwargs cannot be null");
+ this.timestamp = System.currentTimeMillis();
+ }
+
+ public String getTool() {
+ return tool;
+ }
+
+ public Map<String, Object> getKwargs() {
+ return kwargs;
+ }
+
+ public long getTimestamp() {
+ return timestamp;
+ }
+
+ @Override
+ public String toString() {
+ return "ToolRequestEvent{"
+ + "tool='"
+ + tool
+ + '\''
+ + ", kwargs="
+ + kwargs
+ + ", timestamp="
+ + timestamp
+ + '}';
+ }
+}
diff --git a/api/src/main/java/org/apache/flink/agents/api/event/ToolResponseEvent.java b/api/src/main/java/org/apache/flink/agents/api/event/ToolResponseEvent.java
new file mode 100644
index 0000000..5115c69
--- /dev/null
+++ b/api/src/main/java/org/apache/flink/agents/api/event/ToolResponseEvent.java
@@ -0,0 +1,93 @@
+/*
+ * 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.event;
+
+import java.util.Objects;
+
+/** Event representing a result from tool call */
+public class ToolResponseEvent {
+
+ private final ToolRequestEvent request;
+ private final Object response;
+ private final boolean success;
+ private final String error;
+ private final long timestamp;
+
+ public ToolResponseEvent(ToolRequestEvent request, Object response) {
+ this.request = Objects.requireNonNull(request, "request cannot be null");
+ this.response = response;
+ this.success = true;
+ this.error = null;
+ this.timestamp = System.currentTimeMillis();
+ }
+
+ public ToolResponseEvent(ToolRequestEvent request, String error) {
+ this.request = Objects.requireNonNull(request, "request cannot be null");
+ this.response = null;
+ this.success = false;
+ this.error = Objects.requireNonNull(error, "error cannot be null");
+ this.timestamp = System.currentTimeMillis();
+ }
+
+ public ToolRequestEvent getRequest() {
+ return request;
+ }
+
+ public Object getResponse() {
+ return response;
+ }
+
+ public boolean isSuccess() {
+ return success;
+ }
+
+ public String getError() {
+ return error;
+ }
+
+ public long getTimestamp() {
+ return timestamp;
+ }
+
+ @Override
+ public String toString() {
+ if (success) {
+ return "ToolResponseEvent{"
+ + "request="
+ + request
+ + ", response="
+ + response
+ + ", success=true"
+ + ", timestamp="
+ + timestamp
+ + '}';
+ } else {
+ return "ToolResponseEvent{"
+ + "request="
+ + request
+ + ", error='"
+ + error
+ + '\''
+ + ", success=false"
+ + ", timestamp="
+ + timestamp
+ + '}';
+ }
+ }
+}
diff --git a/api/src/main/java/org/apache/flink/agents/api/prompt/Prompt.java b/api/src/main/java/org/apache/flink/agents/api/prompt/Prompt.java
new file mode 100644
index 0000000..3db41d1
--- /dev/null
+++ b/api/src/main/java/org/apache/flink/agents/api/prompt/Prompt.java
@@ -0,0 +1,196 @@
+/*
+ * 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.prompt;
+
+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.ResourceType;
+import org.apache.flink.agents.api.resource.SerializableResource;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeInfo;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.function.Function;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
+/**
+ * Prompt for a language model
+ *
+ * <p>The template can be either a string or a sequence of ChatMessage objects.
+ */
+public class Prompt extends SerializableResource {
+ private static final String FIELD_TEMPLATE = "template";
+
+ @JsonProperty(FIELD_TEMPLATE)
+ private final PromptTemplate template;
+
+ @JsonCreator
+ private Prompt(@JsonProperty(FIELD_TEMPLATE) PromptTemplate promptTemplate) {
+ this.template = promptTemplate;
+ }
+
+ public Prompt(String template) {
+ this.template = PromptTemplate.fromString(template);
+ }
+
+ public Prompt(List<ChatMessage> template) {
+ this.template = PromptTemplate.fromMessages(template);
+ }
+
+ public String formatString(Map<String, String> kwargs) {
+ return template.match(
+ // Handle string template
+ content -> format(content, kwargs),
+ // Handle messages template
+ messages -> {
+ List<String> formattedMessages = new ArrayList<>();
+ for (ChatMessage message : messages) {
+ String formattedContent = format(message.getContent(), kwargs);
+ String formatted = message.getRole().getValue() + ": " + formattedContent;
+ formattedMessages.add(formatted);
+ }
+ return String.join("\n", formattedMessages);
+ });
+ }
+
+ public List<ChatMessage> formatMessages(MessageRole defaultRole, Map<String, String> kwargs) {
+ return template.match(
+ // Handle string template
+ content ->
+ Collections.singletonList(
+ new ChatMessage(defaultRole, format(content, kwargs))),
+ // Handle messages template
+ messages ->
+ messages.stream()
+ .map(
+ message ->
+ new ChatMessage(
+ message.getRole(),
+ format(message.getContent(), kwargs)))
+ .collect(Collectors.toList()));
+ }
+
+ @JsonIgnore
+ @Override
+ public ResourceType getResourceType() {
+ return ResourceType.PROMPT;
+ }
+
+ private static final Pattern BRACE_PATTERN = Pattern.compile("\\{([^}]+)\\}");
+
+ /** Format template string with keyword arguments */
+ private static String format(String template, Map<String, String> kwargs) {
+ if (template == null) {
+ return "";
+ }
+
+ String result = template;
+ for (Map.Entry<String, String> entry : kwargs.entrySet()) {
+ String placeholder = "{" + entry.getKey() + "}";
+ String value = entry.getValue() != null ? entry.getValue() : "";
+ result = result.replace(placeholder, value);
+ }
+ return result;
+ }
+
+ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS)
+ private abstract static class PromptTemplate {
+ public static PromptTemplate fromString(String content) {
+ return new StringTemplate(content);
+ }
+
+ public static PromptTemplate fromMessages(List<ChatMessage> messages) {
+ return new MessagesTemplate(messages);
+ }
+
+ /**
+ * Pattern matching method for type-safe operations. This replaces instanceof checks and
+ * casting.
+ */
+ public abstract <T> T match(
+ Function<String, T> onString, Function<List<ChatMessage>, T> onMessages);
+ }
+
+ /** String template implementation. */
+ private static class StringTemplate extends PromptTemplate {
+ private static final String FIELD_CONTENT = "content";
+
+ @JsonProperty(FIELD_CONTENT)
+ private final String content;
+
+ @JsonCreator
+ public StringTemplate(@JsonProperty(FIELD_CONTENT) String content) {
+ this.content = Objects.requireNonNull(content, "content cannot be null");
+ }
+
+ public String getContent() {
+ return content;
+ }
+
+ @Override
+ public <T> T match(
+ Function<String, T> onString, Function<List<ChatMessage>, T> onMessages) {
+ return onString.apply(content);
+ }
+
+ @Override
+ public String toString() {
+ return "StringTemplate{content='" + content + "'}";
+ }
+ }
+
+ /** Messages template implementation. */
+ private static class MessagesTemplate extends PromptTemplate {
+ private static final String FIELD_MESSAGES = "messages";
+
+ @JsonProperty(FIELD_MESSAGES)
+ private final List<ChatMessage> messages;
+
+ @JsonCreator
+ public MessagesTemplate(@JsonProperty(FIELD_MESSAGES) List<ChatMessage> messages) {
+ Objects.requireNonNull(messages, "messages cannot be null");
+ if (messages.isEmpty()) {
+ throw new IllegalArgumentException("Messages cannot be empty");
+ }
+ this.messages = new ArrayList<>(messages);
+ }
+
+ public List<ChatMessage> getMessages() {
+ return new ArrayList<>(messages);
+ }
+
+ @Override
+ public <T> T match(
+ Function<String, T> onString, Function<List<ChatMessage>, T> onMessages) {
+ return onMessages.apply(new ArrayList<>(messages));
+ }
+
+ @Override
+ public String toString() {
+ return "MessagesTemplate{messages=" + messages.size() + " items}";
+ }
+ }
+}
diff --git a/api/src/main/java/org/apache/flink/agents/api/resource/Resource.java b/api/src/main/java/org/apache/flink/agents/api/resource/Resource.java
index 19b0122..4a50e8f 100644
--- a/api/src/main/java/org/apache/flink/agents/api/resource/Resource.java
+++ b/api/src/main/java/org/apache/flink/agents/api/resource/Resource.java
@@ -24,14 +24,6 @@ package org.apache.flink.agents.api.resource;
* <p>Resources are components that can be used by agents during action execution.
*/
public abstract class Resource {
-
- /**
- * Get the name of the resource.
- *
- * @return the resource name
- */
- public abstract String getName();
-
/**
* Get the type of the resource.
*
diff --git a/api/src/test/java/org/apache/flink/agents/api/chat/messages/ChatMessageTest.java b/api/src/test/java/org/apache/flink/agents/api/chat/messages/ChatMessageTest.java
new file mode 100644
index 0000000..f24bae1
--- /dev/null
+++ b/api/src/test/java/org/apache/flink/agents/api/chat/messages/ChatMessageTest.java
@@ -0,0 +1,152 @@
+/*
+ * 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.chat.messages;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Test cases for ChatMessage class, Tests message creation, role handling, content management, and
+ * serialization.
+ */
+class ChatMessageTest {
+
+ private ChatMessage userMessage;
+ private ChatMessage systemMessage;
+ private ChatMessage assistantMessage;
+
+ @BeforeEach
+ void setUp() {
+ userMessage = new ChatMessage(MessageRole.USER, "Hello, how are you?");
+ systemMessage = new ChatMessage(MessageRole.SYSTEM, "You are a helpful assistant.");
+ assistantMessage = new ChatMessage(MessageRole.ASSISTANT, "I'm doing well, thank you!");
+ }
+
+ @Test
+ @DisplayName("Test ChatMessage creation with role and content")
+ void testChatMessageCreation() {
+ assertEquals(MessageRole.USER, userMessage.getRole());
+ assertEquals("Hello, how are you?", userMessage.getContent());
+
+ assertEquals(MessageRole.SYSTEM, systemMessage.getRole());
+ assertEquals("You are a helpful assistant.", systemMessage.getContent());
+
+ assertEquals(MessageRole.ASSISTANT, assistantMessage.getRole());
+ assertEquals("I'm doing well, thank you!", assistantMessage.getContent());
+ }
+
+ @Test
+ @DisplayName("Test default constructor creates USER message")
+ void testDefaultConstructor() {
+ ChatMessage defaultMessage = new ChatMessage();
+ assertEquals(MessageRole.SYSTEM, defaultMessage.getRole());
+ assertEquals("", defaultMessage.getContent());
+ assertNotNull(defaultMessage.getToolCalls());
+ assertNotNull(defaultMessage.getExtraArgs());
+ }
+
+ @Test
+ @DisplayName("Test ChatMessage with tool calls")
+ void testChatMessageWithToolCalls() {
+ ChatMessage messageWithTools =
+ new ChatMessage(MessageRole.ASSISTANT, "Let me help you with that.");
+
+ // Add a tool call
+ Map<String, Object> toolCall = new HashMap<>();
+ toolCall.put("id", "call_123");
+ toolCall.put(
+ "function",
+ new HashMap<String, Object>() {
+ {
+ put("name", "get_weather");
+ put("arguments", "{\"location\": \"NYC\"}");
+ }
+ });
+ messageWithTools.getToolCalls().add(toolCall);
+
+ assertEquals(1, messageWithTools.getToolCalls().size());
+ assertEquals("call_123", messageWithTools.getToolCalls().get(0).get("id"));
+ }
+
+ @Test
+ @DisplayName("Test ChatMessage with extra arguments")
+ void testChatMessageWithExtraArgs() {
+ ChatMessage messageWithExtras = new ChatMessage(MessageRole.USER, "Test message");
+
+ messageWithExtras.getExtraArgs().put("temperature", 0.7);
+ messageWithExtras.getExtraArgs().put("max_tokens", 100);
+
+ assertEquals(0.7, messageWithExtras.getExtraArgs().get("temperature"));
+ assertEquals(100, messageWithExtras.getExtraArgs().get("max_tokens"));
+ }
+
+ @Test
+ @DisplayName("Test ChatMessage equality")
+ void testChatMessageEquality() {
+ ChatMessage message1 = new ChatMessage(MessageRole.USER, "Hello");
+ ChatMessage message2 = new ChatMessage(MessageRole.USER, "Hello");
+ ChatMessage message3 = new ChatMessage(MessageRole.SYSTEM, "Hello");
+
+ assertEquals(message1, message2);
+ assertNotEquals(message1, message3);
+ }
+
+ @Test
+ @DisplayName("Test ChatMessage toString representation")
+ void testChatMessageToString() {
+ String userString = userMessage.toString();
+ assertTrue(userString.contains("user"));
+ assertTrue(userString.contains("Hello, how are you?"));
+ }
+
+ @Test
+ @DisplayName("Test all MessageRole values")
+ void testMessageRoles() {
+ assertEquals("user", MessageRole.USER.getValue());
+ assertEquals("system", MessageRole.SYSTEM.getValue());
+ assertEquals("assistant", MessageRole.ASSISTANT.getValue());
+ assertEquals("tool", MessageRole.TOOL.getValue());
+ }
+
+ @Test
+ @DisplayName("Test ChatMessage content modification")
+ void testContentModification() {
+ ChatMessage message = new ChatMessage(MessageRole.USER, "Original content");
+ assertEquals("Original content", message.getContent());
+
+ message.setContent("Modified content");
+ assertEquals("Modified content", message.getContent());
+ }
+
+ @Test
+ @DisplayName("Test ChatMessage role modification")
+ void testRoleModification() {
+ ChatMessage message = new ChatMessage(MessageRole.USER, "Test content");
+ assertEquals(MessageRole.USER, message.getRole());
+
+ message.setRole(MessageRole.ASSISTANT);
+ assertEquals(MessageRole.ASSISTANT, message.getRole());
+ }
+}
diff --git a/api/src/test/java/org/apache/flink/agents/api/chat/model/BaseChatModelTest.java b/api/src/test/java/org/apache/flink/agents/api/chat/model/BaseChatModelTest.java
new file mode 100644
index 0000000..d6c9a5c
--- /dev/null
+++ b/api/src/test/java/org/apache/flink/agents/api/chat/model/BaseChatModelTest.java
@@ -0,0 +1,241 @@
+/*
+ * 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.chat.model;
+
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.prompt.Prompt;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Test cases for BaseChatModel class, Tests chat model functionality, prompt processing, and
+ * response generation.
+ */
+class BaseChatModelTest {
+
+ private TestChatModel chatModel;
+ private Prompt simplePrompt;
+ private Prompt conversationPrompt;
+
+ /** Test implementation of BaseChatModel for testing purposes. */
+ private static class TestChatModel extends BaseChatModel {
+ private String responsePrefix = "Test Response: ";
+
+ public TestChatModel(BiFunction<String, ResourceType, Resource> getResource) {
+ super(getResource);
+ }
+
+ @Override
+ public ChatMessage chat(List<ChatMessage> messages) {
+ // Simple test implementation that echoes the last user message
+
+ String lastUserContent = "";
+ for (ChatMessage message : messages) {
+ if (message.getRole() == MessageRole.USER) {
+ lastUserContent = message.getContent();
+ }
+ }
+
+ if (lastUserContent.isEmpty()) {
+ lastUserContent = "No user message found";
+ }
+
+ return new ChatMessage(MessageRole.ASSISTANT, responsePrefix + lastUserContent);
+ }
+
+ public void setResponsePrefix(String prefix) {
+ this.responsePrefix = prefix;
+ }
+ }
+
+ @BeforeEach
+ void setUp() {
+ chatModel = new TestChatModel(null);
+
+ // Create simple prompt
+ simplePrompt = new Prompt("You are a helpful assistant. User says: {user_input}");
+
+ // Create conversation prompt
+ List<ChatMessage> conversationTemplate =
+ Arrays.asList(
+ new ChatMessage(MessageRole.SYSTEM, "You are a helpful AI assistant."),
+ new ChatMessage(MessageRole.USER, "{user_message}"));
+ conversationPrompt = new Prompt(conversationTemplate);
+ }
+
+ @Test
+ @DisplayName("Test ChatModel resource type")
+ void testChatModelResourceType() {
+ assertEquals(ResourceType.CHAT_MODEL, chatModel.getResourceType());
+ }
+
+ @Test
+ @DisplayName("Test basic chat functionality")
+ void testBasicChat() {
+ Map<String, String> variables = new HashMap<>();
+ variables.put("user_input", "Hello, how are you?");
+
+ // Format the prompt with variables
+ Prompt formattedPrompt =
+ new Prompt(simplePrompt.formatMessages(MessageRole.SYSTEM, variables));
+
+ ChatMessage response =
+ chatModel.chat(formattedPrompt.formatMessages(MessageRole.USER, new HashMap<>()));
+
+ assertNotNull(response);
+ assertEquals(MessageRole.ASSISTANT, response.getRole());
+ assertTrue(response.getContent().contains("Test Response:"));
+ }
+
+ @Test
+ @DisplayName("Test chat with conversation prompt")
+ void testChatWithConversationPrompt() {
+ Map<String, String> variables = new HashMap<>();
+ variables.put("user_message", "What's the weather like?");
+
+ Prompt formattedPrompt =
+ new Prompt(conversationPrompt.formatMessages(MessageRole.SYSTEM, variables));
+
+ ChatMessage response =
+ chatModel.chat(formattedPrompt.formatMessages(MessageRole.USER, new HashMap<>()));
+
+ assertNotNull(response);
+ assertEquals(MessageRole.ASSISTANT, response.getRole());
+ assertTrue(response.getContent().contains("What's the weather like?"));
+ }
+
+ @Test
+ @DisplayName("Test chat with empty prompt")
+ void testChatWithEmptyPrompt() {
+ Prompt emptyPrompt = new Prompt("");
+
+ ChatMessage response =
+ chatModel.chat(emptyPrompt.formatMessages(MessageRole.USER, new HashMap<>()));
+
+ assertNotNull(response);
+ assertEquals(MessageRole.ASSISTANT, response.getRole());
+ assertTrue(response.getContent().contains("No user message found"));
+ }
+
+ @Test
+ @DisplayName("Test chat with multiple user messages")
+ void testChatWithMultipleUserMessages() {
+ List<ChatMessage> multipleMessages =
+ Arrays.asList(
+ new ChatMessage(MessageRole.SYSTEM, "You are a helpful assistant."),
+ new ChatMessage(MessageRole.USER, "First message"),
+ new ChatMessage(MessageRole.ASSISTANT, "I understand"),
+ new ChatMessage(
+ MessageRole.USER, "Second message - this should be the response"));
+
+ Prompt multiPrompt = new Prompt(multipleMessages);
+
+ ChatMessage response =
+ chatModel.chat(multiPrompt.formatMessages(MessageRole.USER, new HashMap<>()));
+
+ assertNotNull(response);
+ assertTrue(response.getContent().contains("Second message - this should be the response"));
+ }
+
+ @Test
+ @DisplayName("Test chat model configuration")
+ void testChatModelConfiguration() {
+ chatModel.setResponsePrefix("Custom Response: ");
+
+ Map<String, String> variables = new HashMap<>();
+ variables.put("user_input", "Test message");
+
+ Prompt formattedPrompt =
+ new Prompt(simplePrompt.formatMessages(MessageRole.SYSTEM, variables));
+
+ ChatMessage response =
+ chatModel.chat(formattedPrompt.formatMessages(MessageRole.USER, new HashMap<>()));
+
+ assertTrue(response.getContent().startsWith("Custom Response:"));
+ }
+
+ @Test
+ @DisplayName("Test chat with system-only prompt")
+ void testChatWithSystemOnlyPrompt() {
+ Prompt systemOnlyPrompt =
+ new Prompt(
+ Arrays.asList(
+ new ChatMessage(MessageRole.SYSTEM, "System instruction only")));
+
+ ChatMessage response =
+ chatModel.chat(systemOnlyPrompt.formatMessages(MessageRole.USER, new HashMap<>()));
+
+ assertNotNull(response);
+ assertEquals(MessageRole.ASSISTANT, response.getRole());
+ assertTrue(response.getContent().contains("No user message found"));
+ }
+
+ @Test
+ @DisplayName("Test chat response format")
+ void testChatResponseFormat() {
+ Map<String, String> variables = new HashMap<>();
+ variables.put("user_input", "Format test");
+
+ Prompt formattedPrompt =
+ new Prompt(simplePrompt.formatMessages(MessageRole.SYSTEM, variables));
+
+ ChatMessage response =
+ chatModel.chat(formattedPrompt.formatMessages(MessageRole.USER, new HashMap<>()));
+
+ // Verify response structure
+ assertNotNull(response.getRole());
+ assertNotNull(response.getContent());
+ assertNotNull(response.getToolCalls());
+ assertNotNull(response.getExtraArgs());
+ assertTrue(response.getContent().length() > 0);
+ }
+
+ @Test
+ @DisplayName("Test chat with long input")
+ void testChatWithLongInput() {
+ StringBuilder longInput = new StringBuilder();
+ for (int i = 0; i < 100; i++) {
+ longInput.append("This is a long message part ").append(i).append(". ");
+ }
+
+ Map<String, String> variables = new HashMap<>();
+ variables.put("user_input", longInput.toString());
+
+ Prompt formattedPrompt =
+ new Prompt(simplePrompt.formatMessages(MessageRole.SYSTEM, variables));
+
+ ChatMessage response =
+ chatModel.chat(formattedPrompt.formatMessages(MessageRole.USER, new HashMap<>()));
+
+ assertNotNull(response);
+ assertTrue(response.getContent().length() > 0);
+ }
+}
diff --git a/api/src/test/java/org/apache/flink/agents/api/prompt/PromptTest.java b/api/src/test/java/org/apache/flink/agents/api/prompt/PromptTest.java
new file mode 100644
index 0000000..454c496
--- /dev/null
+++ b/api/src/test/java/org/apache/flink/agents/api/prompt/PromptTest.java
@@ -0,0 +1,260 @@
+/*
+ *
+ * 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.prompt;
+
+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.ResourceType;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/**
+ * Test cases for Prompt class, Tests prompt creation, variable substitution, message formatting,
+ * and different template types.
+ */
+class PromptTest {
+
+ private Prompt textPrompt;
+ private Prompt messagesPrompt;
+ private Map<String, String> variables;
+
+ @BeforeEach
+ void setUp() {
+ // Create text-based prompt template
+ String textTemplate =
+ "You are a product review analyzer, please generate a score and the dislike reasons "
+ + "(if any) for the review. The product {product_id} is {description}, and user review is '{review}'.";
+ textPrompt = new Prompt(textTemplate);
+
+ // Create message-based prompt template
+ List<ChatMessage> messageTemplate =
+ Arrays.asList(
+ new ChatMessage(
+ MessageRole.SYSTEM,
+ "You are a product review analyzer, please generate a score and the dislike reasons "
+ + "(if any) for the review."),
+ new ChatMessage(
+ MessageRole.USER,
+ "The product {product_id} is {description}, and user review is '{review}'."));
+ messagesPrompt = new Prompt(messageTemplate);
+
+ // Set up test variables
+ variables = new HashMap<>();
+ variables.put("product_id", "12345");
+ variables.put(
+ "description", "wireless noise-canceling headphones with 20-hour battery life");
+ variables.put("review", "The headphones broke after one week of use. Very poor quality");
+ }
+
+ @Test
+ @DisplayName("Test text prompt to string formatting")
+ void testTextPromptToString() {
+ String expected =
+ "You are a product review analyzer, please generate a score and the dislike reasons "
+ + "(if any) for the review. The product 12345 is wireless noise-canceling headphones with 20-hour "
+ + "battery life, and user review is 'The headphones broke after one week of use. Very poor quality'.";
+
+ String actual = textPrompt.formatString(variables);
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ @DisplayName("Test text prompt to messages formatting")
+ void testTextPromptToMessages() {
+ List<ChatMessage> messages = textPrompt.formatMessages(MessageRole.SYSTEM, variables);
+
+ assertEquals(1, messages.size());
+ assertEquals(MessageRole.SYSTEM, messages.get(0).getRole());
+ assertTrue(messages.get(0).getContent().contains("12345"));
+ assertTrue(messages.get(0).getContent().contains("wireless noise-canceling headphones"));
+ assertTrue(messages.get(0).getContent().contains("The headphones broke after one week"));
+ }
+
+ @Test
+ @DisplayName("Test messages prompt to string formatting")
+ void testMessagesPromptToString() {
+ String expected =
+ "system: You are a product review analyzer, please generate a score and the dislike reasons "
+ + "(if any) for the review.\n"
+ + "user: The product 12345 is wireless noise-canceling headphones with 20-hour battery life, "
+ + "and user review is 'The headphones broke after one week of use. Very poor quality'.";
+
+ String actual = messagesPrompt.formatString(variables);
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ @DisplayName("Test messages prompt to messages formatting")
+ void testMessagesPromptToMessages() {
+ List<ChatMessage> messages = messagesPrompt.formatMessages(MessageRole.SYSTEM, variables);
+
+ assertEquals(2, messages.size());
+
+ // Check system message
+ assertEquals(MessageRole.SYSTEM, messages.get(0).getRole());
+ assertEquals(
+ "You are a product review analyzer, please generate a score and the dislike reasons "
+ + "(if any) for the review.",
+ messages.get(0).getContent());
+
+ // Check user message with variable substitution
+ assertEquals(MessageRole.USER, messages.get(1).getRole());
+ assertTrue(messages.get(1).getContent().contains("12345"));
+ assertTrue(messages.get(1).getContent().contains("wireless noise-canceling headphones"));
+ }
+
+ @Test
+ @DisplayName("Test prompt with missing variables")
+ void testPromptWithMissingVariables() {
+ Map<String, String> incompleteVars = new HashMap<>();
+ incompleteVars.put("product_id", "12345");
+ // Missing 'description' and 'review'
+
+ String result = textPrompt.formatString(incompleteVars);
+ // Should still contain placeholder variables
+ assertTrue(result.contains("{description}"));
+ assertTrue(result.contains("{review}"));
+ assertFalse(result.contains("{product_id}")); // This should be replaced
+ }
+
+ @Test
+ @DisplayName("Test prompt with extra variables")
+ void testPromptWithExtraVariables() {
+ Map<String, String> extraVars = new HashMap<>(variables);
+ extraVars.put("extra_var", "not used");
+ extraVars.put("another_extra", "also not used");
+
+ // Should work fine, extra variables are ignored
+ String result = textPrompt.formatString(extraVars);
+ assertFalse(result.contains("{extra_var}"));
+ assertFalse(result.contains("{another_extra}"));
+ assertTrue(result.contains("12345")); // Normal variables still work
+ }
+
+ @Test
+ @DisplayName("Test prompt resource type")
+ void testPromptResourceType() {
+ assertEquals(ResourceType.PROMPT, textPrompt.getResourceType());
+ assertEquals(ResourceType.PROMPT, messagesPrompt.getResourceType());
+ }
+
+ @Test
+ @DisplayName("Test empty prompt")
+ void testEmptyPrompt() {
+ Prompt emptyPrompt = new Prompt("");
+ String result = emptyPrompt.formatString(new HashMap<>());
+ assertEquals("", result);
+
+ List<ChatMessage> messages = emptyPrompt.formatMessages(MessageRole.USER, new HashMap<>());
+ assertEquals(1, messages.size());
+ assertEquals("", messages.get(0).getContent());
+ }
+
+ @Test
+ @DisplayName("Test prompt with special characters")
+ void testPromptWithSpecialCharacters() {
+ String specialTemplate = "Handle special chars: {text} with symbols like @#$%^&*()";
+ Prompt specialPrompt = new Prompt(specialTemplate);
+
+ Map<String, String> specialVars = new HashMap<>();
+ specialVars.put("text", "Hello & Welcome!");
+
+ String result = specialPrompt.formatString(specialVars);
+ assertTrue(result.contains("Hello & Welcome!"));
+ assertTrue(result.contains("@#$%^&*()"));
+ }
+
+ @Test
+ @DisplayName("Test prompt with nested braces")
+ void testPromptWithNestedBraces() {
+ String nestedTemplate = "JSON example: {{\"key\": \"{value}\"}}";
+ Prompt nestedPrompt = new Prompt(nestedTemplate);
+
+ Map<String, String> nestedVars = new HashMap<>();
+ nestedVars.put("value", "test");
+
+ String result = nestedPrompt.formatString(nestedVars);
+ assertTrue(result.contains("{\"key\": \"test\"}"));
+ }
+
+ @Test
+ @DisplayName("Test complex conversation prompt")
+ void testComplexConversationPrompt() {
+ List<ChatMessage> conversationTemplate =
+ Arrays.asList(
+ new ChatMessage(
+ MessageRole.SYSTEM,
+ "You are {assistant_type} specialized in {domain}."),
+ new ChatMessage(MessageRole.USER, "Hello, I need help with {task}."),
+ new ChatMessage(
+ MessageRole.ASSISTANT,
+ "I'd be happy to help with {task}. Let me know what specifically you need."),
+ new ChatMessage(MessageRole.USER, "{user_request}"));
+
+ Prompt conversationPrompt = new Prompt(conversationTemplate);
+
+ Map<String, String> conversationVars = new HashMap<>();
+ conversationVars.put("assistant_type", "an AI assistant");
+ conversationVars.put("domain", "software development");
+ conversationVars.put("task", "debugging");
+ conversationVars.put("user_request", "My code is throwing a NullPointerException");
+
+ List<ChatMessage> messages =
+ conversationPrompt.formatMessages(MessageRole.SYSTEM, conversationVars);
+
+ assertEquals(4, messages.size());
+ assertTrue(messages.get(0).getContent().contains("an AI assistant"));
+ assertTrue(messages.get(0).getContent().contains("software development"));
+ assertTrue(messages.get(3).getContent().contains("NullPointerException"));
+ }
+
+ @Test
+ @DisplayName("Test string prompt serialize and deserialize")
+ void testStringPromptSerializeAndDeserialize() throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(textPrompt);
+ Prompt deserialized = mapper.readValue(json, Prompt.class);
+ Map<String, String> empty = new HashMap<>();
+ Assertions.assertEquals(textPrompt.formatString(empty), deserialized.formatString(empty));
+ }
+
+ @Test
+ @DisplayName("Test message prompt serialize and deserialize")
+ void testMessagePromptSerializeAndDeserialize() throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(messagesPrompt);
+ Prompt deserialized = mapper.readValue(json, Prompt.class);
+ Map<String, String> empty = new HashMap<>();
+ Assertions.assertEquals(
+ messagesPrompt.formatString(empty), deserialized.formatString(empty));
+ }
+}
diff --git a/examples/src/main/java/org/apache/flink/agents/examples/AgentWithResource.java b/examples/src/main/java/org/apache/flink/agents/examples/AgentWithResource.java
new file mode 100644
index 0000000..6bc3e74
--- /dev/null
+++ b/examples/src/main/java/org/apache/flink/agents/examples/AgentWithResource.java
@@ -0,0 +1,127 @@
+/*
+ * 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.examples;
+
+import org.apache.flink.agents.api.Agent;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.OutputEvent;
+import org.apache.flink.agents.api.annotation.Action;
+import org.apache.flink.agents.api.annotation.ChatModel;
+import org.apache.flink.agents.api.annotation.Tool;
+import org.apache.flink.agents.api.annotation.ToolParam;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModel;
+import org.apache.flink.agents.api.context.RunnerContext;
+import org.apache.flink.agents.api.prompt.Prompt;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.tools.BaseTool;
+import org.apache.flink.agents.plan.tools.ToolParameters;
+import org.apache.flink.agents.plan.tools.ToolResponse;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+
+public class AgentWithResource extends Agent {
+ public static class MockChatModel extends BaseChatModel {
+ private final String endpoint;
+
+ public MockChatModel(
+ BiFunction<String, ResourceType, Resource> getResource,
+ String endpoint,
+ String promptName,
+ List<String> toolNames) {
+ super(getResource, promptName, toolNames);
+ this.endpoint = endpoint;
+ }
+
+ @Override
+ public ChatMessage chat(List<ChatMessage> messages) {
+ Prompt prompt = (Prompt) getResource.apply(promptName, ResourceType.PROMPT);
+ BaseTool tool = (BaseTool) getResource.apply(toolNames.get(0), ResourceType.TOOL);
+ Map<String, Object> params = new HashMap<>();
+ params.put("a", 1);
+ params.put("b", 2);
+ params.put("operation", "add");
+ ToolParameters parameters = new ToolParameters(params);
+ ToolResponse result = tool.call(parameters);
+ String output =
+ String.format(
+ "Prompt: %s, input: %s, endpoint: %s, tool call result: %s",
+ prompt.formatString(new HashMap<>()),
+ messages.get(0).getContent(),
+ endpoint,
+ result.getResult());
+ return new ChatMessage(MessageRole.ASSISTANT, output);
+ }
+ }
+
+ @org.apache.flink.agents.api.annotation.Prompt
+ public static Prompt myPrompt() {
+ return new Prompt("This is a test prompt");
+ }
+
+ @ChatModel
+ public static Map<String, Object> myChatModel() {
+ Map<String, Object> meta = new HashMap<>();
+ meta.put(ChatModel.CHAT_MODEL_CLASS_NAME, MockChatModel.class.getName());
+ meta.put(
+ ChatModel.CHAT_MODEL_ARGUMENTS,
+ List.of("127.0.0.1", "myPrompt", List.of("calculate")));
+ meta.put(
+ ChatModel.CHAT_MODEL_ARGUMENTS_TYPES,
+ List.of(String.class.getName(), String.class.getName(), List.class.getName()));
+ return meta;
+ }
+
+ @Tool(description = "Performs basic arithmetic operations")
+ public static double calculate(
+ @ToolParam(name = "a") Double a,
+ @ToolParam(name = "b") Double b,
+ @ToolParam(name = "operation") String operation) {
+ switch (operation.toLowerCase()) {
+ case "add":
+ return a + b;
+ case "subtract":
+ return a - b;
+ case "multiply":
+ return a * b;
+ case "divide":
+ if (b == 0) throw new IllegalArgumentException("Division by zero");
+ return a / b;
+ default:
+ throw new IllegalArgumentException("Unknown operation: " + operation);
+ }
+ }
+
+ @Action(listenEvents = {InputEvent.class})
+ public static void process(InputEvent event, RunnerContext ctx) throws Exception {
+ BaseChatModel chatModel =
+ (BaseChatModel) ctx.getResource("myChatModel", ResourceType.CHAT_MODEL);
+ ChatMessage response =
+ chatModel.chat(
+ Collections.singletonList(
+ new ChatMessage(MessageRole.USER, (String) event.getInput())));
+ ctx.sendEvent(new OutputEvent(response.getContent()));
+ }
+}
diff --git a/examples/src/main/java/org/apache/flink/agents/examples/AgentWithResourceExample.java b/examples/src/main/java/org/apache/flink/agents/examples/AgentWithResourceExample.java
new file mode 100644
index 0000000..90338bb
--- /dev/null
+++ b/examples/src/main/java/org/apache/flink/agents/examples/AgentWithResourceExample.java
@@ -0,0 +1,56 @@
+/*
+ * 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.examples;
+
+import org.apache.flink.agents.api.AgentsExecutionEnvironment;
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.streaming.api.datastream.DataStream;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+
+/**
+ * Example to test MemoryObject in a complete Java Flink execution environment. This job triggers
+ * the {@link MemoryObjectAgent} to test storing and retrieving complex data structures.
+ */
+public class AgentWithResourceExample {
+
+ public static void main(String[] args) throws Exception {
+ // Create the execution environment
+ StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
+ env.setParallelism(1);
+
+ // Use two different keys (1 and 2) to show that memory is isolated per key.
+ DataStream<String> inputStream = env.fromElements("This is the test input");
+
+ // Create agents execution environment
+ AgentsExecutionEnvironment agentsEnv =
+ AgentsExecutionEnvironment.getExecutionEnvironment(env);
+
+ // Apply agent to the DataStream and use the integer itself as the key
+ DataStream<Object> outputStream =
+ agentsEnv
+ .fromDataStream(inputStream, (KeySelector<String, String>) value -> value)
+ .apply(new AgentWithResource())
+ .toDataStream();
+
+ // Print the results
+ outputStream.print();
+
+ // Execute the pipeline
+ agentsEnv.execute();
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/AgentPlan.java b/plan/src/main/java/org/apache/flink/agents/plan/AgentPlan.java
index 3efee14..d2e2f0f 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/AgentPlan.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/AgentPlan.java
@@ -21,6 +21,7 @@ package org.apache.flink.agents.plan;
import org.apache.flink.agents.api.Agent;
import org.apache.flink.agents.api.Event;
import org.apache.flink.agents.api.annotation.ChatModel;
+import org.apache.flink.agents.api.annotation.Prompt;
import org.apache.flink.agents.api.annotation.Tool;
import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceType;
@@ -30,6 +31,9 @@ import org.apache.flink.agents.plan.resourceprovider.JavaSerializableResourcePro
import org.apache.flink.agents.plan.resourceprovider.ResourceProvider;
import org.apache.flink.agents.plan.serializer.AgentPlanJsonDeserializer;
import org.apache.flink.agents.plan.serializer.AgentPlanJsonSerializer;
+import org.apache.flink.agents.plan.tools.FunctionTool;
+import org.apache.flink.agents.plan.tools.ToolMetadata;
+import org.apache.flink.agents.plan.tools.ToolMetadataFactory;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonSerialize;
@@ -40,11 +44,12 @@ import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.Callable;
+import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
/** Agent plan compiled from user defined agent. */
@@ -154,7 +159,15 @@ public class AgentPlan implements Serializable {
ResourceProvider provider = resourceProviders.get(type).get(name);
// Create resource using provider
- Resource resource = provider.provide(() -> this.getResource(name, type));
+ 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);
@@ -194,7 +207,8 @@ public class AgentPlan implements Serializable {
method.getAnnotation(org.apache.flink.agents.api.annotation.Action.class);
// Get the event types this action listens to
- Class<? extends Event>[] listenEventTypes = actionAnnotation.listenEvents();
+ Class<? extends Event>[] listenEventTypes =
+ Objects.requireNonNull(actionAnnotation).listenEvents();
// Convert event types to string names
List<String> eventTypeNames = new ArrayList<>();
@@ -229,15 +243,19 @@ public class AgentPlan implements Serializable {
for (Field field : agentClass.getDeclaredFields()) {
field.setAccessible(true); // Allow access to private fields
+ String errMsg =
+ "Failed to access field "
+ + field.getName()
+ + " in agent class "
+ + agentClass.getName();
+
// Check for @Tool annotation
if (field.isAnnotationPresent(Tool.class)) {
- Tool toolAnnotation = field.getAnnotation(Tool.class);
- String resourceName =
- toolAnnotation.name().isEmpty() ? field.getName() : toolAnnotation.name();
+ String resourceName = field.getName();
try {
Object fieldValue = field.get(agent);
- if (fieldValue != null && fieldValue instanceof Resource) {
+ if (fieldValue instanceof Resource) {
Resource resource = (Resource) fieldValue;
ResourceProvider provider =
createResourceProvider(
@@ -245,26 +263,18 @@ public class AgentPlan implements Serializable {
addResourceProvider(provider);
}
} catch (IllegalAccessException e) {
- throw new Exception(
- "Failed to access field "
- + field.getName()
- + " in agent class "
- + agentClass.getName(),
- e);
+ throw new Exception(errMsg, e);
}
}
// Check for @ChatModel annotation
if (field.isAnnotationPresent(ChatModel.class)) {
ChatModel chatModelAnnotation = field.getAnnotation(ChatModel.class);
- String resourceName =
- chatModelAnnotation.name().isEmpty()
- ? field.getName()
- : chatModelAnnotation.name();
+ String resourceName = field.getName();
try {
Object fieldValue = field.get(agent);
- if (fieldValue != null && fieldValue instanceof Resource) {
+ if (fieldValue instanceof Resource) {
Resource resource = (Resource) fieldValue;
ResourceProvider provider =
createResourceProvider(
@@ -275,15 +285,53 @@ public class AgentPlan implements Serializable {
addResourceProvider(provider);
}
} catch (IllegalAccessException e) {
- throw new Exception(
- "Failed to access field "
- + field.getName()
- + " in agent class "
- + agentClass.getName(),
- e);
+ throw new Exception(errMsg, e);
}
}
}
+
+ // Scan static methods annotated with @Tool (method-based tools)
+ for (Method method : agentClass.getDeclaredMethods()) {
+ if (method.isAnnotationPresent(Tool.class)
+ && Modifier.isStatic(method.getModifiers())) {
+ Tool toolAnn = method.getAnnotation(Tool.class);
+ String name = method.getName();
+
+ // Build parameter type names for reconstruction
+ Class<?>[] paramTypes = method.getParameterTypes();
+
+ ToolMetadata metadata = ToolMetadataFactory.fromStaticMethod(method);
+ JavaFunction javaFunction =
+ new JavaFunction(method.getDeclaringClass(), method.getName(), paramTypes);
+
+ FunctionTool tool = new FunctionTool(metadata, javaFunction);
+ JavaSerializableResourceProvider provider =
+ JavaSerializableResourceProvider.createResourceProvider(
+ name, ResourceType.TOOL, tool);
+
+ addResourceProvider(provider);
+ } else if (method.isAnnotationPresent(Prompt.class)) {
+ String promptName = method.getName();
+ SerializableResource prompt = (SerializableResource) method.invoke(null);
+
+ JavaSerializableResourceProvider provider =
+ JavaSerializableResourceProvider.createResourceProvider(
+ promptName, ResourceType.PROMPT, prompt);
+
+ addResourceProvider(provider);
+ } else if (method.isAnnotationPresent(ChatModel.class)) {
+ String chatModelName = method.getName();
+ Map<String, Object> meta = (Map<String, Object>) method.invoke(null);
+ JavaResourceProvider provider =
+ new JavaResourceProvider(
+ chatModelName,
+ ResourceType.CHAT_MODEL,
+ (String) meta.get(ChatModel.CHAT_MODEL_CLASS_NAME),
+ (List<Object>) meta.get(ChatModel.CHAT_MODEL_ARGUMENTS),
+ (List<String>) meta.get(ChatModel.CHAT_MODEL_ARGUMENTS_TYPES));
+ addResourceProvider(provider);
+ }
+ }
}
/**
@@ -291,25 +339,16 @@ public class AgentPlan implements Serializable {
* serializable.
*/
private ResourceProvider createResourceProvider(
- String name, ResourceType type, Resource resource, Class<?> agentClass) {
+ String name, ResourceType type, Resource resource, Class<?> agentClass)
+ throws Exception {
if (resource instanceof SerializableResource) {
// For serializable resources, use JavaSerializableResourceProvider
SerializableResource serializableResource = (SerializableResource) resource;
- return new JavaSerializableResourceProvider(
- name, type, agentClass.getPackage().getName(), resource.getClass().getName()) {
- @Override
- public Resource provide(Callable<Resource> getResource) throws Exception {
- return serializableResource;
- }
- };
+ return JavaSerializableResourceProvider.createResourceProvider(
+ name, type, serializableResource);
} else {
- // For non-serializable resources, use JavaResourceProvider
- return new JavaResourceProvider(name, type) {
- @Override
- public Resource provide(Callable<Resource> getResource) throws Exception {
- return resource;
- }
- };
+ throw new UnsupportedOperationException(
+ "Only support declared SerializableResource as field of Agent.");
}
}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/JavaResourceProvider.java b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/JavaResourceProvider.java
index f63f7f2..5b74a81 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/JavaResourceProvider.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/JavaResourceProvider.java
@@ -21,19 +21,53 @@ package org.apache.flink.agents.plan.resourceprovider;
import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceType;
-import java.util.concurrent.Callable;
+import java.lang.reflect.Constructor;
+import java.util.List;
+import java.util.function.BiFunction;
/** Java Resource provider that carries resource instance to be used at runtime. */
public class JavaResourceProvider extends ResourceProvider {
+ private final String className;
+ private final List<Object> parameters;
+ private final List<String> parameterTypes;
- public JavaResourceProvider(String name, ResourceType type) {
+ public JavaResourceProvider(
+ String name,
+ ResourceType type,
+ String className,
+ List<Object> parameters,
+ List<String> parameterTypes) {
super(name, type);
+ this.className = className;
+ this.parameters = parameters;
+ this.parameterTypes = parameterTypes;
}
@Override
- public Resource provide(Callable<Resource> getResource) throws Exception {
- // This provider is expected to be used with a Callable that returns a Resource instance.
- // The actual resource creation logic should be implemented in the Callable.
- return getResource.call();
+ public Resource provide(BiFunction<String, ResourceType, Resource> getResource)
+ throws Exception {
+ Class<?> clazz = Class.forName(className);
+ Class<?>[] types = new Class[parameters.size() + 1];
+ Object[] mergeParameters = new Object[parameters.size() + 1];
+ mergeParameters[0] = getResource;
+ types[0] = BiFunction.class;
+ for (int i = 1; i < mergeParameters.length; i++) {
+ types[i] = Class.forName(parameterTypes.get(i - 1));
+ mergeParameters[i] = parameters.get(i - 1);
+ }
+ Constructor<?> constructor = clazz.getConstructor(types);
+ return (Resource) constructor.newInstance(mergeParameters);
+ }
+
+ public List<Object> getParameters() {
+ return parameters;
+ }
+
+ public List<String> getParameterTypes() {
+ return parameterTypes;
+ }
+
+ public String getClassName() {
+ return className;
}
}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/JavaSerializableResourceProvider.java b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/JavaSerializableResourceProvider.java
index bc72799..9200cfe 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/JavaSerializableResourceProvider.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/JavaSerializableResourceProvider.java
@@ -21,8 +21,11 @@ package org.apache.flink.agents.plan.resourceprovider;
import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceType;
import org.apache.flink.agents.api.resource.SerializableResource;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnore;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
-import java.util.concurrent.Callable;
+import java.util.function.BiFunction;
/**
* Serializable Resource Provider for Java-based resources.
@@ -31,21 +34,56 @@ import java.util.concurrent.Callable;
* execution.
*/
public class JavaSerializableResourceProvider extends SerializableResourceProvider {
+ @JsonIgnore private SerializableResource resource;
+
+ private final String serializedResource;
+ private static final ObjectMapper objectMapper = new ObjectMapper();
+
+ public JavaSerializableResourceProvider(
+ String name,
+ ResourceType type,
+ String module,
+ String clazz,
+ String serializedResource) {
+ super(name, type, module, clazz);
+ this.serializedResource = serializedResource;
+ }
public JavaSerializableResourceProvider(
- String name, ResourceType type, String module, String clazz) {
+ String name,
+ ResourceType type,
+ String module,
+ String clazz,
+ SerializableResource resource,
+ String serializedResource) {
super(name, type, module, clazz);
+ this.resource = resource;
+ this.serializedResource = serializedResource;
+ }
+
+ public static JavaSerializableResourceProvider createResourceProvider(
+ String name, ResourceType type, SerializableResource resource)
+ throws JsonProcessingException {
+ return new JavaSerializableResourceProvider(
+ name,
+ type,
+ resource.getClass().getPackageName(),
+ resource.getClass().getName(),
+ resource,
+ objectMapper.writeValueAsString(resource));
+ }
+
+ public String getSerializedResource() {
+ return serializedResource;
}
@Override
- public Resource provide(Callable<Resource> getResource) throws Exception {
- // This provider is expected to be used with a Callable that returns a SerializableResource
- // instance.
- // The actual resource creation logic should be implemented in the Callable.
- Resource resource = getResource.call();
- if (!(resource instanceof SerializableResource)) {
- throw new IllegalArgumentException(
- "Expected a SerializableResource, but got: " + resource.getClass().getName());
+ public Resource provide(BiFunction<String, ResourceType, Resource> getResource)
+ throws Exception {
+ if (resource == null) {
+ resource =
+ (SerializableResource)
+ objectMapper.readValue(serializedResource, Class.forName(getClazz()));
}
return resource;
}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/PythonResourceProvider.java b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/PythonResourceProvider.java
index fd39807..329a2db 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/PythonResourceProvider.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/PythonResourceProvider.java
@@ -23,7 +23,7 @@ import org.apache.flink.agents.api.resource.ResourceType;
import java.util.Map;
import java.util.Objects;
-import java.util.concurrent.Callable;
+import java.util.function.BiFunction;
/**
* Python Resource provider that carries resource metadata to create Resource objects at runtime.
@@ -61,7 +61,8 @@ public class PythonResourceProvider extends ResourceProvider {
}
@Override
- public Resource provide(Callable<Resource> getResource) throws Exception {
+ public Resource provide(BiFunction<String, ResourceType, Resource> getResource)
+ throws Exception {
// TODO: Implement Python resource creation logic
// This would typically involve calling into Python runtime to create the
// resource
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/PythonSerializableResourceProvider.java b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/PythonSerializableResourceProvider.java
index c1d218f..d39cb37 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/PythonSerializableResourceProvider.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/PythonSerializableResourceProvider.java
@@ -24,7 +24,7 @@ import org.apache.flink.agents.api.resource.SerializableResource;
import java.util.Map;
import java.util.Objects;
-import java.util.concurrent.Callable;
+import java.util.function.BiFunction;
/**
* Resource Provider that carries Resource object or serialized object.
@@ -66,7 +66,8 @@ public class PythonSerializableResourceProvider extends SerializableResourceProv
}
@Override
- public Resource provide(Callable<Resource> getResource) throws Exception {
+ public Resource provide(BiFunction<String, ResourceType, Resource> getResource)
+ throws Exception {
// TODO: Implement Python resource deserialization logic
// This would typically involve calling into Python runtime to deserialize the
// resource
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/ResourceProvider.java b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/ResourceProvider.java
index 911cc62..2e819d2 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/ResourceProvider.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/resourceprovider/ResourceProvider.java
@@ -25,7 +25,7 @@ import org.apache.flink.agents.plan.serializer.ResourceProviderJsonSerializer;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonSerialize;
-import java.util.concurrent.Callable;
+import java.util.function.BiFunction;
/**
* Resource provider that carries resource metadata to create Resource objects at runtime.
@@ -70,5 +70,6 @@ public abstract class ResourceProvider implements java.io.Serializable {
* @return the created resource
* @throws Exception if the resource cannot be created
*/
- public abstract Resource provide(Callable<Resource> getResource) throws Exception;
+ public abstract Resource provide(BiFunction<String, ResourceType, Resource> getResource)
+ throws Exception;
}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/serializer/ResourceProviderJsonDeserializer.java b/plan/src/main/java/org/apache/flink/agents/plan/serializer/ResourceProviderJsonDeserializer.java
index d221a53..681896f 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/serializer/ResourceProviderJsonDeserializer.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/serializer/ResourceProviderJsonDeserializer.java
@@ -27,6 +27,7 @@ import org.apache.flink.agents.plan.resourceprovider.ResourceProvider;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.DeserializationContext;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
@@ -40,6 +41,7 @@ import java.util.Map;
* implementation.
*/
public class ResourceProviderJsonDeserializer extends StdDeserializer<ResourceProvider> {
+ private static ObjectMapper mapper = new ObjectMapper();
public ResourceProviderJsonDeserializer() {
super(ResourceProvider.class);
@@ -50,22 +52,23 @@ public class ResourceProviderJsonDeserializer extends StdDeserializer<ResourcePr
JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
- String providerType = node.get("__resource_provider_type__").asText();
+ JsonNode marker = node.get("__resource_provider_type__");
+ if (marker == null) {
+ throw new IOException("Missing __resource_provider_type__ in ResourceProvider JSON");
+ }
+ String providerType = marker.asText();
- ResourceProvider provider;
if (PythonResourceProvider.class.getSimpleName().equals(providerType)) {
- provider = deserializePythonResourceProvider(node);
+ return deserializePythonResourceProvider(node);
} else if (PythonSerializableResourceProvider.class.getSimpleName().equals(providerType)) {
- provider = deserializePythonSerializableResourceProvider(node);
+ return deserializePythonSerializableResourceProvider(node);
} else if (JavaResourceProvider.class.getSimpleName().equals(providerType)) {
- provider = deserializeJavaResourceProvider(node);
+ return deserializeJavaResourceProvider(node);
} else if (JavaSerializableResourceProvider.class.getSimpleName().equals(providerType)) {
- provider = deserializeJavaSerializableResourceProvider(node);
+ return deserializeJavaSerializableResourceProvider(node);
} else {
throw new IOException("Unsupported resource provider type: " + providerType);
}
-
- return provider;
}
private PythonResourceProvider deserializePythonResourceProvider(JsonNode node) {
@@ -102,7 +105,27 @@ public class ResourceProviderJsonDeserializer extends StdDeserializer<ResourcePr
private JavaResourceProvider deserializeJavaResourceProvider(JsonNode node) {
String name = node.get("name").asText();
String type = node.get("type").asText();
- return new JavaResourceProvider(name, ResourceType.fromValue(type));
+ String className = node.get("className").asText();
+ List<Object> parameters = new ArrayList<>();
+ List<String> parameterTypes = new ArrayList<>();
+
+ // TODO: There is a general requirement that support json serialize/deserialize arbitrary
+ // parameters when serialize/deserialize AgentPlan. The current implementation is not
+ // elegant, we should unify and refactor later.
+ JsonNode parametersNode = node.get("parameters");
+ JsonNode parameterTypesNode = node.get("parameterTypes");
+ try {
+ for (int i = 0; i < parametersNode.size(); i++) {
+ String clazzName = parameterTypesNode.get(i).asText();
+ parameterTypes.add(clazzName);
+ Class<?> clazz = Class.forName(clazzName);
+ parameters.add(mapper.treeToValue(parametersNode.get(i), clazz));
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ return new JavaResourceProvider(
+ name, ResourceType.fromValue(type), className, parameters, parameterTypes);
}
private JavaSerializableResourceProvider deserializeJavaSerializableResourceProvider(
@@ -111,8 +134,9 @@ public class ResourceProviderJsonDeserializer extends StdDeserializer<ResourcePr
String type = node.get("type").asText();
String module = node.get("module").asText();
String clazz = node.get("clazz").asText();
+ String serializedResource = node.get("serializedResource").asText();
return new JavaSerializableResourceProvider(
- name, ResourceType.fromValue(type), module, clazz);
+ name, ResourceType.fromValue(type), module, clazz, serializedResource);
}
private Object parseJsonNode(JsonNode node) {
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/serializer/ResourceProviderJsonSerializer.java b/plan/src/main/java/org/apache/flink/agents/plan/serializer/ResourceProviderJsonSerializer.java
index 29a5e32..acebefd 100644
--- a/plan/src/main/java/org/apache/flink/agents/plan/serializer/ResourceProviderJsonSerializer.java
+++ b/plan/src/main/java/org/apache/flink/agents/plan/serializer/ResourceProviderJsonSerializer.java
@@ -28,6 +28,7 @@ import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.Serialize
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
+import java.util.List;
/**
* Custom serializer for {@link ResourceProvider} that handles the serialization of different
@@ -53,15 +54,10 @@ public class ResourceProviderJsonSerializer extends StdSerializer<ResourceProvid
serializePythonSerializableResourceProvider(
jsonGenerator, (PythonSerializableResourceProvider) resourceProvider);
} else if (resourceProvider instanceof JavaResourceProvider) {
- jsonGenerator.writeStringField("name", resourceProvider.getName());
- jsonGenerator.writeStringField("type", resourceProvider.getType().getValue());
+ serializeJavaResourceProvider(jsonGenerator, (JavaResourceProvider) resourceProvider);
} else if (resourceProvider instanceof JavaSerializableResourceProvider) {
- jsonGenerator.writeStringField("name", resourceProvider.getName());
- jsonGenerator.writeStringField("type", resourceProvider.getType().getValue());
- jsonGenerator.writeStringField(
- "module", ((JavaSerializableResourceProvider) resourceProvider).getModule());
- jsonGenerator.writeStringField(
- "clazz", ((JavaSerializableResourceProvider) resourceProvider).getClazz());
+ serializeJavaSerializableResourceProvider(
+ jsonGenerator, (JavaSerializableResourceProvider) resourceProvider);
} else {
throw new IllegalArgumentException(
"Unsupported resource provider type: " + resourceProvider.getClass().getName());
@@ -119,4 +115,38 @@ public class ResourceProviderJsonSerializer extends StdSerializer<ResourceProvid
gen.writeStringField("__resource_provider_type__", "PythonSerializableResourceProvider");
}
+
+ private void serializeJavaSerializableResourceProvider(
+ JsonGenerator gen, JavaSerializableResourceProvider provider) throws IOException {
+ gen.writeStringField("name", provider.getName());
+ gen.writeStringField("type", provider.getType().getValue());
+ gen.writeStringField("module", provider.getModule());
+ gen.writeStringField("clazz", provider.getClazz());
+ gen.writeStringField("serializedResource", provider.getSerializedResource());
+ gen.writeStringField(
+ "__resource_provider_type__",
+ JavaSerializableResourceProvider.class.getSimpleName());
+ }
+
+ private void serializeJavaResourceProvider(JsonGenerator gen, JavaResourceProvider provider)
+ throws IOException {
+ gen.writeStringField("name", provider.getName());
+ gen.writeStringField("type", provider.getType().getValue());
+ gen.writeStringField("className", provider.getClassName());
+ List<Object> parameters = provider.getParameters();
+ gen.writeFieldName("parameters");
+ gen.writeStartArray();
+ for (Object parameter : parameters) {
+ gen.writeObject(parameter);
+ }
+ gen.writeEndArray();
+ gen.writeFieldName("parameterTypes");
+ gen.writeStartArray();
+ for (String type : provider.getParameterTypes()) {
+ gen.writeString(type);
+ }
+ gen.writeEndArray();
+ gen.writeStringField(
+ "__resource_provider_type__", JavaResourceProvider.class.getSimpleName());
+ }
}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/BaseTool.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/BaseTool.java
new file mode 100644
index 0000000..0f17ebe
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/BaseTool.java
@@ -0,0 +1,62 @@
+/*
+ * 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.tools;
+
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.resource.SerializableResource;
+
+/**
+ * Simplified base class for all tools. Focus on essential tool functionality without
+ * overcomplicated features.
+ */
+public abstract class BaseTool extends SerializableResource {
+
+ protected final ToolMetadata metadata;
+
+ protected BaseTool(ToolMetadata metadata) {
+ this.metadata = java.util.Objects.requireNonNull(metadata, "metadata cannot be null");
+ }
+
+ /** Get the metadata of this tool. */
+ public final ToolMetadata getMetadata() {
+ return metadata;
+ }
+
+ /** Return resource type of class. */
+ @Override
+ public final ResourceType getResourceType() {
+ return ResourceType.TOOL;
+ }
+
+ /** Return tool type of class. */
+ public abstract ToolType getToolType();
+
+ /** Call the tool with parameters. This is the core method for tool execution. */
+ public abstract ToolResponse call(ToolParameters parameters);
+
+ /** Get the tool name from metadata. */
+ public final String getName() {
+ return metadata.getName();
+ }
+
+ /** Get the tool description from metadata. */
+ public final String getDescription() {
+ return metadata.getDescription();
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/FunctionTool.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/FunctionTool.java
new file mode 100644
index 0000000..be545d1
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/FunctionTool.java
@@ -0,0 +1,136 @@
+/*
+ *
+ * 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.tools;
+
+import org.apache.flink.agents.api.annotation.Tool;
+import org.apache.flink.agents.api.annotation.ToolParam;
+import org.apache.flink.agents.plan.Function;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.tools.serializer.FunctionToolJsonDeserializer;
+import org.apache.flink.agents.plan.tools.serializer.FunctionToolJsonSerializer;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.annotation.JsonSerialize;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Parameter;
+
+/**
+ * Plan-level implementation of a tool that wraps a static Java method. This belongs in the plan
+ * module as it handles the implementation logic for converting user-defined @Tool methods into
+ * executable tools.
+ */
+@JsonSerialize(using = FunctionToolJsonSerializer.class)
+@JsonDeserialize(using = FunctionToolJsonDeserializer.class)
+public class FunctionTool extends BaseTool {
+
+ private final Function function;
+
+ /** Create a FunctionTool from ToolMetadata and Function */
+ public FunctionTool(ToolMetadata metadata, Function function) {
+ super(metadata);
+ this.function = function;
+ }
+
+ /** Create a FunctionTool from a static method annotated with @Tool */
+ public static FunctionTool fromStaticMethod(Method method) throws Exception {
+ if (!Modifier.isStatic(method.getModifiers())) {
+ throw new IllegalArgumentException(
+ "FunctionTool only supports static methods. Method: " + method.getName());
+ }
+
+ Tool toolAnnotation = method.getAnnotation(Tool.class);
+ String name = method.getName();
+ String description = toolAnnotation != null ? toolAnnotation.description() : "";
+
+ ToolMetadata metadata =
+ new ToolMetadata(name, description, SchemaUtils.generateSchema(method));
+ JavaFunction javaFunction =
+ new JavaFunction(
+ method.getDeclaringClass(), method.getName(), method.getParameterTypes());
+
+ return new FunctionTool(metadata, javaFunction);
+ }
+
+ /**
+ * Create a FunctionTool from a static method with explicit description. This does not require a
+ * method-level @Tool annotation.
+ */
+ public static FunctionTool fromStaticMethod(String description, Method method)
+ throws Exception {
+ if (!Modifier.isStatic(method.getModifiers())) {
+ throw new IllegalArgumentException(
+ "FunctionTool only supports static methods. Method: " + method.getName());
+ }
+ ToolMetadata metadata =
+ new ToolMetadata(
+ method.getName(),
+ description != null ? description : "",
+ SchemaUtils.generateSchema(method));
+ JavaFunction javaFunction =
+ new JavaFunction(
+ method.getDeclaringClass(), method.getName(), method.getParameterTypes());
+ return new FunctionTool(metadata, javaFunction);
+ }
+
+ @Override
+ public ToolType getToolType() {
+ return ToolType.FUNCTION;
+ }
+
+ @Override
+ public ToolResponse call(ToolParameters parameters) {
+ try {
+ // Map ToolParameters to method arguments by name and type
+ Method method = ((JavaFunction) function).getMethod();
+ Parameter[] methodParams = method.getParameters();
+ Object[] args = new Object[methodParams.length];
+ for (int i = 0; i < methodParams.length; i++) {
+ Parameter p = methodParams[i];
+ String paramName = p.getName();
+ if (p.isAnnotationPresent(ToolParam.class)) {
+ ToolParam ann = p.getAnnotation(ToolParam.class);
+ if (!ann.name().isEmpty()) {
+ paramName = ann.name();
+ }
+ }
+ Object value = parameters.getParameter(paramName, p.getType());
+ if (value == null && p.isAnnotationPresent(ToolParam.class)) {
+ ToolParam ann = p.getAnnotation(ToolParam.class);
+ if (ann.required() && ann.defaultValue().isEmpty()) {
+ throw new IllegalArgumentException(
+ "Missing required parameter: " + paramName);
+ }
+ }
+ args[i] = value;
+ }
+
+ Object result = function.call(args);
+ return ToolResponse.success(result);
+ } catch (Exception e) {
+ return ToolResponse.error(e);
+ }
+ }
+
+ public Function getFunction() {
+ return function;
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/SchemaUtils.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/SchemaUtils.java
new file mode 100644
index 0000000..f1210f8
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/SchemaUtils.java
@@ -0,0 +1,89 @@
+/*
+ *
+ * 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.tools;
+
+import org.apache.flink.agents.api.annotation.ToolParam;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Parameter;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+public class SchemaUtils {
+ /** Generate JSON schema from method signature for tool parameters. */
+ public static String generateSchema(Method method) throws JsonProcessingException {
+ ObjectMapper mapper = new ObjectMapper();
+ Map<String, Object> schema = new HashMap<>();
+ schema.put("type", "object");
+
+ Map<String, Object> properties = new HashMap<>();
+ List<String> required = new java.util.ArrayList<>();
+
+ Parameter[] parameters = method.getParameters();
+ for (Parameter param : parameters) {
+ String paramName = param.getName();
+
+ // Check for custom parameter name from annotation
+ if (param.isAnnotationPresent(ToolParam.class)) {
+ ToolParam toolParam = param.getAnnotation(ToolParam.class);
+ if (!Objects.requireNonNull(toolParam).name().isEmpty()) {
+ paramName = toolParam.name();
+ }
+ if (toolParam.required()) {
+ required.add(paramName);
+ }
+ }
+
+ Map<String, Object> paramSchema = getParamSchema(param);
+
+ properties.put(paramName, paramSchema);
+ }
+
+ schema.put("properties", properties);
+ if (!required.isEmpty()) {
+ schema.put("required", required);
+ }
+
+ return mapper.writeValueAsString(schema);
+ }
+
+ private static Map<String, Object> getParamSchema(Parameter param) {
+ Map<String, Object> paramSchema = new HashMap<>();
+ Class<?> paramType = param.getType();
+
+ if (paramType == String.class) {
+ paramSchema.put("type", "string");
+ } else if (paramType == int.class || paramType == Integer.class) {
+ paramSchema.put("type", "integer");
+ } else if (paramType == double.class || paramType == Double.class) {
+ paramSchema.put("type", "number");
+ } else if (paramType == boolean.class || paramType == Boolean.class) {
+ paramSchema.put("type", "boolean");
+ } else {
+ paramSchema.put("type", "object");
+ }
+ return paramSchema;
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolMetadata.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolMetadata.java
new file mode 100644
index 0000000..581c7ca
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolMetadata.java
@@ -0,0 +1,88 @@
+/*
+ * 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.tools;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonCreator;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonIgnoreProperties;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonProperty;
+
+import java.util.Objects;
+
+/**
+ * API-level metadata for a tool. This stays in the API module as it's a core data model that users
+ * interact with. Implementation logic for creating metadata from methods is handled in the plan
+ * module.
+ */
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class ToolMetadata {
+ private static final String FIELD_NAME = "name";
+ private static final String FIELD_DESCRIPTION = "description";
+ private static final String FIELD_INPUT_SCHEMA = "inputSchema";
+
+ @JsonProperty(FIELD_NAME)
+ private final String name;
+
+ @JsonProperty(FIELD_DESCRIPTION)
+ private final String description;
+
+ @JsonProperty(FIELD_INPUT_SCHEMA)
+ private final String inputSchema;
+
+ @JsonCreator
+ public ToolMetadata(
+ @JsonProperty(FIELD_NAME) String name,
+ @JsonProperty(FIELD_DESCRIPTION) String description,
+ @JsonProperty(FIELD_INPUT_SCHEMA) String inputSchema) {
+ this.name = Objects.requireNonNull(name, "name cannot be null");
+ this.description = Objects.requireNonNull(description, "description cannot be null");
+ this.inputSchema = Objects.requireNonNull(inputSchema, "inputSchema cannot be null");
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getDescription() {
+ return description;
+ }
+
+ public String getInputSchema() {
+ return inputSchema;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ ToolMetadata that = (ToolMetadata) o;
+ return Objects.equals(name, that.name)
+ && Objects.equals(description, that.description)
+ && Objects.equals(inputSchema, that.inputSchema);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(name, description, inputSchema);
+ }
+
+ @Override
+ public String toString() {
+ return String.format("ToolMetadata{name='%s', description='%s'}", name, description);
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolMetadataFactory.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolMetadataFactory.java
new file mode 100644
index 0000000..f9c0526
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolMetadataFactory.java
@@ -0,0 +1,52 @@
+/*
+ *
+ * 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.tools;
+
+import org.apache.flink.agents.api.annotation.Tool;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonProcessingException;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+/**
+ * Plan-level utility for creating ToolMetadata from annotated methods. it handles the
+ * implementation logic for converting @Tool annotations into ToolMetadata objects.
+ */
+public class ToolMetadataFactory {
+
+ /** Create ToolMetadata from a static method annotated with @Tool. */
+ public static ToolMetadata fromStaticMethod(Method method) throws JsonProcessingException {
+ if (!Modifier.isStatic(method.getModifiers())) {
+ throw new IllegalArgumentException("Only static methods are supported");
+ }
+
+ Tool toolAnnotation = method.getAnnotation(Tool.class);
+ if (toolAnnotation == null) {
+ throw new IllegalArgumentException("Method must be annotated with @Tool");
+ }
+
+ String name = method.getName();
+ String description = toolAnnotation.description();
+ String schema = SchemaUtils.generateSchema(method);
+
+ return new ToolMetadata(name, description, schema);
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolParameters.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolParameters.java
new file mode 100644
index 0000000..c33db89
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolParameters.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.plan.tools;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/** Container for tool parameters with type-safe parameter retrieval. */
+public class ToolParameters {
+
+ private final Map<String, Object> parameters;
+
+ public ToolParameters() {
+ this.parameters = new HashMap<>();
+ }
+
+ public ToolParameters(Map<String, Object> parameters) {
+ this.parameters = parameters != null ? new HashMap<>(parameters) : new HashMap<>();
+ }
+
+ /** Check if a parameter exists. */
+ public boolean hasParameter(String name) {
+ return parameters.containsKey(name);
+ }
+
+ /** Get a parameter with type conversion. */
+ @SuppressWarnings("unchecked")
+ public <T> T getParameter(String name, Class<T> type) {
+ Object value = parameters.get(name);
+ if (value == null) {
+ return null;
+ }
+
+ // Direct type match
+ if (type.isInstance(value)) {
+ return (T) value;
+ }
+
+ // Type conversion for common cases
+ return convertValue(value, type);
+ }
+
+ /** Get raw parameter value. */
+ public Object getParameter(String name) {
+ return parameters.get(name);
+ }
+
+ public List<Object> getParameters() {
+ return List.copyOf(parameters.values());
+ }
+
+ /** Add a parameter. */
+ public void addParameter(String name, Object value) {
+ parameters.put(name, value);
+ }
+
+ /** Get all parameter names. */
+ public Set<String> getParameterNames() {
+ return parameters.keySet();
+ }
+
+ /** Get the number of parameters. */
+ public int size() {
+ return parameters.size();
+ }
+
+ /** Check if parameters are empty. */
+ public boolean isEmpty() {
+ return parameters.isEmpty();
+ }
+
+ @SuppressWarnings("unchecked")
+ private <T> T convertValue(Object value, Class<T> type) {
+ String stringValue = value.toString();
+
+ if (type == String.class) {
+ return (T) stringValue;
+ } else if (type == Integer.class || type == int.class) {
+ return (T) Integer.valueOf(stringValue);
+ } else if (type == Long.class || type == long.class) {
+ return (T) Long.valueOf(stringValue);
+ } else if (type == Double.class || type == double.class) {
+ return (T) Double.valueOf(stringValue);
+ } else if (type == Float.class || type == float.class) {
+ return (T) Float.valueOf(stringValue);
+ } else if (type == Boolean.class || type == boolean.class) {
+ return (T) Boolean.valueOf(stringValue);
+ } else if (type == Byte.class || type == byte.class) {
+ return (T) Byte.valueOf(stringValue);
+ } else if (type == Short.class || type == short.class) {
+ return (T) Short.valueOf(stringValue);
+ }
+
+ throw new IllegalArgumentException(
+ "Cannot convert parameter value to type " + type.getSimpleName());
+ }
+
+ @Override
+ public String toString() {
+ return "ToolParameters{" + parameters + "}";
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolResponse.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolResponse.java
new file mode 100644
index 0000000..25d4731
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolResponse.java
@@ -0,0 +1,191 @@
+/*
+ * 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.tools;
+
+import java.util.Objects;
+
+/**
+ * Represents the response from a tool execution. Contains the result data, success status, and any
+ * error information.
+ */
+public class ToolResponse {
+
+ private final Object result;
+ private final boolean success;
+ private final String error;
+ private final long executionTimeMs;
+ private final String toolName;
+
+ private ToolResponse(
+ Object result, boolean success, String error, long executionTimeMs, String toolName) {
+ this.result = result;
+ this.success = success;
+ this.error = error;
+ this.executionTimeMs = executionTimeMs;
+ this.toolName = toolName;
+ }
+
+ /** Create a successful response with result. */
+ public static ToolResponse success(Object result) {
+ return new ToolResponse(result, true, null, 0, null);
+ }
+
+ /** Create a successful response with result and execution time. */
+ public static ToolResponse success(Object result, long executionTimeMs) {
+ return new ToolResponse(result, true, null, executionTimeMs, null);
+ }
+
+ /** Create a successful response with result, execution time, and tool name. */
+ public static ToolResponse success(Object result, long executionTimeMs, String toolName) {
+ return new ToolResponse(result, true, null, executionTimeMs, toolName);
+ }
+
+ /** Create an error response. */
+ public static ToolResponse error(String error) {
+ return new ToolResponse(
+ null, false, Objects.requireNonNull(error, "error cannot be null"), 0, null);
+ }
+
+ /** Create an error response with execution time. */
+ public static ToolResponse error(String error, long executionTimeMs) {
+ return new ToolResponse(
+ null,
+ false,
+ Objects.requireNonNull(error, "error cannot be null"),
+ executionTimeMs,
+ null);
+ }
+
+ /** Create an error response with execution time and tool name. */
+ public static ToolResponse error(String error, long executionTimeMs, String toolName) {
+ return new ToolResponse(
+ null,
+ false,
+ Objects.requireNonNull(error, "error cannot be null"),
+ executionTimeMs,
+ toolName);
+ }
+
+ /** Create an error response from an exception. */
+ public static ToolResponse error(Throwable throwable) {
+ String errorMessage = throwable.getMessage();
+ if (errorMessage == null || errorMessage.isEmpty()) {
+ errorMessage = throwable.getClass().getSimpleName();
+ }
+ return new ToolResponse(null, false, errorMessage, 0, null);
+ }
+
+ /** Create an error response from an exception with execution time. */
+ public static ToolResponse error(Throwable throwable, long executionTimeMs) {
+ String errorMessage = throwable.getMessage();
+ if (errorMessage == null || errorMessage.isEmpty()) {
+ errorMessage = throwable.getClass().getSimpleName();
+ }
+ return new ToolResponse(null, false, errorMessage, executionTimeMs, null);
+ }
+
+ /** Get the result of the tool execution. */
+ public Object getResult() {
+ return result;
+ }
+
+ /** Get the result with type casting. */
+ @SuppressWarnings("unchecked")
+ public <T> T getResult(Class<T> type) {
+ if (result == null) {
+ return null;
+ }
+
+ if (type.isAssignableFrom(result.getClass())) {
+ return (T) result;
+ }
+
+ throw new ClassCastException(
+ String.format(
+ "Cannot cast result of type %s to %s",
+ result.getClass().getSimpleName(), type.getSimpleName()));
+ }
+
+ /** Check if the tool execution was successful. */
+ public boolean isSuccess() {
+ return success;
+ }
+
+ /** Check if the tool execution failed. */
+ public boolean isError() {
+ return !success;
+ }
+
+ /** Get the error message if the execution failed. */
+ public String getError() {
+ return error;
+ }
+
+ /** Get the execution time in milliseconds. */
+ public long getExecutionTimeMs() {
+ return executionTimeMs;
+ }
+
+ /** Get the tool name if available. */
+ public String getToolName() {
+ return toolName;
+ }
+
+ /** Get the result as a string representation. */
+ public String getResultAsString() {
+ if (result == null) {
+ return null;
+ }
+ return result.toString();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ ToolResponse that = (ToolResponse) o;
+ return success == that.success
+ && executionTimeMs == that.executionTimeMs
+ && Objects.equals(result, that.result)
+ && Objects.equals(error, that.error)
+ && Objects.equals(toolName, that.toolName);
+ }
+
+ @Override
+ public int hashCode() {
+ return Objects.hash(result, success, error, executionTimeMs, toolName);
+ }
+
+ @Override
+ public String toString() {
+ if (success) {
+ return String.format(
+ "ToolResponse{success=true, result=%s, executionTime=%dms%s}",
+ result,
+ executionTimeMs,
+ toolName != null ? ", toolName='" + toolName + "'" : "");
+ } else {
+ return String.format(
+ "ToolResponse{success=false, error='%s', executionTime=%dms%s}",
+ error,
+ executionTimeMs,
+ toolName != null ? ", toolName='" + toolName + "'" : "");
+ }
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolType.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolType.java
new file mode 100644
index 0000000..98fa0b3
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/ToolType.java
@@ -0,0 +1,58 @@
+/*
+ * 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.tools;
+
+/** Enumeration of tool types supported by Flink-Agents. */
+public enum ToolType {
+ /** Tool provided by the model provider (e.g., "web_search_preview" of OpenAI models). */
+ MODEL_BUILT_IN("model_built_in"),
+
+ /** Python/Java function defined by user. */
+ FUNCTION("function"),
+
+ /** Remote function indicated by name. */
+ REMOTE_FUNCTION("remote_function"),
+
+ /** Tool provided by MCP server. */
+ MCP("mcp");
+
+ private final String value;
+
+ ToolType(String value) {
+ this.value = value;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public String toString() {
+ return value;
+ }
+
+ public static ToolType fromString(String value) {
+ for (ToolType type : values()) {
+ if (type.value.equalsIgnoreCase(value)) {
+ return type;
+ }
+ }
+ throw new IllegalArgumentException("Unknown tool type: " + value);
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/serializer/FunctionToolJsonDeserializer.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/serializer/FunctionToolJsonDeserializer.java
new file mode 100644
index 0000000..85dd66a
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/serializer/FunctionToolJsonDeserializer.java
@@ -0,0 +1,95 @@
+/*
+ * 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.tools.serializer;
+
+import org.apache.flink.agents.plan.Function;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.tools.FunctionTool;
+import org.apache.flink.agents.plan.tools.ToolMetadata;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.DeserializationContext;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+
+import java.io.IOException;
+
+/**
+ * Custom deserializer for {@link FunctionTool} that handles the deserialization of the metadata and
+ * function.
+ */
+public class FunctionToolJsonDeserializer extends StdDeserializer<FunctionTool> {
+
+ public FunctionToolJsonDeserializer() {
+ super(FunctionTool.class);
+ }
+
+ @Override
+ public FunctionTool deserialize(
+ JsonParser jsonParser, DeserializationContext deserializationContext)
+ throws IOException {
+ JsonNode node = jsonParser.getCodec().readTree(jsonParser);
+ ToolMetadata metadata =
+ new ObjectMapper().treeToValue(node.get("metadata"), ToolMetadata.class);
+
+ // Deserialize the function based on its type
+ JsonNode functionNode = node.get("function");
+ String funcType = functionNode.get("func_type").asText();
+ Function func;
+ if (JavaFunction.class.getSimpleName().equals(funcType)) {
+ func = deserializeJavaFunction(functionNode);
+ } else if (PythonFunction.class.getSimpleName().equals(funcType)) {
+ func = deserializePythonFunction(functionNode);
+ } else {
+ throw new IOException("Unsupported function type: " + funcType);
+ }
+
+ return new FunctionTool(metadata, func);
+ }
+
+ private PythonFunction deserializePythonFunction(JsonNode execNode) {
+ String module = execNode.get("module").asText();
+ String qualName = execNode.get("qualname").asText();
+ return new PythonFunction(module, qualName);
+ }
+
+ private JavaFunction deserializeJavaFunction(JsonNode execNode) throws IOException {
+ String qualName = execNode.get("qualname").asText();
+ String methodName = execNode.get("method_name").asText();
+ Class<?>[] parameterTypes = new Class<?>[execNode.get("parameter_types").size()];
+ for (int i = 0; i < parameterTypes.length; i++) {
+ try {
+ String parameterTypeName = execNode.get("parameter_types").get(i).asText();
+ parameterTypes[i] = Class.forName(parameterTypeName);
+ } catch (ClassNotFoundException e) {
+ throw new IOException("Failed to deserialize parameter type", e);
+ }
+ }
+ try {
+ return new JavaFunction(qualName, methodName, parameterTypes);
+ } catch (Exception e) {
+ throw new RuntimeException(
+ String.format(
+ "Failed to create JavaFunction with qualName \"%s\" and method name \"%s\"",
+ qualName, methodName),
+ e);
+ }
+ }
+}
diff --git a/plan/src/main/java/org/apache/flink/agents/plan/tools/serializer/FunctionToolJsonSerializer.java b/plan/src/main/java/org/apache/flink/agents/plan/tools/serializer/FunctionToolJsonSerializer.java
new file mode 100644
index 0000000..ad6461d
--- /dev/null
+++ b/plan/src/main/java/org/apache/flink/agents/plan/tools/serializer/FunctionToolJsonSerializer.java
@@ -0,0 +1,90 @@
+/*
+ * 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.tools.serializer;
+
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.tools.FunctionTool;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonGenerator;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.SerializerProvider;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ser.std.StdSerializer;
+
+import java.io.IOException;
+
+/**
+ * Custom serializer for {@link FunctionTool} that handles the serialization of the metadata and
+ * function.
+ */
+public class FunctionToolJsonSerializer extends StdSerializer<FunctionTool> {
+ private static final String PYTHON_FUNC_TYPE = "PythonFunction";
+ private static final String JAVA_FUNC_TYPE = "JavaFunction";
+
+ public FunctionToolJsonSerializer() {
+ super(FunctionTool.class);
+ }
+
+ @Override
+ public void serialize(
+ FunctionTool tool, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
+ throws IOException {
+ jsonGenerator.writeStartObject();
+
+ jsonGenerator.writeObjectField("metadata", tool.getMetadata());
+
+ jsonGenerator.writeFieldName("function");
+ if (tool.getFunction() instanceof JavaFunction) {
+ JavaFunction javaFunction = (JavaFunction) tool.getFunction();
+ serializeJavaFunction(jsonGenerator, javaFunction);
+ } else if (tool.getFunction() instanceof PythonFunction) {
+ PythonFunction pythonFunction = (PythonFunction) tool.getFunction();
+ serializePythonFunction(jsonGenerator, pythonFunction);
+ } else {
+ throw new IllegalArgumentException(
+ "Unsupported function type: " + tool.getFunction().getClass().getName());
+ }
+
+ jsonGenerator.writeEndObject();
+ }
+
+ private void serializePythonFunction(JsonGenerator gen, PythonFunction func)
+ throws IOException {
+ gen.writeStartObject();
+ // Mark it as a Python function
+ gen.writeStringField("func_type", PYTHON_FUNC_TYPE);
+ // Write the Python function details
+ gen.writeStringField("module", func.getModule());
+ gen.writeStringField("qualname", func.getQualName());
+ gen.writeEndObject();
+ }
+
+ private void serializeJavaFunction(JsonGenerator gen, JavaFunction func) throws IOException {
+ gen.writeStartObject();
+ // Mark it as a Java function
+ gen.writeStringField("func_type", JAVA_FUNC_TYPE);
+ // Write the Java function details
+ gen.writeStringField("qualname", func.getQualName());
+ gen.writeStringField("method_name", func.getMethodName());
+ gen.writeArrayFieldStart("parameter_types");
+ for (Class<?> paramType : func.getParameterTypes()) {
+ gen.writeString(paramType.getName());
+ }
+ gen.writeEndArray();
+ gen.writeEndObject();
+ }
+}
diff --git a/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareChatModelTest.java b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareChatModelTest.java
new file mode 100644
index 0000000..734126e
--- /dev/null
+++ b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareChatModelTest.java
@@ -0,0 +1,141 @@
+/*
+ *
+ * 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;
+
+import org.apache.flink.agents.api.Agent;
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.annotation.Action;
+import org.apache.flink.agents.api.annotation.ChatModel;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.MessageRole;
+import org.apache.flink.agents.api.chat.model.BaseChatModel;
+import org.apache.flink.agents.api.context.RunnerContext;
+import org.apache.flink.agents.api.prompt.Prompt;
+import org.apache.flink.agents.api.resource.Resource;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.resourceprovider.ResourceProvider;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.function.BiFunction;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class AgentPlanDeclareChatModelTest {
+
+ private AgentPlan agentPlan;
+
+ public static class MockChatModel extends BaseChatModel {
+ public MockChatModel(BiFunction<String, ResourceType, Resource> getResource) {
+ super(getResource);
+ }
+
+ public MockChatModel(
+ BiFunction<String, ResourceType, Resource> getResource, String promptName) {
+ super(getResource, promptName);
+ }
+
+ public MockChatModel(
+ BiFunction<String, ResourceType, Resource> getResource, List<String> toolNames) {
+ super(getResource, toolNames);
+ }
+
+ public MockChatModel(
+ BiFunction<String, ResourceType, Resource> getResource,
+ String promptName,
+ List<String> toolNames) {
+ super(getResource, promptName, toolNames);
+ }
+
+ @Override
+ public ChatMessage chat(List<ChatMessage> messages) {
+ // Return a deterministic response based on prompt name to assert on.
+ return new ChatMessage(MessageRole.ASSISTANT, "ok:" + messages.get(0).getContent());
+ }
+ }
+
+ static class ChatAgent extends Agent {
+ @ChatModel
+ public static Map<String, Object> testChatModel() {
+ Map<String, Object> meta = new HashMap<>();
+ meta.put(ChatModel.CHAT_MODEL_CLASS_NAME, MockChatModel.class.getName());
+ meta.put(ChatModel.CHAT_MODEL_ARGUMENTS, List.of("myPrompt", List.of("calculator")));
+ meta.put(
+ ChatModel.CHAT_MODEL_ARGUMENTS_TYPES,
+ List.of(String.class.getName(), List.class.getName()));
+ return meta;
+ }
+
+ @Action(listenEvents = {InputEvent.class})
+ public void onInput(Event e, RunnerContext ctx) {
+ // no-op for this test; validates action registration signature
+ }
+ }
+
+ @BeforeEach
+ void setup() throws Exception {
+ agentPlan = new AgentPlan(new ChatAgent());
+ }
+
+ @Test
+ @DisplayName("Discover @ChatModel in AgentPlan resource providers")
+ void discoverChatModel() {
+ Map<ResourceType, Map<String, ResourceProvider>> providers =
+ agentPlan.getResourceProviders();
+ assertTrue(providers.containsKey(ResourceType.CHAT_MODEL));
+ Map<String, ResourceProvider> cm = providers.get(ResourceType.CHAT_MODEL);
+ assertTrue(cm.containsKey("testChatModel"));
+ }
+
+ @Test
+ @DisplayName("Retrieve chat model and invoke chat(Prompt)")
+ void retrieveAndChat() throws Exception {
+ BaseChatModel model =
+ (BaseChatModel) agentPlan.getResource("testChatModel", ResourceType.CHAT_MODEL);
+ assertNotNull(model);
+
+ Prompt prompt = new Prompt("Hello world");
+ ChatMessage reply = model.chat(prompt.formatMessages(MessageRole.USER, new HashMap<>()));
+
+ assertEquals(MessageRole.ASSISTANT, reply.getRole());
+ assertEquals("ok:Hello world", reply.getContent());
+ }
+
+ @Test
+ @DisplayName("AgentPlan JSON round trip keeps chat model usable")
+ void jsonRoundTrip() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(agentPlan);
+ AgentPlan restored = mapper.readValue(json, AgentPlan.class);
+
+ BaseChatModel model =
+ (BaseChatModel) restored.getResource("testChatModel", ResourceType.CHAT_MODEL);
+ ChatMessage reply =
+ model.chat(new Prompt("Hi").formatMessages(MessageRole.USER, new HashMap<>()));
+ assertEquals("ok:Hi", reply.getContent());
+ }
+}
diff --git a/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareToolFieldTest.java b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareToolFieldTest.java
new file mode 100644
index 0000000..98e95bd
--- /dev/null
+++ b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareToolFieldTest.java
@@ -0,0 +1,202 @@
+/*
+ *
+ * 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;
+
+import org.apache.flink.agents.api.Agent;
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.annotation.Action;
+import org.apache.flink.agents.api.annotation.Tool;
+import org.apache.flink.agents.api.annotation.ToolParam;
+import org.apache.flink.agents.api.context.RunnerContext;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.resourceprovider.ResourceProvider;
+import org.apache.flink.agents.plan.tools.BaseTool;
+import org.apache.flink.agents.plan.tools.FunctionTool;
+import org.apache.flink.agents.plan.tools.ToolMetadata;
+import org.apache.flink.agents.plan.tools.ToolParameters;
+import org.apache.flink.agents.plan.tools.ToolResponse;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+/** Field-based FunctionTool extraction and invocation tests. */
+class AgentPlanDeclareToolFieldTest {
+
+ private AgentPlan agentPlan;
+
+ // Static methods to be wrapped by FunctionTool
+ public static double calculate(
+ @ToolParam(name = "a") double a,
+ @ToolParam(name = "b") double b,
+ @ToolParam(name = "operation") String operation) {
+ switch (operation.toLowerCase()) {
+ case "add":
+ return a + b;
+ case "subtract":
+ return a - b;
+ case "multiply":
+ return a * b;
+ case "divide":
+ if (b == 0) throw new IllegalArgumentException("Division by zero");
+ return a / b;
+ default:
+ throw new IllegalArgumentException("Unknown operation: " + operation);
+ }
+ }
+
+ public static String getWeather(
+ @ToolParam(name = "location") String location,
+ @ToolParam(name = "units") String units) {
+ double temp = "fahrenheit".equals(units) ? 72.0 : 22.0;
+ return String.format(
+ "Weather in %s: %.1f°%s, Sunny",
+ location, temp, "fahrenheit".equals(units) ? "F" : "C");
+ }
+
+ static class TestAgent extends Agent {
+ @Tool private final BaseTool calculator = createCalculatorTool();
+
+ @Tool private final BaseTool weather = createWeatherTool();
+
+ @Action(listenEvents = {InputEvent.class})
+ public void onInput(Event e, RunnerContext ctx) {
+ /* no-op */
+ }
+
+ private static BaseTool createCalculatorTool() {
+ try {
+ Method m =
+ AgentPlanDeclareToolFieldTest.class.getMethod(
+ "calculate", double.class, double.class, String.class);
+ return FunctionTool.fromStaticMethod("Performs basic arithmetic operations", m);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static BaseTool createWeatherTool() {
+ try {
+ Method m =
+ AgentPlanDeclareToolFieldTest.class.getMethod(
+ "getWeather", String.class, String.class);
+ return FunctionTool.fromStaticMethod("Get weather information for a location", m);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ }
+
+ @BeforeEach
+ void setup() throws Exception {
+ agentPlan = new AgentPlan(new TestAgent());
+ }
+
+ @Test
+ @DisplayName("Extract FunctionTool resources into providers")
+ void extractTools() {
+ Map<ResourceType, Map<String, ResourceProvider>> providers =
+ agentPlan.getResourceProviders();
+ assertTrue(providers.containsKey(ResourceType.TOOL));
+ Map<String, ?> toolProviders = providers.get(ResourceType.TOOL);
+ assertTrue(toolProviders.containsKey("calculator"));
+ assertTrue(toolProviders.containsKey("weather"));
+ }
+
+ @Test
+ @DisplayName("Retrieve FunctionTool and call with parameters")
+ void callCalculator() throws Exception {
+ BaseTool tool = (BaseTool) agentPlan.getResource("calculator", ResourceType.TOOL);
+ assertInstanceOf(FunctionTool.class, tool);
+ ToolResponse r =
+ tool.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a", 15.0,
+ "b", 3.0,
+ "operation", "multiply"))));
+ assertTrue(r.isSuccess());
+ assertEquals(45.0, (Double) r.getResult(), 0.001);
+ }
+
+ @Test
+ @DisplayName("Call weather FunctionTool")
+ void callWeather() throws Exception {
+ BaseTool tool = (BaseTool) agentPlan.getResource("weather", ResourceType.TOOL);
+ assertInstanceOf(FunctionTool.class, tool);
+ ToolResponse r =
+ tool.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "location", "London",
+ "units", "fahrenheit"))));
+ assertTrue(r.isSuccess());
+ assertTrue(r.getResultAsString().contains("London"));
+ assertTrue(r.getResultAsString().contains("72.0°F"));
+ }
+
+ @Test
+ @DisplayName("FunctionTool metadata and schema")
+ void metadataSchema() throws Exception {
+ FunctionTool tool = (FunctionTool) agentPlan.getResource("calculator", ResourceType.TOOL);
+ ToolMetadata md = tool.getMetadata();
+ assertEquals("calculate", md.getName());
+ assertEquals("Performs basic arithmetic operations", md.getDescription());
+ assertNotNull(md.getInputSchema());
+ String json = md.getInputSchema();
+ assertTrue(json.contains("\"a\""));
+ assertTrue(json.contains("\"b\""));
+ assertTrue(json.contains("\"operation\""));
+ }
+
+ @Test
+ @DisplayName("FunctionTool error cases")
+ void calculatorErrors() throws Exception {
+ BaseTool tool = (BaseTool) agentPlan.getResource("calculator", ResourceType.TOOL);
+ ToolResponse r =
+ tool.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a", 10.0,
+ "b", 0.0,
+ "operation", "divide"))));
+ assertFalse(r.isSuccess());
+
+ r =
+ tool.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a", 1.0,
+ "b", 1.0,
+ "operation", "noop"))));
+ assertFalse(r.isSuccess());
+ }
+}
diff --git a/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareToolMethodTest.java b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareToolMethodTest.java
new file mode 100644
index 0000000..980351a
--- /dev/null
+++ b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanDeclareToolMethodTest.java
@@ -0,0 +1,221 @@
+/*
+ *
+ * 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;
+
+import org.apache.flink.agents.api.Agent;
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.annotation.Action;
+import org.apache.flink.agents.api.annotation.Tool;
+import org.apache.flink.agents.api.annotation.ToolParam;
+import org.apache.flink.agents.api.context.RunnerContext;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.resourceprovider.ResourceProvider;
+import org.apache.flink.agents.plan.tools.BaseTool;
+import org.apache.flink.agents.plan.tools.ToolMetadata;
+import org.apache.flink.agents.plan.tools.ToolParameters;
+import org.apache.flink.agents.plan.tools.ToolResponse;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+class AgentPlanDeclareToolMethodTest {
+
+ private AgentPlan agentPlan;
+
+ static class TestAgent extends Agent {
+ @Tool(description = "Performs basic arithmetic operations")
+ public static double calculate(
+ @ToolParam(name = "a") Double a,
+ @ToolParam(name = "b") Double b,
+ @ToolParam(name = "operation") String operation) {
+ switch (operation.toLowerCase()) {
+ case "add":
+ return a + b;
+ case "subtract":
+ return a - b;
+ case "multiply":
+ return a * b;
+ case "divide":
+ if (b == 0) throw new IllegalArgumentException("Division by zero");
+ return a / b;
+ default:
+ throw new IllegalArgumentException("Unknown operation: " + operation);
+ }
+ }
+
+ @Tool(description = "Get weather information for a location")
+ public static String getWeather(
+ @ToolParam(name = "location") String location,
+ @ToolParam(name = "units") String units) {
+ double temp = "fahrenheit".equals(units) ? 72.0 : 22.0;
+ return String.format(
+ "Weather in %s: %.1f°%s, Sunny",
+ location, temp, "fahrenheit".equals(units) ? "F" : "C");
+ }
+
+ @Action(listenEvents = {InputEvent.class})
+ public void process(Event event, RunnerContext ctx) {
+ // no-op
+ }
+ }
+
+ @BeforeEach
+ void setup() throws Exception {
+ agentPlan = new AgentPlan(new TestAgent());
+ }
+
+ @Test
+ @DisplayName("Discover static @Tool methods and register providers")
+ void discoverTools() {
+ Map<ResourceType, Map<String, ResourceProvider>> providers =
+ agentPlan.getResourceProviders();
+ assertTrue(providers.containsKey(ResourceType.TOOL));
+ Map<String, ?> toolProviders = providers.get(ResourceType.TOOL);
+ assertTrue(toolProviders.containsKey("calculate"));
+ assertTrue(toolProviders.containsKey("getWeather"));
+ }
+
+ @Test
+ @DisplayName("Retrieve tool and call with parameters")
+ void retrieveAndCallTool() throws Exception {
+ BaseTool calculator = (BaseTool) agentPlan.getResource("calculate", ResourceType.TOOL);
+ ToolParameters tp =
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a", 15.0,
+ "b", 3.0,
+ "operation", "multiply")));
+ ToolResponse r = calculator.call(tp);
+ assertTrue(r.isSuccess());
+ assertEquals(45.0, (Double) r.getResult(), 0.001);
+
+ BaseTool weather = (BaseTool) agentPlan.getResource("getWeather", ResourceType.TOOL);
+ ToolResponse wr =
+ weather.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "location", "London",
+ "units", "fahrenheit"))));
+ assertTrue(wr.isSuccess());
+ assertTrue(wr.getResultAsString().contains("London"));
+ assertTrue(wr.getResultAsString().contains("72.0°F"));
+ }
+
+ @Test
+ @DisplayName("Parameter conversion and errors")
+ void paramConversionAndErrors() throws Exception {
+ BaseTool calculator = (BaseTool) agentPlan.getResource("calculate", ResourceType.TOOL);
+
+ ToolResponse r =
+ calculator.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a",
+ 10, // int
+ "b",
+ 2.5, // double
+ "operation",
+ "divide"))));
+ assertTrue(r.isSuccess());
+ assertEquals(4.0, (Double) r.getResult(), 0.001);
+
+ r =
+ calculator.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a", "20",
+ "b", "4",
+ "operation", "subtract"))));
+ assertTrue(r.isSuccess());
+ assertEquals(16.0, (Double) r.getResult(), 0.001);
+
+ // Division by zero
+ r =
+ calculator.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a", 10.0,
+ "b", 0.0,
+ "operation", "divide"))));
+ assertFalse(r.isSuccess());
+ assertNotNull(r.getError());
+
+ // Invalid operation
+ r =
+ calculator.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a", 1.0,
+ "b", 1.0,
+ "operation", "noop"))));
+ assertFalse(r.isSuccess());
+ assertNotNull(r.getError());
+ }
+
+ @Test
+ @DisplayName("Metadata and schema shape")
+ void metadataSchema() throws Exception {
+ BaseTool calculator = (BaseTool) agentPlan.getResource("calculate", ResourceType.TOOL);
+ ToolMetadata md = calculator.getMetadata();
+ assertEquals("calculate", md.getName());
+ assertEquals("Performs basic arithmetic operations", md.getDescription());
+ assertNotNull(md.getInputSchema());
+ String json = md.getInputSchema();
+ assertTrue(json.contains("\"a\""));
+ assertTrue(json.contains("\"b\""));
+ assertTrue(json.contains("\"operation\""));
+ }
+
+ @Test
+ @DisplayName("AgentPlan json serialize and deserialized with ToolResourceProvider")
+ void testAgentPlanJsonSerializable() throws Exception {
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(agentPlan);
+ AgentPlan restored = mapper.readValue(json, AgentPlan.class);
+ BaseTool calculator = (BaseTool) restored.getResource("calculate", ResourceType.TOOL);
+ ToolResponse r =
+ calculator.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a", 6.0,
+ "b", 7.0,
+ "operation", "multiply"))));
+ assertTrue(r.isSuccess());
+ assertEquals(42.0, (Double) r.getResult(), 0.001);
+ }
+}
diff --git a/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanTest.java b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanTest.java
index 1855c54..0837f0f 100644
--- a/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanTest.java
+++ b/plan/src/test/java/org/apache/flink/agents/plan/AgentPlanTest.java
@@ -28,7 +28,6 @@ import org.apache.flink.agents.api.context.RunnerContext;
import org.apache.flink.agents.api.resource.Resource;
import org.apache.flink.agents.api.resource.ResourceType;
import org.apache.flink.agents.api.resource.SerializableResource;
-import org.apache.flink.agents.plan.resourceprovider.JavaResourceProvider;
import org.apache.flink.agents.plan.resourceprovider.JavaSerializableResourceProvider;
import org.apache.flink.agents.plan.resourceprovider.ResourceProvider;
import org.junit.jupiter.api.Test;
@@ -55,14 +54,13 @@ public class AgentPlanTest {
}
/** Test tool resource class. */
- public static class TestTool extends Resource {
+ public static class TestTool extends SerializableResource {
private final String name;
public TestTool(String name) {
this.name = name;
}
- @Override
public String getName() {
return name;
}
@@ -81,7 +79,6 @@ public class AgentPlanTest {
this.name = name;
}
- @Override
public String getName() {
return name;
}
@@ -115,15 +112,13 @@ public class AgentPlanTest {
/** Test agent class with resource annotations. */
public static class TestAgentWithResources extends Agent {
- @Tool(name = "myTool")
- private TestTool tool = new TestTool("myTool");
+ @Tool private TestTool myTool = new TestTool("myTool");
@ChatModel
private TestSerializableChatModel chatModel =
new TestSerializableChatModel("defaultChatModel");
- @Tool(name = "anotherTool")
- private TestTool anotherTool = new TestTool("anotherTool");
+ @Tool private TestTool anotherTool = new TestTool("anotherTool");
@org.apache.flink.agents.api.annotation.Action(listenEvents = {InputEvent.class})
public void handleInputEvent(InputEvent event, RunnerContext context) {
@@ -254,14 +249,14 @@ public class AgentPlanTest {
assertThat(toolProviders).containsKey("myTool");
assertThat(toolProviders).containsKey("anotherTool");
- // Verify that tool providers are JavaResourceProvider (non-serializable)
+ // Verify that tool providers are JavaSerializableResourceProvider (non-serializable)
ResourceProvider myToolProvider = toolProviders.get("myTool");
- assertThat(myToolProvider).isInstanceOf(JavaResourceProvider.class);
+ assertThat(myToolProvider).isInstanceOf(JavaSerializableResourceProvider.class);
assertThat(myToolProvider.getName()).isEqualTo("myTool");
assertThat(myToolProvider.getType()).isEqualTo(ResourceType.TOOL);
ResourceProvider anotherToolProvider = toolProviders.get("anotherTool");
- assertThat(anotherToolProvider).isInstanceOf(JavaResourceProvider.class);
+ assertThat(anotherToolProvider).isInstanceOf(JavaSerializableResourceProvider.class);
assertThat(anotherToolProvider.getName()).isEqualTo("anotherTool");
assertThat(anotherToolProvider.getType()).isEqualTo(ResourceType.TOOL);
@@ -297,14 +292,12 @@ public class AgentPlanTest {
Resource myTool = agentPlan.getResource("myTool", ResourceType.TOOL);
assertThat(myTool).isNotNull();
assertThat(myTool).isInstanceOf(TestTool.class);
- assertThat(myTool.getName()).isEqualTo("myTool");
assertThat(myTool.getResourceType()).isEqualTo(ResourceType.TOOL);
// Test getting a chat model resource
Resource chatModel = agentPlan.getResource("chatModel", ResourceType.CHAT_MODEL);
assertThat(chatModel).isNotNull();
assertThat(chatModel).isInstanceOf(TestSerializableChatModel.class);
- assertThat(chatModel.getName()).isEqualTo("defaultChatModel");
assertThat(chatModel.getResourceType()).isEqualTo(ResourceType.CHAT_MODEL);
// Test that resources are cached (should be the same instance)
diff --git a/plan/src/test/java/org/apache/flink/agents/plan/FunctionToolPlanTest.java b/plan/src/test/java/org/apache/flink/agents/plan/FunctionToolPlanTest.java
new file mode 100644
index 0000000..e8cce1f
--- /dev/null
+++ b/plan/src/test/java/org/apache/flink/agents/plan/FunctionToolPlanTest.java
@@ -0,0 +1,124 @@
+/*
+ *
+ * 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;
+
+import org.apache.flink.agents.api.Agent;
+import org.apache.flink.agents.api.annotation.Tool;
+import org.apache.flink.agents.api.annotation.ToolParam;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.tools.FunctionTool;
+import org.apache.flink.agents.plan.tools.ToolMetadata;
+import org.apache.flink.agents.plan.tools.ToolParameters;
+import org.apache.flink.agents.plan.tools.ToolResponse;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.node.ObjectNode;
+import org.junit.jupiter.api.DisplayName;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.jupiter.api.Assertions.*;
+
+class FunctionToolPlanTest {
+
+ // Java static tool method
+ public static double calc(
+ @ToolParam(name = "a") double a,
+ @ToolParam(name = "b") double b,
+ @ToolParam(name = "operation") String op) {
+ switch (op.toLowerCase()) {
+ case "add":
+ return a + b;
+ case "sub":
+ return a - b;
+ case "mul":
+ return a * b;
+ case "div":
+ if (b == 0) throw new IllegalArgumentException("Division by zero");
+ return a / b;
+ default:
+ throw new IllegalArgumentException("Unknown operation: " + op);
+ }
+ }
+
+ static class TestAgent extends Agent {
+ @Tool private final FunctionTool javaTool;
+
+ @Tool private final FunctionTool pyTool;
+
+ TestAgent() {
+ try {
+ Method m =
+ FunctionToolPlanTest.class.getMethod(
+ "calc", double.class, double.class, String.class);
+ this.javaTool = FunctionTool.fromStaticMethod("java calculator", m);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ // Build a minimal metadata for a non-Java function tool using PythonFunction
+ ObjectMapper om = new ObjectMapper();
+ ObjectNode schema = om.createObjectNode();
+ schema.put("type", "object");
+ ToolMetadata md = new ToolMetadata("py_tool", "python tool", schema.asText());
+ PythonFunction pyFunc = new PythonFunction("mod", "qual");
+ this.pyTool = new FunctionTool(md, pyFunc);
+ }
+ }
+
+ @Test
+ @DisplayName("FunctionTool via AgentPlan: JavaFunction success, PythonFunction error")
+ void functionToolAgentPlan() throws Exception {
+ AgentPlan plan = new AgentPlan(new TestAgent());
+
+ FunctionTool javaTool = (FunctionTool) plan.getResource("javaTool", ResourceType.TOOL);
+ ToolResponse ok =
+ javaTool.call(
+ new ToolParameters(
+ new HashMap<>(
+ Map.of(
+ "a", 12.0,
+ "b", 3.0,
+ "operation", "mul"))));
+ assertTrue(ok.isSuccess());
+ assertEquals(36.0, (Double) ok.getResult(), 1e-9);
+
+ FunctionTool pyTool = (FunctionTool) plan.getResource("pyTool", ResourceType.TOOL);
+ ToolResponse err = pyTool.call(new ToolParameters(new HashMap<>(Map.of("x", 1))));
+ assertFalse(err.isSuccess());
+ }
+
+ @Test
+ @DisplayName("FunctionTool.fromStaticMethod maps @ToolParam by name")
+ void javaFunctionMapping() throws Exception {
+ Method m =
+ FunctionToolPlanTest.class.getMethod(
+ "calc", double.class, double.class, String.class);
+ FunctionTool tool = FunctionTool.fromStaticMethod("desc", m);
+ ToolResponse ok =
+ tool.call(
+ new ToolParameters(
+ new HashMap<>(Map.of("a", 10, "b", 2.5, "operation", "div"))));
+ assertTrue(ok.isSuccess());
+ assertEquals(4.0, (Double) ok.getResult(), 1e-9);
+ }
+}
diff --git a/plan/src/test/java/org/apache/flink/agents/plan/tools/FunctionToolTest.java b/plan/src/test/java/org/apache/flink/agents/plan/tools/FunctionToolTest.java
new file mode 100644
index 0000000..19a03e7
--- /dev/null
+++ b/plan/src/test/java/org/apache/flink/agents/plan/tools/FunctionToolTest.java
@@ -0,0 +1,81 @@
+/*
+ * 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.tools;
+
+import org.apache.flink.agents.api.annotation.Tool;
+import org.apache.flink.agents.api.annotation.ToolParam;
+import org.apache.flink.agents.plan.JavaFunction;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.lang.reflect.Method;
+
+public class FunctionToolTest {
+ @Tool(description = "Performs basic arithmetic operations")
+ public static double calculate(
+ @ToolParam(name = "a") Double a,
+ @ToolParam(name = "b") Double b,
+ @ToolParam(name = "operation") String operation) {
+ switch (operation.toLowerCase()) {
+ case "add":
+ return a + b;
+ case "subtract":
+ return a - b;
+ case "multiply":
+ return a * b;
+ case "divide":
+ if (b == 0) throw new IllegalArgumentException("Division by zero");
+ return a / b;
+ default:
+ throw new IllegalArgumentException("Unknown operation: " + operation);
+ }
+ }
+
+ @Test
+ public void testToolMetadataSerializable() throws Exception {
+ Method method =
+ FunctionToolTest.class.getMethod(
+ "calculate", Double.class, Double.class, String.class);
+ ToolMetadata origin = ToolMetadataFactory.fromStaticMethod(method);
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(origin);
+ ToolMetadata deserialize = mapper.readValue(json, ToolMetadata.class);
+ Assertions.assertEquals(origin, deserialize);
+ }
+
+ @Test
+ public void testFunctionToolSerializable() throws Exception {
+ Method method =
+ FunctionToolTest.class.getMethod(
+ "calculate", Double.class, Double.class, String.class);
+ ToolMetadata metadata = ToolMetadataFactory.fromStaticMethod(method);
+ JavaFunction javaFunction =
+ new JavaFunction(
+ method.getDeclaringClass(),
+ method.getName(),
+ new Class[] {Double.class, Double.class, String.class});
+ FunctionTool tool = new FunctionTool(metadata, javaFunction);
+ ObjectMapper mapper = new ObjectMapper();
+ String json = mapper.writeValueAsString(tool);
+ FunctionTool deserialize = mapper.readValue(json, FunctionTool.class);
+ Assertions.assertEquals(tool.getMetadata(), deserialize.getMetadata());
+ Assertions.assertEquals(tool.getFunction(), deserialize.getFunction());
+ }
+}