spring ai如何使用function call调用第三方模型

背景

一直困惑于ai是如何使用插件或者其他一些功能的,后来发现,很多大模型都支持function call功能,如何让大模型能够联网查询呢,function call就可以做到。

什么是function call

Function calling enables developers to connect language models to external data and systems. You can define a set of functions as tools that the model has access to, and it can use them when appropriate based on the conversation history. You can then execute those functions on the application side, and provide results back to the model.
函数调用使开发人员能够将语言模型连接到外部数据和系统。您可以将一组函数定义为模型有权访问的工具,并且它可以根据对话历史记录在适当的时候使用它们。然后,您可以在应用程序端执行这些函数,并将结果返回给模型。

你可以理解为,大模型允许你按照一定的格式,告诉大模型你可以提供的函数和函数功能,然后当你调用大模型的时候,它可以参考是否有可用的函数来完成本次工作,如果有的话,返回值里就会指示要调用函数,并且给出入参。

怎么用function call?

官方文档写的很清楚,可以参考:Function Calling 函数调用
我主要是照着这个文档整的,好的,接下来直接给例子:
涉及到以下几个类:
你的函数类:

@Service
@Slf4j
public class WeatherService implements Function<WeatherService.Request, WeatherService.Response> {
   
    public enum Unit {
    C, F }

    @JsonClassDescription("Get the weather in location") // // function description
    public record Request(String location, Unit unit) {
   }

    
### 如何在Spring框架中调用AI函数 为了实现这一目标,配置文件中的`application.properties`或`application.yml`应当包含特定于OpenAI的属性设置。这些属性定义了连接至API的基础URL以及必要的认证密钥。 对于基于Spring的应用程序来说,在`application.properties`内指定如下内容: ```properties spring.ai.openai.base-url=https://api.openai.com/v1 spring.ai.openai.api-key=your_api_key_here ``` 上述配置使得应用程序能够通过设定好的基础地址访问OpenAI的服务,并利用提供的API键完成身份验证过程[^1]。 创建用于管理与外部AI服务交互的服务类时,推荐采用依赖注入的方式引入所需的HTTP客户端工具(如RestTemplate或是WebClient),以便更好地遵循面向对象编程原则并简化单元测试流程。下面是一个简单的例子展示如何构建这样的服务层组件来发起对AI端点的请求: ```java @Service public class AiService { private final RestTemplate restTemplate; private final String baseUrl; @Autowired public AiService(@Value("${spring.ai.openai.base-url}") String baseUrl, RestTemplateBuilder restTemplateBuilder) { this.restTemplate = restTemplateBuilder.build(); this.baseUrl = baseUrl; } /** * 发送消息给AI聊天接口. */ public ChatResponse sendMessage(String message, Long chatId){ HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); Map<String, Object> body = new HashMap<>(); body.put("message", message); body.put("chatId", chatId); HttpEntity<Map<String, Object>> request = new HttpEntity<>(body, headers); ResponseEntity<ChatResponse> response = restTemplate.postForEntity(baseUrl + "/chat/{id}", request, ChatResponse.class, chatId); return response.getBody(); } } ``` 此代码片段展示了怎样封装对外部AI服务的具体调用逻辑,同时保持良好的可读性和维护性。值得注意的是,这里假设存在一个名为`ChatResponse`的数据传输对象(DTO),它用来映射来自服务器响应的消息结构[^3]。 当涉及到个人数据处理时,务必考虑到技术中立性的保护措施,即无论自动化手段还是手动操作都应确保个人信息的安全和隐私得到妥善保障[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盖丽男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值