Spring AI(六)Tool Calling本地回调方法
关于Tool Calling应该有很多解释,我这里就不赘述了。说说我的理解把,主要就是两个方面的用途:
1、当想使用私有数据回答的时候,可以使用这个。
2、提供数据给LLM进行定向回答或者优化答案的时候,可以用这个。
举个例子:
快递查询这种数据,基本上都不会喂给LLM,那我们想通过LLM查询快递信息就可以用这种方式实现。
第一步构建一个工具类。
在方法层面上增加@Tool的注解。
这个注解有两个常用属性。
description:简单就是提问的大概的描述。
returnDirect:是否直接返回结果,默认是false,也就是说会吧内容返回给LLM进行加工组合之后返回。
public class KuaiDiQueryTools {@Tool(description = "Please help me check the logistics information for the logistics tracking number ")public String getKuaiDiQuery(@ToolParam(description = "logistics tracking number,such as YT196807550996") String logisticsTrackingNumber){return "已发货\n" +"09-11 14:09正在安排圆通快递揽收\n" +"仓库处理中\n" +"09-11 14:02已打印快递单\n" +"09-11 13:57已出库\n" +"商家备货中\n" +"09-11 13:23已下单,商家正在安排配货";}
}
@ToolParam 是加到参数上面的,这个就是有些变量参数的时候用到。比如我们查询物流需要提供物流单号一样。同样需要指定description,用来做参数说明和举例。
@GetMapping("/chat/steam")public Flux<String> chatStream(String msg, HttpServletResponse response){response.setCharacterEncoding("UTF-8");return chatClient.prompt(msg).tools(new KuaiDiQueryTools()).stream().content();}
使用其实比较简单,就是在聊天的时候指定就行。或者在chatClient的时候的使用defaultTools指定。
如果不需要LLM进行处理直接返回
@Tool(description = "Please help me check the logistics information for the logistics tracking number ",returnDirect = true)
多个tool calling
新增一个tool
public class BaiduMapTools {@Tool(description = "Help me plan the route from the departure point to the destination ")public String getLine(@ToolParam(description = "departure point,such as beijing") String departurePoint,@ToolParam(description = "destination,such as shanghai") String destination){return "自驾出行";}
}
/*** 流式返回* @param msg* @param response* @return*/@GetMapping("/chat/steam")public Flux<String> chatStream(String msg, HttpServletResponse response){response.setCharacterEncoding("UTF-8");return chatClient.prompt(msg).tools(new KuaiDiQueryTools()).tools(new BaiduMapTools()).stream().content();}
但是如果我想让回答按我指定的内容,不走LLM的话,就会出现只有一个tool返回的情况,如果单独只指定一个tool的
returnDirect = true
又发现没啥效果。
其实我期望输出的是,自驾出行+我自定义的物流信息。但是貌似除了两次对话,没有太好的别的方法