最近spring-ai-alibaba主干分支新增了对Tushare的支持,一起来看看如何使用
简单样例
老样子,分三步进行:
第一步:添加依赖
<dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-tool-calling-tushare</artifactId></dependency>
第二步:添加配置
spring.ai.alibaba.toolcalling.tushare.token=your token
第三步:代码调用
@GetMapping("/tool")public String tool(String input) {return chatClient.prompt().toolNames("tushareGetStockQuotes").user(input).call().content();}
扩展知识
接口固定只能查询日行情,不够用想要调用其他接口怎么办?
在引入前面jar包和添加配置后,自定义一个bean来搞定
public class TushareCustomServiceimplements Function<TushareCustomService.Request, TushareCustomService.Response> {private final WebClientTool webClientTool;private final TushareProperties tushareProperties;public TushareCustomService(JsonParseTool jsonParseTool, TushareProperties tushareProperties) {this.webClientTool = WebClientTool.builder(jsonParseTool, tushareProperties).build();this.tushareProperties = tushareProperties;}/*** 获取股票日行情* @param tsCode 股票代码,例如000001.SZ* @param startDate 开始日期,格式yyyyMMdd* @param endDate 结束日期,格式yyyyMMdd* @return https://tushare.pro/document/2?doc_id=27*/private String getStockQuotes(String tsCode, String startDate, String endDate) {try {//第二步:准备请求参数Map<String, String> params = new HashMap<>(3);params.put("ts_code", tsCode);params.put("start_date", startDate);params.put("end_date", endDate);//第三步,修改api_name和fields//api_name=daily,daily即tushare接口名称//fields为想要接收的字段Map<String, Object> valueMap = Map.of("api_name", "daily", "token", tushareProperties.getToken(), "params",params, "fields", "ts_code,trade_date,open,high,low,close,pre_close,change,pct_chg,vol,amount");return webClientTool.post("", valueMap).block();}catch (Exception e) {throw new RuntimeException("Failed to get stock quotes", e);}}@Overridepublic Response apply(Request request) {try {return new Response(this.getStockQuotes(request.tsCode, request.startDate, request.endDate));}catch (Exception e) {return new Response("Error occurred while processing the request.");}}//第一步:修改Request请求字段@JsonClassDescription("根据股票代码或日期获取股票日行情")public record Request(@JsonProperty(value = "ts_code") @JsonPropertyDescription("股票代码,例如000001.SZ") String tsCode,@JsonProperty(value = "start_date") @JsonPropertyDescription("开始日期,格式yyyyMMdd") String startDate,@JsonProperty(value = "end_date") @JsonPropertyDescription("结束日期,格式yyyyMMdd") String endDate) {}public record Response(String message) {}}
三步套用上面的代码:
第一步:修改Request字段,修改为希望大模型从对话中提取的字段,也即调用tushare接口的参数
第二步:修改请求参数,将调用接口时传递的params修改为接口所需入参
第三步:修改接口名称api_name和返回字段列表fields
然后将该类传递给ChatClient即可
ps:该包目前还在主干分支中,使用需自行打包或等下一个版本(>1.0.0.2)