sangkyoonnam commented on code in PR #1444:
URL: https://github.com/apache/flink-agents/pull/1444#discussion_r4711236652


##########
python/flink_agents/plan/routing/executor.py:
##########
@@ -0,0 +1,111 @@
+################################################################################
+#  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.
+#################################################################################
+"""Run a resolved route's candidates and keep its routing metadata."""
+
+from typing import Any, Awaitable, Callable, TypeVar
+from uuid import UUID
+
+from flink_agents.api.events.model_routing_event import ModelRoutingEvent
+from flink_agents.api.memory_object import MemoryObject
+from flink_agents.api.runner_context import RunnerContext
+from flink_agents.plan.routing.resolved_route import ResolvedModelRoute
+
+# Sensory-memory key; checkpointed state, so the name must not change.
+ROUTING_METADATA_CONTEXT = "_ROUTING_METADATA_CONTEXT"
+
+T = TypeVar("T")
+
+
+class CandidateAttemptFailed(Exception):
+    """A candidate exhausted its retry budget or could not be prepared."""
+
+    def __init__(self, error: Exception) -> None:
+        """Wrap the candidate's final error."""
+        super().__init__(str(error))
+        self.error = error
+
+
+class ModelRoutingExecutionException(Exception):
+    """Every candidate in the attempt order failed."""
+
+    def __init__(self, tried: list[str], errors: list[Exception]) -> None:
+        """Keep each candidate's cause, in attempt order."""
+        super().__init__(f"all {len(tried)} candidates failed")
+        self.tried = tried
+        self.errors = errors
+
+
+async def execute(
+    initial_request_id: UUID,
+    selection: ResolvedModelRoute,
+    attempt: Callable[[str, str], Awaitable[T]],
+    ctx: RunnerContext,
+) -> tuple[str, T]:
+    """Try the route's candidates in order and return the first that answers.
+
+    ``attempt(candidate, durable_id)`` raises ``CandidateAttemptFailed`` to 
move on to
+    the next candidate. For a router, a fallback answer is announced with a
+    ``ModelRoutingEvent`` and the route's response metadata is stored for the 
request.
+    """
+    tried: list[str] = []
+    errors: list[Exception] = []
+    for candidate in selection.attempt_order():
+        tried.append(candidate)
+        try:
+            result = await attempt(candidate, 
selection.durable_chat_call_id(candidate))
+        except CandidateAttemptFailed as failure:
+            errors.append(failure.error)
+            continue
+        if selection.is_router:
+            if candidate != selection.selected_model:
+                ctx.send_event(
+                    ModelRoutingEvent(
+                        request_id=initial_request_id,
+                        router=selection.requested_model,
+                        candidates=selection.candidates,
+                        selected_model=candidate,
+                        decision_source="fallback",
+                        fallback_enabled=selection.fallback_enabled,
+                        reason=f"fallback after selected model 
'{selection.selected_model}' failed",
+                        metadata=selection.metadata,
+                    )
+                )
+            _store_metadata(

Review Comment:
   Done in 1272fe72. `execute` now returns an `ExecutionResult` with the 
round's routing metadata and stores nothing. `plan/routing/metadata.py` builds, 
saves and takes the block, as `RoutingMetadata` does in Java, and 
`ResolvedModelRoute` no longer builds it. The chat action goes through 
`save_routing_metadata` before a tool loop, `get_and_clear_routing_metadata` 
for the final response and `clear_routing_metadata` on failure, so it no longer 
touches the storage key. The sensory-memory key is unchanged.
   
   



##########
python/flink_agents/plan/routing/model_router.py:
##########
@@ -0,0 +1,93 @@
+################################################################################
+#  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.
+#################################################################################
+"""The model router resource the engine instantiates for a router 
declaration."""
+
+from typing import Any
+
+from pydantic import Field, PrivateAttr, model_validator
+
+from flink_agents.api.chat_models.routing import RouterDeclaration, 
RoutingStrategy
+from flink_agents.api.resource import (
+    Resource,
+    ResourceDescriptor,
+    ResourceName,
+    ResourceType,
+)
+
+# The class path a declaration names: the placeholder the builder and the YAML
+# ``router`` alias write, which is also the path of the api declaration class 
that
+# descriptors named while the declaration was the resource.
+_DECLARATION_CLASS = ResourceName.ModelRouter.MODEL_ROUTER
+
+
+class ModelRouter(Resource):
+    """The ``MODEL_ROUTER`` resource: a router declaration decoded for the 
engine.
+
+    It selects nothing by itself; ``flink_agents.plan.routing.resolver`` asks 
the
+    strategy for the first model. The declaration rules run when the agent 
plan is
+    built or restored (``validate_routing``), and again here on the effective
+    arguments, because the provider merges ``ModelRouter.*`` configuration 
into the
+    descriptor arguments when it creates this resource.
+    """
+
+    _routing_executor: Any = PrivateAttr(default=None)
+
+    candidates: list[str]
+    candidate_descriptions: dict[str, str] = Field(default_factory=dict)
+    default_model: str | None = None
+    fallback: bool = False
+    strategy_type: str
+    strategy_args: dict[str, Any] = Field(default_factory=dict)
+    strategy_executor_class: str | None = None
+
+    @model_validator(mode="after")
+    def _validate_effective_arguments(self) -> "ModelRouter":
+        RouterDeclaration(
+            **self.model_dump(include=set(RouterDeclaration.model_fields))
+        )
+        return self
+
+    @classmethod
+    def resource_type(cls) -> ResourceType:
+        """Return the router resource type."""
+        return ResourceType.MODEL_ROUTER
+
+    @property
+    def strategy(self) -> RoutingStrategy:
+        """Return the strategy declaration."""
+        return RoutingStrategy(
+            self.strategy_type, self.strategy_args, 
self.strategy_executor_class
+        )
+
+    @staticmethod
+    def resource_descriptor(declaration: ResourceDescriptor) -> 
ResourceDescriptor:
+        """Return ``declaration`` with this class named as the resource to 
provide.
+
+        A Python descriptor that names the declaration is provided as this 
resource.
+        Any other descriptor, including a Java one, is returned unchanged.
+        """
+        if declaration.language != "python" or (
+            f"{declaration.target_module}.{declaration.target_clazz}"
+            != _DECLARATION_CLASS
+        ):
+            return declaration

Review Comment:
   Done in 0c164c07. Every Python router descriptor is now provided as the 
plan-side `ModelRouter`, whatever class it names, and custom `clazz` 
replacement is gone. The placeholder is `MODEL_ROUTER_PLACEHOLDER` in both 
languages and the MCP one is `MCP_SERVER_PLACEHOLDER`, with the aliases, tests 
and the resource consistency script updated. Python descriptors need a 
`module.ClassName`, so `ResourceDescriptor` now accepts the bare placeholder as 
a Python class; it's never imported, since the plan names the resource first. I 
kept the Java constant names (`ModelRouter.MODEL_ROUTER`, `MCP_SERVER`) and 
changed only their values. Happy to rename the constants too if you'd prefer.
   



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