uipath-functions

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

UiPath Python Coded Functions

UiPath Python Coded Functions

What Python Coded Functions Are

什么是Python编码函数

Python Coded Functions are atomic, bespoke units of business logic — deterministic Python code packaged as a first-class UiPath artifact. Use them when generic activities don't cover the required logic: calling a third-party API with custom auth, processing documents with domain-specific rules, querying ERP systems via Integration Service connections, or transforming data in ways that no out-of-the-box activity handles.
A Coded Function is not an agent. It does not reason, route, or call LLMs. It takes typed input, executes deterministic code, and returns typed output.
Python编码函数是原子化、定制化的业务逻辑单元——作为一等UiPath工件打包的确定性Python代码。当通用活动无法覆盖所需逻辑时使用:通过自定义认证调用第三方API、使用领域特定规则处理文档、通过集成服务连接查询ERP系统,或者以开箱即用活动无法实现的方式转换数据。
编码函数不是智能体。它不进行推理、路由或调用LLM。它接收类型化输入,执行确定性代码,并返回类型化输出。

Invocation surfaces

调用场景

A Python Coded Function can be invoked from any UiPath surface:
SurfaceHow
Maestro BPMNService Task node
Maestro FlowCoded Agent node or Service Task
Coded Agents (LangGraph / LlamaIndex / OpenAI Agents)Called as a tool or step
Other Coded FunctionsDirect Python call or Orchestrator job
Orchestrator API
POST /Jobs/StartJobs
CLI
uip function pack
uip function publish
Python编码函数可从任意UiPath场景调用:
场景调用方式
Maestro BPMN服务任务节点
Maestro Flow编码智能体节点或服务任务
编码智能体(LangGraph / LlamaIndex / OpenAI Agents)作为工具或步骤调用
其他编码函数直接Python调用或Orchestrator任务
Orchestrator API
POST /Jobs/StartJobs
CLI
uip function pack
uip function publish

Python Functions vs JS Functions

Python函数 vs JS函数

Python Coded FunctionJS/TS Function
Job semanticsYes — Orchestrator job ID, audit trail, retry, schedulingNo — inline HTTP only, no job lifecycle
InvocationMaestro, Flow, Agents, Orchestrator APIHTTP endpoint (BFF for Coded Apps)
RuntimeServerless or Local Unattended RobotServerless HTTP shared tier
SDK accessFull UiPath Python SDK (assets, buckets, queues, connections)Workload token forwarding only
Scaffold
uip function new <name> --language py
uip function new <name> --language ts
(default)
Init
uip function init
(generates entry-points.json)
Not needed
Local dev
uip function run
uip function serve
+
uip function run
Best forAgentic process steps, ERP integration, document AI, data pipelinesBackend-for-Frontend for Coded Apps
Use Python when the logic needs job semantics, platform SDK access, or is invoked from Maestro/agents. Use JS when the caller is a Coded App frontend and low HTTP latency matters.

Python编码函数JS/TS函数
任务语义支持——Orchestrator任务ID、审计追踪、重试、调度不支持——仅内联HTTP调用,无任务生命周期
调用方式Maestro、Flow、智能体、Orchestrator APIHTTP端点(编码应用的后端前置服务)
运行时无服务器或本地无人值守机器人无服务器HTTP共享层
SDK访问权限完整UiPath Python SDK(资产、存储桶、队列、连接)仅支持工作负载令牌转发
脚手架命令
uip function new <name> --language py
uip function new <name> --language ts
(默认)
初始化
uip function init
(生成entry-points.json)
无需初始化
本地开发
uip function run
uip function serve
+
uip function run
适用场景智能体流程步骤、ERP集成、文档AI、数据管道编码应用的前端后端前置服务
当逻辑需要任务语义、平台SDK访问权限,或需从Maestro/智能体调用时使用Python。当调用方是编码应用前端且低HTTP延迟至关重要时使用JS。

CLI Reference

CLI参考

