一、概述
概述
-
Spring AI 的函数调用(Function Calling)功能允许大语言模型在生成回答时触发预定义的外部函数,从而实现动态数据获取或业务逻辑操作(如查询数据库、调用 API 等)。
-
SpringAI 帮我们规范了函数定义、注册等过程,并在发起模型请求之前自动将函数注入到 Prompt 中,而当模型决策在合适的时候去调用某个函数时,Spring AI 完成函数调用动作,最终将函数执行结果与原始问题再一并发送给模型,模型根据新的输入决策下一步动作。这其中涉及与大模型的多次交互过程,一次函数调用就是一次完成的交互过程。
函数调用的核心流程
-
定义函数:声明可供模型调用的函数(名称、描述、参数结构)。
-
模型交互:将函数信息与用户输入一起发送给模型,模型决定是否需要调用函数。
-
执行函数:解析模型的函数调用请求,执行对应的业务逻辑。
-
返回结果:将函数执行结果返回给模型,生成最终回答。
二、函数调用实现
1.创建自定义的Function
下面CalculatorService类自定义了加法和乘法运算的函数
package com.zhan.springai.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;
import java.util.function.Function;
/**
* @author zhanxuewei
*/
@Configuration
public class CalculatorService {
public record AddOperation(int a, int b) {
}
public record MulOperation(int m, int n) {
}
@Bean
@Description("加法运算")
public Function<AddOperation, Integer> addOperation() {
return request -> {
return request.a + request.b;
};
}
@Bean
@Description("乘法运算")
public Function<MulOperation, Integer> mulOperation() {
return request -> {
return request.m * request.n;
};
}
}
总结:Spring AI 使自定义函数这个过程变得简单,只需定义一个返回 java.util.Function 的 @Bean 定义,并在调用 ChatModel 时将 bean 名称作为选项进行注册即可。在底层,Spring 会用适当的适配器代码包装你的函数,以便与 AI 模型进行交互,免去了编写繁琐的代码。
2.编写Controller
package com.zhan.springai.controller;
import com.zhan.springai.common.Constants;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zhanxuewei
*/
@RestController
@RequestMapping(Constants.API_PREFIX_V1 + "/ai/function")
public class FunctionController {
@Autowired
private ChatModel chatModel;
@GetMapping(value = "/chat", produces = MediaType.APPLICATION_STREAM_JSON_VALUE)
public String ragJsonText(@RequestParam(value = "userMessage") String userMessage) {
return ChatClient.builder(chatModel).build().prompt().system("""
您是算术计算器的代理。
您能够支持加法运算、乘法运算等操作,其余功能将在后续版本中添加,如果用户问的问题不支持请告知详情。
在提供加法运算、乘法运算等操作之前,您必须从用户处获取如下信息:两个数字,运算类型。
请调用自定义函数执行加法运算、乘法运算。
请讲中文。
""").user(userMessage).functions("addOperation", "mulOperation").call().content();
}
}
为了让模型知道并调用你的自定义函数,您需要在 Prompt 请求中启用它,如上述代码,在functions("addOperation", "mulOperation")中告知ChatClient要使用这两个自定义函数。
另外指定了System Prompt:要求AI 模型被设定为一个算术计算器代理,能够执行加法和乘法运算,并且要求用户提供两个数字和运算类型。这个提示词内容很关键,如何让AI按照自己的意图去执行,要不断测试提示词内容。
3.测试