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-platform/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "uipath-platform"
version = "0.3.23"
version = "0.3.24"
description = "HTTP client library for programmatic access to UiPath Platform"
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 @@ -62,6 +62,7 @@
BatchTransformFailedException,
BatchTransformNotCompleteException,
ContextGroundingIndexNotFoundError,
EnrichedException,
OperationNotCompleteException,
)
from uipath.platform.orchestrator.job import JobState
Expand Down Expand Up @@ -90,6 +91,20 @@ def _documents_service(
)


# Auth (job token), timeouts, conflicts and throttling are not the caller's fault.
_SYSTEM_CLIENT_STATUSES = frozenset({401, 408, 409, 429})


def _trigger_creation_category(error: Exception) -> ErrorCategory:
if (
isinstance(error, EnrichedException)
and 400 <= error.status_code < 500
and error.status_code not in _SYSTEM_CLIENT_STATUSES
):
return ErrorCategory.USER
return ErrorCategory.SYSTEM


def _try_convert_to_json_format(value: str | None) -> Any:
"""Attempts to parse a string as JSON and returns the parsed object or original string.

Expand Down Expand Up @@ -521,6 +536,7 @@ async def create_trigger(self, suspend_value: Any) -> UiPathResumeTrigger:
unknown model type is encountered.
Exception: If any underlying UiPath service calls fail.
"""
trigger_type: UiPathResumeTriggerType | None = None
try:
trigger_type = self._determine_trigger_type(suspend_value)
trigger_name = self._determine_trigger_name(suspend_value)
Expand Down Expand Up @@ -576,10 +592,13 @@ async def create_trigger(self, suspend_value: Any) -> UiPathResumeTrigger:
except UiPathFaultedTriggerError:
raise
except Exception as e:
message = (
f"Failed to create resume trigger of type {trigger_type.value}"
if trigger_type is not None
else "Failed to create resume trigger"
)
raise UiPathFaultedTriggerError(
ErrorCategory.SYSTEM,
"Failed to create HITL action",
f"{str(e)}",
_trigger_creation_category(e), message, str(e)
) from e
return resume_trigger

Expand All @@ -590,11 +609,19 @@ async def _create_external_trigger(self, external_trigger: ExternalTrigger):
return

uipath = UiPath()
await uipath.api_client.request_async(
method="POST",
url="orchestrator_/api/JobTriggers/SaveExternalTrigger",
json=external_trigger.model_dump(by_alias=True),
)
try:
await uipath.api_client.request_async(
method="POST",
url="orchestrator_/api/JobTriggers/SaveExternalTrigger",
json=external_trigger.model_dump(by_alias=True),
)
except Exception as e:
# Our own call: a 4xx here is not the caller's fault.
raise UiPathFaultedTriggerError(
ErrorCategory.SYSTEM,
"Failed to register the resume trigger with Orchestrator",
str(e),
) from e