All Python Coded Function lifecycle commands use
uip function
:
bash
uip function new <name> -l py     # scaffold a new Python Functions project (--language py required)
uip function init                 # Python only — generate entry-points.json, bindings.json, project.uiproj
uip function pack                 # pack to .nupkg for deployment
uip function publish              # upload .nupkg to Orchestrator (prompts for feed, or use --feed-id)
uip function push                 # sync project to Studio Web
uip function run
works for both Python and JS/TS.
uip function serve
is JS/TS only — it starts the local HTTP server that
run
invokes against.

所有Python编码函数生命周期命令均使用
uip function
bash
uip function new <name> -l py     # 搭建新的Python函数项目(必须指定--language py)
uip function init                 # 仅Python可用——生成entry-points.json、bindings.json、project.uiproj
uip function pack                 # 打包为.nupkg用于部署
uip function publish              # 将.nupkg上传至Orchestrator(提示选择源,或使用--feed-id)
uip function push                 # 将项目同步至Studio Web
uip function run
适用于Python和JS/TS。
uip function serve
仅JS/TS可用——启动本地HTTP服务器供
run
调用。

Workflow

工作流程

Step 1: Scaffold

步骤1:搭建项目

bash
uip function new <name> --language py       # Python Coded Function
uip function new <name> --language ts       # TypeScript Function (JS/TS, no job semantics)
uip function new <name> --language js       # JavaScript Function (JS/TS, no job semantics)
--language py
is required for Python.
The default language is TypeScript — omitting
--language
scaffolds a JS/TS project. Always pass
-l py
or
--language py
when building a Python Coded Function.
--empty
skips the hello-world function (JS/TS only).
The scaffold follows the installed packages. With a framework package present in the environment (
uipath-langchain
,
llama-index
,
openai-agents
),
uip function new -l py
emits that framework's agent scaffold —
langgraph.json
plus an LLM
main.py
— not a function scaffold. Expected behaviour, not a broken flag. Recovery, in one pass:
  1. Delete the framework config (
    langgraph.json
    and equivalents).
  2. Replace
    main.py
    with the function template (Step 3).
  3. Keep
    pyproject.toml
    's
    [project]
    metadata (Step 5) — swap
    dependencies
    for what the function needs.
Do not re-run
new
with different flag spellings, and do not read CLI or SDK internals to explain the scaffold. Reshape the project and move on.
bash
uip function new <name> --language py       # Python编码函数
uip function new <name> --language ts       # TypeScript函数(JS/TS,无任务语义)
uip function new <name> --language js       # JavaScript函数(JS/TS,无任务语义)
搭建Python项目必须指定
--language py
。默认语言是TypeScript——省略
--language
将搭建JS/TS项目。构建Python编码函数时务必传递
-l py
--language py
--empty
参数会跳过hello-world函数(仅JS/TS可用)。
脚手架内容取决于已安装的包。若环境中存在框架包(
uipath-langchain
llama-index
openai-agents
),
uip function new -l py
会生成该框架的智能体脚手架——
langgraph.json
加LLM版
main.py
——而非函数脚手架。这是预期行为,并非命令异常。可通过以下步骤恢复:
  1. 删除框架配置文件(
    langgraph.json
    及同类文件)。
  2. main.py
    替换为函数模板(步骤3)。
  3. 保留
    pyproject.toml
    [project]
    元数据(步骤5)——将
    dependencies
    替换为函数所需依赖。
请勿使用不同参数拼写重新运行
new
命令,也无需通过阅读CLI或SDK内部代码来解释脚手架内容。直接调整项目结构即可。

Step 2: Define Function Schema

步骤2:定义函数 schema

Use typed I/O. The SDK accepts pydantic
BaseModel
,
pydantic.dataclasses.dataclass
, a stdlib
@dataclass
, or a thin class with typed annotations. The shipped samples favor pydantic (
BaseModel
in csv-processor,
pydantic.dataclasses.dataclass
in calculator/greeter):
python
from pydantic import BaseModel

class Input(BaseModel):
    document_id: str = ""

class Output(BaseModel):
    vendor_name: str = ""
    total_amount: float = 0.0
    error_type: str = ""     # populated on failure, empty on success
    error_message: str = ""  # human-readable error detail
