sangkyoonnam commented on code in PR #1497: URL: https://github.com/apache/flink-agents/pull/1497#discussion_r4776730570
########## python/flink_agents/plan/routing/escalation_evaluator.py: ########## @@ -0,0 +1,564 @@ +################################################################################ +# 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. +################################################################################# +"""Judge one routed round against a router's escalation policy. + +Mirrors ``org.apache.flink.agents.plan.routing.EscalationEvaluator``: the built-in +structural checks run first, then the declared signals in order. The first signal +that rejects the round decides the hop; a signal that cannot judge the round fails +the request. +""" + +import importlib +import inspect +import json +import logging +from concurrent.futures import CancelledError +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Mapping, Sequence +from uuid import UUID + +from jsonschema import Draft202012Validator + +from flink_agents.api.chat_message import ( + ChatMessage, + MediaBlock, + MessageRole, + TextBlock, + ToolCallBlock, + ToolResultBlock, +) +from flink_agents.api.chat_models.escalation import ( + ARGS_KEY, + DECISION_MODEL_KEY, + INSTRUCTIONS_KEY, + MIN_PROBABILITY_KEY, + SIGNAL_CLASS_KEY, + SIGNAL_TYPE_CUSTOM, + SIGNAL_TYPE_DECISION_MODEL, + Escalation, + EscalationSignal, + QualityContext, + QualitySignal, + QualityVerdict, +) +from flink_agents.api.chat_result import ChatResult +from flink_agents.api.decision_models import ( + DecisionRequest, + PredicateAnswer, + PredicateQuestion, +) +from flink_agents.api.resource import ResourceType +from flink_agents.api.runner_context import RunnerContext +from flink_agents.plan.actions import chat_retry_stats +from flink_agents.plan.actions.decision_model_action import decide_with_retries +from flink_agents.plan.resource.java.java_chat_model import JavaChatModelSetup + +if TYPE_CHECKING: + from flink_agents.api.chat_models.chat_model import BaseChatModelSetup + +_logger = logging.getLogger(__name__) + +# Signal name recorded for the built-in checks. +STRUCTURAL = "structural" +# Question key used for the decision-model signal. +QUESTION_KEY = "quality" +DEFAULT_INSTRUCTIONS = ( + "Does the ANSWER fully and correctly satisfy the REQUEST, with no missing steps," + " refusals, or placeholders? Judge the answer, not the question." +) + + +class SignalFailure(Exception): + """A signal could not judge the round; the request fails.""" + + +@dataclass(frozen=True) +class EscalationDecision: + """The decision to escalate a round, as Java's ``EscalationDecision``.""" + + from_tier: str + to_tier: str + signal: str + reason: str | None + score: float | None = None + + +def tier_index(policy: Escalation, candidate: str) -> int: + """Position of ``candidate`` in the tiers, or -1 when it is not a tier.""" + tiers = policy.tier_names + return tiers.index(candidate) if candidate in tiers else -1 + + +def can_escalate(policy: Escalation, candidate: str, escalations_so_far: int) -> bool: + """True when a rejected answer from ``candidate`` would move the request up a tier. + + The candidate is a tier below the last one and the request still has hops. A + fallback candidate outside the tiers never escalates. + """ + return ( + tier_index(policy, candidate) >= 0 + and policy.next_tier(candidate) is not None + and escalations_so_far < policy.effective_max_escalations + ) + + +def output_schema_rejected( + policy: Escalation, candidate: str, error: Exception +) -> EscalationDecision: + """The structural rejection of an answer the schema could not be applied to.""" + next_tier = policy.next_tier(candidate) + if next_tier is None: + msg = f"'{candidate}' is the last tier" + raise ValueError(msg) + return EscalationDecision( + candidate, + next_tier, + STRUCTURAL, + f"answer could not be shaped into the output schema: {_first_line(error)}", + ) + + +def _error_text(error: BaseException) -> str: + return f"{type(error).__name__}: {error}" + + +def _first_line(error: BaseException) -> str: + text = _error_text(error) + return text.split("\n", 1)[0].strip() + + +async def evaluate( + policy: Escalation, + request_id: UUID, + router: str, + candidate: str, + escalations_so_far: int, + messages: Sequence[ChatMessage], + prompt_args: Mapping[str, Any] | None, + response: ChatResult, + chat_model: "BaseChatModelSetup | None", + ctx: RunnerContext, +) -> EscalationDecision | None: + """Decide whether the round produced by ``candidate`` should escalate. + + Returns None to accept the round. Raises ``SignalFailure`` when a signal cannot + judge it (resource lookup, provider error after retries, a custom signal + raising); cancellation and durable storage failures propagate. + """ + if not can_escalate(policy, candidate, escalations_so_far): + return None + next_tier = policy.next_tier(candidate) + # A Java-declared candidate binds its tools on the Java side; the Python setup + # never opens them, so the tool checks cannot be applied to it. + tools_known = chat_model is not None and not isinstance( + chat_model, JavaChatModelSetup + ) + tools = _safe_tools(chat_model) if tools_known else [] + context = QualityContext( + request_id=request_id, + router=router, + candidate=candidate, + tier_index=tier_index(policy, candidate), + tiers=policy.tier_names, + messages=effective_messages(chat_model, messages, prompt_args), Review Comment: Thanks for the repro. Fixed in 55e86006: the chat action renders a gated Python candidate's prompt once and hands the evaluator the messages it sent, so the signal sees "A" too. `test_signal_sees_the_prompt_the_candidate_received` covers your case. Java's `EscalationEvaluator` has the same problem, since it calls `effectiveMessages` and renders the prompt again (EscalationEvaluator.java:147). I'll send a separate PR for the Java side unless you'd rather fold it in here. ########## python/flink_agents/plan/actions/chat_model_action.py: ########## @@ -887,17 +989,71 @@ async def attempt(candidate: str, durable_id: str) -> _ChatAttemptResult: output_schema, ctx, durable_id=durable_id, - final_turn=budget_reason is not None, + final_turn=final_turn, + gated=gated, ) if budget_reason is not None and result.response.tool_calls: msg = f"Soft finalization returned tool calls (budget reason: {budget_reason})" raise _InvalidClosingResponse(msg) return result + async def judge( + candidate: str, result: _ChatAttemptResult, escalations: int + ) -> tuple[EscalationDecision | None, _ChatAttemptResult, int]: + # Quality gate: on a tier below the last one, an answer that fails a + # structural check or a declared signal is discarded before any of its + # tool calls runs. + policy = selection.escalation + decision = await escalation_evaluator.evaluate( + policy, + initial_request_id, + selection.requested_model, + candidate, + escalations, + messages, Review Comment: The intent is to judge the answer against the original task. Like Java, the signal sees the messages before the closing instruction, and a tool call on the closing turn fails the attempt before the gate runs (ModelRoutingExecutor.java:184-190), so the tool checks never decide that turn. 55e86006 adds `test_closing_turn_signal_sees_the_task_without_the_instruction` for it. If you think the signal should know it was a closing turn, I can add that to `QualityContext`. -- 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]
