Skip to content

Instant 结构化流式解析

Instant 解决的是这个问题: 你既想早点看到结果,又不想退回到一堆难以消费的纯文本 token。

适合什么时候读

  • 你已经用 output() 定义了结构
  • 你要做实时 UI、渐进式摘要或提前触发下游逻辑
  • 你不想等完整 JSON 都生成完再开始处理

你会学到什么

  • 为什么结构化流式前必须先定义 output()
  • instant 事件里的 pathwildcard_pathdelta 分别代表什么
  • 什么时候该先固定 response 再同时消费 streaming 和最终数据
  • 为什么服务端和 TriggerFlow 场景默认优先 get_async_generator(type="instant")

Instant 的数据流

这张图要说明的是: instant 不是“另一份结果”,它是同一次结构化请求在生成过程中的可消费视图。

最小示例

python
from agently import Agently

agent = Agently.create_agent()

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

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

print()
print(response.result.get_data())

Async First 推荐写法

如果这是服务端、异步 worker、SSE 或 TriggerFlow 里的真实逻辑,更推荐直接使用异步生成器:

python
async for item in response.get_async_generator(type="instant"):
    if item.is_complete and item.wildcard_path == "tips[*]":
        print(item.path, item.value)

final_data = await response.async_get_data()

这组写法特别适合:

  • 一边更新 UI,一边保留最终结构结果
  • 一边把完成字段推给 TriggerFlow 事件,一边继续等待剩余字段
  • 同一请求被多个异步消费者复用

pathwildcard_path 怎么理解

  • path: 当前这个具体字段的位置,例如 tips[0]
  • wildcard_path: 把列表索引抽象掉后的模式,例如 tips[*]
  • delta: 当前字段这次新增的文本片段

如果你在做列表类 UI,通常更适合用 wildcard_path 来匹配字段类型,再按 path 区分具体项。

一个更贴近前端的理解方式

你不是在接“原始 token 流”,而是在接“哪块界面该更新”的事件流。

什么时候要先 get_response()

如果你既要流式消费,又要最后拿完整结构化结果,最好先固定一次 response:

  • 流式阶段用 response.result.get_generator(type="instant")
  • 收尾阶段用 response.result.get_data()

这样不会因为多次消费而重新发请求。

如果你在异步运行时里工作,可以把这条规则理解成:

  • 流式阶段用 response.get_async_generator(type="instant")
  • 收尾阶段用 await response.async_get_data()

常见误区

  • 还没定义 output(),就直接想做结构化流式。
  • delta 文本流硬拼字段,而不是直接消费 instant
  • 一边流式读,一边又重新发起一次请求拿最终结果。

下一步去哪

  • agently-output-control
  • agently-model-response