使用类型化输入输出。SDK支持pydantic
BaseModel
pydantic.dataclasses.dataclass
、标准库
@dataclass
,或带有类型注解的轻量类。官方示例优先使用pydantic(csv-processor使用
BaseModel
,calculator/greeter使用
pydantic.dataclasses.dataclass
):
python
from pydantic import BaseModel

class Input(BaseModel):
    document_id: str = ""

class Output(BaseModel):
    vendor_name: str = ""
    total_amount: float = 0.0
    error_type: str = ""     # 执行失败时填充,成功时为空
    error_message: str = ""  # 人类可读的错误详情

Step 3: Implement Business Logic

步骤3:实现业务逻辑

Do NOT make LLM calls inside a Coded Function. LLM calls introduce non-determinism and latency that break the function contract. If the step requires LLM reasoning or multi-step AI decisions, use a framework-based agent (LangGraph, LlamaIndex, OpenAI Agents) instead.
请勿在编码函数内部调用LLM。LLM调用会引入非确定性和延迟,违反函数约定。若步骤需要LLM推理或多步AI决策,请使用基于框架的智能体(LangGraph、LlamaIndex、OpenAI Agents)替代。

Minimal template

最小模板

python
from __future__ import annotations

from pydantic import BaseModel
from uipath.tracing import traced
from uipath.platform import UiPath

class Input(BaseModel):
    document_id: str = ""

class Output(BaseModel):
    result: str = ""
    error_type: str = ""
    error_message: str = ""
python
from __future__ import annotations

from pydantic import BaseModel
from uipath.tracing import traced
from uipath.platform import UiPath

class Input(BaseModel):
    document_id: str = ""

class Output(BaseModel):
    result: str = ""
    error_type: str = ""
    error_message: str = ""

Lazy SDK singleton — never instantiate UiPath() at module level

延迟初始化SDK单例——绝不在模块级别实例化UiPath()

_sdk: UiPath | None = None
def sdk() -> UiPath: global _sdk if _sdk is None: _sdk = UiPath() return _sdk
@traced(name="my_function", run_type="uipath") def my_function(input: Input) -> Output: out = Output() try: # SDK calls, data processing, rule-based logic only asset = sdk().assets.retrieve("MY_ASSET", folder_path="Shared") out.result = str(asset.value) except Exception as exc: out.error_type = "FAILED" out.error_message = str(exc) return out

Key rules:
- **Typed I/O** — pydantic `BaseModel`, `pydantic.dataclasses.dataclass`, stdlib `@dataclass`, or a thin class with typed annotations; samples favor pydantic
- **`def` or `async def`** — both supported (csv-processor uses `async def main`); the function name is arbitrary
- **Lazy SDK init** — instantiate `UiPath()` inside a getter, never at module level
- **Errors returned, not raised** — populate `error_type`/`error_message` output fields and return; never let exceptions bubble out of the entrypoint
- **`@traced(name=..., run_type="uipath")`** — apply to the entrypoint and any sub-functions you want visible in LLM Ops Traces
_sdk: UiPath | None = None
def sdk() -> UiPath: global _sdk if _sdk is None: _sdk = UiPath() return _sdk
@traced(name="my_function", run_type="uipath") def my_function(input: Input) -> Output: out = Output() try: # 仅允许SDK调用、数据处理、基于规则的逻辑 asset = sdk().assets.retrieve("MY_ASSET", folder_path="Shared") out.result = str(asset.value) except Exception as exc: out.error_type = "FAILED" out.error_message = str(exc) return out

核心规则:
- **类型化输入输出**——支持pydantic `BaseModel`、`pydantic.dataclasses.dataclass`、标准库`@dataclass`,或带有类型注解的轻量类;示例优先使用pydantic
- **`def`或`async def`**——两者均支持(csv-processor使用`async def main`);函数名称可自定义
- **延迟初始化SDK**——在 getter 函数内部实例化`UiPath()`,绝不在模块级别实例化
- **返回错误而非抛出异常**——填充`error_type`/`error_message`输出字段并返回;绝不让异常从入口点冒泡
- **`@traced(name=..., run_type="uipath")`**——应用于入口点及所有需要在LLM Ops追踪中可见的子函数