def _determine_trigger_type(self, value: Any) -> UiPathResumeTriggerType:
"""Determines the resume trigger type based on the input value.
Expand Down
136 changes: 135 additions & 1 deletion packages/uipath-platform/tests/services/test_hitl.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import Any
from unittest.mock import AsyncMock, patch

import httpx
import pytest
from pytest_httpx import HTTPXMock
from uipath.core.errors import ErrorCategory, UiPathFaultedTriggerError
Expand Down Expand Up @@ -72,7 +73,10 @@
ValidateExtractionAction,
)
from uipath.platform.documents.documents import DocumentsApiVersion
from uipath.platform.errors import ContextGroundingIndexNotFoundError
from uipath.platform.errors import (
ContextGroundingIndexNotFoundError,
EnrichedException,
)
from uipath.platform.orchestrator import Job, JobErrorInfo
from uipath.platform.orchestrator.job import JobState
from uipath.platform.resume_triggers import (
Expand All @@ -97,6 +101,23 @@ def setup_test_env(
monkeypatch.setenv(key, value)


def _http_error(status_code: int, url: str, message: str) -> EnrichedException:
request = httpx.Request("POST", url)
response = httpx.Response(status_code, request=request, json={"message": message})
return EnrichedException(
httpx.HTTPStatusError("http error", request=request, response=response)
)


def _ecs_create_deep_rag_error(status_code: int) -> EnrichedException:
return _http_error(
status_code,
"https://cloud.uipath.com/org/tenant/ecs_/v2/indexes/idx/createDeepRag",
"No valid files to use for Summarization. Please update and resync your "
"index, or use a different matching pattern.",
)


class TestHitlReader:
"""Tests for the HitlReader class."""

Expand Down Expand Up @@ -1843,6 +1864,119 @@ async def test_missing_deep_rag_index_is_deployment_error(
assert error.detail == "ContextGroundingIndex 'Files' not found"
assert error.__cause__ is missing_index

@pytest.mark.anyio
@pytest.mark.parametrize(
("status_code", "expected_category"),
[
(400, ErrorCategory.USER),
(401, ErrorCategory.SYSTEM),
(403, ErrorCategory.USER),
(404, ErrorCategory.USER),
(408, ErrorCategory.SYSTEM),
(409, ErrorCategory.SYSTEM),
(429, ErrorCategory.SYSTEM),
(500, ErrorCategory.SYSTEM),
],
)
async def test_deep_rag_http_failure_category_follows_status(
self,
setup_test_env: None,
status_code: int,
expected_category: ErrorCategory,
) -> None:
create_deep_rag = CreateDeepRag(
name="test-deep-rag",
index_name="Files",
prompt="test prompt",
glob_pattern="**/*.pdf",
citation_mode=CitationMode.INLINE,
index_folder_path="/test/path",
)
ecs_error = _ecs_create_deep_rag_error(status_code)

with patch(
"uipath.platform.context_grounding._context_grounding_service.ContextGroundingService.start_deep_rag_async",
new=AsyncMock(side_effect=ecs_error),
):
with pytest.raises(UiPathFaultedTriggerError) as exc_info:
await UiPathResumeTriggerCreator().create_trigger(create_deep_rag)

error = exc_info.value
assert (error.category, error.message) == (
expected_category,
"Failed to create resume trigger of type DeepRag",
)
assert "HITL" not in str(error)
assert "No valid files to use for Summarization" in error.detail
assert error.__cause__ is ecs_error

@pytest.mark.anyio
async def test_external_trigger_registration_client_error_stays_system(
self,
setup_test_env: None,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv("UIPATH_JOB_KEY", "test-job-key")
wait_deep_rag = WaitDeepRag(
deep_rag=DeepRagCreationResponse(
id="test-deep-rag-id",
last_deep_rag_status=DeepRagStatus.IN_PROGRESS,
created_date="2024-01-01",
),
index_folder_path="/test/path",
)
registration_error = _http_error(
400,
"https://cloud.uipath.com/org/tenant/orchestrator_/api/JobTriggers/"
"SaveExternalTrigger",
"Invalid external trigger.",
)

with patch(
"uipath.platform.common._api_client.ApiClient.request_async",
new=AsyncMock(side_effect=registration_error),
):
with pytest.raises(UiPathFaultedTriggerError) as exc_info:
await UiPathResumeTriggerCreator().create_trigger(wait_deep_rag)

error = exc_info.value
assert (error.category, error.message) == (
ErrorCategory.SYSTEM,
"Failed to register the resume trigger with Orchestrator",
)
assert "SaveExternalTrigger" in error.detail

@pytest.mark.anyio
async def test_invoke_process_client_error_is_user_error(
self,
setup_test_env: None,
) -> None:
invoke_process = InvokeProcess(
name="TestProcess",
process_folder_path="/missing/folder",
input_arguments={},
)
start_jobs_error = _http_error(
400,
"https://cloud.uipath.com/org/tenant/orchestrator_/odata/Jobs/"
"UiPath.Server.Configuration.OData.StartJobs",
"Folder does not exist or the user does not have access to the folder.",
)

with patch(
"uipath.platform.orchestrator._processes_service.ProcessesService.invoke_async",
new=AsyncMock(side_effect=start_jobs_error),
):
with pytest.raises(UiPathFaultedTriggerError) as exc_info:
await UiPathResumeTriggerCreator().create_trigger(invoke_process)

error = exc_info.value
assert (error.category, error.message) == (
ErrorCategory.USER,
"Failed to create resume trigger of type Job",
)
assert "Folder does not exist" in error.detail

@pytest.mark.anyio
async def test_create_resume_trigger_wait_deep_rag(
self,
Expand Down
2 changes: 1 addition & 1 deletion packages/uipath-platform/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions packages/uipath/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
[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"
dependencies = [
"uipath-core>=0.5.35, <0.6.0",
"uipath-runtime>=0.13.7, <0.14.0",
"uipath-platform>=0.3.20, <0.4.0",
"uipath-platform>=0.3.24, <0.4.0",
"uipath-ipc>=2.5.1, <2.6.0",
"click>=8.3.3, <9.0.0",
"httpx>=0.28.1",
Expand Down
3 changes: 3 additions & 0 deletions packages/uipath/src/uipath/_cli/_evals/_telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from typing import Any

from uipath._cli._utils._common import get_claim_from_token
from uipath.core.errors import UiPathFaultedTriggerError
from uipath.core.events import EventBus
from uipath.eval.runtime.events import (
EvalRunCreatedEvent,
Expand Down Expand Up @@ -248,6 +249,8 @@ async def _on_eval_run_updated(self, event: EvalRunUpdatedEvent) -> None:
if isinstance(exception, UiPathBaseRuntimeError):
properties["ErrorCode"] = exception.error_info.code
properties["ErrorCategory"] = exception.error_info.category.value
elif isinstance(exception, UiPathFaultedTriggerError):
properties["ErrorCategory"] = exception.category.value

self._enrich_properties(properties)

Expand Down
3 changes: 3 additions & 0 deletions packages/uipath/src/uipath/eval/runtime/runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
)
from pydantic import BaseModel, ValidationError

from uipath.core.errors import ErrorCategory, UiPathFaultedTriggerError
from uipath.core.events import EventBus
from uipath.core.tracing import UiPathTraceManager
from uipath.runtime import (
Expand Down Expand Up @@ -118,6 +119,8 @@ def _is_user_facing_error(exception: BaseException) -> bool:
failures of the agent under evaluation, not eval infrastructure crashes,
so they must not be flagged as runtime exceptions.
"""
if isinstance(exception, UiPathFaultedTriggerError):
return exception.category == ErrorCategory.USER
return (
isinstance(exception, UiPathBaseRuntimeError)
and exception.error_info.category == UiPathErrorCategory.USER
Expand Down
29 changes: 29 additions & 0 deletions packages/uipath/tests/cli/eval/test_eval_telemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,35 @@ async def test_on_eval_run_updated_user_error_includes_classification(
assert properties["ErrorCategory"] == "User"
assert properties["IsRuntimeException"] is False

@pytest.mark.asyncio
@patch("uipath._cli._evals._telemetry.track_event")
async def test_on_eval_run_updated_faulted_trigger_emits_category(
self, mock_track_event
):
from uipath.core.errors import ErrorCategory, UiPathFaultedTriggerError

subscriber = EvalTelemetrySubscriber()
error = UiPathFaultedTriggerError(
ErrorCategory.USER,
"Failed to create resume trigger of type DeepRag",
"Status Code: 400, No valid files to use for Summarization.",
)
event = self._create_eval_run_updated_event(
success=False,
exception_details=EvalItemExceptionDetails(
exception=error, runtime_exception=True
),
)

await subscriber._on_eval_run_updated(event)

mock_track_event.assert_called_once()
event_name, properties = mock_track_event.call_args[0]
assert event_name == "EvalRun.Failed"
assert properties["ErrorType"] == "UiPathFaultedTriggerError"
assert properties.get("ErrorCategory") == "User"
assert "ErrorCode" not in properties

@pytest.mark.asyncio
@patch("uipath._cli._evals._telemetry.track_event")
async def test_on_eval_run_updated_with_scores(self, mock_track_event):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from pathlib import Path
from typing import Any, AsyncGenerator

from uipath.core.errors import ErrorCategory, UiPathFaultedTriggerError
from uipath.core.events import EventBus
from uipath.core.tracing import UiPathTraceManager
from uipath.eval.helpers import EvalHelpers
Expand Down Expand Up @@ -49,6 +50,16 @@ def test_unknown_category_error_is_not_user_facing():
assert _is_user_facing_error(_make_error(UiPathErrorCategory.UNKNOWN)) is False


def test_user_category_trigger_error_is_user_facing():
error = UiPathFaultedTriggerError(ErrorCategory.USER, "Failed", "400")
assert _is_user_facing_error(error) is True


def test_system_category_trigger_error_is_not_user_facing():
error = UiPathFaultedTriggerError(ErrorCategory.SYSTEM, "Failed", "500")
assert _is_user_facing_error(error) is False


def test_plain_exception_is_not_user_facing():
assert _is_user_facing_error(ValueError("boom")) is False

Expand Down
4 changes: 2 additions & 2 deletions packages/uipath/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading