当前位置: 代码网 > it编程>编程语言>Java > SpringBoot集成Spring AI Alibaba实现工具调用实战教程

SpringBoot集成Spring AI Alibaba实现工具调用实战教程

2026年08月04日 Java 我要评论
前言让大模型在对话中调用你写好的 java 方法(查时间、查天气等)。版本spring boot:3.4.5spring-ai-alibaba-starter-dashscope:1.1.2.1jav

前言

让大模型在对话中调用你写好的 java 方法(查时间、查天气等)。

版本

  • spring boot:3.4.5
  • spring-ai-alibaba-starter-dashscope:1.1.2.1
  • java:17

spring-ai更新速度快,请以官方为准

一、依赖引入

<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-web</artifactid>
</dependency>
<dependency>
    <groupid>com.alibaba.cloud.ai</groupid>
    <artifactid>spring-ai-alibaba-starter-dashscope</artifactid>
    <version>1.1.2.1</version>
</dependency>
<!-- dashscope-sdk 可能带旧版 jsonschema-generator,与 spring-ai-model 冲突时需对齐 -->
<dependencymanagement>
    <dependencies>
        <dependency>
            <groupid>com.github.victools</groupid>
            <artifactid>jsonschema-generator</artifactid>
            <version>4.38.0</version>
        </dependency>
    </dependencies>
</dependencymanagement>
<dependency>
    <groupid>com.alibaba</groupid>
    <artifactid>dashscope-sdk-java</artifactid>
    <version>2.22.18</version>
    <exclusions>
        <!-- 避免与 boot 自带的 logback 双绑 slf4j -->
        <exclusion>
            <groupid>org.slf4j</groupid>
            <artifactid>slf4j-simple</artifactid>
        </exclusion>
    </exclusions>
</dependency>

二、yml 配置

spring:
  application:
    name: spring-tool-demo
  ai:
    dashscope:
      api-key: ${dashscope_api_key}
      chat:
        options:
          # 需支持 tool calling 的对话模型
          model: qwen-max
          temperature: 0.7

三、代码案例:声明式工具(@tool)

1. 日期工具

@component  // 交给 spring 管理,便于注入到 chatclient
public class datetool {

    /**
     * description 很重要:模型靠它判断「什么时候该调这个工具」。
     * 工具名默认是方法名 getcurrentdatetime。
     */
    @tool(description = "get the current date and time in the user's timezone")
    public string getcurrentdatetime() {
        // 返回给模型的真实数据;模型再组织成自然语言回复用户
        return dateformatutil.now(); // 例如 yyyy-mm-dd hh:mm:ss
    }
}

2. 天气工具(普通业务方法 + @tool)

@component
public class weathertool {

    /**
     * 查询指定城市天气。
     * district 建议用拼音,如 beijing / shanghai,方便模型稳定传参。
     */
    @tool(description = "查询指定城市的天气情况")
    public string getweather(string district) {
        // 这里用 switch 模拟业务;真实项目可调第三方天气 api
        return switch (district) {
            case "beijing" -> "天气清凉";
            case "shanghai" -> "天气炎热";
            case "guangzhou" -> "天气闷热";
            default -> "未知地区";
        };
    }
}

四、注册到 chatclient(defaulttools)

@configuration
public class clientconfig {

    /**
     * 构建带默认工具的 chatclient。
     * defaulttools:该 client 每次对话都可用这些工具。
     */
    @bean(name = "toolclient")
    public chatclient toolclient(dashscopechatmodel chatmodel,
                                 datetool datetool,
                                 weathertool weathertool) {
        return chatclient.builder(chatmodel)
                // 传入带 @tool 方法的对象实例即可,框架会扫注解并生成 schema
                .defaulttools(datetool, weathertool)
                .build();
    }
}

注意:若已在 defaulttools 注册,请求里不要再写 .tools(new datetool()),否则会报:

multiple tools with the same name (getcurrentdatetime) found

defaulttools 与单次 .tools() 二选一(或确保工具名不重复)。

五、controller 调用

1. 查当前时间

@restcontroller
public class testcontroller {

    @resource(name = "toolclient")
    private chatclient toolclient;

    /**
     * get /get/currenttime
     * 用户说「要当前时间」→ 模型决定调用 getcurrentdatetime → 把结果组织成回答
     */
    @getmapping("/get/currenttime")
    public string getcurrenttime() {
        return toolclient.prompt()
                .system("you are a helpful assistant.")
                .user("get the current date and time in the user's timezone")
                // 不要再 .tools(...),工具已在 defaulttools 里
                .call()
                .content();
    }
}

2. 查天气

@restcontroller
public class weathercontroller {

    @resource(name = "toolclient")
    private chatclient toolclient;

    /**
     * get /get/weather?district=上海
     * system 提示把中文城市转成拼音参数,和 weathertool 的 case 对齐
     */
    @getmapping("/get/weather")
    public string getweather(@requestparam string district) {
        return toolclient.prompt()
                .system("你可以通过工具获取天气情况,"
                        + "中文请转换成拼音作为调用工具的参数,例如上海对应'shanghai'")
                .user("查一下" + district + "的天气")
                .call()
                .content();
    }
}

六、调用流程

到此这篇关于springboot集成spring ai alibaba实现工具调用实战教程的文章就介绍到这了,更多相关spring ai alibaba工具调用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com