MapOperator 算子是最通用的算子,常用于将函数应用于输入数据。

有两种方式可以使用 MapOpeartor 算子

使用Map函数构建MapOperator

  1. from dbgpt.core.awel import DAG, MapOperator
  2. with DAG("awel_hello_world") as dag:
  3. task = MapOperator(map_function=lambda x: print(f"Hello, {x}!"))

实现一个自定义MapOperator

  1. from dbgpt.core.awel import DAG, MapOperator
  2. class MyMapOperator(MapOperator[str, None]):
  3. async def map(self, x: str) -> None:
  4. print(f"Hello, {x}!")
  5. with DAG("awel_hello_world") as dag:
  6. task = MyMapOperator()

例子

数字加倍

awel_tutorial 目录创建一个新的文件,命名为map_operator_double_number.py, 添加如下代码

  1. import asyncio
  2. from dbgpt.core.awel import DAG, MapOperator
  3. class DoubleNumberOperator(MapOperator[int, int]):
  4. async def map(self, x: int) -> int:
  5. print(f"Received {x}, returning {x * 2}")
  6. return x * 2
  7. with DAG("awel_double_number") as dag:
  8. task = DoubleNumberOperator()
  9. assert asyncio.run(task.call(2)) == 4

运行下面的命令执行对应的代码, 可以看到如下的输出 “Received 2, returning 4

  1. poetry run python awel_tutorial/map_operator_double_number.py
  2. Received 2, returning 4