wenjin272 commented on code in PR #1397:
URL: https://github.com/apache/flink-agents/pull/1397#discussion_r4678762243


##########
api/src/main/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetup.java:
##########
@@ -329,19 +329,28 @@ public ChatResult chat(
             List<Tool> tools,
             @Nullable Map<String, Object> modelParams,
             @Nullable Object outputSchema) {
+        return callConnection(messages, tools, modelParams, outputSchema, 
tools.isEmpty());
+    }
+
+    private ChatResult callConnection(

Review Comment:
   Could we simplify both Java and Python to strip tool-only parameters 
whenever the effective tool list is empty? Java could retain the original 
delegation to the explicit-tools `chat` method and remove `callConnection`, 
while Python could remove `disable_tools` and check the resolved tool list 
directly.



##########
api/src/main/java/org/apache/flink/agents/api/event/ChatRequestEvent.java:
##########
@@ -114,17 +129,23 @@ private static Map<String, Object> 
normalizeAttributes(Map<String, Object> attri
             }
             attributes.put("messages", messages);
         }
+        Object budget = attributes.get("budget");
+        if (budget instanceof Map) {
+            attributes.put("budget", MAPPER.convertValue(budget, 
ReActLoopBudget.class));
+        } else if (budget != null && !(budget instanceof ReActLoopBudget)) {

Review Comment:
   Could we remove this `else if` check and keep only the map-to-budget 
conversion? The normal construction and serialization paths already produce a 
`ReActLoopBudget` or a map, so a dedicated check for manually supplied invalid 
types seems unnecessary here.



##########
plan/src/main/java/org/apache/flink/agents/plan/resource/python/PythonChatModelSetup.java:
##########
@@ -107,6 +107,32 @@ public ChatResult chat(
         }
     }
 
+    @Override
+    public List<ChatMessage> prepareRequestMessages(
+            List<ChatMessage> messages, Map<String, Object> promptArgs) {
+        try (PythonObjectScope scope = new PythonObjectScope()) {
+            List<Object> pythonMessages = new ArrayList<>();
+            for (ChatMessage message : messages) {
+                
pythonMessages.add(scope.own(adapter.toPythonChatMessage(message)));
+            }
+            Object prepared =
+                    scope.own(
+                            adapter.callMethod(
+                                    chatModelSetup,
+                                    "prepare_request_messages",
+                                    Map.of(
+                                            "messages",
+                                            pythonMessages,
+                                            "prompt_args",
+                                            promptArgs == null ? Map.of() : 
promptArgs)));
+            List<ChatMessage> result = new ArrayList<>();
+            for (Object message : (List<?>) prepared) {
+                result.add(adapter.fromPythonChatMessage(message));

Review Comment:
   `PythonChatModelSetup.prepareRequestMessages()` reconstructs messages when 
converting them back from Python, so unchanged conversation messages become new 
Java objects. Since `pinnedRenderedIndices` identifies generated prompts by 
object identity, it incorrectly pins the entire conversation, preventing 
`max_context_chars` from trimming history.
   
   Could we instead apply the limit to the original conversation before calling 
`prepareRequestMessages`, retaining system messages and the latest message, 
then add the prompt/skills messages? This would remove the identity-based 
inference while preserving the `List<ChatMessage>` return type. Please update 
the documentation and tests to clarify that added prompt/skills messages are 
outside the budget and the final context may exceed the limit.



##########
plan/src/main/java/org/apache/flink/agents/plan/serializer/ActionJsonDeserializer.java:
##########
@@ -146,7 +147,7 @@ private JavaFunction deserializeJavaFunction(JsonNode 
execNode) throws IOExcepti
 
     private Map<String, Object> deserializeJavaConfig(JsonNode node) throws 
Exception {
 
-        ObjectMapper mapper = new ObjectMapper();
+        ObjectMapper mapper = new ObjectMapper().registerModule(new 
JavaTimeModule());

Review Comment:
   Could we centralize the `JavaTimeModule` registration in a shared mapper 
factory and cache the resulting mapper in a `private static final` field at 
each call site? This would avoid repeated setup and allocation while allowing 
each component to retain its own serializers and mixins, without sharing a 
mutable global mapper.



##########
e2e-test/flink-agents-end-to-end-tests-resource-cross-language/src/test/java/org/apache/flink/agents/resource/test/ReActLoopBudgetCrossLanguageTest.java:
##########
@@ -0,0 +1,405 @@
+/*
+ * 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.resource.test;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
+import org.apache.flink.agents.api.AgentsExecutionEnvironment;
+import org.apache.flink.agents.api.Event;
+import org.apache.flink.agents.api.InputEvent;
+import org.apache.flink.agents.api.OutputEvent;
+import org.apache.flink.agents.api.agents.Agent;
+import org.apache.flink.agents.api.agents.AgentExecutionOptions;
+import org.apache.flink.agents.api.agents.ReActLoopBudget;
+import org.apache.flink.agents.api.chat.messages.ChatMessage;
+import org.apache.flink.agents.api.chat.messages.ChatResult;
+import org.apache.flink.agents.api.chat.messages.TokenUsage;
+import org.apache.flink.agents.api.chat.messages.ToolCallBlock;
+import org.apache.flink.agents.api.chat.model.BaseChatModelConnection;
+import org.apache.flink.agents.api.chat.model.BaseChatModelSetup;
+import org.apache.flink.agents.api.context.RunnerContext;
+import org.apache.flink.agents.api.event.ChatRequestEvent;
+import org.apache.flink.agents.api.event.ChatResponseEvent;
+import org.apache.flink.agents.api.event.ToolResponseEvent;
+import org.apache.flink.agents.api.resource.PythonResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceContext;
+import org.apache.flink.agents.api.resource.ResourceDescriptor;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.api.tools.Tool;
+import org.apache.flink.agents.plan.AgentPlan;
+import org.apache.flink.agents.plan.PythonFunction;
+import org.apache.flink.agents.plan.actions.Action;
+import org.apache.flink.agents.runtime.actionstate.ActionState;
+import org.apache.flink.agents.runtime.actionstate.ActionStateKeyEncoder;
+import org.apache.flink.agents.runtime.actionstate.ActionStateSerde;
+import org.apache.flink.agents.runtime.actionstate.ActionStateStore;
+import org.apache.flink.agents.runtime.operator.ActionExecutionOperatorFactory;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.common.typeutils.base.StringSerializer;
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
+import org.apache.flink.util.CloseableIterator;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+import pemja.core.PythonInterpreter;
+import pemja.core.PythonInterpreterConfig;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/** Runs real Python actions/resources through Pemja in Flink jobs. */
+@Timeout(60)
+public class ReActLoopBudgetCrossLanguageTest {
+    private static final AtomicInteger NORMAL_CALLS = new AtomicInteger();
+    private static final AtomicInteger CLOSING_CALLS = new AtomicInteger();
+    private static final AtomicInteger TOOL_CALLS = new AtomicInteger();
+
+    @BeforeEach
+    void reset() {
+        NORMAL_CALLS.set(0);
+        CLOSING_CALLS.set(0);
+        TOOL_CALLS.set(0);
+        RecoveryStore.STATES.clear();
+        RecoveryStore.CRASHED.set(false);
+        RecoveryStore.READ_PERSISTED_START.set(false);
+        RecoveryStore.startPayload = null;
+    }
+
+    @ParameterizedTest
+    @ValueSource(longs = {1L, 60001L, 31536000000L, 34560000001L, 
63072000000L, 86399999999999999L})
+    void budgetJsonRoundTripsThroughPython(long millis) throws Exception {
+        var config =
+                PythonInterpreterConfig.newBuilder()
+                        
.setPythonExec(System.getenv().getOrDefault("PYTHON_EXECUTABLE", "python3"))
+                        .build();
+        try (var interpreter = new PythonInterpreter(config)) {
+            interpreter.exec("from flink_agents.api.react_loop_budget import 
ReActLoopBudget");
+            var mapper = new ObjectMapper().registerModule(new 
JavaTimeModule());
+            for (var mode : ReActLoopBudget.BudgetMode.values()) {
+                var budget =
+                        ReActLoopBudget.builder()
+                                .maxTurns(2)
+                                .maxTokens(100L)
+                                .maxTime(Duration.ofMillis(millis))
+                                .mode(mode)
+                                .build();
+                interpreter.set("budget_json", 
mapper.writeValueAsString(budget));
+                interpreter.exec(
+                        "wire_json = 
ReActLoopBudget.model_validate_json(budget_json).model_dump_json()");
+                var restored =
+                        mapper.readValue(
+                                (String) interpreter.get("wire_json"), 
ReActLoopBudget.class);
+                
assertThat(restored.getMaxTime()).isEqualTo(budget.getMaxTime());
+                
assertThat(restored.getMaxTurns()).isEqualTo(budget.getMaxTurns());
+                
assertThat(restored.getMaxTokens()).isEqualTo(budget.getMaxTokens());
+                assertThat(restored.getMode()).isEqualTo(budget.getMode());
+            }
+        }
+    }
+
+    public static class Connection extends BaseChatModelConnection {
+        public Connection(ResourceDescriptor descriptor, ResourceContext ctx) {
+            super(descriptor, ctx);
+        }
+
+        @Override
+        public ChatResult chat(
+                List<ChatMessage> messages, List<Tool> tools, Map<String, 
Object> params) {
+            if (tools.isEmpty()) {
+                CLOSING_CALLS.incrementAndGet();
+                assertThat(params).doesNotContainKey("tool_choice");
+                assertThat(messages.get(messages.size() - 1).getText())
+                        .contains("Do not call tools");
+                return new ChatResult(ChatMessage.assistant("closed"));
+            }
+            NORMAL_CALLS.incrementAndGet();
+            if (messages.stream().anyMatch(message -> 
"hello:time-job".equals(message.getText()))) {
+                try {
+                    Thread.sleep(11000);
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new RuntimeException(e);
+                }
+            }
+            assertThat(params).containsEntry("tool_choice", "required");
+            return new ChatResult(
+                    ChatMessage.assistant(List.of(new ToolCallBlock("call", 
"echo", Map.of()))),
+                    null,
+                    null,
+                    new TokenUsage(3L, 2L),
+                    null,
+                    Map.of());
+        }
+    }
+
+    public static class Setup extends BaseChatModelSetup {
+        public Setup(ResourceDescriptor descriptor, ResourceContext ctx) {
+            super(descriptor, ctx);
+        }
+
+        @Override
+        public Map<String, Object> getParameters() {
+            return new HashMap<>(Map.of("tool_choice", "required"));
+        }
+    }
+
+    public static String echo() {
+        TOOL_CALLS.incrementAndGet();
+        return "tool result";
+    }
+
+    public static void request(Event event, RunnerContext ctx) {
+        String[] args = 
InputEvent.fromEvent(event).getInput().toString().split(":");
+        ReActLoopBudget.Builder builder =
+                
ReActLoopBudget.builder().mode(ReActLoopBudget.BudgetMode.valueOf(args[0]));
+        if (args[1].startsWith("turn")) 
builder.maxTurns(args[1].endsWith("-replay") ? 2 : 1);
+        if (args[1].startsWith("token")) 
builder.maxTokens(args[1].endsWith("-replay") ? 10L : 5L);
+        builder.maxTime(Duration.ofMillis(args[1].equals("time-job") ? 10000 : 
60000));
+        ctx.sendEvent(
+                new ChatRequestEvent(
+                        "model",
+                        List.of(ChatMessage.user("hello:" + args[1])),
+                        null,
+                        null,
+                        null,
+                        builder.build()));
+    }
+
+    public static void receive(Event event, RunnerContext ctx) {
+        ChatResponseEvent response = ChatResponseEvent.fromEvent(event);
+        ctx.sendEvent(
+                new OutputEvent(
+                        response.isSuccess()
+                                ? response.getResponse().getText()
+                                : response.getError()));
+    }
+
+    private static Agent agent(boolean javaModel) throws Exception {
+        Agent agent = new Agent();
+        agent.addResource(
+                "connection",
+                ResourceType.CHAT_MODEL_CONNECTION,
+                
ResourceDescriptor.Builder.newBuilder(Connection.class.getName()).build());
+        agent.addResource(
+                "echo",
+                ResourceType.TOOL,
+                
Tool.fromMethod(ReActLoopBudgetCrossLanguageTest.class.getMethod("echo")));
+        ResourceDescriptor descriptor =
+                javaModel
+                        ? 
ResourceDescriptor.Builder.newBuilder(Setup.class.getName())
+                                .addInitialArgument("connection", "connection")
+                                .addInitialArgument("model", "local")
+                                .addInitialArgument("tools", List.of("echo"))
+                                .build()
+                        : PythonResourceDescriptor.Builder.newBuilder(
+                                        
"flink_agents.runtime.tests.budget_bridge_fixtures.BudgetModelSetup")
+                                .addInitialArgument("connection", "connection")
+                                .addInitialArgument("model", "local")
+                                .addInitialArgument("tools", List.of("echo"))
+                                .build();
+        agent.addResource("model", ResourceType.CHAT_MODEL, descriptor);
+        agent.addAction(
+                new String[] {InputEvent.EVENT_TYPE},
+                ReActLoopBudgetCrossLanguageTest.class.getMethod(
+                        "request", Event.class, RunnerContext.class));
+        agent.addAction(
+                new String[] {ChatResponseEvent.EVENT_TYPE},
+                ReActLoopBudgetCrossLanguageTest.class.getMethod(
+                        "receive", Event.class, RunnerContext.class));
+        return agent;
+    }
+
+    private static AgentPlan plan(boolean python) throws Exception {
+        AgentPlan plan = new AgentPlan(agent(python));
+        if (python) {
+            Map<String, Action> actions = new HashMap<>(plan.getActions());
+            actions.put(
+                    "chat_model_action",
+                    new Action(
+                            "chat_model_action",
+                            new PythonFunction(
+                                    
"flink_agents.plan.actions.chat_model_action",
+                                    "process_chat_request_or_tool_response"),
+                            List.of(ChatRequestEvent.EVENT_TYPE, 
ToolResponseEvent.EVENT_TYPE)));
+            plan = new AgentPlan(actions, plan.getResourceProviders(), 
plan.getConfig());
+        }
+        plan.getConfig().set(AgentExecutionOptions.CHAT_ASYNC, false);
+        plan.getConfig().set(AgentExecutionOptions.TOOL_CALL_ASYNC, false);
+        plan.getConfig().set(AgentExecutionOptions.MAX_RETRIES, 0);
+        return plan;
+    }
+
+    @ParameterizedTest
+    @CsvSource({
+        "true,HARD,turn", "true,SOFT,turn", "false,HARD,turn", 
"false,SOFT,turn",
+        "true,HARD,token", "true,SOFT,token", "false,HARD,token", 
"false,SOFT,token",
+        "true,HARD,time", "true,SOFT,time", "false,HARD,time", 
"false,SOFT,time"
+    })
+    void budgetsRunThroughPublicApiInFlinkJob(boolean javaModel, String mode, 
String limit)

Review Comment:
   Could we also add a Java-only budget E2E test to the integration module, 
similar to the Python-only test? The Java-only cases currently live in the 
cross-language module, whose CI matrix differs from the Java integration 
matrix. This would verify budget behavior across the supported Flink/JDK 
combinations.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to