Spring AI 1.0.0-M6版本stream()方法无法触发函数调用问题
Spring AI 1.0.0-M6流式调用无法触发工具函数的问题解决
问题现象
在Spring AI 1.0.0-M6版本中,使用stream()方法进行流式返回时,无法触发绑定的工具函数(如示例中的DateTimeTools);但使用同步的call()方法时,工具函数可以正常执行并返回结果。
流式调用代码(无法触发工具)
@GetMapping(value = "/tools", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<String> chat() { System.out.println("tools..."); DateTimeTools toolx = new DateTimeTools(); Flux<String> content = chatClient .prompt("What day is tomorrow?") .tools(toolx) .stream() .content(); return content; }
同步调用代码(正常触发工具)
@GetMapping(value = "/tools") public String chat() { System.out.println("tools..."); DateTimeTools toolx = new DateTimeTools(); String content = chatClient .prompt("What day is tomorrow?") .tools(toolx) .call() .content(); return content; }
原因分析
Spring AI 1.0.0-M6作为早期里程碑版本,流式处理流程与同步调用的工具调用逻辑未完全对齐:
- 同步
call()方法内部会自动检测模型返回的工具调用指令,执行对应的工具函数,并将工具结果回传给模型生成最终响应。 - 流式
stream()方法仅直接返回模型的原始响应片段,没有内置自动处理工具调用的触发、执行和结果回传逻辑。
解决方案
方案1:手动处理流式响应中的工具调用
自行解析流式返回的每个响应片段,判断是否包含工具调用的JSON结构,执行对应工具后,将结果重新发送给模型继续生成响应。示例代码如下:
@GetMapping(value = "/tools-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<String> chatWithStreamToolHandling() { DateTimeTools toolx = new DateTimeTools(); Prompt prompt = new Prompt("What day is tomorrow?", List.of(new Tool(toolx))); return chatClient.stream(prompt) .flatMap(response -> { if (!response.getToolCalls().isEmpty()) { // 执行工具调用 ToolCallResponse toolResponse = toolx.call(response.getToolCalls().get(0)); // 构造包含工具结果的后续prompt Prompt followUpPrompt = new Prompt( MessageBuilder.from(response.getResult().getOutput()) .add(toolResponse.toMessage()) .build() ); // 继续调用模型获取最终响应 return chatClient.stream(followUpPrompt).content(); } else { // 无工具调用,直接返回内容片段 return Flux.just(response.getResult().getOutput().getContent()); } }); }
方案2:升级Spring AI版本
Spring AI的后续正式版本(如1.0.0正式版及以上)已修复流式调用下的工具触发问题,建议升级到最新稳定版本,无需额外处理即可让stream()方法自动触发工具调用。
内容的提问来源于stack exchange,提问作者Qiu8Boy
相关产品推荐
相关产品推荐

