Skip to content
Merged
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.22"
version = "0.3.23"
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 @@ -18,7 +18,12 @@
VersionMode,
resource_override,
)
from ._config import UiPathApiConfig, UiPathConfig, resolve_coded_agenthub_config
from ._config import (
UiPathApiConfig,
UiPathConfig,
resolve_coded_agenthub_config,
resolve_execution_type,
)
from ._endpoints_manager import EndpointManager
from ._execution_context import ExecutionSourceContext, UiPathExecutionContext
from ._folder_context import FolderContext, header_folder
Expand Down Expand Up @@ -89,6 +94,7 @@
"TokenData",
"UiPathConfig",
"resolve_coded_agenthub_config",
"resolve_execution_type",
"CreateTask",
"CreateEscalation",
"WaitEscalation",
Expand Down
37 changes: 36 additions & 1 deletion packages/uipath-platform/src/uipath/platform/common/_config.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
import os
from functools import cached_property
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any

from pydantic import BaseModel

if TYPE_CHECKING:
from ._span_utils import ExecutionType


class UiPathApiConfig(BaseModel):
base_url: str
Expand Down Expand Up @@ -267,3 +270,35 @@ def resolve_coded_agenthub_config() -> str | None:
and not UiPathConfig.is_rooted_to_debug_job
)
return None if deployed else AGENTHUB_CONFIG_CODED_AGENTS_PLAYGROUND


_DEBUG_EXECUTION_SOURCES = frozenset({"playground", "eval"})


def resolve_execution_type() -> "ExecutionType":
"""Whether the current run is a debug run or a deployed run.

This is the value agent spans report as ``executionType`` and memory search
sends to LLMOps, so both describe a run the same way. The run is ``Debug``
when any of these says so, and ``Runtime`` otherwise:

- ``UIPATH_IS_DEBUG=true``, set in the environment of debug and eval jobs.
- Orchestrator's ``isDebug`` internal argument, which marks a debug job and
every job started from it. A Maestro solution debug runs a deployed
process with ``uipath run`` under one, so the command alone says runtime.
- The CLI command: ``uipath debug`` / ``dev`` (playground) or ``eval``.

Each signal can only turn a run into ``Debug``; none turns a debug run into
``Runtime``.
"""
from uipath.platform.constants import ENV_IS_DEBUG

from ._execution_context import UiPathExecutionContext
from ._span_utils import ExecutionType

is_debug = (
os.getenv(ENV_IS_DEBUG, "").lower() == "true"
or UiPathConfig.is_rooted_to_debug_job
or UiPathExecutionContext().execution_source in _DEBUG_EXECUTION_SOURCES
)
return ExecutionType.DEBUG if is_debug else ExecutionType.RUNTIME
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
ENV_FOLDER_PATH = "UIPATH_FOLDER_PATH"
ENV_JOB_KEY = "UIPATH_JOB_KEY"
ENV_JOB_ID = "UIPATH_JOB_ID"
ENV_IS_DEBUG = "UIPATH_IS_DEBUG"
ENV_ROBOT_KEY = "UIPATH_ROBOT_KEY"
ENV_TENANT_ID = "UIPATH_TENANT_ID"
ENV_TENANT_NAME = "UIPATH_TENANT_NAME"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

from ..common._base_service import BaseService
from ..common._bindings import resource_override
from ..common._config import UiPathApiConfig
from ..common._config import UiPathApiConfig, resolve_execution_type
from ..common._execution_context import UiPathExecutionContext
from ..common._folder_context import FolderContext, header_folder
from ..common._models import Endpoint, RequestSpec
Expand All @@ -28,6 +28,25 @@

_MEMORY_SPACES_BASE = "/ecs_/v2/episodicmemories"
_LLMOPS_AGENT_BASE = "/llmopstenant_/api/Agent/memory"
# vNext search: one route for both memory types, told apart by memoryType. It is
# the only search route that takes executionType.
_LLMOPS_MEMORY_BASE = "/llmopstenant_/api/Memory"

# LLMOps MemoryType, which the search route binds as an integer.
_MEMORY_TYPE_EPISODIC = 0
_MEMORY_TYPE_ESCALATION = 1


def _search_body(request: MemorySearchRequest, memory_type: int) -> dict[str, Any]:
"""Build the vNext search body for one memory type.

``executionType`` defaults to the run's own value, so every search tells
LLMOps whether a debug or a deployed run is asking.
"""
body = request.model_dump(by_alias=True, exclude_none=True)
body["memoryType"] = memory_type
body.setdefault("executionType", resolve_execution_type())
return body


class MemoryService(FolderContext, BaseService):
Expand Down Expand Up @@ -213,7 +232,7 @@
response = self.request(
spec.method,
spec.endpoint,
json=request.model_dump(by_alias=True, exclude_none=True),
json=_search_body(request, _MEMORY_TYPE_EPISODIC),
headers=spec.headers,
).json()
return MemorySearchResponse.model_validate(response)
Expand Down Expand Up @@ -245,7 +264,7 @@
await self.request_async(
spec.method,
spec.endpoint,
json=request.model_dump(by_alias=True, exclude_none=True),
json=_search_body(request, _MEMORY_TYPE_EPISODIC),
headers=spec.headers,
)
).json()
Expand Down Expand Up @@ -279,7 +298,7 @@
response = self.request(
spec.method,
spec.endpoint,
json=request.model_dump(by_alias=True, exclude_none=True),
json=_search_body(request, _MEMORY_TYPE_ESCALATION),
headers=spec.headers,
).json()
return EscalationMemorySearchResponse.model_validate(response)
Expand Down Expand Up @@ -311,7 +330,7 @@
await self.request_async(
spec.method,
spec.endpoint,
json=request.model_dump(by_alias=True, exclude_none=True),
json=_search_body(request, _MEMORY_TYPE_ESCALATION),
headers=spec.headers,
)
).json()
Expand Down Expand Up @@ -458,11 +477,11 @@
folder_key = self._resolve_folder(folder_key, folder_path)
return RequestSpec(
method="POST",
endpoint=Endpoint(f"{_LLMOPS_AGENT_BASE}/{memory_space_id}/search"),
endpoint=Endpoint(f"{_LLMOPS_MEMORY_BASE}/{memory_space_id}/search"),
headers={**header_folder(folder_key, None)},
)

