跳转到内容

装饰器

步骤 #

step(func: Callable[P, R]) -> StepFunction[P, R]
step(*, workflow: Type['Workflow'] | None = None, num_workers: int = 4, retry_policy: RetryPolicy | None = None) -> Callable[[Callable[P, R]], StepFunction[P, R]]
step(func: Callable[P, R] | None = None, *, workflow: Type['Workflow'] | None = None, num_workers: int = 4, retry_policy: RetryPolicy | None = None) -> Callable[[Callable[P, R]], StepFunction[P, R]] | StepFunction[P, R]

将一个可调用对象装饰为工作流步骤。

该装饰器会检查函数签名以推断可接受的事件类型、返回的事件类型、可选的 Context 参数(可选择性地包含类型化状态模型),以及通过 typing.Annotated 进行的任何资源注入。

当应用于自由函数时,通过 workflow=MyWorkflow提供工作流类。对于实例方法,关联是自动的。

参数:

名称 类型 描述 默认
workflow type[工作流] | None

用于附加自由函数步骤的工作流类。对于方法而言不是必需的。

None
num_workers int

此步骤的工作线程数量。默认为4。

4
retry_policy RetryPolicy | None

用于处理失败的可选重试策略。

None

返回:

名称 类型 描述
Callable Callable[[Callable[P, R]], StepFunction[P, R]] | StepFunction[P, R]

原始函数,附带内部步骤元数据注释。

引发:

类型 描述
WorkflowValidationError

如果签名验证失败,或在装饰自由函数时未指定 workflow

示例:

方法步骤:

class MyFlow(Workflow):
    @step
    async def start(self, ev: StartEvent) -> StopEvent:
        return StopEvent(result="done")

自由函数步骤:

class MyWorkflow(Workflow):
    pass

@step(workflow=MyWorkflow)
async def generate(ev: StartEvent) -> NextEvent: ...
workflows/decorators.py中的源代码
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def step(
    func: Callable[P, R] | None = None,
    *,
    workflow: Type["Workflow"] | None = None,
    num_workers: int = 4,
    retry_policy: RetryPolicy | None = None,
) -> Callable[[Callable[P, R]], StepFunction[P, R]] | StepFunction[P, R]:
    """
    Decorate a callable to declare it as a workflow step.

    The decorator inspects the function signature to infer the accepted event
    type, return event types, optional `Context` parameter (optionally with a
    typed state model), and any resource injections via `typing.Annotated`.

    When applied to free functions, provide the workflow class via
    `workflow=MyWorkflow`. For instance methods, the association is automatic.

    Args:
        workflow (type[Workflow] | None): Workflow class to attach the free
            function step to. Not required for methods.
        num_workers (int): Number of workers for this step. Defaults to 4.
        retry_policy (RetryPolicy | None): Optional retry policy for failures.

    Returns:
        Callable: The original function, annotated with internal step metadata.

    Raises:
        WorkflowValidationError: If signature validation fails or when decorating
            a free function without specifying `workflow`.

    Examples:
        Method step:

        ```python
        class MyFlow(Workflow):
            @step
            async def start(self, ev: StartEvent) -> StopEvent:
                return StopEvent(result="done")
        ```

        Free function step:

        ```python
        class MyWorkflow(Workflow):
            pass

        @step(workflow=MyWorkflow)
        async def generate(ev: StartEvent) -> NextEvent: ...
        ```
    """

    def decorator(func: Callable[P, R]) -> StepFunction[P, R]:
        if not isinstance(num_workers, int) or num_workers <= 0:
            raise WorkflowValidationError(
                "num_workers must be an integer greater than 0"
            )

        func = make_step_function(func, num_workers, retry_policy)

        # If this is a free function, call add_step() explicitly.
        if is_free_function(func.__qualname__):
            if workflow is None:
                msg = f"To decorate {func.__name__} please pass a workflow class to the @step decorator."
                raise WorkflowValidationError(msg)
            workflow.add_step(func)

        return func

    if func is not None:
        # The decorator was used without parentheses, like `@step`
        return decorator(func)
    return decorator