uipath-functions
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseUiPath 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:
| Surface | How |
|---|---|
| Maestro BPMN | Service Task node |
| Maestro Flow | Coded Agent node or Service Task |
| Coded Agents (LangGraph / LlamaIndex / OpenAI Agents) | Called as a tool or step |
| Other Coded Functions | Direct Python call or Orchestrator job |
| Orchestrator API | |
| CLI | |
Python编码函数可从任意UiPath场景调用:
| 场景 | 调用方式 |
|---|---|
| Maestro BPMN | 服务任务节点 |
| Maestro Flow | 编码智能体节点或服务任务 |
| 编码智能体(LangGraph / LlamaIndex / OpenAI Agents) | 作为工具或步骤调用 |
| 其他编码函数 | 直接Python调用或Orchestrator任务 |
| Orchestrator API | |
| CLI | |
Python Functions vs JS Functions
Python函数 vs JS函数
| Python Coded Function | JS/TS Function | |
|---|---|---|
| Job semantics | Yes — Orchestrator job ID, audit trail, retry, scheduling | No — inline HTTP only, no job lifecycle |
| Invocation | Maestro, Flow, Agents, Orchestrator API | HTTP endpoint (BFF for Coded Apps) |
| Runtime | Serverless or Local Unattended Robot | Serverless HTTP shared tier |
| SDK access | Full UiPath Python SDK (assets, buckets, queues, connections) | Workload token forwarding only |
| Scaffold | | |
| Init | | Not needed |
| Local dev | | |
| Best for | Agentic process steps, ERP integration, document AI, data pipelines | Backend-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 API | HTTP端点(编码应用的后端前置服务) |
| 运行时 | 无服务器或本地无人值守机器人 | 无服务器HTTP共享层 |
| SDK访问权限 | 完整UiPath Python SDK(资产、存储桶、队列、连接) | 仅支持工作负载令牌转发 |
| 脚手架命令 | | |
| 初始化 | | 无需初始化 |
| 本地开发 | | |
| 适用场景 | 智能体流程步骤、ERP集成、文档AI、数据管道 | 编码应用的前端后端前置服务 |
当逻辑需要任务语义、平台SDK访问权限,或需从Maestro/智能体调用时使用Python。当调用方是编码应用前端且低HTTP延迟至关重要时使用JS。
CLI Reference
CLI参考
All Python Coded Function lifecycle commands use :
uip functionbash
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 Webworks for both Python and JS/TS.uip function runis JS/TS only — it starts the local HTTP server thatuip function serveinvokes against.run
所有Python编码函数生命周期命令均使用:
uip functionbash
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适用于Python和JS/TS。uip function run仅JS/TS可用——启动本地HTTP服务器供uip function serve调用。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--language-l py--language py--emptyThe scaffold follows the installed packages. With a framework package present in the environment (, , ), emits that framework's agent scaffold — plus an LLM — not a function scaffold. Expected behaviour, not a broken flag. Recovery, in one pass:
uipath-langchainllama-indexopenai-agentsuip function new -l pylanggraph.jsonmain.py- Delete the framework config (and equivalents).
langgraph.json - Replace with the function template (Step 3).
main.py - Keep 's
pyproject.tomlmetadata (Step 5) — swap[project]for what the function needs.dependencies
Do not re-run with different flag spellings, and do not read CLI or SDK internals to explain the scaffold. Reshape the project and move on.
newbash
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项目必须指定。默认语言是TypeScript——省略将搭建JS/TS项目。构建Python编码函数时务必传递或。
--language py--language-l py--language py--empty脚手架内容取决于已安装的包。若环境中存在框架包(、、),会生成该框架的智能体脚手架——加LLM版——而非函数脚手架。这是预期行为,并非命令异常。可通过以下步骤恢复:
uipath-langchainllama-indexopenai-agentsuip function new -l pylanggraph.jsonmain.py- 删除框架配置文件(及同类文件)。
langgraph.json - 将替换为函数模板(步骤3)。
main.py - 保留的
pyproject.toml元数据(步骤5)——将[project]替换为函数所需依赖。dependencies
请勿使用不同参数拼写重新运行命令,也无需通过阅读CLI或SDK内部代码来解释脚手架内容。直接调整项目结构即可。
newStep 2: Define Function Schema
步骤2:定义函数 schema
Use typed I/O. The SDK accepts pydantic , , a stdlib , or a thin class with typed annotations. The shipped samples favor pydantic ( in csv-processor, in calculator/greeter):
BaseModelpydantic.dataclasses.dataclass@dataclassBaseModelpydantic.dataclasses.dataclasspython
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 、、标准库,或带有类型注解的轻量类。官方示例优先使用pydantic(csv-processor使用,calculator/greeter使用):
BaseModelpydantic.dataclasses.dataclass@dataclassBaseModelpydantic.dataclasses.dataclasspython
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
uipath.json步骤4:在uipath.json
中注册
uipath.jsonjson
{
"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 . Both the key and the function name are arbitrary.
"<file>:<function_name>"This map is what identifies the project as a Coded Function — the runtime's reads the entrypoint type from .
functionsdetermine_project_type()uipath.jsonjson
{
"runtimeOptions": { "isConversational": false },
"functions": {
"main": "main.py:my_function"
}
}键为入口点名称——可为任意字符串,用于标记可调用入口点。值为。键和函数名称均可自定义。
"<file>:<function_name>"此映射是识别项目为编码函数的标志——运行时的会从读取入口点类型。
functionsdetermine_project_type()uipath.jsonStep 5: Declare dependencies in pyproject.toml
pyproject.toml步骤5:在pyproject.toml
中声明依赖
pyproject.tomltoml
[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
]authorsuip function packProject authors cannot be emptyNo section. The project is identified as a Coded Function by the map in (Step 4).
[build-system]functionsuipath.jsontoml
[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处理环境/资产配置
]authorsuip function packProject authors cannot be empty无需 section。项目通过中的映射(步骤4)被识别为编码函数。
[build-system]uipath.jsonfunctionsStep 6: Generate Entry Points
步骤6:生成入口点
bash
uip function initPython only. Discovers entrypoints and generates , , and . Must run before or . Re-run whenever Input/Output schemas or the entrypoint registration in changes.
entry-points.jsonbindings.jsonproject.uiprojpackpushuipath.jsonbash
uip function init仅Python可用。自动发现入口点并生成、和。必须在或之前运行。每当输入/输出 schema 或中的入口点注册发生变化时,需重新运行。
entry-points.jsonbindings.jsonproject.uiprojpackpushuipath.jsonStep 7: SDK Capabilities
步骤7:SDK功能
Full SDK reference: https://uipath.github.io/uipath-python/
Access UiPath platform resources via :
sdk()python
from uipath.platform import UiPath
from uipath.platform.connections.connections import ActivityMetadata, ActivityParameterLocationInfo通过访问UiPath平台资源:
sdk()python
from uipath.platform import UiPath
from uipath.platform.connections.connections import ActivityMetadata, ActivityParameterLocationInfoAssets — 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 ..."},
)
undefinedresult = 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 ..."},
)
undefinedFile attachment inputs
文件附件输入
To accept a runtime file, type an field as (pydantic model, not a dataclass):
InputAttachmentpython
from pydantic import BaseModel
from uipath.platform.attachments import Attachment
class Input(BaseModel):
attachment: Attachmentuip function initAttachmentx-uipath-resource-kind: JobAttachmententry-points.jsonattachment.full_nameattachment.content若要接收运行时文件,需将输入字段类型设为(pydantic模型,而非数据类):
Attachmentpython
from pydantic import BaseModel
from uipath.platform.attachments import Attachment
class Input(BaseModel):
attachment: Attachmentuip function initAttachmententry-points.jsonx-uipath-resource-kind: JobAttachmentattachment.full_nameattachment.contentStep 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-interactiveTo sync to Studio Web instead of publishing to Orchestrator:
bash
uip function pushbash
uip function pack # 创建.nupkg文件
uip function publish # 上传至Orchestrator(交互式源选择器)
uip function publish --feed-id <FEED_ID> # CI/非交互式场景若要同步至Studio Web而非发布到Orchestrator:
bash
uip function pushImportant Notes
重要注意事项
- must never be instantiated at module level — always inside a function body
UiPath() - The map in
functionsmarks the project as a Coded Function (uipath.jsonreads the entrypoint type fromdetermine_project_type())uipath.json - must run before
uip function initorpack— it generatespushentry-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
- works for both Python and JS/TS local execution;
uip function runis JS/TS only (starts the local HTTP server thatuip function serveinvokes against)run - 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之前运行——它会生成pushentry-points.json - Python函数具备完整任务语义:Orchestrator任务ID、审计追踪、重试、调度
- JS函数无任务语义,无法作为Orchestrator任务启动——当调用方是Maestro、Flow或智能体时使用Python
- 适用于Python和JS/TS本地执行;
uip function run仅JS/TS可用(启动本地HTTP服务器供uip function serve调用)run - 若云托管工作需要认证,请运行。
uip login --organization "<ORG>" --tenant "<TENANT>" --output json