def _escalation_search_spec(

Check warning on line 484 in packages/uipath-platform/src/uipath/platform/memory/_memory_service.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Update this function so that its implementation is not identical to _search_spec on line 471.

See more on https://sonarcloud.io/project/issues?id=UiPath_uipath-python&issues=AaIzSs6RsO7_ZYIXkq2t&open=AaIzSs6RsO7_ZYIXkq2t&pullRequest=2035
self,
memory_space_id: str,
folder_key: Optional[str] = None,
Expand All @@ -471,9 +490,7 @@
folder_key = self._resolve_folder(folder_key, folder_path)
return RequestSpec(
method="POST",
endpoint=Endpoint(
f"{_LLMOPS_AGENT_BASE}/{memory_space_id}/escalation/search"
),
endpoint=Endpoint(f"{_LLMOPS_MEMORY_BASE}/{memory_space_id}/search"),
headers={**header_folder(folder_key, None)},
)

Expand Down
31 changes: 30 additions & 1 deletion packages/uipath-platform/src/uipath/platform/memory/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,16 @@
Escalation memory operations also go through LLMOps.
"""

import json
from enum import Enum
from typing import Any, Dict, List, Optional

from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, field_validator

from ..common._span_utils import ExecutionType

# Capitalized keys some stored escalation answers use, mapped to CachedRecall's.
_CACHED_RECALL_KEYS = {"Output": "output", "Outcome": "outcome"}

# ── Enums ──────────────────────────────────────────────────────────────

Expand Down Expand Up @@ -144,6 +150,10 @@ class MemorySearchRequest(BaseModel):
definition_system_prompt: Optional[str] = Field(
None, alias="definitionSystemPrompt"
)
# Whether the calling run is a debug or a deployed run. LLMOps counts how often
# deployed runs use each memory. Left unset, the service fills it from
# resolve_execution_type(), the same value agent spans report.
execution_type: Optional[ExecutionType] = Field(None, alias="executionType")


class MemoryMatch(BaseModel):
Expand Down Expand Up @@ -205,6 +215,25 @@ class EscalationMemoryMatch(BaseModel):

answer: Optional[CachedRecall] = Field(None, alias="answer")

@field_validator("answer", mode="before")
@classmethod
def _parse_stored_answer(cls, value: Any) -> Any:
"""Parse the answer LLMOps returns as the stored JSON string.

Keys may be stored capitalized (``Output`` / ``Outcome``). An answer that
is not valid JSON is passed through unchanged and still fails validation.
"""
if isinstance(value, str):
try:
value = json.loads(value)
except json.JSONDecodeError:
return value
if isinstance(value, dict):
return {
_CACHED_RECALL_KEYS.get(key, key): item for key, item in value.items()
}
return value


class EscalationMemorySearchResponse(BaseModel):
"""Response from LLMOps escalation memory search."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""Tests for resolve_execution_type, the debug-vs-deployed value of a run."""

import pytest

from uipath.platform.common import (
ExecutionSourceContext,
ExecutionType,
UiPathConfig,
resolve_execution_type,
)


@pytest.fixture(autouse=True)
def _no_debug_signal(monkeypatch: pytest.MonkeyPatch, tmp_path):
"""Start every test from a run that nothing marks as debug."""
monkeypatch.delenv("UIPATH_IS_DEBUG", raising=False)
monkeypatch.chdir(tmp_path)
UiPathConfig.reset()
yield
UiPathConfig.reset()


def _write_is_debug(tmp_path, value: bool) -> None:
flag = "true" if value else "false"
(tmp_path / "uipath.json").write_text(
f'{{"runtime": {{"internalArguments": {{"isDebug": {flag}}}}}}}'
)
UiPathConfig.reset()


def test_runtime_when_no_signal() -> None:
assert resolve_execution_type() == ExecutionType.RUNTIME


@pytest.mark.parametrize("value", ["true", "True", "TRUE"])
def test_debug_when_is_debug_env_is_true(
monkeypatch: pytest.MonkeyPatch, value: str
) -> None:
monkeypatch.setenv("UIPATH_IS_DEBUG", value)

assert resolve_execution_type() == ExecutionType.DEBUG


@pytest.mark.parametrize("value", ["false", "", "1"])
def test_runtime_when_is_debug_env_is_not_true(
monkeypatch: pytest.MonkeyPatch, value: str
) -> None:
monkeypatch.setenv("UIPATH_IS_DEBUG", value)

assert resolve_execution_type() == ExecutionType.RUNTIME


def test_debug_when_orchestrator_marks_job_as_debug(tmp_path) -> None:
# Maestro solution debug: a deployed process run with `uipath run` under a debug job.
_write_is_debug(tmp_path, True)

with ExecutionSourceContext("runtime"):
assert resolve_execution_type() == ExecutionType.DEBUG


def test_runtime_when_orchestrator_is_debug_is_false(tmp_path) -> None:
_write_is_debug(tmp_path, False)

assert resolve_execution_type() == ExecutionType.RUNTIME


@pytest.mark.parametrize(
("source", "expected"),
[
("playground", ExecutionType.DEBUG),
("eval", ExecutionType.DEBUG),
("runtime", ExecutionType.RUNTIME),
],
)
def test_follows_cli_execution_source(source: str, expected: ExecutionType) -> None:
with ExecutionSourceContext(source):
assert resolve_execution_type() == expected
Loading
Loading