🌊 流式输出
沿用快速开始组件,在模型 Spec 上设置 .stream(true),再通过 ExecuteOption.eventListener(...) 接收事件。
# 接收增量并获取最终结果
.stream(true) 开启模型流式响应。创建以下服务,通过 agent.text.delta 事件接收文本增量,执行成功后返回完整回复:
import com.yomahub.liteflow.core.ExecuteOption;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.flow.LiteflowResponse;
import org.springframework.stereotype.Service;
import java.util.function.Consumer;
@Service
public class ChatService {
private final FlowExecutor flowExecutor;
public ChatService(FlowExecutor flowExecutor) {
this.flowExecutor = flowExecutor;
}
public String chat(String input) {
return chat(input, delta -> {});
}
public String chat(String input, Consumer<String> onTextDelta) {
LiteflowResponse response = flowExecutor.execute2Resp(
"chatChain", input,
ExecuteOption.of().eventListener(event -> {
if ("agent.text.delta".equals(event.getType())
&& event.getText() != null) {
onTextDelta.accept(event.getText());
}
}));
if (!response.isSuccess()) {
throw new IllegalStateException("Agent 执行失败", response.getCause());
}
return response.getSlot().getResponseData();
}
}
在注入 ChatService 的 Controller、测试或其他业务代码中调用:
String answer = chatService.chat("介绍一下 LiteFlow", System.out::print);
System.out.println();
运行时,控制台会随着模型生成逐段输出文本;方法返回后,answer 是完整回复。只需要完整回复时调用 chatService.chat("介绍一下 LiteFlow"),无需提供回调。
execute2Resp(...) 会等待执行结束,但事件回调在执行过程中触发。已经展示了增量内容后,不要再把完整回复追加一次。
前端流式展示时,把回调接到应用的 SSE 或 WebSocket 发送逻辑。普通 Controller 等方法结束后才返回 answer,浏览器就只能收到最终结果。更多事件见本页下方的“展示执行状态”。
# 启动与验证
以上示例依赖现有 Spring Boot 启动类及组件扫描。运行项目前,在同一启动环境中配置 API Key:
export DEEPSEEK_API_KEY='替换为你的 API Key'
mvn spring-boot:run
调用上面的服务,应看到流式回复,并在进程工作目录下生成 data/agent-state。此时每次调用都是新对话;连续对话见多轮对话。
# 展示执行状态
快速开始已展示 agent.text.delta 的监听方式。同一个监听器还可以根据事件类型显示执行状态:
| 事件 | 常见用途 |
|---|---|
agent.text.delta | 正文增量,读取 event.getText() |
agent.tool.call.start/agent.tool.call.end | 工具调用开始/参数接收结束 |
agent.tool.result.end | 工具结果完成 |
agent.confirm.required/agent.confirm.result | 人工确认请求/结果 |
agent.result | 当前 Agent 的结果 |
agent.error | 执行错误 |
多 Agent 流程可通过事件的节点和请求标识区分来源。agent.result 不代表整条链结束,最终仍应检查 response.isSuccess()。监听器异常默认会中断调用;允许展示事件丢失时,才设置 event.listener-failure-mode=LOG_AND_CONTINUE。



