当前位置: 首页> 娱乐> 明星 > Spring Ai入门

Spring Ai入门

时间:2025/7/19 0:19:11来源:https://blog.csdn.net/azy_123/article/details/139946429 浏览次数:0次

        SpringAI是一个AI工程应用框架,旨在将Spring生态系统的设计原则(如可移植性和模块化设计)应用于AI领域。它推广使用Plain Old Java Object(POJO)作为AI应用程序的构建块,从而为Java开发者提供了一种更简洁的方式与人工智能进行交互。SpringAI的推出被认为是Java开发领域的一大福音,因为它结合了Spring生态系统的设计原则和模块化的概念,降低了接入大型语言模型(LLM)的学习成本。

下面演示如何基于springBoot和OpenAi接口实现ChatGPT:

1、创建Spring Ai工程

2、添加api配置

spring:application:name: spring-ai-chatgptai:openai:api-key: xxxxxxxxxxxxxxxxxxxxxx(自己的api-key)base-url: xxxxxxxxxxxxxxxxxxxxxx(自己的中转地址)

3、在controller里调用api

(1)使用chatClient

@Autowiredprivate ChatClient chatClient;//chatclient@GetMapping("/chat")public String chat(@RequestParam("message") String message) {return this.chatClient.prompt().user(message).call().content();}//chatclient流式访问@GetMapping(value = "/stream", produces = "text/html;charset=UTF-8")public Flux<String> chatStream(@RequestParam("message") String message) {Flux<String> output = chatClient.prompt().user(message).stream().content();return output;}
@Configuration
public class AIConfig {@BeanChatClient chatClient(ChatClient.Builder builder) {return builder.defaultSystem("You are a friendly chat bot that answers question in the voice of a Pirate").build();}
}

(2)使用chatModel

@Autowiredprivate ChatModel chatModel;//ChatModel@GetMapping(value = "/chat/model", produces = "text/html;charset=UTF-8")public String chatModel(@RequestParam("message") String message) {ChatResponse response = chatModel.call(new Prompt(message,OpenAiChatOptions.builder().withModel("gpt-4-32k").withTemperature(0.8F).build()));return response.getResult().getOutput().getContent();}

(3)文生图

@Autowiredprivate OpenAiImageModel openAiImageModel;//文生图@GetMapping(value = "/text2Img", produces = "text/html;charset=UTF-8")public String text2Img(@RequestParam("message") String message) {ImageResponse response = openAiImageModel.call(new ImagePrompt(message,OpenAiImageOptions.builder().withQuality("hd").withN(1).withHeight(1024).withWidth(1024).build()));return response.getResult().getOutput().getUrl();}

(4)文生语音

@Autowiredprivate OpenAiAudioSpeechModel openAiAudioSpeechModel;//文生语音@GetMapping(value = "/text2audio", produces = "text/html;charset=UTF-8")public String text2audit(@RequestParam("message") String message) {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("大家下午好,我叫王大锤", speechOptions);SpeechResponse response = openAiAudioSpeechModel.call(speechPrompt);byte[] body = response.getResult().getOutput();//将byte[]存为MP3文件try {writeByteArrayToMp3(body, System.getProperty("user.dir"));} catch (IOException e) {throw new RuntimeException(e);}return "ok";}public static void writeByteArrayToMp3(byte[] audioBytes, String outputFilePath) throws IOException {//创建FileOutputStream实例FileOutputStream fos = new FileOutputStream(outputFilePath + "/yuyin.mp3");//将字节数组写入文件fos.write(audioBytes);//关闭文件输入流fos.close();}

(5)语音转文本

@Autowiredprivate OpenAiAudioTranscriptionModel openAiAudioTranscriptionModel;//语音转文本@GetMapping(value = "/text2audio", produces = "text/html;charset=UTF-8")public String audio2text(@RequestParam("message") String message) {OpenAiAudioApi.TranscriptResponseFormat responseFormat = OpenAiAudioApi.TranscriptResponseFormat.VTT;OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder().withResponseFormat(OpenAiAudioApi.TranscriptResponseFormat.TEXT).withTemperature(0f).withResponseFormat(responseFormat).build();var audioFile = new ClassPathResource("/hello.mp3");AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions);AudioTranscriptionResponse response = openAiAudioTranscriptionModel.call(transcriptionRequest);return response.getResult().getOutput();}

(6)多模态

@GetMapping("/mutil")public String mutilModel(@RequestParam(value = "message", defaultValue = "你从这个图片中看到了什么呢") String message) throws IOException {// 图片的二进制流byte[] imageData = new ClassPathResource("/test.png").getContentAsByteArray();var userMessage = new UserMessage(message,List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData))); //mediaOpenAiChatOptions aiChatOptions = OpenAiChatOptions.builder().withModel(OpenAiApi.ChatModel.GPT_4_TURBO_PREVIEW.getValue()).build();ChatResponse response = chatModel.call(new Prompt(userMessage, aiChatOptions));return response.getResult().getOutput().getContent();}
关键字:Spring Ai入门

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: