SpringBoot3 简单集成 Spring AI 并使用

2024-08-22 14:04

本文主要是介绍SpringBoot3 简单集成 Spring AI 并使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 准备
      • JDK17
      • api key
    • 创建项目
    • 编写配置文件
    • 创建controller
    • 启动并测试
    • 角色预设
    • 流式响应\异步响应
    • ChatModel(聊天模型)
    • ImageModel(文生图)
    • 文生语音
    • 语言翻译
    • 多模态
    • Function Calling (函数调用第三方API)

准备

JDK17

电脑要装有jdk17。对于有多个jdk需求的开发者来说。推荐使用jdk版本管理工具。
使用jabba在Windows上管理多个版本的JDK-详细教程

api key

前期需要准备一个api key。

没有的可以申请一个免费的。github上有免费的可以自己去申请。

创建项目

打开IDEA新建项目。
新建j项目
添加web和OpenAI的依赖。
在这里插入图片描述

编写配置文件

创建配置文件application.yaml,注意替换成自己的key和url。

spring:ai:openai:api-key: sk-xxxxxbase-url: https://api.xxx.tech

创建controller

示例使用官网文档里面的就行。
Spring AI 官方文档

下面是我手动修改了一部分的代码。

@RestController
@RequestMapping("/ai")
public class ChatController {private final ChatClient chatClient;public ChatController(ChatClient.Builder chatClientBuilder) {this.chatClient = chatClientBuilder.build();}@GetMapping("/chat")String generation(@RequestParam(value = "message") String message ) {return this.chatClient.prompt().user(message).call().content();}
}

启动并测试

可以看到测试是成功的。
在这里插入图片描述接下来是一些扩展的东西了。

角色预设

角色预设可以使用配置类进行全局预设,也可以单独预设。
1、全局预设
编写配置类

@Configuration
class Config {@BeanChatClient chatClient(ChatClient.Builder builder) {return builder.defaultSystem("你现在是一个资深的游戏专家").build();}}

再修改一下controller 的 ChatClient 的注入方式。

@RestController
@RequestMapping("/ai")
public class ChatController {@Resourceprivate  ChatClient chatClient;@GetMapping("/chat")String generation(@RequestParam(value = "message") String message ) {return this.chatClient.prompt().user(message).call().content();}
}

增加了角色预设之后的结果。好像有了角色预设确实专业一点点。

在这里插入图片描述

2、单独预设
在call调用之前,调用system方法就能预设。

    @GetMapping("/chat")String chat(@RequestParam(value = "message") String message ) {return this.chatClient.prompt().user(message).system("你是游戏测评大师") // 单独预设角色.call().content();}

流式响应\异步响应

让stream您获得异步响应,如下所示

    @GetMapping("/streamChat")Flux<String> streamChat(@RequestParam(value = "message") String message ) {Flux<String> output = chatClient.prompt().user(message).stream().content();return output;}

在 1.0.0 M2 中,我们将提供一种便捷方法,让您使用反应式stream()方法返回 Java 实体。(当前使用的还是M1,M2还没出来)

在浏览器测试的话可能会出现乱码,解决方法是GetMapping注解增加produces属性。在PostMan测试并没有乱码。

    @GetMapping(value = "/streamChat",produces = "text/html;charset=UTF-8")

ChatModel(聊天模型)

上面使用的是chatClient是AI模型最基本的功能,所以SpringAI对其做了封装,chatClient是和大模型是解耦的,不管使用哪个大模型,client都是能够使用的。而ChatModel接口确是大模型厂商自己实现的,当你引入starter时,它对应的AutoConfiguration会将ChatModel自动注入到Spring容器。

每个厂商的ChatOptions可能不一样,对应的需要去官网查看。

    @Resourceprivate ChatModel chatModel;@GetMapping("/chat/model")String chatModel(@RequestParam(value = "message") String message ) {ChatResponse response = chatModel.call(new Prompt(message,OpenAiChatOptions.builder().withModel("gpt-4o").withTemperature(0.4f).build()));return response.getResult().getOutput().getContent();}

ImageModel(文生图)

    @Resourceprivate OpenAiImageModel openAiImageModel;@GetMapping("/text2Image")String text2Image(@RequestParam(value = "message") String message ){ImageResponse response = openAiImageModel.call(new ImagePrompt(message,OpenAiImageOptions.builder().withQuality("hd") // hd表示高清.withN(1) // 图片数量.withHeight(1024) // 图片高度.withWidth(1024).build()) // 图片宽度);return response.getResult().getOutput().getUrl(); // 支持返回base64格式的图片}

文生语音

和上面一样的套路,我直接把官网文档搬过来。

OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder().withModel("tts-1").withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY).withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3).withSpeed(1.0f).build();SpeechPrompt speechPrompt = new SpeechPrompt("Hello, this is a text-to-speech example.", speechOptions);
SpeechResponse response = openAiAudioSpeechModel.call(speechPrompt);

语言翻译

OpenAiAudioApi.TranscriptResponseFormat responseFormat = OpenAiAudioApi.TranscriptResponseFormat.VTT;OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder().withLanguage("en").withPrompt("Ask not this, but ask that").withTemperature(0f).withResponseFormat(responseFormat).build();
AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions);
AudioTranscriptionResponse response = openAiTranscriptionModel.call(transcriptionRequest);

多模态

模态是指模型同时理解和处理来自各种来源的信息的能力,包括文本、图像、音频和其他数据格式。

Spring AI Message API 提供了支持多模式 LLM 所需的所有抽象。

在这里插入图片描述代码如下,可以上传图片问问题。

byte[] imageData = new ClassPathResource("/multimodal.test.png").getContentAsByteArray();var userMessage = new UserMessage("Explain what do you see in this picture?", // contentList.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData))); // mediaChatResponse response = chatModel.call(new Prompt(List.of(userMessage)));

Function Calling (函数调用第三方API)

人工智能模型中功能支持的集成,允许模型请求执行客户端功能,从而根据需要动态访问必要的信息或执行任务。

可以借助Function Calling实现动态的数据的获取,通过api接口返回的数据参与对话。
在这里插入图片描述想要使用Function,首先需要定义Function,并注册为Bean。

在下面的Function中我定义了一个三方接口,用来获取最新的彩票开奖号码。

package com.sifan.springai.function;import com.fasterxml.jackson.annotation.JsonClassDescription;
import org.json.JSONObject;
import org.springframework.context.annotation.Description;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;import java.util.List;
import java.util.function.Function;//@Description作用是可帮助 AI 模型确定要调用哪个客户端函数
@Description("获取最新通用中奖号码信息")
// Bean的名字是lotteryFunction
@Component(value = "lotteryFunction")
public class LotteryFunction implements Function<LotteryFunction.Request, LotteryFunction.Response>  {// 密封类,相当于加了Lombok的@Data注解的POJO类@JsonClassDescription("目前提供八种彩种,ssq:双色球,qlc:七乐彩,fc3d:福彩3D,cjdlt:超级大乐透,qxc:七星彩,pl3:排列3,pl5:排列(5),kl8:快乐8")public record Request(String code){}public record Response(String openCode){}@Overridepublic Response apply(Request request) {// 判空if(request.code.equals("")){return new Response("参数为空,请输入彩票种类标识");}List<String> codeList = List.of("ssq", "qlc", "fc3d", "cjdlt", "qxc", "pl3", "pl5", "kl8");// 判断code是否在codeList中if(!codeList.contains(request.code)){return new Response("请输入正确的彩票种类标识,只支持:"+codeList);}String openCode = getOpenCode(request.code);return new Response(openCode);}/*** api接口文档地址:https://www.mxnzp.com/doc/detail?id=3*获取最新通用本期中奖号码* @param code 彩票种类标识,目前提供八种彩种,ssq:双色球,qlc:七乐彩,fc3d:福彩3D,cjdlt:超级大乐透,qxc:七星彩,pl3:排列3,pl5:排列(5),kl8:快乐8* @return*/private String getOpenCode(String code){String url = String.format("https://www.mxnzp.com/api/lottery/common/latest?code=%s&app_secret=%s&app_id=%s",code, getAppSecret(), getAppId());RestTemplate restTemplate = new RestTemplate();ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);String body = responseEntity.getBody();JSONObject bodyJson = new JSONObject(body);JSONObject data =bodyJson.getJSONObject("data");return data.getString("openCode");}private String getAppSecret(){return "xxxxxx"; // 换成自己的}private String getAppId(){return "xxxxx";  // 换成自己的}
}

Controller层如何使用呢,在控制层只需要调用withFunction并且指定Bean名字就行。代码如下。

    @Resourceprivate ChatModel chatModel;@GetMapping("/chat/model/fc")String chatModelFC(@RequestParam(value = "message") String message ) {ChatResponse response = chatModel.call(new Prompt(message,OpenAiChatOptions.builder().withFunction("lotteryFunction") // 这里指定Bean名字.withModel("gpt-3.5-turbo").withTemperature(0.4f).build()));return response.getResult().getOutput().getContent();}

下面来测试一下。

在这里插入图片描述

这篇关于SpringBoot3 简单集成 Spring AI 并使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1096481

相关文章

SpringMVC获取请求参数的方法

《SpringMVC获取请求参数的方法》:本文主要介绍SpringMVC获取请求参数的方法,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下... 目录1、通过ServletAPI获取2、通过控制器方法的形参获取请求参数3、@RequestParam4、@

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t

SpringBoot应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

Python虚拟环境终极(含PyCharm的使用教程)

《Python虚拟环境终极(含PyCharm的使用教程)》:本文主要介绍Python虚拟环境终极(含PyCharm的使用教程),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录一、为什么需要虚拟环境?二、虚拟环境创建方式对比三、命令行创建虚拟环境(venv)3.1 基础命令3

Python Transformer 库安装配置及使用方法

《PythonTransformer库安装配置及使用方法》HuggingFaceTransformers是自然语言处理(NLP)领域最流行的开源库之一,支持基于Transformer架构的预训练模... 目录python 中的 Transformer 库及使用方法一、库的概述二、安装与配置三、基础使用:Pi

关于pandas的read_csv方法使用解读

《关于pandas的read_csv方法使用解读》:本文主要介绍关于pandas的read_csv方法使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录pandas的read_csv方法解读read_csv中的参数基本参数通用解析参数空值处理相关参数时间处理相关

使用Node.js制作图片上传服务的详细教程

《使用Node.js制作图片上传服务的详细教程》在现代Web应用开发中,图片上传是一项常见且重要的功能,借助Node.js强大的生态系统,我们可以轻松搭建高效的图片上传服务,本文将深入探讨如何使用No... 目录准备工作搭建 Express 服务器配置 multer 进行图片上传处理图片上传请求完整代码示例

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn