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


##########
api/src/main/java/org/apache/flink/agents/api/agents/AgentExecutionOptions.java:
##########
@@ -124,4 +124,11 @@ public class AgentExecutionOptions {
                             "short-term-memory.state-ttl.visibility",
                             ShortTermMemoryTtlVisibility.class,
                             ShortTermMemoryTtlVisibility.NEVER_RETURN_EXPIRED);
+
+    /**
+     * The most characters of one tool result that the built-in chat action 
sends to the model; a
+     * longer result is cut in the middle. At least 100. Unset by default: 
results are sent in full.
+     */
+    public static final ConfigOption<Integer> 
CONTEXT_MANAGEMENT_TOOL_RESULTS_MAX_CHARS =

Review Comment:
   Could we move this option into a dedicated `ContextManagementOptions` class 
and name it `TOOL_RESULTS_MAX_CHARS`? The class name already provides the 
context, so the `CONTEXT_MANAGEMENT_` prefix would be redundant. This would 
also keep future context management options together instead of expanding 
`AgentExecutionOptions`.
   
   The configuration key can remain `context-management.tool-results.max-chars`.



##########
api/src/main/java/org/apache/flink/agents/api/event/ChatRequestEvent.java:
##########
@@ -193,4 +200,46 @@ public Map<String, Object> getPromptArgs() {
     public Map<String, Object> getUserContext() {
         return UserDefinedContext.get(this);
     }
+
+    /**
+     * Sets the policy of this request, which replaces the agent's default 
policy as a whole. With
+     * {@code null}, the request uses the agent's default policy.
+     *
+     * @return this event
+     */
+    public ChatRequestEvent withContextManagement(@Nullable 
ContextManagementPolicy policy) {
+        if (policy == null) {
+            getAttributes().remove(CONTEXT_MANAGEMENT);
+        } else {
+            setAttr(CONTEXT_MANAGEMENT, policy.toMap());

Review Comment:
   Could we store the `ContextManagementPolicy` object directly in the event 
attributes, as we already do with `ReActLoopBudget`, and use Jackson for 
serialization and deserialization?
   
   With the appropriate Jackson annotations, we could restore the typed policy 
in `normalizeAttributes()` and remove the hand-written `toMap()`, `fromMap()`, 
and `integer()` methods. Value-range validation could stay in the policy 
constructor. We should preserve the distinction between an omitted policy and 
an explicitly disabled policy, along with the existing strict input validation.



##########
plan/src/main/java/org/apache/flink/agents/plan/actions/ChatModelAction.java:
##########
@@ -319,9 +338,16 @@ private static void chat(
             Map<String, Object> promptArgs,
             @Nullable Object outputSchema,
             @Nullable Map<String, Object> userContext,
+            @Nullable ContextManagementPolicy requestPolicy,
             RunnerContext ctx,
             @Nullable String reason)
             throws Exception {
+        ContextManagementPolicy policy =
+                requestPolicy != null
+                        ? requestPolicy
+                        : 
ContextManagementPolicy.fromConfiguration(ctx.getConfig());
+        List<ChatMessage> sentMessages = ToolResultTruncation.apply(messages, 
policy);

Review Comment:
   Could we introduce a general context management entry point here, such as 
`ContextManager.apply(messages, policy)`, instead of calling 
`ToolResultTruncation` directly?
   
   `ChatModelAction` should apply the context management policy without knowing 
the specific processing steps. This would keep future masking or summarization 
logic, including their ordering, out of the chat action. For now, a simple 
helper in `plan` that delegates to `ToolResultTruncation` should be enough.



##########
python/flink_agents/api/core_options.py:
##########
@@ -396,6 +396,17 @@ class AgentExecutionOptions:
         default=ShortTermMemoryTtlVisibility.NEVER_RETURN_EXPIRED,
     )
 
+    # The most characters of one tool result that the built-in chat action 
sends to
+    # the model; a longer result is cut in the middle. At least 100. Unset by 
default:
+    # tool results are sent in full. The built-in chat action of Java agents 
applies
+    # it. The one of Python agents does not yet; the option is declared here 
to keep
+    # the Java and Python options the same.
+    CONTEXT_MANAGEMENT_TOOL_RESULTS_MAX_CHARS = ConfigOption(

Review Comment:
   Keeping this PR Java-only is fine, but could we leave this option out of the 
Python API until the Python chat action supports it? Exposing an option that 
has no effect may mislead users.
   
   Once the Java option moves into `ContextManagementOptions`, it would no 
longer need a Python counterpart just to satisfy the `AgentExecutionOptions` 
parity check. We can add the Python option together with its implementation. 
Python should still preserve the `context_management` event attribute for 
cross-language interoperability.



##########
api/src/main/java/org/apache/flink/agents/api/chat/contextmanagement/ContextManagementPolicy.java:
##########
@@ -0,0 +1,208 @@
+/*
+ * 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.contextmanagement;
+
+import org.apache.flink.agents.api.agents.AgentExecutionOptions;
+import org.apache.flink.agents.api.configuration.ReadableConfiguration;
+
+import javax.annotation.Nullable;
+
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * How the built-in chat action bounds the model input of one chat request.
+ *
+ * <p>A chat request and its tool-call loop send the request's whole 
conversation to the model on
+ * every call, including every earlier tool result. A policy limits how much 
of one tool result is
+ * sent ({@link #getToolResultMaxChars()}). Only the messages sent to the 
model change; the
+ * conversation the framework keeps for the request stays complete.
+ *
+ * <p>The default policy of an agent comes from the {@code 
context-management.*} execution options
+ * ({@link #fromConfiguration}). A {@link 
org.apache.flink.agents.api.event.ChatRequestEvent} can
+ * carry its own policy, which replaces the default as a whole for that 
request; {@link #disabled()}
+ * switches context management off for the request.
+ */
+public final class ContextManagementPolicy {
+
+    /** Map form key of {@link #getToolResultMaxChars()}. */
+    public static final String TOOL_RESULT_MAX_CHARS = "tool_result_max_chars";
+
+    /** The smallest accepted limit. It leaves room for the marker of a cut 
and text around it. */
+    public static final int MIN_TOOL_RESULT_MAX_CHARS = 100;
+
+    private static final ContextManagementPolicy DISABLED =
+            new ContextManagementPolicy(null, TOOL_RESULT_MAX_CHARS);
+
+    @Nullable private final Integer toolResultMaxChars;
+
+    /**
+     * @param name what an error calls the limit: its map form key or its 
configuration key
+     */
+    private ContextManagementPolicy(@Nullable Integer toolResultMaxChars, 
String name) {
+        if (toolResultMaxChars != null && toolResultMaxChars < 
MIN_TOOL_RESULT_MAX_CHARS) {
+            throw new IllegalArgumentException(
+                    name
+                            + " must be at least "
+                            + MIN_TOOL_RESULT_MAX_CHARS
+                            + ", got "
+                            + toolResultMaxChars);
+        }
+        this.toolResultMaxChars = toolResultMaxChars;
+    }
+
+    public static Builder builder() {
+        return new Builder();
+    }
+
+    /** A policy with nothing set. On a chat request it switches context 
management off. */
+    public static ContextManagementPolicy disabled() {
+        return DISABLED;
+    }
+
+    /**
+     * The policy declared by the {@code context-management.*} execution 
options, disabled when none
+     * of them is set.
+     *
+     * @throws IllegalArgumentException if a configured value is not an 
integer or is out of range,
+     *     named by its configuration key
+     */
+    public static ContextManagementPolicy 
fromConfiguration(ReadableConfiguration config) {

Review Comment:
   Could we move `fromConfiguration()` to a helper in the `plan` module? Its 
current callers are `ChatModelAction` and `CompileUtils`, so both could use it 
there without reversing the module dependency direction.
   
   This would keep `ContextManagementPolicy` focused on the user-facing policy 
and its value validation. Reading execution options and adding 
configuration-specific error messages could stay in the helper, which would 
also remove the need for the policy constructor’s `name` parameter.



##########
plan/src/main/java/org/apache/flink/agents/plan/actions/ChatModelAction.java:
##########
@@ -331,7 +357,7 @@ private static void chat(
                     ModelRoutingExecutor.execute(
                             initialRequestId,
                             route,
-                            messages,
+                            sentMessages,

Review Comment:
   Could we apply the context management policy before resolving the model 
route, then use the processed messages for both routing and model invocation?
   
   The router should make its decision based on the input the model will 
actually receive, especially when routing depends on input size or content. 
Context management should run uniformly in the chat action, independently of 
the selected candidate, with fallback and escalation using the same processed 
messages. The full conversation should remain unchanged in state.



##########
plan/src/main/java/org/apache/flink/agents/plan/actions/ChatModelAction.java:
##########
@@ -180,6 +194,9 @@ private static void saveToolRequestEventContext(
         if (userContext != null) {
             context.put(USER_CONTEXT, userContext);
         }
+        if (requestPolicy != null) {
+            context.put(CONTEXT_MANAGEMENT, requestPolicy.toMap());

Review Comment:
   Could we store `requestPolicy` directly here and read it back as a 
`ContextManagementPolicy` when processing the tool response? The policy is 
immutable, and the state serialization already preserves concrete types, so the 
`toMap()` / `fromMap()` conversion seems unnecessary.
   
   Please also verify that the policy survives state recovery and is still 
applied afterward, including an explicitly disabled policy.



##########
runtime/src/test/java/org/apache/flink/agents/runtime/context/ChatModelActionContextRecoveryTest.java:
##########
@@ -114,6 +117,10 @@ void 
restoredToolRequestMemoryKeepsTheOriginalRequestContext() throws Exception
                         .orElseThrow();
         assertThat(parked.getValue()).isEqualTo(liveParked);
         assertThat(parked.getValue()).isNotSameAs(liveParked);
+        // The request's policy is restored as the map it was parked as.
+        Map<?, ?> parkedContext = (Map<?, ?>) parked.getValue();
+        assertThat(((Map<?, ?>) 
parkedContext.get(toolRequest.getId())).get("context_management"))
+                .isEqualTo(Map.of("tool_result_max_chars", 500));

Review Comment:
   Could we strengthen this recovery test by returning a tool result longer 
than the configured 500-character limit and capturing the next model input?
   
   The current `"ok"` result would look the same whether or not the restored 
policy is applied. Asserting that the model receives the truncated result while 
the stored conversation retains the full result would verify the behavior after 
recovery, beyond just preserving the policy value.



-- 
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