Skip to content

KeyWaiter 键级等待

当输出是结构化的 Agently Output Format 时,你可以在结果未完成前,提前拿到某些 key 的值。这对于流式 UI、早期触发任务非常关键。

KeyWaiter 基于 instant 结构化流式解析,因此必须先定义 output()

单 key 提前获取

python
from agently import Agently

agent = Agently.create_agent()

agent.input("34643523+52131231=?").output(
  {
    "thinking": (str,),
    "result": (float,),
    "reply": (str,),
  }
)

reply = agent.get_key_result("thinking")
print(reply)

多 key 流式监听

python
gen = agent.wait_keys(["thinking", "reply"])
for key, value in gen:
  print(key, value)

使用回调处理不同 key

python
(
  agent.input("34643523+52131231=?")
  .output(
    {
      "thinking": (str,),
      "result": (float,),
      "reply": (str,),
    }
  )
  .when_key("thinking", lambda v: print("🤔:", v))
  .when_key("result", lambda v: print("✅:", v))
  .when_key("reply", lambda v: print("⏩:", v))
  .start_waiter()
)

关键规则

  • 必须先定义 output()
  • must_in_prompt=True 可以强制校验 key 在 output 中