### Set Up UiPath Project with uv Package Manager Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md This sequence initializes a new `uv` project, creates and activates a virtual environment, then installs the `uipath` package. It concludes by verifying the `uipath` installation, establishing a ready-to-use Python environment. ```shell uv init . --python 3.10 uv venv # For Windows PowerShell: .venv\Scripts\Activate.ps1 # For Windows Bash: source .venv/Scripts/activate source .venv/bin/activate uv add uipath uipath --version ``` -------------------------------- ### Set Up UiPath Project with pip Package Manager Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md This sequence creates and activates a virtual environment using `venv`, upgrades `pip`, and installs the `uipath` package. It finishes by verifying the `uipath` installation, preparing the Python environment for development. ```shell python -m venv .venv # For Windows PowerShell: .venv\Scripts\Activate.ps1 # For Windows Bash: source .venv/Scripts/activate source .venv/bin/activate python -m pip install --upgrade pip pip install uipath uipath --version ``` -------------------------------- ### Create Project Directory for UiPath Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md These commands create a new directory for your UiPath project and navigate into it, preparing the environment for further setup. Examples are provided for both Linux/macOS/Bash and Windows PowerShell environments. ```shell mkdir example cd example ``` ```powershell New-Item -ItemType Directory -Path example Set-Location example ``` -------------------------------- ### Initialize UiPath Project Metadata File Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md This command creates the `uipath.json` file, which contains essential project metadata. It also executes your `main.py` script to analyze its structure and gather information about inputs and outputs, ensuring proper project configuration. ```shell uipath init ``` -------------------------------- ### Define Python Code Structure for UiPath Project Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md This Python example demonstrates structuring `main.py` with dataclasses for input and output, essential for UiPath project compatibility. It defines an `EchoIn` class for message, repeat count, and prefix, and an `EchoOut` class for the processed message, showcasing basic data handling. ```python from dataclasses import dataclass from typing import Optional @dataclass class EchoIn: message: str repeat: Optional[int] = 1 prefix: Optional[str] = None @dataclass class EchoOut: message: str def main(input: EchoIn) -> EchoOut: result = [] for _ in range(input.repeat or 1): line = input.message if input.prefix: line = f"{input.prefix}: {line}" result.append(line) return EchoOut(message="\n".join(result)) ``` -------------------------------- ### Package UiPath Python Project Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md Use the `uipath pack` command to package your project into a distributable format. This command compiles the project and prepares it for publishing, displaying project details like name, version, and authors. ```shell > uipath pack ⠋ Packaging project ... Name : test Version : 0.1.0 Description: Add your description here Authors : Your Name ✓ Project successfully packaged. ``` -------------------------------- ### Configure Project Authors in pyproject.toml Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md Before packaging, add author details to the `pyproject.toml` file under the `description` field. This ensures proper attribution for the published package. ```toml authors = [{ name = "Your Name", email = "your.email@uipath.com" }] ``` -------------------------------- ### Invoke UiPath Process with Python SDK Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md This Python code demonstrates how to use the UiPath SDK to invoke a process. It initializes the SDK and calls the `processes.invoke` method, passing the process name and a dictionary of input arguments. ```python from uipath import UiPath def main(): sdk = UiPath() sdk.processes.invoke( "test", input_arguments={ "message": "Hello, World!", "repeat": 3, "prefix": "[Echo]" } ) ``` -------------------------------- ### Expected Output from UiPath Process Execution Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md This snippet shows the expected console output from the `test` process invoked via the UiPath SDK. It demonstrates how the input arguments are processed and formatted by the UiPath automation. ```text [Echo]: Hello, World! Echo: Hello, World! Echo: Hello, World! ``` -------------------------------- ### Authenticate UiPath CLI for Local Development Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md This command initiates the authentication flow, opening a browser for login and allowing tenant selection in the terminal. Successful authentication generates a `.env` file with access tokens and configuration, enabling local script debugging and project publishing. ```shell uipath auth ``` -------------------------------- ### Run and Debug UiPath Project Locally Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md This command allows you to execute your `main.py` file locally, passing a JSON string as input for testing purposes. It's a crucial step for debugging your UiPath project and verifying its behavior before deployment. ```shell uipath run main.py '{"message": "test"}' ``` -------------------------------- ### Publish UiPath Python Package Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md Publish your packaged UiPath project to a selected feed using the `uipath publish` command. The command prompts for a destination feed (e.g., Orchestrator Tenant Processes Feed or Personal Workspace Feed) and confirms successful publication. ```shell > uipath publish ⠋ Fetching available package feeds... 👇 Select package feed: 0: Orchestrator Tenant Processes Feed 1: Orchestrator Personal Workspace Feed Select feed number: 0 Selected feed: Orchestrator Tenant Processes Feed ⠸ Publishing most recent package: test.0.1.0.nupkg ... ✓ Package published successfully! ``` -------------------------------- ### Run Python Script with UiPath CLI Source: https://github.com/uipath/uipath-python/blob/main/docs/core/getting_started.md Execute a Python script, such as `main.py`, using the `uipath run` command. This command initiates the execution of the specified script, which in turn can invoke UiPath processes. ```shell > uipath run main.py ``` -------------------------------- ### Install Project Dependencies with uv Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Install all project dependencies, including optional extras, into the virtual environment using 'uv'. The '--no-cache' flag ensures a fresh installation. ```sh uv sync --all-extras --no-cache ``` -------------------------------- ### Configure pyproject.toml for UiPath Packaging Source: https://github.com/uipath/uipath-python/blob/main/README.md Example of the required 'description' and 'authors' fields within the pyproject.toml file, essential for successful packaging of UiPath projects. ```toml description = "Your package description" authors = [{name = "Your Name", email = "your.email@example.com"}] ``` -------------------------------- ### Install UiPath Python SDK Source: https://github.com/uipath/uipath-python/blob/main/README.md Commands to install the UiPath Python SDK package using popular Python package managers like pip and uv. ```bash pip install uipath ``` ```bash uv add uipath ``` -------------------------------- ### Verify Python 3.10 Installation Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md After installing Python 3.10, run this command to confirm the installation and check the version number. ```sh python3.10 --version ``` -------------------------------- ### Package UiPath Project into .nupkg Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md This command packages your UiPath project into a `.nupkg` file, which is the deployable format for UiPath. It provides an example of the command execution and its output. ```shell > uipath pack ⠋ Packaging project ... Name : test Version : 0.1.0 Description: Add your description here Authors : Your Name ✓ Project successfully packaged. ``` -------------------------------- ### API Style Guide: Create a Resource Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Specifies the standard method for adding a new resource to the system. The `create` method is used for this purpose. ```APIDOC Standard Methods and Naming Conventions: - Create a Resource - Method Name: `create` - Purpose: Add a new resource to the system ``` -------------------------------- ### Authenticate with UiPath CLI Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md This command initiates the authentication process for the UiPath CLI, guiding the user to open a browser link for authentication and then select a tenant from available options. ```shell > uipath auth ⠋ Authenticating with UiPath ... 🔗 If a browser window did not open, please open the following URL in your browser: [LINK] 👇 Select tenant: 0: Tenant1 1: Tenant2 Select tenant number: 0 Selected tenant: Tenant1 ✓ Authentication successful. ``` -------------------------------- ### Debug UiPath Project with VS Code Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md Instructions for setting up step-by-step debugging for UiPath projects using `debugpy` and VS Code. It covers installing `debugpy`, running the agent with debugging enabled, and the expected terminal output when the debugger attaches. ```console # Install debugpy package [uv] pip install debugpy # Run agent with debugging enabled uipath run [ENTRYPOINT] [INPUT] --debug 🐛 Debug server started on port 5678 📌 Waiting for debugger to attach... - VS Code: Run -> Start Debugging -> Python Debugger: Attach ✓ Debugger attached successfully! ``` -------------------------------- ### Python Example: List Multiple Resources Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Demonstrates how to fetch a collection of resources using the 'list' method, optionally applying filters. This is part of the API's standard method for retrieving multiple resource instances. ```python resources = Resource.list(filters={}) ``` -------------------------------- ### Install UiPath SDK in Editable Mode with uv Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Install the UiPath SDK into the virtual environment in editable mode. This allows changes to the SDK source code to be reflected without reinstallation, facilitating local development. ```sh uv add --editable ${PATH_TO_SDK} ``` -------------------------------- ### Invoke UiPath Job Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md This command starts a UiPath job on the platform, allowing you to pass JSON input to the agent. It provides a link to monitor the job's progress after it has successfully started. ```shell > uipath invoke agent '{"topic": "UiPath"}' ⠴ Loading configuration ... ⠴ Starting job ... ✨ Job started successfully! 🔗 Monitor your job here: [LINK] ``` -------------------------------- ### API Style Guide: List Multiple Resources Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Outlines the standard method for fetching a collection of resources. The `list` method allows optional filtering via query parameters to refine the results. ```APIDOC Standard Methods and Naming Conventions: - List Multiple Resources - Method Name: `list` - Purpose: Fetch a collection of resources, optionally filtered by query parameters ``` -------------------------------- ### Define pyproject.toml for UiPath Packaging Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md For successful packaging, your `pyproject.toml` file must include a `description` field (avoiding certain special characters) and `author` information. This example shows the required format. ```toml description = "Your package description" authors = [{name = "Your Name", email = "your.email@example.com"}] ``` -------------------------------- ### Execute UiPath Project with Input Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md This command runs your UiPath project, allowing you to pass JSON formatted input directly to your `main.py` file. The example shows how to pass a simple message. ```shell > uipath run main.py '{"message": "test"}' [2025-04-11 10:13:58,857][INFO] {'message': 'test'} ``` -------------------------------- ### Search Contextual Information with UiPath Grounding Service Source: https://github.com/uipath/uipath-python/blob/main/README.md Example demonstrating how to search for contextual information within a knowledge index using the SDK's context grounding service, specifying the index name, query, and number of results. ```python # Search for contextual information results = sdk.context_grounding.search( name="my-knowledge-index", query="How do I process an invoice?", number_of_results=5 ) ``` -------------------------------- ### API Style Guide: Resource Identifiers Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md This general rule specifies that 'key' should be used instead of 'id' for all resource identifiers within the API. ```APIDOC General Rule: - Use `key` instead of `id` for resource identifiers ``` -------------------------------- ### UiPath Cloud Platform: Failed to Prepare Environment Error Message Source: https://github.com/uipath/uipath-python/blob/main/docs/FAQ.md This JSON snippet shows the structure of the 'Failed to prepare environment' error message encountered when deploying Python coded agents to UiPath Cloud Platform, indicating issues with package dependency installation. ```json { "Code": "Serverless.PythonCodedAgent.PrepareEnvironmentError", "Title": "Failed to prepare environment", "Detail": "An error occurred while installing the package dependencies. Please try again. If the error persists, please contact support.", "Category": "System", "Status": null } ``` -------------------------------- ### API Style Guide: Update a Resource Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Defines the standard method for modifying an existing resource. The `update` method is used to apply changes to a resource instance. ```APIDOC Standard Methods and Naming Conventions: - Update a Resource - Method Name: `update` - Purpose: Modify an existing resource ``` -------------------------------- ### Download File from UiPath Buckets Service Source: https://github.com/uipath/uipath-python/blob/main/README.md Example demonstrating how to download a file from a specified UiPath cloud storage bucket using the SDK's buckets service, requiring bucket key, blob path, and local destination. ```python # Download a file from a bucket sdk.buckets.download( bucket_key="my-bucket", blob_file_path="path/to/file.xlsx", destination_path="local/path/file.xlsx" ) ``` -------------------------------- ### Redacting Trace Data with Privacy Controls Source: https://github.com/uipath/uipath-python/blob/main/docs/core/traced.md This example shows how to use the `hide_input` and `hide_output` parameters to prevent sensitive input and output data from being logged in the trace, ensuring privacy and security for specific operations. ```python @traced(hide_input=True, hide_output=True) def sensitive_operation(secret): ... ``` -------------------------------- ### API Style Guide: Retrieve Single Resource Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Defines the standard method for retrieving a single resource instance. The primary method is `retrieve`, which uses a unique identifier (`key`). Variations like `retrieve_by_[field_name]` are available for other fields. ```APIDOC Standard Methods and Naming Conventions: - Retrieve a Single Resource - Method Name: `retrieve` - Purpose: Obtain a specific resource instance using its unique identifier (using `key` instead of `id`) - Variations: - `retrieve_by_[field_name]` (for fields other than `key`) ``` -------------------------------- ### Masking Sensitive Data with Input/Output Processors Source: https://github.com/uipath/uipath-python/blob/main/docs/core/traced.md Processors allow you to mask, redact, or transform sensitive data before it is recorded in the trace. This example demonstrates how to use `input_processor` to mask a password and `output_processor` to anonymize an email in the trace data. ```python def mask_inputs(inputs): inputs = inputs.copy() if 'password' in inputs: inputs['password'] = '***REDACTED***' return inputs def anonymize_output(output): if isinstance(output, dict) and 'email' in output: output = output.copy() output['email'] = 'anonymous@example.com' return output @traced(input_processor=mask_inputs, output_processor=anonymize_output) def login(user, password): # ... return {"email": user + "@example.com"} ``` -------------------------------- ### Apply @traced() Decorator to Functions Source: https://github.com/uipath/uipath-python/blob/main/docs/core/traced.md Apply the `@traced()` decorator to any function (sync, async, generator, or async generator) to automatically record its execution as a trace span. This example shows basic usage for both synchronous and asynchronous functions. ```python from uipath.tracing import traced @traced() def my_function(x, y): return x + y @traced(name="custom_span", run_type="my_type") async def my_async_function(a, b): return a * b ``` -------------------------------- ### Tracing Functions in UiPath Langchain Agents Source: https://github.com/uipath/uipath-python/blob/main/docs/core/traced.md When integrating with `uipath-langchain`, the framework automatically handles trace submission, eliminating the need to explicitly call `wait_for_tracers()`. This example demonstrates applying `@traced()` to a custom function within a Langchain agent context. ```python @traced() def my_custom_traced_function(input: str) -> str: return { "x": "some-output" } ``` -------------------------------- ### Python Package Discovery: Custom Configuration in pyproject.toml Source: https://github.com/uipath/uipath-python/blob/main/docs/FAQ.md This TOML configuration snippet demonstrates how to explicitly define packages for discovery within `pyproject.toml` using `setuptools`, which can resolve deployment issues when a non-standard project structure is maintained for UiPath Python agents. ```toml [tool.setuptools] py-modules = [] packages = ["your_package"] ``` -------------------------------- ### Basic Usage of UiPath Python SDK Source: https://github.com/uipath/uipath-python/blob/main/README.md Demonstrates how to initialize the UiPath SDK and perform common operations such as invoking a process and retrieving an asset. ```python from uipath import UiPath # Initialize the SDK sdk = UiPath() # Execute a process job = sdk.processes.invoke( name="MyProcess", input_arguments={"param1": "value1", "param2": 42} ) # Work with assets asset = sdk.assets.retrieve(name="MyAsset") ``` -------------------------------- ### Initialize UiPath Project Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md The `uipath init` command analyzes your `main.py` file to understand its structure, inputs, and outputs, then creates a `uipath.json` file to configure your UiPath project. ```shell > uipath init ⠋ Initializing UiPath project ... ✓ Created 'uipath.json' file. ``` -------------------------------- ### Initialize UiPath Project with CLI Source: https://github.com/uipath/uipath-python/blob/main/README.md Command to create a uipath.json configuration file for a new UiPath project. An optional entrypoint can be provided, otherwise, it attempts to find a single Python file. ```bash uipath init [ENTRYPOINT] ``` -------------------------------- ### Python Project Structure: Recommended Layout for UiPath Deployment Source: https://github.com/uipath/uipath-python/blob/main/docs/FAQ.md This snippet illustrates the recommended project structure for Python coded agents to avoid 'Failed to prepare environment' errors in UiPath Cloud Platform, emphasizing the use of a non-top-level 'src' directory for packages. ```plaintext project_root/ ├── src/ │ └── your_package/ │ ├── __init__.py │ └── your_modules.py ├── pyproject.toml └── setup.cfg/setup.py ``` -------------------------------- ### Create and Navigate to Project Directory Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Create a new directory for your project and change the current working directory into it, preparing for project initialization. ```sh mkdir project cd project ``` -------------------------------- ### Available UiPath Python SDK Services Overview Source: https://github.com/uipath/uipath-python/blob/main/README.md A list of core services provided by the UiPath Python SDK, detailing their purpose and functionality for interacting with UiPath Cloud Platform. ```APIDOC sdk.processes: Manage and execute UiPath automation processes sdk.assets: Work with assets (variables, credentials) stored in UiPath sdk.buckets: Manage cloud storage containers for automation files sdk.connections: Handle connections to external systems sdk.context_grounding: Work with semantic contexts for AI-enabled automation sdk.jobs: Monitor and manage automation jobs sdk.queues: Work with transaction queues sdk.actions: Work with Action Center sdk.api_client: Direct access to the API client for custom requests ``` -------------------------------- ### Initialize Python Project with uv Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Initialize the current directory as a Python project, specifying Python 3.10 as the target interpreter version for 'uv'. ```sh uv init . --python 3.10 ``` -------------------------------- ### Package UiPath Project with CLI Source: https://github.com/uipath/uipath-python/blob/main/README.md Command to package the current UiPath project into a .nupkg file, which is the deployable format for UiPath Orchestrator. ```bash uipath pack ``` -------------------------------- ### Configure UiPath SDK Environment Variables Source: https://github.com/uipath/uipath-python/blob/main/README.md Instructions for setting up environment variables in a .env file, including the UiPath Cloud Platform URL and access token, required for SDK authentication. ```plaintext UIPATH_URL=https://cloud.uipath.com/ACCOUNT_NAME/TENANT_NAME UIPATH_ACCESS_TOKEN=YOUR_TOKEN_HERE ``` -------------------------------- ### Debug UiPath Project with CLI Source: https://github.com/uipath/uipath-python/blob/main/README.md Command to execute a Python script with provided JSON input arguments, facilitating local debugging of UiPath automations. ```bash uipath run ENTRYPOINT [INPUT] ``` -------------------------------- ### Create Python Virtual Environment with uv Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Use 'uv' to create a new virtual environment in the current working directory, isolating project dependencies. ```sh uv venv ``` -------------------------------- ### Publish UiPath Package with CLI Source: https://github.com/uipath/uipath-python/blob/main/README.md Command to publish the most recently created .nupkg package directly to your configured UiPath Orchestrator instance. ```bash uipath publish ``` -------------------------------- ### Authenticate UiPath CLI Source: https://github.com/uipath/uipath-python/blob/main/README.md Command to initiate the authentication process for the UiPath Command Line Interface, which opens a browser for login and updates the .env file with necessary credentials. ```bash uipath auth ``` -------------------------------- ### Publish UiPath Package to Feed Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md The `uipath publish` command allows you to select an available package feed (e.g., Orchestrator Tenant Processes Feed) and publish your most recently packaged `.nupkg` file to it. Prerequisites include `pyproject.toml` and `uipath.json`. ```shell > uipath publish ⠋ Fetching available package feeds... 👇 Select package feed: 0: Orchestrator Tenant Processes Feed 1: Orchestrator Personal Workspace Feed Select feed number: 0 Selected feed: Orchestrator Tenant Processes Feed ⠸ Publishing most recent package: test.0.1.0.nupkg ... ✓ Package published successfully! ``` -------------------------------- ### Configure Additional Files for UiPath Packaging Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md To include files beyond the default types in your `.nupkg` package, update the `uipath.json` file with a `settings` section. This configuration allows specifying individual files and new file extensions to be included. ```json { "settings": { "filesIncluded": [ "" ], "fileExtensionsIncluded": [ "" ] } } ``` -------------------------------- ### Configure UiPath Environment Variables in .env and System Source: https://github.com/uipath/uipath-python/blob/main/docs/core/environment_variables.md Illustrates how to define UiPath-related environment variables in a local `.env` file and as system-wide exports, demonstrating the priority order for variable loading. ```bash # .env file UIPATH_FOLDER_PATH=/default/path # System environment export UIPATH_FOLDER_PATH=/system/path ``` -------------------------------- ### Set UiPath SDK Path Environment Variable Source: https://github.com/uipath/uipath-python/blob/main/CONTRIBUTING.md Define an environment variable 'PATH_TO_SDK' pointing to the local clone of the UiPath Python SDK repository. Replace 'YOUR_USERNAME' with your actual username. ```sh PATH_TO_SDK=/Users/YOUR_USERNAME/uipath-python ``` -------------------------------- ### Jinja2 Template for GitHub Issue Link Generation Source: https://github.com/uipath/uipath-python/blob/main/docs/overrides/partials/actions.html This Jinja2 template dynamically constructs a URL to create a new GitHub issue. It populates the issue title with the current page's title or site name, and the body with a link to the current page and a placeholder for user input. The `urlencode` filter ensures proper URL formatting for the title and body parameters. ```Jinja2 {% set title = ("\\[" + (page.title or config.site_name) + "\\] Your title here") | urlencode %} {% set body = ("Page link:: " + config.site_url + page.url + "\\n\\n ## My Issue/Suggestion") | urlencode %} [Report an issue](https://github.com/UiPath/uipath-python/issues/new?title={{ title }}&body={{ body }}) ``` -------------------------------- ### Using Langchain's @traceable() Attribute Source: https://github.com/uipath/uipath-python/blob/main/docs/core/traced.md This snippet shows how to use Langchain's native `@traceable()` attribute for tracing. It's important to note that using both `@traced()` from UiPath and `@traceable()` from Langchain simultaneously will result in duplicate trace spans. ```python @traceable() # @traced() ---> do not use both at the same time or it will duplicate spans. def my_custom_traced_function(input: str) -> str: return { "x": "some-output" } ``` -------------------------------- ### UiPath Attachments Service Module API Reference Source: https://github.com/uipath/uipath-python/blob/main/docs/core/attachments.md This entry provides a reference to the `uipath._services.attachments_service` module, which is a core component for interacting with attachment-related functionalities in UiPath Python automations. Further details on its methods and classes would typically be found within the module's source or generated documentation. ```APIDOC uipath._services.attachments_service ``` -------------------------------- ### UiPath CLI OAuth 2.0 PKCE Authentication Flow Source: https://github.com/uipath/uipath-python/blob/main/src/uipath/_cli/_auth/index.html Comprehensive JavaScript implementation for the UiPath CLI's client-side authentication. It includes functions for parsing URL query parameters, securely exchanging authorization codes for access tokens using PKCE, parsing JWTs, and orchestrating the entire authentication process with integrated logging and error handling. ```javascript const baseUrl = '__PY_REPLACE_REDIRECT_URI__'.replace('/oidc/login', ''); const logs = []; // Parse URL query parameters function getQueryParams() { const params = {}; const queryString = window.location.search; const urlParams = new URLSearchParams(queryString); for (const [key, value] of urlParams.entries()) { params[key] = value; } return params; } // Exchange authorization code for tokens async function exchangeCodeForToken(code, codeVerifier) { try { // Prepare form data for token request const formData = new URLSearchParams(); formData.append('grant_type', 'authorization_code'); formData.append('code', code); formData.append('redirect_uri', '__PY_REPLACE_REDIRECT_URI__'); formData.append('client_id', '__PY_REPLACE_CLIENT_ID__'); formData.append('code_verifier', codeVerifier); // Make token request const response = await fetch('https://__PY_REPLACE_DOMAIN__.uipath.com/identity_/connect/token', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: formData }); if (!response.ok) { const errorText = await response.text(); throw new Error(`Token request failed: ${response.status} ${response.statusText} - ${errorText}`); } const tokenData = await response.json(); return tokenData; } catch (error) { console.error('Error exchanging code for token:', error); logs.push({ timestamp: new Date().toISOString(), message: 'Error exchanging code for token:', error: error.message }); throw error; } } // Parse JWT token function parseJwt(token) { try { const base64Url = token.split('.')[1]; const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); const jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); return JSON.parse(jsonPayload); } catch (e) { console.error('Error parsing JWT:', e); logs.push({ timestamp: new Date().toISOString(), message: 'Error parsing JWT:', error: e.message }); return null; } } async function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } async function sendLogs(logs) { await fetch(`${baseUrl}/log`, { method: 'POST', body: JSON.stringify(logs) }); } // Main function to handle the authentication flow async function handleAuthentication() { const params = getQueryParams(); logs.push({ timestamp: new Date().toISOString(), message: 'Params:', params: params }); try { // Check if we have an authorization code if (params.code && params.state) { // Get code verifier from session storage const codeVerifier = "__PY_REPLACE_CODE_VERIFIER__"; const state = "__PY_REPLACE_EXPECTED_STATE__"; if (!codeVerifier) { throw new Error('Code verifier not found in session storage'); } if (!params.state || params.state != state) { throw new Error('Invalid state parameter. Possible CSRF attack.'); } // Exchange code for token const tokenData = await exchangeCodeForToken(params.code, codeVerifier); await sendLogs(logs); const setTokenResult = await fetch(`${baseUrl}/set_token`, { method: 'POST', body: JSON.stringify(tokenData) }); // Show success message document.querySelector('h1').textContent = 'If this windows does not close automatically, you may close it now'; setTimeout(() => { document.querySelector('button').click(); }, 500); sessionStorage.removeItem('oidc_state'); sessionStorage.removeItem('oidc_code_verifier'); // Remove code and state from URL to prevent refresh issues window.history.replaceState({}, document.title, window.location.pathname); } } catch (error) { console.error('Error during authentication:', error); logs.push({ timestamp: new Date().toISOString(), message: 'Error during authentication:', error: error.message }); await sendLogs(logs); document.querySelector('h1').textContent = 'Authentication failed. Please try again.'; } } // Start authentication process when page loads handleAuthentication(); ``` -------------------------------- ### Escape JSON Input for UiPath Run Command Source: https://github.com/uipath/uipath-python/blob/main/docs/cli/index.md Demonstrates the correct syntax for escaping JSON input when using the `uipath run` command across different shell environments: Bash/ZSH, Windows CMD, and Windows PowerShell, to ensure proper parsing of the input. ```console uipath run agent '{"topic": "UiPath"}' ``` ```console uipath run agent "{\"\"topic\"\": \"\"UiPath\"\"}" ``` ```console uipath run agent '`{\`"topic\`":\`"uipath\`"}`' ``` -------------------------------- ### Initialize Google Tag Manager in HTML Template Source: https://github.com/uipath/uipath-python/blob/main/docs/overrides/main.html This JavaScript snippet initializes Google Tag Manager by asynchronously loading its script. It's typically embedded within the section of an HTML page, often via a templating engine like Jinja2, to track user interactions and page views. The '{{ config.google_tag_manager_id }}' variable is expected to be dynamically replaced with the actual GTM container ID. ```JavaScript (function (w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = 'https://www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', 'dataLayer', '{{ config.google_tag_manager_id }}'); ``` -------------------------------- ### @traced() Decorator Parameters Source: https://github.com/uipath/uipath-python/blob/main/docs/core/traced.md This section details the configurable parameters for the `@traced()` decorator, including their types and descriptions, allowing for custom naming, categorization, data processing, and privacy controls for trace spans. ```APIDOC name: Optional[str] Description: Custom name for the trace span. Defaults to the function name. run_type: Optional[str] Description: Category for the run (e.g., "uipath"). Useful for filtering traces. span_type: Optional[str] Description: Custom type for the span. Defaults to function type (sync/async/generator). input_processor: Optional[Callable[[dict], dict]] Description: Function to process/transform inputs before recording. Receives a dict of arguments. output_processor: Optional[Callable[[Any], Any]] Description: Function to process/transform outputs before recording. Receives the function's return value. hide_input: bool Description: If True, input data is redacted in the trace for privacy/security. hide_output: bool Description: If True, output data is redacted in the trace for privacy/security. ``` -------------------------------- ### UiPath Orchestrator Runtime Log Level Configuration Source: https://github.com/uipath/uipath-python/blob/main/docs/core/environment_variables.md Documents the `LOG_LEVEL` environment variable and its possible values, which control the verbosity of logs displayed in the UiPath Orchestrator UI during process execution. ```APIDOC LOG_LEVEL: Description: Controls the verbosity of logging in the Orchestrator UI's Log tab during runtime execution. Default: INFORMATION Levels: TRACE: Most detailed logging level, shows all possible information DEBUG: Detailed information for debugging purposes INFORMATION: General operational information WARNING: Warning messages for potentially harmful situations ERROR: Error events that might still allow the application to continue CRITICAL: Critical events that may lead to application failure NONE: No logging ``` -------------------------------- ### Ensuring Traces are Sent in Plain Python Agents Source: https://github.com/uipath/uipath-python/blob/main/docs/core/traced.md When using `traced()` with plain Python agents, it is crucial to call `wait_for_tracers()` at the end of the script. This ensures that all collected trace data is sent before the agent terminates, preventing data loss. ```python from uipath.tracing import traced, wait_for_tracers @traced(name="process_payment", run_type="payment", hide_input=True) def process_payment(card_number, amount): # Sensitive input will not be logged return {"status": "success", "amount": amount} @traced() def main(): process_payment() def main_wait_traces(): try: main() finally: # this needs to be called after the last `traced` function is done # to ensure the trace associated with main is saved wait_for_tracers() if __name__ == "__main__": main_wait_traces() ``` -------------------------------- ### Reference UiPath Secret Asset in Environment Variable Source: https://github.com/uipath/uipath-python/blob/main/docs/core/environment_variables.md Shows the required format for an environment variable to securely reference a secret asset managed within UiPath Orchestrator, enhancing security for sensitive data. ```bash NAME=%ASSETS/your-secret-asset-name% ``` -------------------------------- ### Hide Authentication Button CSS Source: https://github.com/uipath/uipath-python/blob/main/src/uipath/_cli/_auth/index.html A small CSS rule to hide a button element, likely used to manage UI visibility during the authentication process. ```css button { opacity: 0; } ``` -------------------------------- ### Disable UiPath CLI Telemetry via Environment Variable Source: https://github.com/uipath/uipath-python/blob/main/docs/core/environment_variables.md Provides the specific environment variable setting to opt out of telemetry collection for the UiPath CLI, to be placed in the project's `.env` file. ```bash UIPATH_TELEMETRY_ENABLED=false ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.