Skip to content
Draft
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
42 changes: 42 additions & 0 deletions docs/human_in_the_loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
///
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
3 changes: 3 additions & 0 deletions samples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 2 additions & 0 deletions samples/deepagent-workspace-files/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
UIPATH_URL=https://alpha.uipath.com/<organization>/<tenant>
UIPATH_ACCESS_TOKEN=YOUR TOKEN HERE
58 changes: 58 additions & 0 deletions samples/deepagent-workspace-files/README.md
Original file line number Diff line number Diff line change
@@ -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.
14 changes: 14 additions & 0 deletions samples/deepagent-workspace-files/agent.mermaid
Original file line number Diff line number Diff line change
@@ -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
39 changes: 39 additions & 0 deletions samples/deepagent-workspace-files/graph.py
Original file line number Diff line number Diff line change
@@ -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,
)
5 changes: 5 additions & 0 deletions samples/deepagent-workspace-files/langgraph.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"graphs": {
"agent": "./graph.py:deep_agent"
}
}
17 changes: 17 additions & 0 deletions samples/deepagent-workspace-files/pyproject.toml
Original file line number Diff line number Diff line change
@@ -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",
]
5 changes: 5 additions & 0 deletions samples/deepagent-workspace-files/uipath.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"runtimeOptions": {
"isConversational": false
}
}
2 changes: 2 additions & 0 deletions src/uipath_langchain/agent/advanced/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
MEMORY_INDEX_VIRTUAL_PATH,
create_state_with_input,
)
from .workspace_backend import UiPathWorkspaceBackend

__all__ = [
"MEMORY_DIR_NAME",
Expand All @@ -36,6 +37,7 @@
"ConversationalAdvancedAgentGraphState",
"FilesystemBackend",
"SubAgent",
"UiPathWorkspaceBackend",
"build_code_interpreter_middleware",
"create_advanced_agent",
"create_advanced_agent_graph",
Expand Down
58 changes: 58 additions & 0 deletions src/uipath_langchain/agent/advanced/workspace_backend.py
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions src/uipath_langchain/runtime/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading