Skip to content

if / elif / else 条件分支

当你的路由逻辑是“按优先级顺序判断”时,优先用 if / elif / else

推荐示例

python
from agently import TriggerFlow, TriggerFlowRuntimeData

flow = TriggerFlow()

def is_high_score(data: TriggerFlowRuntimeData):
    return data.value["score"] >= 90

def is_medium_score(data: TriggerFlowRuntimeData):
    return data.value["score"] >= 80

@flow.chunk("grade_a")
async def grade_a(_: TriggerFlowRuntimeData):
    return "A"

@flow.chunk("grade_b")
async def grade_b(_: TriggerFlowRuntimeData):
    return "B"

@flow.chunk("grade_c")
async def grade_c(_: TriggerFlowRuntimeData):
    return "C"

(
    flow.to(lambda _: {"score": 82})
    .if_condition(is_high_score)
    .to(grade_a)
    .elif_condition(is_medium_score)
    .to(grade_b)
    .else_condition()
    .to(grade_c)
    .end_condition()
    .end()
)

当前最佳实践

  • 需要配置导出时,condition 使用具名函数
  • 条件函数只负责判断,不负责副作用
  • 如果分支要导出 JSON/YAML,提前 register_condition_handler(...)

不再推荐

  • 用复杂副作用逻辑塞进条件函数
  • 期待匿名 lambda condition 可导出为 flow config 运行可以,Mermaid 可以,但配置导出不支持