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


##########
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:
   I went with the placeholder. Naming a plan class in api was not a good idea.
   
   The plan sets the router class before it creates the provider, when it 
compiles an agent and when it restores a plan. A plan that still names the api 
class keeps working. JavaResourceProvider is the same as main again. The Python 
constant and the YAML and cross-language tests are updated.
   
   Done in 409a43e2.
   



##########
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:
   Done in 0a07cd1a. Names are as in your table. EscalationDecision and 
ModelRoutingExecutionException are top-level classes.
   



##########
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:
   Done in 5cdc5f0c. Result carries the request id, the attempt and the routing 
metadata. ResolvedModelRoute keeps the route only. A RoutingMetadata helper 
builds and stores the block for the executor. ChatModelAction calls 
saveRoutingMetadata or getAndClearRoutingMetadata.
   



##########
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:
   Done in 857ae1ce. The executor records every attempt there. ChatModelAction 
reads the totals and clears them. The strategy executors and the evaluator use 
it too.
   



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