SpringAI 函数工具调用

工具调用

工具调用(也称为函数调用)是 AI 应用中的一种常见模式,允许模型与一组 API 或工具交互,增强其功能。

工具调用作用:

  • 信息检索

    此类工具可用于从外部来源检索信息,例如数据库、网络服务、文件系统或网络搜索引擎。目标是增强模型的知识,使其能够回答它原本无法回答的问题。因此,它们可以在检索增强生成(RAG)场景中使用。例如,可以使用工具检索特定位置的当前天气、检索最新的新闻文章或查询数据库中的特定记录。

  • 执行操作

    例如发送电子邮件、在数据库中创建新记录、提交表单或触发工作流。目标是自动化原本需要人工干预或明确编程的任务。例如,可以使用工具为与聊天机器人互动的客户预订航班、填写网页上的表单,或在代码生成场景中根据自动化测试(TDD)实现 Java 类。

工具调用链路

example

go 复制代码
@RestController
publicclass ToolController {
    @Autowired
    ChatClient chatClient;

    @GetMapping("/toolcall")
    public String toolCall(@RequestParam("msg") String msg){
        String response = chatClient.prompt(msg)
                //.tools(new DateTimeTools())
                .call()
                .content();
        return response;
    }

}

不加工具调用情况下:

自定义获取日期的函数:

go 复制代码
public class DateTimeTools {

    @Tool(description = "今天是几号以及时间的时区")
    String getCurrentDateTime() {
       String response=  LocalDateTime.now().atZone(LocaleContextHolder.getTimeZone().toZoneId()).toString();
        System.out.println("getCurrentDateTime:"+response);
        return response;
    }
}

自定义发送邮件函数工具

go 复制代码
@Tool(description = "发送邮件")
    String SendEmail(String mailText) {
        // 邮箱配置信息(替换为实际值)
        String host = "smtp.163.com";       // SMTP服务器
        String username = "from@163.com"; // 邮箱账号
        String password = "授权码";      // 邮箱授权码(非登录密码!)
        String toAddress = "to@163.com"; // 收件人

        // 邮件属性配置
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "465"); // SSL端口
        props.put("mail.smtp.auth", "true"); // 需要认证
        props.put("mail.smtp.ssl.enable", "true"); // 启用SSL
        props.put("mail.debug", "true"); // 调试模式(可选)

        // 创建会话
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                returnnew PasswordAuthentication(username, password);
            }
        });
        try {
            // 创建邮件
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username)); // 发件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress)); // 收件人
            message.setSubject("SpringAI测试主题"); // 主题
            message.setText("SpringAI:"+mailText); // 纯文本内容
            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功!");

        } catch (MessagingException e) {
            e.printStackTrace();
            System.err.println("邮件发送失败: " + e.getMessage());
        }
        return"发送邮件成功";
    }

function作为tool进行调用

定义一个function

go 复制代码
public class WeatherService  implements Function<WeatherRequest,WeatherResponse> {
    public WeatherResponse apply(WeatherRequest request) {
        return new WeatherResponse(23.0, Unit.C);
    }
}
public enum Unit {C, F}
public record WeatherRequest(String location, Unit unit) {}
public record WeatherResponse(double temp, Unit unit) {}

定义toolcallback和调用

go 复制代码
@GetMapping("/functionCall")
    public String functionCall(@RequestParam("msg") String msg){
        //定义toolCallback
        ToolCallback toolCallback = FunctionToolCallback
                .builder("currentWeather", new WeatherService())
                .description("获取当地的天气")
                .inputType(WeatherRequest.class)
                .build();
        //调用
        String response = chatClient.prompt(msg)
                .tools(toolCallback) //调用函数
                .call()
                .content();
        return response;
    }
相关推荐
超龄超能程序猿15 小时前
dnSpy 使用教程
windows·microsoft
Leinwin18 小时前
微软开源GitHub Copilot Chat,AI编程领域迎新突破
microsoft·github·copilot
旷世奇才李先生1 天前
Pillow 安装使用教程
深度学习·microsoft·pillow
大熊背1 天前
图像处理专业书籍以及网络资源总结
人工智能·算法·microsoft
Leinwin2 天前
微软发布新一代存储优化型虚拟机:Azure Laosv4、Lasv4 和 Lsv4 系列
microsoft·azure
蹦蹦跳跳真可爱5892 天前
Python----大模型(使用api接口调用大模型)
人工智能·python·microsoft·语言模型
Triv20252 天前
ECU开发工具链1.10版:更强大的测量、校准与数据分析体验.
microsoft·数据分析·汽车电子开发·校准流程自动化·高速信号采集·测试台架集成·实时数据监控
爱奥尼欧2 天前
【Linux 系统】基础IO——Linux中对文件的理解
linux·服务器·microsoft
不惑_2 天前
动感阴影生成器,一键生成立体效果,提升设计质感
microsoft
天府云创2 天前
[开源]微软 PowerToys 获 0.92 版本更新:新增系统托盘图标开 / 关功能、改进 Command Palette
microsoft·效率工具·powertoys·软件帮手·powertoys下载