Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/uipath/pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -207,5 +204,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)
217 changes: 143 additions & 74 deletions packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import math
from typing import Any

from pydantic import ValidationError

from uipath.platform.chat.llm_gateway import (
ToolDefinition,
ToolFunctionDefinition,
Expand All @@ -15,6 +17,34 @@

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`.
MAX_EVALUATION_ATTEMPTS = 3
_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:
"""Create the standard evaluation tool definition for function calling.
Expand Down Expand Up @@ -45,85 +75,124 @@
)


def extract_tool_call_response(response: Any, model: str) -> LLMResponse:

Check warning on line 78 in packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove the unused function parameter "model".

See more on https://sonarcloud.io/project/issues?id=UiPath_uipath-python&issues=AaI6tplRARGzJaXKbhR9&open=AaI6tplRARGzJaXKbhR9&pullRequest=2039
"""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")
Comment on lines +108 to +109

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 A valid score is now thrown away when justification isn't a string. main did str(arguments["justification"]). With this check, {"score": 78, "justification": null} (or a list / object) makes 3 calls and ends as a 0-scored error, Invalid justification format after 3 attempt(s). The same response scored 78 on main; I ran both versions.

The check doesn't guarantee an explanation either: "justification": "" still passes. Providers that don't enforce required don't enforce type: string, so a judge that answers this way fails on every item once consumers pick up 2.15.16. Keep the old coercion, as the numeric-string case below does, and drop the invalid-justification case from _INVALID in the new test file (the only test that changes).

Suggested change
if not isinstance(justification, str):
raise _MalformedEvaluationResponse("Invalid justification format", "object")
if not isinstance(justification, str):
# Older SDK versions stringified this; keep the valid score.
justification = str(justification)


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

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(

Check failure on line 146 in packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this function to reduce its Cognitive Complexity from 20 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=UiPath_uipath-python&issues=AaI6tplRARGzJaXKbhR-&open=AaI6tplRARGzJaXKbhR-&pullRequest=2039
llm: Any,
request_data: dict[str, Any],
model: str,
max_attempts: int = MAX_EVALUATION_ATTEMPTS,
) -> LLMResponse:
"""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}"
)
Comment on lines +150 to +156

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Dead code that also costs the Sonar gate. No caller passes max_attempts, so this range check and the raise AssertionError on line 198 can never run. They are probably the uncovered lines behind Sonar's 89.6% (it needs 90%). Drop the parameter, use the constant in the loop (range(1, MAX_EVALUATION_ATTEMPTS + 1)), and replace the in-loop if attempt == max_attempts and the final AssertionError with one raise ValueError(f"{reason} after {MAX_EVALUATION_ATTEMPTS} attempt(s)") after the loop.

Suggested change
max_attempts: int = MAX_EVALUATION_ATTEMPTS,
) -> LLMResponse:
"""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}"
)
) -> LLMResponse:
"""Retry malformed tool-call responses, not failed gateway requests."""


for attempt in range(1, max_attempts + 1):
try:
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
Comment on lines +166 to +169

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 Every transport failure now shows the same message. On main, a 401, 403, 404 (unknown model) or 429 reached the eval result as Exception thrown by evaluator: <status + URL>. Now all of them become Legacy judge request failed, and from None drops the cause, so nobody can tell an auth problem from throttling without a repro. EnrichedException.status_code is an int and holds no response text, so it is safe to keep.

Suggested change
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
except Exception as error:
# Keep only type and HTTP status; exception text can embed response bodies.
status = getattr(error, "status_code", None)
raise RuntimeError(
f"Legacy judge request failed ({type(error).__name__}, status={status})"
) from None

else:
try:
return extract_tool_call_response(response, model)
except _MalformedEvaluationResponse as error:
reason, argument_shape = str(error), error.argument_shape

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Retries can't change the outcome in some cases, and they multiply cost. Each retry sends the identical request again at once (default temperature=0, no hint to the model). A content_filter finish usually comes back with no tool call, so it is retried twice more and filtered the same way each time. Under line_by_line_evaluation, the worst case is 3 calls per line. Fail fast when a retry can't help:

if finish_reason == "content_filter":
    raise ValueError(f"{reason} (content_filter)")

Also consider adding a one-line corrective user message on retry (for example "Call submit_evaluation with both score (0-100) and justification") so the retry has a better chance than resampling at temperature 0.

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)")
Comment on lines +196 to +197

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 A truncated answer is retried with the same request and the same output cap. finish_reason is logged but never used. The legacy evaluators don't set max_tokens, so every attempt goes out with the gateway default of 4096 (_llm_gateway_service.py:417). The tool schema lists justification before score, so an answer cut at the cap loses score first, which is the incident shape (the new test_finish_reason_does_not_conflate_truncation_with_normal_stop scripts exactly that).

I ran a finish_reason="length" response through the real UiPathLlmChatService: 3 identical POSTs, each with max_tokens=4096 and temperature=0, and the same Missing 'score' error at the end. The description says truncation isn't ruled out. If that is the cause, this PR triples the cost of those items without fixing them, and the eval result can't show it, because the reason only reaches the warning log.

Same family as the earlier content_filter thread, different fix: put the allowlisted finish_reason in the final error so the result says length, and on length / max_tokens retry with a larger max_tokens where the model allows it instead of the same body (the newer judge already sends 8000 for Claude 4.5, llm_as_judge_evaluator.py:257).

Suggested change
if attempt == max_attempts:
raise ValueError(f"{reason} after {attempt} attempt(s)")
if attempt == max_attempts:
raise ValueError(
f"{reason} after {attempt} attempt(s) (finish_reason={finish_reason})"
)

raise AssertionError("validated judge retry loop did not run")
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -175,5 +172,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)
6 changes: 3 additions & 3 deletions packages/uipath/tests/evaluators/test_legacy_llm_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,21 +37,21 @@ 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:
# Second production occurrence from the same eval run: score=950
# (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])
Expand Down
Loading
Loading