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


##########
plan/src/main/java/org/apache/flink/agents/plan/routing/RoutedChatRound.java:
##########
@@ -0,0 +1,421 @@
+/*
+ * 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.routing;
+
+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.model.routing.Escalation;
+import org.apache.flink.agents.api.context.MemoryObject;
+import org.apache.flink.agents.api.context.RunnerContext;
+import org.apache.flink.agents.api.event.ModelRoutingEvent;
+import org.apache.flink.agents.api.metrics.FlinkAgentsMetricGroup;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.actions.ChatModelAction;
+import org.apache.flink.agents.plan.actions.ChatModelInvoker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+
+/**
+ * One model round of a routed chat request: the attempts over the route's 
candidates until an
+ * answer is accepted. The strategy's pick goes first. An attempt that fails 
after its retries falls
+ * back to the next candidate the router allows; an answer a quality signal 
rejects is discarded,
+ * before any of its tool calls runs, and the same conversation goes to the 
next tier, where the
+ * request then stays. The routing events, the escalation metrics and the 
{@code model_routing}
+ * block are produced here. {@code ChatModelAction} resolves the route, runs 
the round and processes
+ * the accepted answer; it never sees the individual attempts.
+ *
+ * <p>The block is observability-only and needed once, on the final response. 
A round whose answer
+ * starts or continues a tool loop parks it in sensory memory, keyed by the 
initial request id, and
+ * the round that produces the final response takes it ({@link 
Accepted#parkForToolRound} and {@link
+ * Accepted#finish}). A tool round of a tiered request keeps the escalation 
policy in force ({@link
+ * #continuedRoute}) and folds its hops into the parked block.
+ */
+public final class RoutedChatRound {

Review Comment:
   Could we make the naming more consistent and explicit? Several names require 
reading the implementation to understand their meaning. Here are some 
suggestions:
   
   | Current name | Suggested name |
   |---|---|
   | `RoutedChatRound` | `ModelRoutingExecutor` |
   | `run()` | `execute()` |
   | `Accepted` | `ModelRoutingExecutor.Result` |
   | `RoundFailed` | `ModelRoutingExecutionException` |
   | `EscalationGate` | `EscalationEvaluator` |
   | `EscalationGate.Outcome` | `EscalationDecision` |
   | `check()` | `evaluate()` |
   | `hop()` | `buildEscalationRecord()` |
   | `hops` | `escalationHistory` |
   | `parkForToolRound()` | `saveRoutingMetadata()` |
   | `finish()` | `getAndClearRoutingMetadata()` |
   | `continuedRoute()` | `resolveRouteAfterToolCalls()` |
   | `attemptOrder()` | `getCandidateAttemptOrder()` |
   
   The exact names are open for discussion; the goal is to make the 
responsibilities clear from the names themselves.



##########
api/src/main/java/org/apache/flink/agents/api/resource/ResourceName.java:
##########
@@ -262,6 +262,10 @@ private VectorStore() {}
     // ==================== ModelRouter ====================
     public static final class ModelRouter {
 
+        /**
+         * The Java model router declaration ({@code 
ModelRouter.of(...).build()}). The descriptor
+         * carries this name; the plan module maps it to the resource it 
instantiates.

Review Comment:
   Could we follow the existing Java MCP pattern here? Since the API-side 
`ModelRouter` is now only a declaration builder, 
`ResourceName.ModelRouter.MODEL_ROUTER` could use a placeholder, with the plan 
layer replacing it with the actual implementation class before creating the 
resource provider.
   
   This would let us drop the changes to `JavaResourceProvider` and keep its 
generic class-based instantiation logic. The corresponding Java router constant 
in the Python API and the YAML/cross-language tests would need to be updated as 
well.



##########
plan/src/main/java/org/apache/flink/agents/plan/routing/RoutedChatRound.java:
##########
@@ -0,0 +1,421 @@
+/*
+ * 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.routing;
+
+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.model.routing.Escalation;
+import org.apache.flink.agents.api.context.MemoryObject;
+import org.apache.flink.agents.api.context.RunnerContext;
+import org.apache.flink.agents.api.event.ModelRoutingEvent;
+import org.apache.flink.agents.api.metrics.FlinkAgentsMetricGroup;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.actions.ChatModelAction;
+import org.apache.flink.agents.plan.actions.ChatModelInvoker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+
+/**
+ * One model round of a routed chat request: the attempts over the route's 
candidates until an
+ * answer is accepted. The strategy's pick goes first. An attempt that fails 
after its retries falls
+ * back to the next candidate the router allows; an answer a quality signal 
rejects is discarded,
+ * before any of its tool calls runs, and the same conversation goes to the 
next tier, where the
+ * request then stays. The routing events, the escalation metrics and the 
{@code model_routing}
+ * block are produced here. {@code ChatModelAction} resolves the route, runs 
the round and processes
+ * the accepted answer; it never sees the individual attempts.
+ *
+ * <p>The block is observability-only and needed once, on the final response. 
A round whose answer
+ * starts or continues a tool loop parks it in sensory memory, keyed by the 
initial request id, and
+ * the round that produces the final response takes it ({@link 
Accepted#parkForToolRound} and {@link
+ * Accepted#finish}). A tool round of a tiered request keeps the escalation 
policy in force ({@link
+ * #continuedRoute}) and folds its hops into the parked block.
+ */
+public final class RoutedChatRound {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(RoutedChatRound.class);
+
+    /** Sensory-memory key of the parked {@code model_routing} blocks, by 
initial request id. */
+    static final String ROUTING_METADATA_CONTEXT = "_ROUTING_METADATA_CONTEXT";
+
+    private RoutedChatRound() {}
+
+    /** The accepted attempt of a round, with the routing block that belongs 
to the request. */
+    public static final class Accepted {
+        private final UUID requestId;
+
+        /** The attempt whose answer was accepted: model, response and retry 
statistics. */
+        public final ChatModelInvoker.ChatAttemptResult attempt;
+
+        @Nullable private final Map<String, Object> routingMetadata;
+
+        Accepted(
+                UUID requestId,
+                ChatModelInvoker.ChatAttemptResult attempt,
+                @Nullable Map<String, Object> routingMetadata) {
+            this.requestId = requestId;
+            this.attempt = attempt;
+            this.routingMetadata = routingMetadata;
+        }
+
+        /**
+         * The answer starts or continues a tool loop: the block waits for the 
final response
+         * instead of being stamped on intermediate messages and copied 
through every tool round.
+         */
+        public void parkForToolRound(MemoryObject sensoryMemory) throws 
Exception {

Review Comment:
   Could we separate the result/route data from routing metadata management?
   
   `Accepted` currently writes to and clears sensory memory, while 
`ResolvedModelRoute` builds response metadata, merges escalation history, and 
extracts escalation counts.
   
   It would be clearer for `Result` to carry the model invocation result and 
routing metadata, and for `ResolvedModelRoute` to retain the route 
configuration and derived behavior, such as candidate attempt order. 
`ModelRoutingExecutor`, optionally through an internal helper, could own 
metadata assembly and storage. `ChatModelAction` would still decide whether to 
execute tools or complete the request and invoke the corresponding executor 
methods.



##########
plan/src/main/java/org/apache/flink/agents/plan/routing/RoutedChatRound.java:
##########
@@ -0,0 +1,421 @@
+/*
+ * 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.routing;
+
+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.model.routing.Escalation;
+import org.apache.flink.agents.api.context.MemoryObject;
+import org.apache.flink.agents.api.context.RunnerContext;
+import org.apache.flink.agents.api.event.ModelRoutingEvent;
+import org.apache.flink.agents.api.metrics.FlinkAgentsMetricGroup;
+import org.apache.flink.agents.api.resource.ResourceType;
+import org.apache.flink.agents.plan.actions.ChatModelAction;
+import org.apache.flink.agents.plan.actions.ChatModelInvoker;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.UUID;
+
+/**
+ * One model round of a routed chat request: the attempts over the route's 
candidates until an
+ * answer is accepted. The strategy's pick goes first. An attempt that fails 
after its retries falls
+ * back to the next candidate the router allows; an answer a quality signal 
rejects is discarded,
+ * before any of its tool calls runs, and the same conversation goes to the 
next tier, where the
+ * request then stays. The routing events, the escalation metrics and the 
{@code model_routing}
+ * block are produced here. {@code ChatModelAction} resolves the route, runs 
the round and processes
+ * the accepted answer; it never sees the individual attempts.
+ *
+ * <p>The block is observability-only and needed once, on the final response. 
A round whose answer
+ * starts or continues a tool loop parks it in sensory memory, keyed by the 
initial request id, and
+ * the round that produces the final response takes it ({@link 
Accepted#parkForToolRound} and {@link
+ * Accepted#finish}). A tool round of a tiered request keeps the escalation 
policy in force ({@link
+ * #continuedRoute}) and folds its hops into the parked block.
+ */
+public final class RoutedChatRound {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(RoutedChatRound.class);
+
+    /** Sensory-memory key of the parked {@code model_routing} blocks, by 
initial request id. */
+    static final String ROUTING_METADATA_CONTEXT = "_ROUTING_METADATA_CONTEXT";
+
+    private RoutedChatRound() {}
+
+    /** The accepted attempt of a round, with the routing block that belongs 
to the request. */
+    public static final class Accepted {
+        private final UUID requestId;
+
+        /** The attempt whose answer was accepted: model, response and retry 
statistics. */
+        public final ChatModelInvoker.ChatAttemptResult attempt;
+
+        @Nullable private final Map<String, Object> routingMetadata;
+
+        Accepted(
+                UUID requestId,
+                ChatModelInvoker.ChatAttemptResult attempt,
+                @Nullable Map<String, Object> routingMetadata) {
+            this.requestId = requestId;
+            this.attempt = attempt;
+            this.routingMetadata = routingMetadata;
+        }
+
+        /**
+         * The answer starts or continues a tool loop: the block waits for the 
final response
+         * instead of being stamped on intermediate messages and copied 
through every tool round.
+         */
+        public void parkForToolRound(MemoryObject sensoryMemory) throws 
Exception {
+            if (routingMetadata != null) {
+                park(sensoryMemory, requestId, routingMetadata);
+            }
+        }
+
+        /**
+         * The answer completes the request: the block to attach to the 
response, or null when the
+         * request never went through a router. Removes whatever the request 
had parked.
+         */
+        @Nullable
+        public Map<String, Object> finish(MemoryObject sensoryMemory) throws 
Exception {
+            Map<String, Object> parked = take(sensoryMemory, requestId);
+            return routingMetadata != null ? routingMetadata : parked;
+        }
+    }
+
+    /** The round produced no accepted answer; {@link #error} is what the 
request fails with. */
+    public static final class RoundFailed extends Exception {
+        public final Exception error;
+
+        RoundFailed(Exception error) {
+            super(error.getMessage(), error);
+            this.error = error;
+        }
+    }
+
+    /**
+     * Runs one round over the route's candidates.
+     *
+     * @throws RoundFailed when every reachable candidate failed, when a 
quality signal could not
+     *     judge the round, or when every tier answered and was rejected; the 
request's parked block
+     *     has been removed when it is thrown
+     */
+    public static Accepted run(
+            UUID requestId,
+            ResolvedModelRoute route,
+            List<ChatMessage> messages,
+            Map<String, Object> promptArgs,
+            @Nullable Object outputSchema,
+            RunnerContext ctx)
+            throws Exception {
+        int numRetries = ChatModelInvoker.configuredRetries(ctx);
+        int retryWaitIntervalSec = 
ChatModelInvoker.configuredRetryWaitSec(ctx);
+
+        List<String> triedModels = new ArrayList<>();
+        // Candidates whose answer a quality signal rejected this round: 
fallback skips them, since
+        // they already answered the request.
+        Set<String> rejected = new HashSet<>();
+        List<Map<String, Object>> hops = new ArrayList<>();
+        long escalatedTokens = 0L;
+        int escalations = route.getEscalationsSoFar();
+        Deque<String> pending = new ArrayDeque<>(route.attemptOrder());
+        // viaFallback: the candidate about to answer was reached because the 
previous one failed
+        // (drives the fallback event); fallbackAttempted: any failure fell 
through this round.
+        boolean viaFallback = false;
+        boolean fallbackAttempted = false;
+        String lastFailedModel = null;
+        Exception lastError = null;
+        while (!pending.isEmpty()) {
+            String candidate = pending.pollFirst();
+            if (rejected.contains(candidate)) {
+                continue;
+            }
+            triedModels.add(candidate);
+            try {
+                ChatModelInvoker.ChatAttemptResult result =
+                        ChatModelInvoker.chatWithRetries(
+                                requestId,
+                                candidate,
+                                route.durableChatCallId(candidate),
+                                messages,
+                                promptArgs,
+                                outputSchema,
+                                ctx,
+                                numRetries,
+                                retryWaitIntervalSec);
+                ChatModelAction.recordAttemptRetryStats(

Review Comment:
   Could we move `recordAttemptRetryStats()` and the related retry-stat 
storage, lookup, cleanup, and metric recording into an internal helper such as 
`ChatRetryStats`? The routing executor currently calls back into 
`ChatModelAction`, creating a dependency in both directions.
   
   Both classes could use the helper: the executor records each attempt, 
including failed attempts, while `ChatModelAction` reads the accumulated totals 
and clears them when the request completes.



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