当前位置:   article > 正文

Spring Ai入门

spring ai

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

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

1、创建Spring Ai工程

2、添加api配置

  1. spring:
  2. application:
  3. name: spring-ai-chatgpt
  4. ai:
  5. openai:
  6. api-key: xxxxxxxxxxxxxxxxxxxxxx(自己的api-key)
  7. base-url: xxxxxxxxxxxxxxxxxxxxxx(自己的中转地址)

3、在controller里调用api

(1)使用chatClient

  1. @Autowired
  2. private ChatClient chatClient;
  3. //chatclient
  4. @GetMapping("/chat")
  5. public String chat(@RequestParam("message") String message) {
  6. return this.chatClient.prompt()
  7. .user(message)
  8. .call()
  9. .content();
  10. }
  11. //chatclient流式访问
  12. @GetMapping(value = "/stream", produces = "text/html;charset=UTF-8")
  13. public Flux<String> chatStream(@RequestParam("message") String message) {
  14. Flux<String> output = chatClient.prompt()
  15. .user(message)
  16. .stream()
  17. .content();
  18. return output;
  19. }
  1. @Configuration
  2. public class AIConfig {
  3. @Bean
  4. ChatClient chatClient(ChatClient.Builder builder) {
  5. return builder.defaultSystem("You are a friendly chat bot that answers question in the voice of a Pirate")
  6. .build();
  7. }
  8. }

(2)使用chatModel

  1. @Autowired
  2. private ChatModel chatModel;
  3. //ChatModel
  4. @GetMapping(value = "/chat/model", produces = "text/html;charset=UTF-8")
  5. public String chatModel(@RequestParam("message") String message) {
  6. ChatResponse response = chatModel.call(
  7. new Prompt(
  8. message,
  9. OpenAiChatOptions.builder()
  10. .withModel("gpt-4-32k")
  11. .withTemperature(0.8F)
  12. .build()
  13. ));
  14. return response.getResult().getOutput().getContent();
  15. }

(3)文生图

  1. @Autowired
  2. private OpenAiImageModel openAiImageModel;
  3. //文生图
  4. @GetMapping(value = "/text2Img", produces = "text/html;charset=UTF-8")
  5. public String text2Img(@RequestParam("message") String message) {
  6. ImageResponse response = openAiImageModel.call(
  7. new ImagePrompt(message,
  8. OpenAiImageOptions.builder()
  9. .withQuality("hd")
  10. .withN(1)
  11. .withHeight(1024)
  12. .withWidth(1024).build())
  13. );
  14. return response.getResult().getOutput().getUrl();
  15. }

(4)文生语音

  1. @Autowired
  2. private OpenAiAudioSpeechModel openAiAudioSpeechModel;
  3. //文生语音
  4. @GetMapping(value = "/text2audio", produces = "text/html;charset=UTF-8")
  5. public String text2audit(@RequestParam("message") String message) {
  6. OpenAiAudioSpeechOptions speechOptions = OpenAiAudioSpeechOptions.builder()
  7. .withModel("tts-1")
  8. .withVoice(OpenAiAudioApi.SpeechRequest.Voice.ALLOY)
  9. .withResponseFormat(OpenAiAudioApi.SpeechRequest.AudioResponseFormat.MP3)
  10. .withSpeed(1.0f)
  11. .build();
  12. SpeechPrompt speechPrompt = new SpeechPrompt("大家下午好,我叫王大锤", speechOptions);
  13. SpeechResponse response = openAiAudioSpeechModel.call(speechPrompt);
  14. byte[] body = response.getResult().getOutput();
  15. //将byte[]存为MP3文件
  16. try {
  17. writeByteArrayToMp3(body, System.getProperty("user.dir"));
  18. } catch (IOException e) {
  19. throw new RuntimeException(e);
  20. }
  21. return "ok";
  22. }
  23. public static void writeByteArrayToMp3(byte[] audioBytes, String outputFilePath) throws IOException {
  24. //创建FileOutputStream实例
  25. FileOutputStream fos = new FileOutputStream(outputFilePath + "/yuyin.mp3");
  26. //将字节数组写入文件
  27. fos.write(audioBytes);
  28. //关闭文件输入流
  29. fos.close();
  30. }

(5)语音转文本

  1. @Autowired
  2. private OpenAiAudioTranscriptionModel openAiAudioTranscriptionModel;
  3. //语音转文本
  4. @GetMapping(value = "/text2audio", produces = "text/html;charset=UTF-8")
  5. public String audio2text(@RequestParam("message") String message) {
  6. OpenAiAudioApi.TranscriptResponseFormat responseFormat = OpenAiAudioApi.TranscriptResponseFormat.VTT;
  7. OpenAiAudioTranscriptionOptions transcriptionOptions = OpenAiAudioTranscriptionOptions.builder()
  8. .withResponseFormat(OpenAiAudioApi.TranscriptResponseFormat.TEXT)
  9. .withTemperature(0f)
  10. .withResponseFormat(responseFormat)
  11. .build();
  12. var audioFile = new ClassPathResource("/hello.mp3");
  13. AudioTranscriptionPrompt transcriptionRequest = new AudioTranscriptionPrompt(audioFile, transcriptionOptions);
  14. AudioTranscriptionResponse response = openAiAudioTranscriptionModel.call(transcriptionRequest);
  15. return response.getResult().getOutput();
  16. }

(6)多模态

  1. @GetMapping("/mutil")
  2. public String mutilModel(@RequestParam(value = "message", defaultValue = "你从这个图片中看到了什么呢") String message) throws IOException {
  3. // 图片的二进制流
  4. byte[] imageData = new ClassPathResource("/test.png").getContentAsByteArray();
  5. var userMessage = new UserMessage(
  6. message,
  7. List.of(new Media(MimeTypeUtils.IMAGE_PNG, imageData))); //media
  8. OpenAiChatOptions aiChatOptions = OpenAiChatOptions.builder()
  9. .withModel(OpenAiApi.ChatModel.GPT_4_TURBO_PREVIEW.getValue())
  10. .build();
  11. ChatResponse response = chatModel.call(new Prompt(userMessage, aiChatOptions));
  12. return response.getResult().getOutput().getContent();
  13. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/974599
推荐阅读
相关标签
  

闽ICP备14008679号