Repository navigation
fix: retry legacy LLM judge on missing score - [SRE-696579] #2039
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -4,6 +4,8 @@ | |||||||||||||||||||||
| import math | ||||||||||||||||||||||
| from typing import Any | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| from pydantic import ValidationError | ||||||||||||||||||||||
|
|
||||||||||||||||||||||
| from uipath.platform.chat.llm_gateway import ( | ||||||||||||||||||||||
| ToolDefinition, | ||||||||||||||||||||||
| ToolFunctionDefinition, | ||||||||||||||||||||||
|
|
@@ -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. | ||||||||||||||||||||||
|
|
@@ -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
|
||||||||||||||||||||||
| """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) | ||||||||||||||||||||||
| 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
|
||||||||||||||||||||||
| 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Dead code that also costs the Sonar gate. No caller passes
Suggested change
|
||||||||||||||||||||||
|
|
||||||||||||||||||||||
| 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟠 Every transport failure now shows the same message. On
Suggested change
|
||||||||||||||||||||||
| else: | ||||||||||||||||||||||
| try: | ||||||||||||||||||||||
| return extract_tool_call_response(response, model) | ||||||||||||||||||||||
| except _MalformedEvaluationResponse as error: | ||||||||||||||||||||||
| reason, argument_shape = str(error), error.argument_shape | ||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. I ran a Same family as the earlier
Suggested change
|
||||||||||||||||||||||
| raise AssertionError("validated judge retry loop did not run") | ||||||||||||||||||||||
There was a problem hiding this comment.
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
justificationisn't a string.maindidstr(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 onmain; I ran both versions.The check doesn't guarantee an explanation either:
"justification": ""still passes. Providers that don't enforcerequireddon't enforcetype: 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 theinvalid-justificationcase from_INVALIDin the new test file (the only test that changes).