Step 4: Register in
uipath.json

步骤4:在
uipath.json
中注册

json
{
  "runtimeOptions": { "isConversational": false },
  "functions": {
    "main": "main.py:my_function"
  }
}
The key is the entrypoint name — it can be any string and marks this as the callable entrypoint. The value is
"<file>:<function_name>"
. Both the key and the function name are arbitrary.
This
functions
map is what identifies the project as a Coded Function
— the runtime's
determine_project_type()
reads the entrypoint type from
uipath.json
.
json
{
  "runtimeOptions": { "isConversational": false },
  "functions": {
    "main": "main.py:my_function"
  }
}
键为入口点名称——可为任意字符串,用于标记可调用入口点。值为
"<file>:<function_name>"
。键和函数名称均可自定义。
functions
映射是识别项目为编码函数的标志
——运行时的
determine_project_type()
会从
uipath.json
读取入口点类型。

Step 5: Declare dependencies in
pyproject.toml

步骤5:在
pyproject.toml
中声明依赖

toml
[project]
name = "my-function"
version = "0.1.0"
description = "..."
authors = [{ name = "Your Name", email = "you@example.com" }]
requires-python = ">=3.11"
dependencies = [
    "uipath",
    "httpx>=0.28",          # if making HTTP calls
    "pydantic-settings>=2", # if using Settings for env/asset config
]
authors
is required — without it
uip function pack
rejects the package with
Project authors cannot be empty
.
No
[build-system]
section. The project is identified as a Coded Function by the
functions
map in
uipath.json
(Step 4).
toml
[project]
name = "my-function"
version = "0.1.0"
description = "..."
authors = [{ name = "Your Name", email = "you@example.com" }]
requires-python = ">=3.11"
dependencies = [
    "uipath",
    "httpx>=0.28",          # 若需发起HTTP调用
    "pydantic-settings>=2", # 若需使用Settings处理环境/资产配置
]
authors
必填项——若缺失,
uip function pack
会返回错误
Project authors cannot be empty
无需
[build-system]
section。项目通过
uipath.json
中的
functions
映射(步骤4)被识别为编码函数。

Step 6: Generate Entry Points

步骤6:生成入口点

bash
uip function init
Python only. Discovers entrypoints and generates
entry-points.json
,
bindings.json
, and
project.uiproj
. Must run before
pack
or
push
. Re-run whenever Input/Output schemas or the entrypoint registration in
uipath.json
changes.
bash
uip function init
仅Python可用。自动发现入口点并生成
entry-points.json
bindings.json
project.uiproj
。必须在
pack
push
之前运行。每当输入/输出 schema 或
uipath.json
中的入口点注册发生变化时,需重新运行。

Step 7: SDK Capabilities

步骤7:SDK功能

Access UiPath platform resources via
sdk()
:
python
from uipath.platform import UiPath
from uipath.platform.connections.connections import ActivityMetadata, ActivityParameterLocationInfo
通过
sdk()
访问UiPath平台资源:
python
from uipath.platform import UiPath
from uipath.platform.connections.connections import ActivityMetadata, ActivityParameterLocationInfo

Assets — retrieve named credentials or config values

资产——获取命名凭据或配置值

asset = sdk().assets.retrieve("ASSET_NAME", folder_path="Shared") value = asset.string_value # or credential_username / credential_password
asset = sdk().assets.retrieve("ASSET_NAME", folder_path="Shared") value = asset.string_value # 或 credential_username / credential_password

Buckets — download files for processing

存储桶——下载文件用于处理

sdk().buckets.download( name="BucketName", blob_file_path="relative/path/file.pdf", destination_path="/tmp/local.pdf", folder_path="Shared", )
sdk().buckets.download( name="BucketName", blob_file_path="relative/path/file.pdf", destination_path="/tmp/local.pdf", folder_path="Shared", )

Integration Service connections — invoke connector activities (ERP, CRM, etc.)

集成服务连接——调用连接器活动(ERP、CRM等)

