From fa900e75d102bfcaedd4351a6f5e8cde972046aa Mon Sep 17 00:00:00 2001 From: Chibi Vikramathithan Date: Wed, 2 Dec 2026 21:05:56 -0800 Subject: [PATCH 1/2] fix(eval): retry legacy LLM judge on malformed tool call Judge models (e.g. anthropic.claude-sonnet-5) intermittently return a complete submit_evaluation tool call without the required score argument. The legacy LLM-as-judge and trajectory evaluators made a single attempt, so one malformed response became an error result scored 0 and dragged the run aggregate down. Retry the judge call up to 3 attempts in total when the tool call is malformed, and log each malformed attempt at WARNING with a preview of the arguments so future occurrences are diagnosable. SRE-696579 --- packages/uipath/pyproject.toml | 2 +- .../legacy_llm_as_judge_evaluator.py | 5 +- .../eval/evaluators/legacy_llm_helpers.py | 57 +++++++ .../evaluators/legacy_trajectory_evaluator.py | 5 +- .../evaluators/test_legacy_llm_judge_retry.py | 153 ++++++++++++++++++ packages/uipath/uv.lock | 2 +- 6 files changed, 216 insertions(+), 8 deletions(-) create mode 100644 packages/uipath/tests/evaluators/test_legacy_llm_judge_retry.py diff --git a/packages/uipath/pyproject.toml b/packages/uipath/pyproject.toml index dae9eebae..41d086e8f 100644 --- a/packages/uipath/pyproject.toml +++ b/packages/uipath/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath" -version = "2.15.15" +version = "2.15.16" description = "Python SDK and CLI for UiPath Platform, enabling programmatic interaction with automation services, process management, and deployment tools." readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/packages/uipath/src/uipath/eval/evaluators/legacy_llm_as_judge_evaluator.py b/packages/uipath/src/uipath/eval/evaluators/legacy_llm_as_judge_evaluator.py index ef2ab8a34..2f5866ce7 100644 --- a/packages/uipath/src/uipath/eval/evaluators/legacy_llm_as_judge_evaluator.py +++ b/packages/uipath/src/uipath/eval/evaluators/legacy_llm_as_judge_evaluator.py @@ -25,7 +25,7 @@ LegacyEvaluationCriteria, LegacyEvaluatorConfig, ) -from .legacy_llm_helpers import create_evaluation_tool, extract_tool_call_response +from .legacy_llm_helpers import create_evaluation_tool, request_evaluation logger = logging.getLogger(__name__) @@ -207,5 +207,4 @@ async def _get_llm_response(self, evaluation_prompt: str) -> LLMResponse: } assert self.llm, "LLM should be initialized before calling this method." - response = await self.llm.chat_completions(**request_data) - return extract_tool_call_response(response, model) + return await request_evaluation(self.llm, request_data, model) diff --git a/packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py b/packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py index 8cb8da0de..1e6fb06cb 100644 --- a/packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py +++ b/packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py @@ -15,6 +15,13 @@ logger = logging.getLogger(__name__) +# Tool schemas mark score/justification required, but providers such as +# Anthropic do not enforce `required` on tool arguments, so a judge model +# occasionally returns a complete submit_evaluation call without `score`. +# The miss is intermittent, so a fresh attempt almost always succeeds. +MAX_EVALUATION_ATTEMPTS = 3 +_ARGUMENTS_PREVIEW_CHARS = 500 + def create_evaluation_tool() -> ToolDefinition: """Create the standard evaluation tool definition for function calling. @@ -127,3 +134,53 @@ def extract_tool_call_response(response: Any, model: str) -> LLMResponse: logger.error(f"❌ {error_msg}") logger.debug(f"Response: {response}") raise ValueError(error_msg) from e + + +def _tool_call_arguments_preview(response: Any) -> str: + """Best-effort, truncated rendering of the first tool call's arguments.""" + try: + arguments = response.choices[0].message.tool_calls[0].arguments + except (AttributeError, IndexError, TypeError): + return "" + return repr(arguments)[:_ARGUMENTS_PREVIEW_CHARS] + + +async def request_evaluation( + llm: Any, + request_data: dict[str, Any], + model: str, + max_attempts: int = MAX_EVALUATION_ATTEMPTS, +) -> LLMResponse: + """Call the judge model and parse its submit_evaluation tool call. + + A response whose tool call is malformed (no tool call, missing or + non-numeric score, out-of-range score) is retried with a fresh request, up + to ``max_attempts`` in total. Transport errors are not retried here; the + LLM client owns those. + + Args: + llm: Chat service exposing an async ``chat_completions(**request_data)`` + request_data: Keyword arguments for ``chat_completions`` + model: The model name (for error logging) + max_attempts: Total number of judge calls allowed + + Returns: + LLMResponse parsed from the first well-formed tool call + + Raises: + ValueError: If every attempt returned a malformed tool call + """ + last_error: ValueError | None = None + for attempt in range(1, max_attempts + 1): + response = await llm.chat_completions(**request_data) + try: + return extract_tool_call_response(response, model) + except ValueError as e: + last_error = e + logger.warning( + f"Malformed submit_evaluation response from model {model} " + f"(attempt {attempt}/{max_attempts}): {e}. " + f"Tool call arguments: {_tool_call_arguments_preview(response)}" + ) + assert last_error is not None + raise last_error diff --git a/packages/uipath/src/uipath/eval/evaluators/legacy_trajectory_evaluator.py b/packages/uipath/src/uipath/eval/evaluators/legacy_trajectory_evaluator.py index 1368d9339..5cf598b64 100644 --- a/packages/uipath/src/uipath/eval/evaluators/legacy_trajectory_evaluator.py +++ b/packages/uipath/src/uipath/eval/evaluators/legacy_trajectory_evaluator.py @@ -26,7 +26,7 @@ LegacyEvaluationCriteria, LegacyEvaluatorConfig, ) -from .legacy_llm_helpers import create_evaluation_tool, extract_tool_call_response +from .legacy_llm_helpers import create_evaluation_tool, request_evaluation logger = logging.getLogger(__name__) @@ -175,5 +175,4 @@ async def _get_llm_response(self, evaluation_prompt: str) -> LLMResponse: "tool_choice": tool_choice, } - response = await self.llm.chat_completions(**request_data) - return extract_tool_call_response(response, model) + return await request_evaluation(self.llm, request_data, model) diff --git a/packages/uipath/tests/evaluators/test_legacy_llm_judge_retry.py b/packages/uipath/tests/evaluators/test_legacy_llm_judge_retry.py new file mode 100644 index 000000000..2f30892ac --- /dev/null +++ b/packages/uipath/tests/evaluators/test_legacy_llm_judge_retry.py @@ -0,0 +1,153 @@ +"""Legacy LLM judges retry a malformed submit_evaluation tool call. + +Production (SRE-696579): anthropic.claude-sonnet-5 intermittently answered the +forced submit_evaluation call without the required ``score`` argument. The +legacy evaluators made a single attempt, so one malformed response became an +``error`` result scored 0.0 and dragged the run-level aggregate down. +""" + +from types import SimpleNamespace +from typing import Any +from unittest.mock import patch + +import pytest + +from uipath.eval.evaluators.base_legacy_evaluator import LegacyEvaluationCriteria +from uipath.eval.evaluators.legacy_llm_as_judge_evaluator import ( + LegacyLlmAsAJudgeEvaluator, +) +from uipath.eval.evaluators.legacy_trajectory_evaluator import ( + LegacyTrajectoryEvaluator, +) +from uipath.eval.models.models import ( + ErrorEvaluationResult, + LegacyEvaluatorCategory, + LegacyEvaluatorType, + NumericEvaluationResult, + WorkloadExecution, +) + +MODEL = "anthropic.claude-sonnet-5" +MISSING_SCORE = {"justification": "Both outputs convey the same core message."} +WELL_FORMED = {"justification": "Semantically equivalent.", "score": 78} + + +def _response(arguments: dict[str, Any]) -> Any: + tool_call = SimpleNamespace( + id="call_1", name="submit_evaluation", arguments=arguments + ) + message = SimpleNamespace(content=None, tool_calls=[tool_call]) + return SimpleNamespace(choices=[SimpleNamespace(message=message)]) + + +class _ScriptedLlm: + """Stands in for UiPathLlmChatService, replaying one response per call.""" + + def __init__(self, *arguments: dict[str, Any]) -> None: + self._responses = [_response(a) for a in arguments] + self.calls = 0 + + async def chat_completions(self, **_: Any) -> Any: + response = self._responses[min(self.calls, len(self._responses) - 1)] + self.calls += 1 + return response + + +def _base_params(category: LegacyEvaluatorCategory) -> dict[str, Any]: + return { + "id": "c0eefd60", + "category": category, + "type": LegacyEvaluatorType.Custom, + "name": "Semantic similarity", + "description": "", + "createdAt": "2026-11-03T00:00:00Z", + "updatedAt": "2026-11-03T00:00:00Z", + "targetOutputKey": "*", + } + + +def _judge(llm: _ScriptedLlm) -> LegacyLlmAsAJudgeEvaluator: + with patch("uipath.platform.UiPath"): + evaluator = LegacyLlmAsAJudgeEvaluator( + **_base_params(LegacyEvaluatorCategory.LlmAsAJudge), + prompt="Expected: {{ExpectedOutput}}\nActual: {{ActualOutput}}", + model=MODEL, + ) + evaluator.llm = llm # type: ignore[assignment] + return evaluator + + +def _trajectory(llm: _ScriptedLlm) -> LegacyTrajectoryEvaluator: + with patch("uipath.platform.UiPath"): + evaluator = LegacyTrajectoryEvaluator( + **_base_params(LegacyEvaluatorCategory.Trajectory), + prompt="Behavior: {{ExpectedAgentBehavior}}\nRun: {{AgentRunHistory}}", + model=MODEL, + ) + evaluator.llm = llm # type: ignore[assignment] + return evaluator + + +_EXECUTION = WorkloadExecution( + agent_input={"question": "How do I enroll in eStatements?"}, + workload_output={"answer": "Use the web browser."}, + workload_trace=[], + expected_agent_behavior="Explains eStatements enrollment.", +) +_CRITERIA = LegacyEvaluationCriteria.model_validate( + { + "expectedOutput": {"answer": "Enroll via the web browser."}, + "expectedAgentBehavior": "Explains eStatements enrollment.", + } +) + +EVALUATORS = [ + pytest.param(_judge, id="llm-as-judge"), + pytest.param(_trajectory, id="trajectory"), +] + + +@pytest.mark.parametrize("make", EVALUATORS) +async def test_missing_score_once_is_retried_and_scored(make: Any) -> None: + llm = _ScriptedLlm(MISSING_SCORE, WELL_FORMED) + + result = await make(llm).evaluate(_EXECUTION, _CRITERIA) + + assert isinstance(result, NumericEvaluationResult), result.details + assert result.score == 78.0 + assert llm.calls == 2 + + +@pytest.mark.parametrize("make", EVALUATORS) +async def test_persistent_missing_score_still_errors(make: Any) -> None: + llm = _ScriptedLlm(MISSING_SCORE) + + result = await make(llm).evaluate(_EXECUTION, _CRITERIA) + + assert isinstance(result, ErrorEvaluationResult) + assert f"Missing 'score' in tool call arguments from model {MODEL}" in str( + result.details + ) + assert llm.calls == 3 + + +@pytest.mark.parametrize("make", EVALUATORS) +async def test_well_formed_first_response_makes_one_call(make: Any) -> None: + llm = _ScriptedLlm(WELL_FORMED) + + result = await make(llm).evaluate(_EXECUTION, _CRITERIA) + + assert isinstance(result, NumericEvaluationResult) + assert llm.calls == 1 + + +async def test_malformed_arguments_are_logged_at_warning( + caplog: pytest.LogCaptureFixture, +) -> None: + llm = _ScriptedLlm(MISSING_SCORE, WELL_FORMED) + + with caplog.at_level("WARNING"): + await _judge(llm).evaluate(_EXECUTION, _CRITERIA) + + warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] + assert any("attempt 1/3" in m and "justification" in m for m in warnings), warnings diff --git a/packages/uipath/uv.lock b/packages/uipath/uv.lock index ee06f3d06..9058b4ef2 100644 --- a/packages/uipath/uv.lock +++ b/packages/uipath/uv.lock @@ -2720,7 +2720,7 @@ wheels = [ [[package]] name = "uipath" -version = "2.15.15" +version = "2.15.16" source = { editable = "." } dependencies = [ { name = "applicationinsights" }, From 6e0ba5966fb6e2fbe8a462a30bf17afeae1eb06c Mon Sep 17 00:00:00 2001 From: Kal Date: Wed, 2 Dec 2026 22:54:16 -0800 Subject: [PATCH 2/2] fix(eval): sanitize legacy judge retry diagnostics --- .../legacy_llm_as_judge_evaluator.py | 5 +- .../eval/evaluators/legacy_llm_helpers.py | 240 +++++++++--------- .../evaluators/legacy_trajectory_evaluator.py | 5 +- .../evaluators/test_legacy_llm_helpers.py | 6 +- .../evaluators/test_legacy_llm_judge_retry.py | 168 +++++++++++- 5 files changed, 289 insertions(+), 135 deletions(-) diff --git a/packages/uipath/src/uipath/eval/evaluators/legacy_llm_as_judge_evaluator.py b/packages/uipath/src/uipath/eval/evaluators/legacy_llm_as_judge_evaluator.py index 2f5866ce7..1087b2443 100644 --- a/packages/uipath/src/uipath/eval/evaluators/legacy_llm_as_judge_evaluator.py +++ b/packages/uipath/src/uipath/eval/evaluators/legacy_llm_as_judge_evaluator.py @@ -161,10 +161,7 @@ def _create_evaluation_prompt( """Create the evaluation prompt for the LLM.""" # Validate that expected output is not empty if is_empty_value(expected_output): - logger.error( - "❌ EMPTY_EXPECTED_OUTPUT: Expected output is empty or contains only empty values. " - f"Received: {repr(expected_output)}" - ) + logger.error("EMPTY_EXPECTED_OUTPUT") raise UiPathEvaluationError( code="EMPTY_EXPECTED_OUTPUT", title="Expected output cannot be empty", diff --git a/packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py b/packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py index 1e6fb06cb..35e9e1df9 100644 --- a/packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py +++ b/packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py @@ -4,6 +4,8 @@ import math from typing import Any +from pydantic import ValidationError + from uipath.platform.chat.llm_gateway import ( ToolDefinition, ToolFunctionDefinition, @@ -18,9 +20,30 @@ # Tool schemas mark score/justification required, but providers such as # Anthropic do not enforce `required` on tool arguments, so a judge model # occasionally returns a complete submit_evaluation call without `score`. -# The miss is intermittent, so a fresh attempt almost always succeeds. MAX_EVALUATION_ATTEMPTS = 3 -_ARGUMENTS_PREVIEW_CHARS = 500 +_FINISH_REASONS = ( + "stop", + "tool_calls", + "function_call", + "length", + "max_tokens", + "end_turn", + "tool_use", + "content_filter", +) + + +class _MalformedEvaluationResponse(ValueError): + def __init__(self, reason: str, argument_shape: str) -> None: + super().__init__(reason) + self.argument_shape = argument_shape + + +def _finish_reason(choice: Any) -> str: + value = getattr(choice, "finish_reason", None) + if value is None: + return "missing" + return next((reason for reason in _FINISH_REASONS if reason == value), "unknown") def create_evaluation_tool() -> ToolDefinition: @@ -53,96 +76,71 @@ def create_evaluation_tool() -> ToolDefinition: def extract_tool_call_response(response: Any, model: str) -> LLMResponse: - """Extract the evaluation response from the tool call. + """Parse a judge response without echoing any provider-supplied values.""" + choices = getattr(response, "choices", None) + if not isinstance(choices, (list, tuple)) or not choices: + raise _MalformedEvaluationResponse( + "No choices in judge response", "unavailable" + ) - Args: - response: The response from the LLM chat completions API - model: The model name used for the request (for error logging) + message = getattr(choices[0], "message", None) + tool_calls = getattr(message, "tool_calls", None) + if not isinstance(tool_calls, (list, tuple)) or not tool_calls: + raise _MalformedEvaluationResponse( + "No tool calls in judge response", "unavailable" + ) - Returns: - LLMResponse: Parsed response with score and justification + arguments = getattr(tool_calls[0], "arguments", None) + if not isinstance(arguments, dict): + raise _MalformedEvaluationResponse( + "Tool call arguments are not an object", "non_object" + ) + if "score" not in arguments: + raise _MalformedEvaluationResponse( + "Missing 'score' in tool call arguments", "object" + ) + if "justification" not in arguments: + raise _MalformedEvaluationResponse( + "Missing 'justification' in tool call arguments", "object" + ) - Raises: - ValueError: If the response format is invalid or missing required fields - """ - try: - if not response.choices or len(response.choices) == 0: - error_msg = f"No choices in response from model {model}" - logger.error(f"❌ {error_msg}") - raise ValueError(error_msg) - - choice = response.choices[0] - message = choice.message - - if not message.tool_calls or len(message.tool_calls) == 0: - error_msg = f"No tool calls in response from model {model}" - logger.error(f"❌ {error_msg}") - logger.debug(f"Response: {response}") - raise ValueError(error_msg) - - tool_call = message.tool_calls[0] - arguments = tool_call.arguments - - if "score" not in arguments: - error_msg = f"Missing 'score' in tool call arguments from model {model}" - logger.error(f"❌ {error_msg}") - logger.debug(f"Arguments: {arguments}") - raise ValueError(error_msg) - - if "justification" not in arguments: - error_msg = ( - f"Missing 'justification' in tool call arguments from model {model}" - ) - logger.error(f"❌ {error_msg}") - logger.debug(f"Arguments: {arguments}") - raise ValueError(error_msg) + justification = arguments["justification"] + if not isinstance(justification, str): + raise _MalformedEvaluationResponse("Invalid justification format", "object") - try: - score = float(arguments["score"]) - except (ValueError, TypeError) as e: - error_msg = ( - f"Non-numeric score {arguments['score']!r} in tool call arguments " - f"from model {model}: expected a number between 0 and 100" - ) - logger.error(f"❌ {error_msg}") - logger.debug(f"Arguments: {arguments}") - raise ValueError(error_msg) from e - - justification = str(arguments["justification"]) - - # Models occasionally emit corrupted numeric tool arguments despite the - # 0-100 range stated in the tool schema (e.g. gemini-2.5-flash returning - # 989898 or 950). Unvalidated, such a value poisons every run-level - # aggregate downstream, so reject it and let the evaluation surface as - # an error instead of recording a fabricated score. - if not math.isfinite(score) or score < 0.0 or score > 100.0: - error_msg = ( - f"Invalid score {score!r} in tool call arguments from model {model}: " - f"expected a number between 0 and 100" - ) - logger.error(f"❌ {error_msg}") - raise ValueError(error_msg) - - logger.debug( - f"✅ Extracted score: {score}, justification length: {len(justification)} chars" + value = arguments["score"] + if isinstance(value, bool) or not isinstance(value, (int, float, str)): + raise _MalformedEvaluationResponse( + "Non-numeric score in tool call arguments", "object" + ) + try: + # Preserve numeric strings accepted by older SDK versions. + score = float(value) + except (TypeError, ValueError, OverflowError): + raise _MalformedEvaluationResponse( + "Non-numeric score in tool call arguments", "object" + ) from None + if not math.isfinite(score) or not 0.0 <= score <= 100.0: + raise _MalformedEvaluationResponse( + "Invalid score: expected a finite number between 0 and 100", "object" ) - return LLMResponse(score=score, justification=justification) - - except (KeyError, IndexError, AttributeError) as e: - error_msg = f"Failed to extract tool call response from model {model}: {str(e)}" - logger.error(f"❌ {error_msg}") - logger.debug(f"Response: {response}") - raise ValueError(error_msg) from e + return LLMResponse(score=score, justification=justification) -def _tool_call_arguments_preview(response: Any) -> str: - """Best-effort, truncated rendering of the first tool call's arguments.""" - try: - arguments = response.choices[0].message.tool_calls[0].arguments - except (AttributeError, IndexError, TypeError): - return "" - return repr(arguments)[:_ARGUMENTS_PREVIEW_CHARS] +def _gateway_rejected_tool_arguments(error: ValidationError) -> bool: + # The normalized SDK validates tool arguments as dictionaries before it + # returns. Only that schema failure is a response error we can retry. + failures = error.errors( + include_input=False, include_context=False, include_url=False + ) + return bool(failures) and all( + len(location := detail["loc"]) == 6 + and location[0] == "choices" + and location[2:4] == ("message", "tool_calls") + and location[-1] == "arguments" + for detail in failures + ) async def request_evaluation( @@ -151,36 +149,50 @@ async def request_evaluation( model: str, max_attempts: int = MAX_EVALUATION_ATTEMPTS, ) -> LLMResponse: - """Call the judge model and parse its submit_evaluation tool call. - - A response whose tool call is malformed (no tool call, missing or - non-numeric score, out-of-range score) is retried with a fresh request, up - to ``max_attempts`` in total. Transport errors are not retried here; the - LLM client owns those. - - Args: - llm: Chat service exposing an async ``chat_completions(**request_data)`` - request_data: Keyword arguments for ``chat_completions`` - model: The model name (for error logging) - max_attempts: Total number of judge calls allowed - - Returns: - LLMResponse parsed from the first well-formed tool call + """Retry malformed tool-call responses, not failed gateway requests.""" + if not 1 <= max_attempts <= MAX_EVALUATION_ATTEMPTS: + raise ValueError( + f"max_attempts must be between 1 and {MAX_EVALUATION_ATTEMPTS}" + ) - Raises: - ValueError: If every attempt returned a malformed tool call - """ - last_error: ValueError | None = None for attempt in range(1, max_attempts + 1): - response = await llm.chat_completions(**request_data) try: - return extract_tool_call_response(response, model) - except ValueError as e: - last_error = e - logger.warning( - f"Malformed submit_evaluation response from model {model} " - f"(attempt {attempt}/{max_attempts}): {e}. " - f"Tool call arguments: {_tool_call_arguments_preview(response)}" - ) - assert last_error is not None - raise last_error + response = await llm.chat_completions(**request_data) + except ValidationError as error: + if not _gateway_rejected_tool_arguments(error): + raise RuntimeError("Legacy judge response validation failed") from None + reason = "Gateway rejected the judge tool argument object" + argument_shape, finish_reason = "rejected_by_gateway", "unavailable" + except Exception: + # The legacy error result displays exception text. Gateway failures + # can embed response bodies, so don't re-export their exceptions. + raise RuntimeError("Legacy judge request failed") from None + else: + try: + return extract_tool_call_response(response, model) + except _MalformedEvaluationResponse as error: + reason, argument_shape = str(error), error.argument_shape + choices = getattr(response, "choices", None) + finish_reason = ( + _finish_reason(choices[0]) + if isinstance(choices, (list, tuple)) and choices + else "unavailable" + ) + + logger.warning( + "Malformed legacy judge response: %s (attempt %d/%d, shape=%s, finish_reason=%s)", + reason, + attempt, + max_attempts, + argument_shape, + finish_reason, + extra={ + "judge_response_shape": argument_shape, + "judge_finish_reason": finish_reason, + "judge_attempt": attempt, + "judge_max_attempts": max_attempts, + }, + ) + if attempt == max_attempts: + raise ValueError(f"{reason} after {attempt} attempt(s)") + raise AssertionError("validated judge retry loop did not run") diff --git a/packages/uipath/src/uipath/eval/evaluators/legacy_trajectory_evaluator.py b/packages/uipath/src/uipath/eval/evaluators/legacy_trajectory_evaluator.py index 5cf598b64..f42fd2033 100644 --- a/packages/uipath/src/uipath/eval/evaluators/legacy_trajectory_evaluator.py +++ b/packages/uipath/src/uipath/eval/evaluators/legacy_trajectory_evaluator.py @@ -117,10 +117,7 @@ def _create_evaluation_prompt( """Create the evaluation prompt for the LLM.""" # Validate that expected agent behavior is not empty if is_empty_value(expected_agent_behavior): - logger.error( - "❌ EMPTY_EXPECTED_AGENT_BEHAVIOR: Expected agent behavior is empty or contains only empty values. " - f"Received: {repr(expected_agent_behavior)}" - ) + logger.error("EMPTY_EXPECTED_AGENT_BEHAVIOR") raise UiPathEvaluationError( code="EMPTY_EXPECTED_AGENT_BEHAVIOR", title="Expected agent behavior cannot be empty", diff --git a/packages/uipath/tests/evaluators/test_legacy_llm_helpers.py b/packages/uipath/tests/evaluators/test_legacy_llm_helpers.py index c44f8d855..513b48d0c 100644 --- a/packages/uipath/tests/evaluators/test_legacy_llm_helpers.py +++ b/packages/uipath/tests/evaluators/test_legacy_llm_helpers.py @@ -37,7 +37,7 @@ def test_out_of_range_score_is_rejected(self) -> None: {"score": 989898, "justification": "matches perfectly"} ) - with pytest.raises(ValueError, match="Invalid score 989898"): + with pytest.raises(ValueError, match="Invalid score: expected a finite number"): extract_tool_call_response(response, "gemini-2.5-flash") def test_out_of_range_950_is_rejected(self) -> None: @@ -45,13 +45,13 @@ def test_out_of_range_950_is_rejected(self) -> None: # (the model most likely intended 95). response = _make_response({"score": 950, "justification": "equivalent"}) - with pytest.raises(ValueError, match="Invalid score 950"): + with pytest.raises(ValueError, match="Invalid score: expected a finite number"): extract_tool_call_response(response, "gemini-2.5-flash") def test_negative_score_is_rejected(self) -> None: response = _make_response({"score": -5, "justification": "bad"}) - with pytest.raises(ValueError, match="Invalid score -5"): + with pytest.raises(ValueError, match="Invalid score: expected a finite number"): extract_tool_call_response(response, "gpt-4o") @pytest.mark.parametrize("boundary", [0, 100]) diff --git a/packages/uipath/tests/evaluators/test_legacy_llm_judge_retry.py b/packages/uipath/tests/evaluators/test_legacy_llm_judge_retry.py index 2f30892ac..9f0fa1cac 100644 --- a/packages/uipath/tests/evaluators/test_legacy_llm_judge_retry.py +++ b/packages/uipath/tests/evaluators/test_legacy_llm_judge_retry.py @@ -26,24 +26,27 @@ NumericEvaluationResult, WorkloadExecution, ) +from uipath.platform.chat.llm_gateway import ChatCompletion MODEL = "anthropic.claude-sonnet-5" MISSING_SCORE = {"justification": "Both outputs convey the same core message."} WELL_FORMED = {"justification": "Semantically equivalent.", "score": 78} -def _response(arguments: dict[str, Any]) -> Any: +def _response(arguments: Any, finish_reason: str | None = "tool_calls") -> Any: tool_call = SimpleNamespace( id="call_1", name="submit_evaluation", arguments=arguments ) message = SimpleNamespace(content=None, tool_calls=[tool_call]) - return SimpleNamespace(choices=[SimpleNamespace(message=message)]) + return SimpleNamespace( + choices=[SimpleNamespace(message=message, finish_reason=finish_reason)] + ) class _ScriptedLlm: """Stands in for UiPathLlmChatService, replaying one response per call.""" - def __init__(self, *arguments: dict[str, Any]) -> None: + def __init__(self, *arguments: Any) -> None: self._responses = [_response(a) for a in arguments] self.calls = 0 @@ -125,7 +128,7 @@ async def test_persistent_missing_score_still_errors(make: Any) -> None: result = await make(llm).evaluate(_EXECUTION, _CRITERIA) assert isinstance(result, ErrorEvaluationResult) - assert f"Missing 'score' in tool call arguments from model {MODEL}" in str( + assert "Missing 'score' in tool call arguments after 3 attempt(s)" in str( result.details ) assert llm.calls == 3 @@ -141,13 +144,158 @@ async def test_well_formed_first_response_makes_one_call(make: Any) -> None: assert llm.calls == 1 -async def test_malformed_arguments_are_logged_at_warning( +_PAYLOAD = "DONOTLOG_fake_synthetic_payload" +_ZERO = {"score": 0, "justification": "Valid zero"} +_INVALID = [ + pytest.param({"justification": _PAYLOAD}, id="missing-score"), + pytest.param({"score": 10}, id="missing-justification"), + pytest.param({"score": True, "justification": _PAYLOAD}, id="boolean"), + pytest.param({"score": float("nan"), "justification": _PAYLOAD}, id="nan"), + pytest.param({"score": float("inf"), "justification": _PAYLOAD}, id="positive-inf"), + pytest.param( + {"score": float("-inf"), "justification": _PAYLOAD}, id="negative-inf" + ), + pytest.param({"score": 101, "justification": _PAYLOAD}, id="above-range"), + pytest.param({"score": -1, "justification": _PAYLOAD}, id="below-range"), + pytest.param({"score": _PAYLOAD, "justification": _PAYLOAD}, id="nonnumeric"), + pytest.param( + {"score": 10, "justification": {"field": _PAYLOAD}}, id="invalid-justification" + ), + pytest.param([_PAYLOAD], id="non-object"), +] + + +@pytest.mark.parametrize("make", EVALUATORS) +@pytest.mark.parametrize("invalid", _INVALID) +async def test_invalid_is_retried_and_preserves_a_valid_zero( + make: Any, invalid: Any +) -> None: + llm = _ScriptedLlm(invalid, _ZERO) + + result = await make(llm).evaluate(_EXECUTION, _CRITERIA) + + assert isinstance(result, NumericEvaluationResult) + assert result.score == 0.0 + assert llm.calls == 2 + + +@pytest.mark.parametrize("make", EVALUATORS) +async def test_malformed_response_does_not_log_or_return_payload( + make: Any, caplog: pytest.LogCaptureFixture +) -> None: + llm = _ScriptedLlm( + {"score": _PAYLOAD, "justification": _PAYLOAD, _PAYLOAD: _PAYLOAD} + ) + llm._responses[0].choices[0].finish_reason = _PAYLOAD + with caplog.at_level("DEBUG"): + result = await make(llm).evaluate(_EXECUTION, _CRITERIA) + + assert isinstance(result, ErrorEvaluationResult) + assert "Non-numeric score" in str(result.details) + assert _PAYLOAD not in str(result.details) + assert _PAYLOAD not in caplog.text + records = [r for r in caplog.records if hasattr(r, "judge_attempt")] + assert [vars(r)["judge_attempt"] for r in records] == [1, 2, 3] + assert all(vars(r)["judge_max_attempts"] == 3 for r in records) + assert all(vars(r)["judge_finish_reason"] == "unknown" for r in records) + assert all(vars(r)["judge_response_shape"] == "object" for r in records) + + +@pytest.mark.parametrize("make", EVALUATORS) +async def test_transport_failure_is_not_retried_or_exposed( + make: Any, caplog: pytest.LogCaptureFixture +) -> None: + llm = _ScriptedLlm() + with patch.object(llm, "chat_completions", side_effect=OSError(_PAYLOAD)) as call: + result = await make(llm).evaluate(_EXECUTION, _CRITERIA) + + assert isinstance(result, ErrorEvaluationResult) + assert "Legacy judge request failed" in str(result.details) + assert _PAYLOAD not in str(result.details) + assert _PAYLOAD not in caplog.text + assert call.await_count == 1 + + +@pytest.mark.parametrize("make", EVALUATORS) +async def test_gateway_schema_rejects_non_object_before_helper_and_retries( + make: Any, caplog: pytest.LogCaptureFixture +) -> None: + llm = _ScriptedLlm() + + # Use the actual normalized gateway response model: a non-object + # arguments field does not survive validation as a Python response. + def parse_gateway_response(*args: Any, **kwargs: Any) -> Any: + if call.await_count > 1: + return _response(_ZERO) + return ChatCompletion.model_validate( + { + "id": "test", + "object": "chat.completion", + "created": 0, + "model": MODEL, + "usage": { + "prompt_tokens": 1, + "completion_tokens": 1, + "total_tokens": 2, + }, + "choices": [ + { + "index": 0, + "message": { + "tool_calls": [ + { + "id": "t1", + "name": "submit_evaluation", + "arguments": [_PAYLOAD], + } + ] + }, + } + ], + } + ) + + with patch.object( + llm, "chat_completions", side_effect=parse_gateway_response + ) as call: + result = await make(llm).evaluate(_EXECUTION, _CRITERIA) + assert isinstance(result, NumericEvaluationResult), result.details + assert result.score == 0.0 + assert call.await_count == 2 + assert _PAYLOAD not in caplog.text + assert any( + getattr(r, "judge_response_shape", None) == "rejected_by_gateway" + for r in caplog.records + ) + + +async def test_finish_reason_does_not_conflate_truncation_with_normal_stop( caplog: pytest.LogCaptureFixture, ) -> None: - llm = _ScriptedLlm(MISSING_SCORE, WELL_FORMED) + llm = _ScriptedLlm(MISSING_SCORE, MISSING_SCORE, WELL_FORMED) + llm._responses[0].choices[0].finish_reason = "length" + llm._responses[1].choices[0].finish_reason = "stop" + result = await _judge(llm).evaluate(_EXECUTION, _CRITERIA) + assert isinstance(result, NumericEvaluationResult) + assert [ + vars(r)["judge_finish_reason"] + for r in caplog.records + if hasattr(r, "judge_finish_reason") + ] == ["length", "stop"] + - with caplog.at_level("WARNING"): - await _judge(llm).evaluate(_EXECUTION, _CRITERIA) +@pytest.mark.parametrize("make", EVALUATORS) +async def test_unrelated_gateway_schema_error_is_not_retried(make: Any) -> None: + llm = _ScriptedLlm() - warnings = [r.getMessage() for r in caplog.records if r.levelname == "WARNING"] - assert any("attempt 1/3" in m and "justification" in m for m in warnings), warnings + def parse_gateway_response(*args: Any, **kwargs: Any) -> Any: + return ChatCompletion.model_validate({"id": [_PAYLOAD]}) + + with patch.object( + llm, "chat_completions", side_effect=parse_gateway_response + ) as call: + result = await make(llm).evaluate(_EXECUTION, _CRITERIA) + assert isinstance(result, ErrorEvaluationResult) + assert "Legacy judge response validation failed" in str(result.details) + assert _PAYLOAD not in str(result.details) + assert call.await_count == 1