wenjin272 commented on code in PR #1397:
URL: https://github.com/apache/flink-agents/pull/1397#discussion_r4662793136
##########
api/src/main/java/org/apache/flink/agents/api/agents/AgentExecutionOptions.java:
##########
@@ -124,4 +124,16 @@ public class AgentExecutionOptions {
"short-term-memory.state-ttl.visibility",
ShortTermMemoryTtlVisibility.class,
ShortTermMemoryTtlVisibility.NEVER_RETURN_EXPIRED);
+
+ public static final ConfigOption<Integer> LOOP_MAX_TURNS =
Review Comment:
Could we move the budget options out of `AgentExecutionOptions` into a
dedicated `ReActLoopBudgetOptions` class? Python could define the corresponding
class in the existing module without introducing a separate file.
##########
api/src/main/java/org/apache/flink/agents/api/agents/ReActLoopBudget.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.agents;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/** Independent limits for a single chat request and its tool rounds. */
+public final class ReActLoopBudget {
+ public enum BudgetMode {
+ SOFT,
+ HARD
+ }
+
+ @Nullable private final Integer maxTurns;
+ @Nullable private final Long maxTokens;
+ @Nullable private final Duration maxTime;
+ private final BudgetMode mode;
+
+ private ReActLoopBudget(
+ @Nullable Integer maxTurns,
+ @Nullable Duration maxTime,
+ @Nullable Long maxTokens,
+ BudgetMode mode) {
+ if (maxTurns != null && maxTurns <= 0 || maxTokens != null &&
maxTokens <= 0)
+ throw new IllegalArgumentException("ReAct loop limits must be
positive");
+ if (maxTime != null
+ && (maxTime.isNegative() || maxTime.isZero() ||
maxTime.getNano() % 1_000_000 != 0))
+ throw new IllegalArgumentException(
+ "max_time must be positive with millisecond precision");
+ if (maxTime != null) maxTime.toMillis();
+ this.maxTurns = maxTurns;
+ this.maxTokens = maxTokens;
+ this.maxTime = maxTime;
+ this.mode = Objects.requireNonNull(mode, "mode");
+ }
+
+ /** Creates a builder with unlimited budgets and soft termination. */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /** Builder for an immutable request-scoped budget. */
+ public static final class Builder {
+ @Nullable private Integer maxTurns;
+ @Nullable private Duration maxTime;
+ @Nullable private Long maxTokens;
+ private BudgetMode mode = BudgetMode.SOFT;
+
+ private Builder() {}
+
+ /** Sets the maximum ordinary inference rounds; null means unlimited.
*/
+ public Builder maxTurns(@Nullable Integer maxTurns) {
+ this.maxTurns = maxTurns;
+ return this;
+ }
+
+ /** Sets the elapsed-time limit; null means unlimited. */
+ public Builder maxTime(@Nullable Duration maxTime) {
+ this.maxTime = maxTime;
+ return this;
+ }
+
+ /** Sets the cumulative input/output token limit; null means
unlimited. */
+ public Builder maxTokens(@Nullable Long maxTokens) {
+ this.maxTokens = maxTokens;
+ return this;
+ }
+
+ /** Sets the termination mode; null selects the default SOFT mode. */
+ public Builder mode(@Nullable BudgetMode mode) {
+ this.mode = mode == null ? BudgetMode.SOFT : mode;
+ return this;
+ }
+
+ /**
+ * Builds a budget after validating its limits.
+ *
+ * @throws IllegalArgumentException if a limit is non-positive or time
has sub-millisecond
+ * precision
+ * @throws ArithmeticException if the time limit cannot be represented
in milliseconds as a
+ * long
+ */
+ public ReActLoopBudget build() {
+ return new ReActLoopBudget(maxTurns, maxTime, maxTokens, mode);
+ }
+ }
+
+ @Nullable
+ public Integer getMaxTurns() {
+ return maxTurns;
+ }
+
+ @Nullable
+ public Long getMaxTokens() {
+ return maxTokens;
+ }
+
+ @Nullable
+ public Duration getMaxTime() {
+ return maxTime;
+ }
+
+ public BudgetMode getMode() {
+ return mode;
+ }
+
+ @JsonValue
+ public Map<String, Object> toMap() {
Review Comment:
Could we use Jackson and Pydantic's built-in serialization instead of
maintaining manual map conversions? In Java, we could annotate the existing
constructor and properties and register `JavaTimeModule` for `Duration`. In
Python, we could use the native `timedelta` field handling. This would remove
the custom millisecond conversion while retaining business validation in the
constructor and validators. Please verify Java/Python round-tripping.
##########
api/src/main/java/org/apache/flink/agents/api/chat/model/BaseChatModelSetup.java:
##########
@@ -292,6 +292,15 @@ public List<ChatMessage> prepareRequestMessages(
return messages;
}
+ /** Applies the setup prompt and calls the model without tools or
tool-only parameters. */
+ public ChatResult chatWithoutTools(
Review Comment:
Could we reuse the existing `chat` API with explicit tools instead of adding
`chatWithoutTools`? The caller could first call `prepareRequestMessages`, then
invoke `chat` with an empty tool list. Please apply the same approach in Python.
##########
plan/src/main/java/org/apache/flink/agents/plan/actions/ReActLoopBudgetUtils.java:
##########
@@ -0,0 +1,164 @@
+/*
+ * 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.actions;
+
+import org.apache.flink.agents.api.agents.AgentExecutionOptions;
+import org.apache.flink.agents.api.agents.ReActLoopBudget;
+import org.apache.flink.agents.api.chat.messages.ChatResult;
+import org.apache.flink.agents.api.chat.messages.TokenUsage;
+import org.apache.flink.agents.api.context.DurableCallable;
+import org.apache.flink.agents.api.context.MemoryObject;
+import org.apache.flink.agents.api.context.RunnerContext;
+import org.apache.flink.agents.api.event.ChatRequestEvent;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+/** Request-scoped loop progress stored in sensory memory as checkpoint-safe
values. */
+final class ReActLoopBudgetUtils {
+ private ReActLoopBudgetUtils() {}
+
+ private static final Logger LOG =
LoggerFactory.getLogger(ReActLoopBudgetUtils.class);
+ static final String LOOP_BUDGET_CONTEXT = "_LOOP_BUDGET_CONTEXT";
+
+ static void initialize(RunnerContext ctx, ChatRequestEvent event) throws
Exception {
Review Comment:
Could we simplify `initialize` by separating budget resolution from
start-time initialization and reducing nested branches? Could we also avoid
redundant existence checks before reads and extract the repeated state keys
into constants? In Java, please use `BudgetMode.SOFT.name()` instead of the
literal `"SOFT"`. Please apply the relevant simplifications in Python as well.
##########
plan/src/main/java/org/apache/flink/agents/plan/actions/ChatModelInvoker.java:
##########
@@ -179,6 +179,31 @@ public static ChatAttemptResult chatWithRetries(
int numRetries,
long retryWaitMillis)
throws ChatAttemptFailed, Exception {
+ return chatWithRetries(
+ initialRequestId,
+ model,
+ durableCallId,
+ messages,
+ promptArgs,
+ outputSchema,
+ ctx,
+ numRetries,
+ retryWaitMillis,
+ false);
+ }
+
+ static ChatAttemptResult chatWithRetries(
Review Comment:
Could we keep a single `chatWithRetries` method with the `finalTurn`
parameter and update existing callers to pass `false`, rather than retaining an
overload that only supplies the default?
##########
plan/src/main/java/org/apache/flink/agents/plan/actions/ChatModelInvoker.java:
##########
@@ -240,8 +265,12 @@ public Class<InvocationOutcome> getResultClass() {
@Override
public InvocationOutcome call() throws Exception {
try {
- return new InvocationOutcome(
- chatModel.chat(messages, promptArgs,
Map.of()), null);
+ ChatResult response =
+ closing
+ ? chatModel.chatWithoutTools(
Review Comment:
Could we unify SOFT budget finalization and native structured-output
conversion through a shared `finalizeResponse()` helper accepting prepared
messages and an optional schema, with tools disabled?
SOFT finalization could pass the conversation history plus the closing
instruction and apply the native schema directly, avoiding a second conversion
call. Normal completion could retain the existing answer-conversion message.
Could we also rename the invoker's `closing` parameter to `finalTurn` and
let the shared helper append `:final` for both paths, removing
`BUDGET_FINALIZATION_SUFFIX`? Please align Java/Python and update the recovery
tests accordingly.
##########
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,391 @@
+/*
+ * 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 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.ActionStateSerde;
+import org.apache.flink.agents.runtime.actionstate.ActionStateStore;
+import org.apache.flink.agents.runtime.operator.ActionExecutionOperator;
+import org.apache.flink.agents.runtime.operator.ActionExecutionOperatorFactory;
+import org.apache.flink.api.common.typeinfo.TypeInformation;
+import org.apache.flink.api.java.functions.KeySelector;
+import org.apache.flink.runtime.checkpoint.OperatorSubtaskState;
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord;
+import org.apache.flink.streaming.util.KeyedOneInputStreamOperatorTestHarness;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.condition.EnabledForJreRange;
+import org.junit.jupiter.api.condition.JRE;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+
+import java.io.IOException;
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Runs real Python actions/resources through Pemja and the checkpointable
operator. */
+@EnabledForJreRange(min = JRE.JAVA_21)
Review Comment:
Could we add job-level E2E tests for Java-only, Python-only, and
cross-language scenarios, using deterministic mock chat models to verify
SOFT/HARD budget behavior through the public APIs, rather than relying solely
on the operator test harness?
Also, why does the entire test class require Java 21+, given that both chat
and tool async execution are disabled?
##########
plan/src/main/java/org/apache/flink/agents/plan/AgentConfiguration.java:
##########
@@ -107,7 +107,7 @@ public <T> void set(ConfigOption<T> option, T value) {
confData.put(option.getKey(), DurationUtils.format(parsed));
return;
}
- confData.put(option.getKey(), value);
+ confData.put(option.getKey(), value instanceof Enum<?> ? ((Enum<?>)
value).name() : value);
Review Comment:
Could you clarify why this enum-to-string conversion is needed? `get()`
already handles enum values, and Jackson serializes them as strings when
passing the plan to Python. If this only supports JSON round-tripping, could we
omit it?
##########
api/src/main/java/org/apache/flink/agents/api/agents/ReActLoopBudget.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.agents;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonValue;
+
+import javax.annotation.Nullable;
+
+import java.time.Duration;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+/** Independent limits for a single chat request and its tool rounds. */
+public final class ReActLoopBudget {
+ public enum BudgetMode {
+ SOFT,
+ HARD
+ }
+
+ @Nullable private final Integer maxTurns;
+ @Nullable private final Long maxTokens;
+ @Nullable private final Duration maxTime;
+ private final BudgetMode mode;
+
+ private ReActLoopBudget(
+ @Nullable Integer maxTurns,
+ @Nullable Duration maxTime,
+ @Nullable Long maxTokens,
+ BudgetMode mode) {
+ if (maxTurns != null && maxTurns <= 0 || maxTokens != null &&
maxTokens <= 0)
+ throw new IllegalArgumentException("ReAct loop limits must be
positive");
+ if (maxTime != null
+ && (maxTime.isNegative() || maxTime.isZero() ||
maxTime.getNano() % 1_000_000 != 0))
+ throw new IllegalArgumentException(
+ "max_time must be positive with millisecond precision");
+ if (maxTime != null) maxTime.toMillis();
+ this.maxTurns = maxTurns;
+ this.maxTokens = maxTokens;
+ this.maxTime = maxTime;
+ this.mode = Objects.requireNonNull(mode, "mode");
+ }
+
+ /** Creates a builder with unlimited budgets and soft termination. */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /** Builder for an immutable request-scoped budget. */
+ public static final class Builder {
Review Comment:
Could we move `Builder` to the end of `ReActLoopBudget`, keeping the main
class implementation together?
##########
plan/src/main/java/org/apache/flink/agents/plan/actions/ChatModelAction.java:
##########
@@ -375,19 +405,33 @@ private static void chat(
ChatModelInvoker.chatWithRetries(
initialRequestId,
candidate,
- selection.durableChatCallId(candidate),
- messages,
+ selection.durableChatCallId(candidate)
+ + (closing ?
BUDGET_FINALIZATION_SUFFIX : ""),
+ closing ? closingMessages(messages) : messages,
Review Comment:
Could we simplify the budget-related handling in three places?
- In Java, include routing metadata in `clearRequestContext` and rely on
`sendFailure` for cleanup, removing calls to `takeRoutingMetadata` that discard
the result.
- Prepare the closing messages once before the candidate loop.
- In Python, centralize the repeated “Soft finalization failed” wrapping in
the outer `_chat_resolved` failure handler, matching Java.
##########
plan/src/main/java/org/apache/flink/agents/plan/actions/ChatModelAction.java:
##########
@@ -361,8 +389,10 @@ private static void chat(
Map<String, Object> promptArgs,
@Nullable Object outputSchema,
@Nullable Map<String, Object> userContext,
- RunnerContext ctx)
+ RunnerContext ctx,
+ @Nullable String reason)
throws Exception {
+ boolean closing = reason != null;
Review Comment:
Could we rename `closing` in `ChatModelAction` to `budgetExhausted` to
reflect why finalization is triggered, while keeping `finalTurn` in
`ChatModelInvoker` to describe the invocation behavior?
--
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]