result = sdk().connections.invoke_activity( activity_metadata=ActivityMetadata( object_path="/executeSuiteQL", method_name="POST", content_type="application/json", parameter_location_info=ActivityParameterLocationInfo(body_fields=["q"]), ), connection_id="<connection-uuid>", activity_input={"q": "SELECT id FROM vendor WHERE ..."}, )
undefined
result = sdk().connections.invoke_activity( activity_metadata=ActivityMetadata( object_path="/executeSuiteQL", method_name="POST", content_type="application/json", parameter_location_info=ActivityParameterLocationInfo(body_fields=["q"]), ), connection_id="<connection-uuid>", activity_input={"q": "SELECT id FROM vendor WHERE ..."}, )
undefined

File attachment inputs

文件附件输入

To accept a runtime file, type an
Input
field as
Attachment
(pydantic model, not a dataclass):
python
from pydantic import BaseModel
from uipath.platform.attachments import Attachment

class Input(BaseModel):
    attachment: Attachment
uip function init
recognizes the
Attachment
type and emits
x-uipath-resource-kind: JobAttachment
in
entry-points.json
— the schema Studio Web and Orchestrator read to render a file picker for that field. Access fields snake_case:
attachment.full_name
,
attachment.content
.
若要接收运行时文件,需将输入字段类型设为
Attachment
(pydantic模型,而非数据类):
python
from pydantic import BaseModel
from uipath.platform.attachments import Attachment

class Input(BaseModel):
    attachment: Attachment
uip function init
会识别
Attachment
类型,并在
entry-points.json
中生成
x-uipath-resource-kind: JobAttachment
——Studio Web和Orchestrator会读取该schema为对应字段渲染文件选择器。通过蛇形命名访问字段:
attachment.full_name
attachment.content

Step 8: Pack and Publish

步骤8:打包与发布

bash
uip function pack                            # creates .nupkg
uip function publish                         # upload to Orchestrator (interactive feed picker)
uip function publish --feed-id <FEED_ID>     # CI/non-interactive
To sync to Studio Web instead of publishing to Orchestrator:
bash
uip function push
bash
uip function pack                            # 创建.nupkg文件
uip function publish                         # 上传至Orchestrator(交互式源选择器)
uip function publish --feed-id <FEED_ID>     # CI/非交互式场景
若要同步至Studio Web而非发布到Orchestrator:
bash
uip function push

Important Notes

重要注意事项

  • UiPath()
    must never be instantiated at module level — always inside a function body
  • The
    functions
    map in
    uipath.json
    marks the project as a Coded Function (
    determine_project_type()
    reads the entrypoint type from
    uipath.json
    )
  • uip function init
    must run before
    pack
    or
    push
    — it generates
    entry-points.json
  • Python Functions have full job semantics: Orchestrator job ID, audit trail, retry, scheduling
  • JS Functions have no job semantics and cannot be started as Orchestrator jobs — use Python when the caller is Maestro, a Flow, or an agent
  • uip function run
    works for both Python and JS/TS local execution;
    uip function serve
    is JS/TS only (starts the local HTTP server that
    run
    invokes against)
  • If cloud-backed work requires authentication, run
    uip login --organization "<ORG>" --tenant "<TENANT>" --output json
    .
  • 绝不在模块级别实例化
    UiPath()
    ——务必在函数体内实例化
  • uipath.json
    中的
    functions
    映射是标记项目为编码函数的标志(
    determine_project_type()
    uipath.json
    读取入口点类型)
  • uip function init
    必须在
    pack
    push
    之前运行——它会生成
    entry-points.json
  • Python函数具备完整任务语义:Orchestrator任务ID、审计追踪、重试、调度
  • JS函数无任务语义,无法作为Orchestrator任务启动——当调用方是Maestro、Flow或智能体时使用Python
  • uip function run
    适用于Python和JS/TS本地执行;
    uip function serve
    仅JS/TS可用(启动本地HTTP服务器供
    run
    调用)
  • 若云托管工作需要认证,请运行
    uip login --organization "<ORG>" --tenant "<TENANT>" --output json