Skip to content
Open
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.16"
version = "2.15.17"
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)
247 changes: 172 additions & 75 deletions packages/uipath/src/uipath/eval/evaluators/legacy_llm_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,55 @@
import math
from typing import Any

from pydantic import ValidationError

from uipath.platform.chat.llm_gateway import (
ToolDefinition,
ToolFunctionDefinition,
ToolParametersDefinition,
ToolPropertyDefinition,
)
from uipath.platform.errors import EnrichedException

from ..models.models import LLMResponse

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
# The normalized gateway defaults to 4096. Give a truncated tool call
# one larger output window rather than sending the same capped request.
_DEFAULT_GATEWAY_MAX_TOKENS = 4096
_TRUNCATION_RETRY_MAX_TOKENS = 8000
_RETRY_INSTRUCTION = (
"Call submit_evaluation with a numeric score (0-100) and a justification."
)
_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 +83,144 @@
)


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

Check warning on line 86 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.

Args:
response: The response from the LLM chat completions API
model: The model name used for the request (for error logging)
"""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"
)

Returns:
LLMResponse: Parsed response with score and justification
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"
)

Raises:
ValueError: If the response format is invalid or missing required fields
"""
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"
)
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:
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)

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"
# 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)
# Older SDKs stringified a supplied justification. Do not turn an
# otherwise valid score into an error if the provider omits it.
justification = str(arguments.get("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 148 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 29 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,
) -> LLMResponse:
"""Retry recoverable malformed tool calls without exposing the response."""
attempt_data = request_data
truncation_retry_sent = False
for attempt in range(1, MAX_EVALUATION_ATTEMPTS + 1):
try:
response = await llm.chat_completions(**attempt_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 EnrichedException as error:
# Retain the numeric status, not the URL or response body.
raise RuntimeError(
f"Legacy judge request failed (HTTP {error.status_code})"
) from None
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

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_EVALUATION_ATTEMPTS,
argument_shape,
finish_reason,
extra={
"judge_response_shape": argument_shape,
"judge_finish_reason": finish_reason,
"judge_attempt": attempt,
"judge_max_attempts": MAX_EVALUATION_ATTEMPTS,
},
)
# Normalization can reject malformed arguments before we see the
# finish reason. That could be a terminal content filter, not truncation.
if (
attempt == MAX_EVALUATION_ATTEMPTS
or finish_reason == "content_filter"
or argument_shape == "rejected_by_gateway"
or truncation_retry_sent
):
break
if finish_reason in ("length", "max_tokens"):
if attempt_data.get("max_tokens", _DEFAULT_GATEWAY_MAX_TOKENS) >= (
_TRUNCATION_RETRY_MAX_TOKENS
):
break
attempt_data = {**attempt_data, "max_tokens": _TRUNCATION_RETRY_MAX_TOKENS}
truncation_retry_sent = True
if attempt_data["messages"] is request_data["messages"]:
attempt_data = {
**attempt_data,
"messages": [
*request_data["messages"],
{"role": "user", "content": _RETRY_INSTRUCTION},
],
}

raise ValueError(
f"{reason} after {attempt} attempt(s) (finish_reason={finish_reason})"
)
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