diff --git a/docs/human_in_the_loop.md b/docs/human_in_the_loop.md index 496a1d06a..f6cb75714 100644 --- a/docs/human_in_the_loop.md +++ b/docs/human_in_the_loop.md @@ -637,3 +637,45 @@ human_response = interrupt("Please review the draft and reply with your decision /// info The interrupt value can be any JSON-serializable object (string, dict, and so on), and the resume value is the payload delivered to the trigger's inbox. There is no status validation, so the agent resumes with exactly what the external caller provides. /// + +--- + +## Keeping files across suspend and resume + +A suspended job can resume hours later on another machine, in a new folder. Files your agent wrote to disk before the suspend are not there anymore, unless they live in the **managed workspace**. + +When the agent runs as an Orchestrator job, the `uipath` CLI gives each run a workspace folder. When the job suspends, the CLI uploads the new and changed files as job attachments. When the job resumes, it downloads them into the new folder before the agent continues. In a conversational agent, the files are also kept from one message to the next. + +For deep agents, pass `UiPathWorkspaceBackend` as the file backend. The file tools (`ls`, `read_file`, `write_file`, `edit_file`) then work inside the managed workspace: + +```python +from deepagents import create_deep_agent +from uipath_langchain.agent.advanced import UiPathWorkspaceBackend + +graph = create_deep_agent( + model=llm, + tools=tools, + backend=UiPathWorkspaceBackend(), +) +``` + +The backend looks up the workspace on every file operation, so it is safe to create it at import time, as above. + +Your own tools can write there too. Call `get_workspace_path()` while the agent is running, not at import time: + +```python +from langchain_core.tools import tool +from uipath.runtime import get_workspace_path + + +@tool +def save_report(text: str) -> str: + """Save the report so it is still there after the job resumes.""" + path = get_workspace_path() / "report.md" + path.write_text(text) + return str(path) +``` + +/// info +The workspace is persisted only in Orchestrator jobs. A local `uipath run` has no managed workspace: `UiPathWorkspaceBackend` falls back to a temporary folder and logs a warning naming it, and `get_workspace_path()` raises `MANAGED_WORKSPACE_UNAVAILABLE`. +/// diff --git a/pyproject.toml b/pyproject.toml index 84d5f42b1..0a46dae83 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "uipath-langchain" -version = "0.18.55" +version = "0.18.57" description = "Python SDK that enables developers to build and deploy LangGraph agents to the UiPath Cloud Platform" readme = { file = "README.md", content-type = "text/markdown" } requires-python = ">=3.11" diff --git a/samples/README.md b/samples/README.md index 631ec8033..bbb566c8f 100644 --- a/samples/README.md +++ b/samples/README.md @@ -51,6 +51,9 @@ This sample shows how to create an agent using LangGraph with multiple tool serv ## [Simple remote MCP](simple-remote-mcp) This sample demonstrates the creation of an agent using LangGraph, which connects to a remote MCP (Model Context Protocol) Server. +## [DeepAgent workspace files](deepagent-workspace-files) +This sample shows a DeepAgents agent whose files are real files on disk and survive a suspend and resume in an Orchestrator job, using `UiPathWorkspaceBackend`. + ## [Simple DeepAgent](simple-deepagent) This sample demonstrates using the DeepAgents library to create an agent with advanced planning, sub-agent delegation, and web search capabilities. diff --git a/samples/deepagent-workspace-files/.env.example b/samples/deepagent-workspace-files/.env.example new file mode 100644 index 000000000..b461469d4 --- /dev/null +++ b/samples/deepagent-workspace-files/.env.example @@ -0,0 +1,2 @@ +UIPATH_URL=https://alpha.uipath.com// +UIPATH_ACCESS_TOKEN=YOUR TOKEN HERE diff --git a/samples/deepagent-workspace-files/README.md b/samples/deepagent-workspace-files/README.md new file mode 100644 index 000000000..5e9f29c4d --- /dev/null +++ b/samples/deepagent-workspace-files/README.md @@ -0,0 +1,58 @@ +# DeepAgent workspace files + +A [DeepAgents](https://github.com/langchain-ai/deepagents) agent that writes a report to a real file, suspends for a human review, and revises the same file after it resumes. In an Orchestrator job the file survives the suspend, even when the job resumes on another machine. + +## Overview + +`UiPathWorkspaceBackend` gives the agent's file tools (`write_file`, `read_file`, `edit_file`, `ls`, `glob`, `grep`) a folder on disk that belongs to the current run. When the job suspends, the UiPath CLI uploads that folder as job attachments. When the job resumes, it downloads them into a new folder before the agent continues. + +Use it when the agent's files need to exist on disk. In this sample, the `request_review` tool opens `report.md` with plain Python, from `backend.cwd`, and sends its text to the reviewer. DeepAgents' default `StateBackend` keeps files inside the graph state instead, where your own tools can't open them. + +## Requirements + +- Python 3.11+ +- A UiPath Automation Cloud tenant. The model runs through the UiPath LLM Gateway, so no model API key is needed. + +## Installation + +```bash +uv venv -p 3.11 .venv +source .venv/bin/activate # On Windows: .venv\Scripts\activate +uv sync +uipath auth +``` + +## Usage + +Run it as a job, so the files are kept: + +```bash +uipath pack +uipath publish +``` + +Start the process in Orchestrator with this input: + +```json +{"messages": [{"type": "human", "content": "Write a short report on the benefits of unit tests"}]} +``` + +The job writes `/report.md`, calls `request_review` and suspends. Resume it with the reviewer's feedback, for example `{"feedback": "Add a section on test speed"}`. The agent then edits the same `/report.md` and replies with the final report. + +You can also run it locally: + +```bash +uipath run agent '{"messages": [{"type": "human", "content": "Write a short report on the benefits of unit tests"}]}' +uipath run agent '{"feedback": "Add a section on test speed"}' --resume +``` + +Outside a job the backend uses a temporary folder and logs a warning naming it. Each local run gets a new folder, so after `--resume` the draft is gone: `edit_file` reports `/report.md` as not found, and the agent writes a new report from scratch. Only jobs keep the workspace, because only jobs resume in a new process. + +## How it works + +1. The UiPath CLI sees that the LangGraph factory opts in to a managed workspace, and wraps each job run with it. +2. Before the run, the CLI restores the files recorded for this job into a new folder and makes it the run's workspace. +3. `UiPathWorkspaceBackend` looks up that folder on every file operation, so a graph built once at import time always uses the current run's folder. +4. When the run suspends, the CLI uploads the folder's changed files as job attachments and records them for the next run. + +Your own tools can open the same folder through `backend.cwd`, or with `uipath.runtime.get_workspace_path()`, which raises outside a managed run. diff --git a/samples/deepagent-workspace-files/agent.mermaid b/samples/deepagent-workspace-files/agent.mermaid new file mode 100644 index 000000000..8d0543cdd --- /dev/null +++ b/samples/deepagent-workspace-files/agent.mermaid @@ -0,0 +1,14 @@ +%% AUTO-GENERATED by `uipath init`. Do not edit manually. +%% Regenerated on every `uipath init`. +flowchart TB + __start__(__start__) + model(model) + tools(tools) + PatchToolCallsMiddleware.before_agent(PatchToolCallsMiddleware.before_agent) + __end__(__end__) + PatchToolCallsMiddleware.before_agent --> model + __start__ --> PatchToolCallsMiddleware.before_agent + model --> __end__ + model --> model + model --> tools + tools --> model diff --git a/samples/deepagent-workspace-files/graph.py b/samples/deepagent-workspace-files/graph.py new file mode 100644 index 000000000..57faeddbe --- /dev/null +++ b/samples/deepagent-workspace-files/graph.py @@ -0,0 +1,39 @@ +"""DeepAgent whose files survive a suspend and resume in an Orchestrator job.""" + +from deepagents import create_deep_agent +from langchain_core.tools import tool +from langgraph.types import interrupt + +from uipath_langchain.agent.advanced import UiPathWorkspaceBackend +from uipath_langchain.chat import UiPathChat + +REPORT = "report.md" + +SYSTEM_PROMPT = f"""You write short reports and revise them after a human review. + +1. Write a first draft of the report to /{REPORT} with write_file. +2. Call request_review. The job may suspend here until the reviewer answers. +3. Revise /{REPORT} with edit_file to apply the reviewer's feedback. +4. Reply with the final report.""" + + +backend = UiPathWorkspaceBackend() + + +@tool +def request_review() -> str: + """Send the current draft of the report to a human reviewer and return their feedback.""" + report = backend.cwd / REPORT + draft = report.read_text() if report.exists() else "(no draft found)" + answer = interrupt({"message": "Review the draft report", "draft": draft}) + if isinstance(answer, dict): + return str(answer.get("feedback", answer)) + return str(answer) + + +deep_agent = create_deep_agent( + model=UiPathChat(model="gpt-4.1-mini-2025-04-14"), + system_prompt=SYSTEM_PROMPT, + tools=[request_review], + backend=backend, +) diff --git a/samples/deepagent-workspace-files/langgraph.json b/samples/deepagent-workspace-files/langgraph.json new file mode 100644 index 000000000..514f9b4c6 --- /dev/null +++ b/samples/deepagent-workspace-files/langgraph.json @@ -0,0 +1,5 @@ +{ + "graphs": { + "agent": "./graph.py:deep_agent" + } +} diff --git a/samples/deepagent-workspace-files/pyproject.toml b/samples/deepagent-workspace-files/pyproject.toml new file mode 100644 index 000000000..224b2458d --- /dev/null +++ b/samples/deepagent-workspace-files/pyproject.toml @@ -0,0 +1,17 @@ +[project] +name = "deepagent-workspace-files" +version = "0.0.1" +description = "DeepAgent whose files survive suspend and resume in an Orchestrator job" +authors = [{ name = "John Doe", email = "john.doe@myemail.com" }] +requires-python = ">=3.11" +dependencies = [ + "deepagents>=0.7.11, <0.8.0", + "langgraph>=1.0.10", + "uipath>=2.15.1", + "uipath-langchain>=0.18.57", +] + +[dependency-groups] +dev = [ + "uipath-dev", +] diff --git a/samples/deepagent-workspace-files/uipath.json b/samples/deepagent-workspace-files/uipath.json new file mode 100644 index 000000000..30c00e944 --- /dev/null +++ b/samples/deepagent-workspace-files/uipath.json @@ -0,0 +1,5 @@ +{ + "runtimeOptions": { + "isConversational": false + } +} diff --git a/src/uipath_langchain/agent/advanced/__init__.py b/src/uipath_langchain/agent/advanced/__init__.py index dc1946b5c..65b1a7466 100644 --- a/src/uipath_langchain/agent/advanced/__init__.py +++ b/src/uipath_langchain/agent/advanced/__init__.py @@ -23,6 +23,7 @@ MEMORY_INDEX_VIRTUAL_PATH, create_state_with_input, ) +from .workspace_backend import UiPathWorkspaceBackend __all__ = [ "MEMORY_DIR_NAME", @@ -36,6 +37,7 @@ "ConversationalAdvancedAgentGraphState", "FilesystemBackend", "SubAgent", + "UiPathWorkspaceBackend", "build_code_interpreter_middleware", "create_advanced_agent", "create_advanced_agent_graph", diff --git a/src/uipath_langchain/agent/advanced/workspace_backend.py b/src/uipath_langchain/agent/advanced/workspace_backend.py new file mode 100644 index 000000000..35eb4a7e9 --- /dev/null +++ b/src/uipath_langchain/agent/advanced/workspace_backend.py @@ -0,0 +1,58 @@ +"""deepagents file backend rooted in the host-managed workspace.""" + +import logging +import tempfile +import threading +from pathlib import Path + +from deepagents.backends import FilesystemBackend +from uipath.runtime import get_workspace_path +from uipath.runtime.errors import UiPathRuntimeError + +logger = logging.getLogger(__name__) + + +class UiPathWorkspaceBackend(FilesystemBackend): + """File backend that reads and writes the workspace of the current run. + + The root folder is looked up on every file operation, so one backend + created when the graph is built follows the workspace of whichever run is + executing. In a UiPath job the host persists that folder across suspend + and resume. Outside a managed run the backend uses one temporary folder, + which is not persisted. + + Args: + virtual_mode: Resolve agent paths under the workspace root and block + traversal outside it. + max_file_size_mb: Largest file the grep fallback reads. + """ + + def __init__(self, *, virtual_mode: bool = True, max_file_size_mb: int = 10): + self._fallback_root: Path | None = None + self._fallback_lock = threading.Lock() + super().__init__(virtual_mode=virtual_mode, max_file_size_mb=max_file_size_mb) + + @property + def cwd(self) -> Path: + """The current run's workspace, or the fallback folder outside one.""" + try: + return get_workspace_path().resolve() + except UiPathRuntimeError: + return self._fallback() + + @cwd.setter + def cwd(self, value: Path) -> None: + """Ignore assignments; the root always comes from the current run.""" + + def _fallback(self) -> Path: + with self._fallback_lock: + if self._fallback_root is None: + self._fallback_root = Path( + tempfile.mkdtemp(prefix="uipath-workspace-") + ).resolve() + logger.warning( + "No managed workspace in this run. Agent files go to %s " + "and are not kept across suspend and resume.", + self._fallback_root, + ) + return self._fallback_root diff --git a/src/uipath_langchain/runtime/factory.py b/src/uipath_langchain/runtime/factory.py index 9d16137b5..0728a944d 100644 --- a/src/uipath_langchain/runtime/factory.py +++ b/src/uipath_langchain/runtime/factory.py @@ -249,6 +249,7 @@ async def get_settings(self) -> UiPathRuntimeFactorySettings | None: return UiPathRuntimeFactorySettings( agent_type=_AGENT_TYPE_CODED, agent_framework=_AGENT_FRAMEWORK, + managed_workspace=True, ) async def get_storage(self) -> UiPathRuntimeStorageProtocol | None: diff --git a/tests/agent/advanced/test_workspace_backend.py b/tests/agent/advanced/test_workspace_backend.py new file mode 100644 index 000000000..9911fda1f --- /dev/null +++ b/tests/agent/advanced/test_workspace_backend.py @@ -0,0 +1,257 @@ +import logging +import tempfile +import uuid +from pathlib import Path +from typing import Any, AsyncGenerator, Awaitable, Callable + +import pytest +from langchain_core.tools import tool +from uipath.runtime import ( + HydrationRuntime, + UiPathExecuteOptions, + UiPathRuntimeResult, + UiPathRuntimeSchema, + UiPathRuntimeStatus, + UiPathStreamOptions, + Workspace, + WorkspaceHydrator, + WorkspaceRegistryStore, + get_workspace_path, +) +from uipath.runtime.events import UiPathRuntimeEvent + +from uipath_langchain.agent.advanced import UiPathWorkspaceBackend + + +class MemoryStorage: + def __init__(self) -> None: + self.values: dict[tuple[str, str, str], Any] = {} + + async def set_value( + self, runtime_id: str, namespace: str, key: str, value: Any + ) -> None: + self.values[(runtime_id, namespace, key)] = value + + async def get_value(self, runtime_id: str, namespace: str, key: str) -> Any: + return self.values.get((runtime_id, namespace, key)) + + +class NoAttachments: + async def upload_async(self, **kwargs: Any) -> Any: + raise AssertionError("a successful run must not upload") + + async def download_async(self, **kwargs: Any) -> str: + raise AssertionError("an empty registry must not download") + + +class StoredAttachments: + def __init__(self) -> None: + self.blobs: dict[uuid.UUID, bytes] = {} + + async def upload_async(self, *, source_path: str, **kwargs: Any) -> uuid.UUID: + key = uuid.uuid4() + self.blobs[key] = Path(source_path).read_bytes() + return key + + async def download_async( + self, *, key: uuid.UUID, destination_path: str, **kwargs: Any + ) -> str: + Path(destination_path).write_bytes(self.blobs[key]) + return destination_path + + +class StepRuntime: + """Runs one step inside the managed run, like a deepagents file tool would.""" + + def __init__( + self, + step: Callable[[], Awaitable[Any]], + status: UiPathRuntimeStatus = UiPathRuntimeStatus.SUCCESSFUL, + ) -> None: + self.step = step + self.status = status + + async def execute( + self, + input: dict[str, Any] | None = None, + options: UiPathExecuteOptions | None = None, + ) -> UiPathRuntimeResult: + return UiPathRuntimeResult( + status=self.status, output={"value": await self.step()} + ) + + async def stream( + self, + input: dict[str, Any] | None = None, + options: UiPathStreamOptions | None = None, + ) -> AsyncGenerator[UiPathRuntimeEvent, None]: + yield await self.execute(input, options) + + async def get_schema(self) -> UiPathRuntimeSchema: + raise NotImplementedError + + async def dispose(self) -> None: + pass + + +async def _run_managed( + workspace: Workspace, + step: Callable[[], Awaitable[Any]], + *, + status: UiPathRuntimeStatus = UiPathRuntimeStatus.SUCCESSFUL, + attachments: Any = None, + storage: MemoryStorage | None = None, +) -> Any: + runtime = HydrationRuntime( + StepRuntime(step, status), + workspace=workspace, + hydrator=WorkspaceHydrator( + workspace_path=workspace.path, + attachments=attachments or NoAttachments(), + ), + registry_store=WorkspaceRegistryStore(storage or MemoryStorage(), "runtime-1"), + ) + result = await runtime.execute() + assert isinstance(result.output, dict) + return result.output["value"] + + +@pytest.fixture +def workspace(tmp_path: Path) -> Workspace: + return Workspace.create(tmp_path / "managed") + + +async def test_files_land_in_the_runs_managed_workspace( + workspace: Workspace, +) -> None: + backend = UiPathWorkspaceBackend() + + async def write() -> str | None: + return backend.write("/notes/plan.md", "step 1").error + + assert await _run_managed(workspace, write) is None + assert (workspace.path / "notes" / "plan.md").read_text() == "step 1" + + +async def test_async_file_tools_see_the_managed_workspace( + workspace: Workspace, +) -> None: + backend = UiPathWorkspaceBackend() + + async def awrite() -> str | None: + return (await backend.awrite("/plan.md", "from a thread")).error + + assert await _run_managed(workspace, awrite) is None + assert (workspace.path / "plan.md").read_text() == "from a thread" + + +async def test_one_backend_follows_each_runs_workspace(tmp_path: Path) -> None: + backend = UiPathWorkspaceBackend() + first = Workspace.create(tmp_path / "first") + second = Workspace.create(tmp_path / "second") + + async def write_first() -> None: + backend.write("/first.md", "first run") + + async def use_second() -> dict[str, Any]: + backend.write("/second.md", "second run") + read = backend.read("/second.md") + return { + "read": read.file_data["content"] if read.file_data else None, + "ls": [e["path"] for e in backend.ls("/").entries or []], + "glob": [m["path"] for m in backend.glob("*.md", "/").matches or []], + "grep": [m["path"] for m in backend.grep("run", "/").matches or []], + } + + await _run_managed(first, write_first) + seen = await _run_managed(second, use_second) + + assert (first.path / "first.md").read_text() == "first run" + assert seen == { + "read": "second run", + "ls": ["/second.md"], + "glob": ["/second.md"], + "grep": ["/second.md"], + } + + +async def test_files_written_before_a_suspend_are_readable_after_resume( + tmp_path: Path, +) -> None: + backend = UiPathWorkspaceBackend() + attachments, storage = StoredAttachments(), MemoryStorage() + + async def write() -> None: + backend.write("/plan.md", "step 1") + + async def read() -> str | None: + result = backend.read("/plan.md") + return result.file_data["content"] if result.file_data else None + + await _run_managed( + Workspace.create(tmp_path / "before"), + write, + status=UiPathRuntimeStatus.SUSPENDED, + attachments=attachments, + storage=storage, + ) + restored = await _run_managed( + Workspace.create(tmp_path / "after"), + read, + attachments=attachments, + storage=storage, + ) + + assert restored == "step 1" + + +async def test_paths_cannot_leave_the_managed_workspace( + workspace: Workspace, +) -> None: + backend = UiPathWorkspaceBackend() + + async def escape() -> None: + backend.write("/../escaped.md", "outside") + + with pytest.raises(ValueError, match="Path traversal not allowed"): + await _run_managed(workspace, escape) + assert not (workspace.path.parent / "escaped.md").exists() + + +def test_outside_a_managed_run_files_go_to_one_temp_folder( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + monkeypatch.chdir(tmp_path) + backend = UiPathWorkspaceBackend() + + with caplog.at_level(logging.WARNING): + backend.write("/a.md", "one") + backend.write("/b.md", "two") + + assert list(tmp_path.iterdir()) == [] + assert backend.cwd.is_relative_to(Path(tempfile.gettempdir()).resolve()) + assert (backend.cwd / "a.md").read_text() == "one" + assert (backend.cwd / "b.md").read_text() == "two" + warnings = [r for r in caplog.records if r.levelno == logging.WARNING] + assert len(warnings) == 1 + assert str(backend.cwd) in warnings[0].getMessage() + + +async def test_sync_tools_run_by_langchain_can_use_the_workspace( + workspace: Workspace, +) -> None: + @tool + def save_report(text: str) -> str: + """Save a report into the workspace.""" + path = get_workspace_path() / "report.md" + path.write_text(text) + return str(path) + + async def call_tool() -> str: + return await save_report.ainvoke({"text": "from a tool"}) + + await _run_managed(workspace, call_tool) + + assert (workspace.path / "report.md").read_text() == "from a tool" diff --git a/tests/runtime/test_factory_managed_workspace.py b/tests/runtime/test_factory_managed_workspace.py new file mode 100644 index 000000000..6f04b5f1a --- /dev/null +++ b/tests/runtime/test_factory_managed_workspace.py @@ -0,0 +1,27 @@ +import os +import tempfile + +import pytest +from uipath.runtime import UiPathRuntimeContext + +from uipath_langchain.runtime.factory import UiPathLangGraphRuntimeFactory + + +@pytest.fixture +def factory() -> UiPathLangGraphRuntimeFactory: + tmpdir = tempfile.mkdtemp() + return UiPathLangGraphRuntimeFactory( + UiPathRuntimeContext( + runtime_dir=tmpdir, + state_file=os.path.join(tmpdir, "state.db"), + ) + ) + + +async def test_factory_asks_the_host_for_a_managed_workspace( + factory: UiPathLangGraphRuntimeFactory, +) -> None: + settings = await factory.get_settings() + + assert settings is not None + assert settings.managed_workspace is True diff --git a/uv.lock b/uv.lock index 4ce80e584..aed363f2c 100644 --- a/uv.lock +++ b/uv.lock @@ -4861,7 +4861,7 @@ wheels = [ [[package]] name = "uipath-langchain" -version = "0.18.55" +version = "0.18.57" source = { editable = "." } dependencies = [ { name = "a2a-sdk" },