Skip to content

Instant 结构化流式解析

当你需要低延迟反馈(实时 UI、渐进式摘要等)时,通常希望结构化结果能够“边生成边消费”。Instant 模式就是为此设计。

先定义输出结构

python
from agently import Agently

agent = Agently.create_agent()

response = (
  agent
  .input("解释递归,并给出 2 个提示")
  .output({
    "definition": (str, "一句话定义"),
    "tips": [("str", "简短提示")]
  })
  .get_response()
)

使用 Instant 生成器

python
for msg in response.get_generator(type="instant"):
  if msg.path == "definition" and msg.delta:
    print(msg.delta, end="", flush=True)
  if msg.wildcard_path == "tips[*]" and msg.delta:
    print(msg.delta, end="", flush=True)
print()

输出路径与消费策略

  • msg.path 是具体字段路径
  • msg.wildcard_path 适用于列表字段
  • msg.delta 是实时增量片段

Instant 的价值在于:结构保持不变,文本逐步补全。配合输出约束,可以做到“流式但不散”。