2024版本idea集成SpringBoot + Ai 手寫一個chatgpt 【推薦】

慈雲數據 6個月前 (05-13) 技術支持 85 0

題目:SpringBoot + OpenAi 代碼獲取

在這裏獲取key和url:獲取免費key

在這裏插入圖片描述

base-url爲這兩個:

在這裏插入圖片描述

在這裏插入圖片描述

話不多說直接來!

一、簡介

Spring AI 是 AI 工程的應用框架。其目标是将 Spring 生态系統設計原則(如可移植性和模塊化設計)應用于 AI,并推廣使用 POJO 作爲 AI 領域應用程序的構建塊。

跨 AI 提供商的可移植 API 支持,适用于聊天、文本到圖像和嵌入模型。支持同步和流 API 選項。還支持下拉以訪問特定于模型的功能

二、Ai聊天程序代碼

1、 創建項目工程

  • 在父工程下面創建新的模塊

    在這裏插入圖片描述

    • 勾選上依賴然後創建

      在這裏插入圖片描述

      • 具體的依賴如下
        Python
        
            4.0.0
            
                org.springframework.boot
                spring-boot-starter-parent
                3.2.4
                 
            
            
            
            com.ysl
            SpringAi
            0.0.1-SNAPSHOT
            pom
            SpringAi
            SpringAi
            
                spring-ai-01-chat
            
            
                17
        
                1.0.0-SNAPSHOT
            
            
                
                    org.springframework.boot
                    spring-boot-starter-web
                
                
                    org.springframework.ai
                    spring-ai-openai-spring-boot-starter
                
                
                    org.springframework.boot
                    spring-boot-devtools
                    runtime
                    true
                
                
                    org.projectlombok
                    lombok
                    true
                
                
                    org.springframework.boot
                    spring-boot-starter-test
                    test
                
            
        
            
                
                    
                        org.springframework.ai
                        spring-ai-bom
                        ${spring-ai.version}
                        pom
                        import
                    
                
            
            
                
                    
                        org.springframework.boot
                        spring-boot-maven-plugin
                        
                            
                                paketobuildpacks/builder-jammy-base:latest
                            
                            
                                
                                    org.projectlombok
                                    lombok
                                
                            
                        
                    
                
            
            
            
                
        
                    spring-snapshot
                    Spring Snapshots
                    https://repo.spring.io/snapshot
                    
                        false
                    
                
            
        
        
        • 編寫yml配置

          在這裏插入圖片描述

          • openai有自動配置類OpenAiAutoConfiguration

            在這裏插入圖片描述

            其中有聊天客戶端,圖片客戶端…等(看下面源碼)

            Python
            //聊天客戶端
            @Bean
            	@ConditionalOnMissingBean
            	@ConditionalOnProperty(prefix = OpenAiChatProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true",
            			matchIfMissing = true)
            	public OpenAiChatClient openAiChatClient(OpenAiConnectionProperties commonProperties,
            			OpenAiChatProperties chatProperties, RestClient.Builder restClientBuilder,
            			List toolFunctionCallbacks, FunctionCallbackContext functionCallbackContext,
            			RetryTemplate retryTemplate, ResponseErrorHandler responseErrorHandler) {
            		var openAiApi = openAiApi(chatProperties.getBaseUrl(), commonProperties.getBaseUrl(),
            				chatProperties.getApiKey(), commonProperties.getApiKey(), restClientBuilder, responseErrorHandler);
            		if (!CollectionUtils.isEmpty(toolFunctionCallbacks)) {
            			chatProperties.getOptions().getFunctionCallbacks().addAll(toolFunctionCallbacks);
            		}
            		return new OpenAiChatClient(openAiApi, chatProperties.getOptions(), functionCallbackContext, retryTemplate);
            	}
            
            Python
            //圖片客戶端
            @Bean
            	@ConditionalOnMissingBean
            	@ConditionalOnProperty(prefix = OpenAiImageProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true",
            			matchIfMissing = true)
            	public OpenAiImageClient openAiImageClient(OpenAiConnectionProperties commonProperties,
            			OpenAiImageProperties imageProperties, RestClient.Builder restClientBuilder, RetryTemplate retryTemplate,
            			ResponseErrorHandler responseErrorHandler) {
            		String apiKey = StringUtils.hasText(imageProperties.getApiKey()) ? imageProperties.getApiKey()
            				: commonProperties.getApiKey();
            		String baseUrl = StringUtils.hasText(imageProperties.getBaseUrl()) ? imageProperties.getBaseUrl()
            				: commonProperties.getBaseUrl();
            		Assert.hasText(apiKey, "OpenAI API key must be set");
            		Assert.hasText(baseUrl, "OpenAI base URL must be set");
            		var openAiImageApi = new OpenAiImageApi(baseUrl, apiKey, restClientBuilder, responseErrorHandler);
            		return new OpenAiImageClient(openAiImageApi, imageProperties.getOptions(), retryTemplate);
            	}
            

            二、一個簡單的示例

            1、直接寫一個Controller層就可以

            Python
            package com.ysl.controller;
            import jakarta.annotation.Resource;
            import org.springframework.ai.chat.ChatResponse;
            import org.springframework.ai.chat.prompt.Prompt;
            import org.springframework.ai.openai.OpenAiChatClient;
            import org.springframework.ai.openai.OpenAiChatOptions;
            import org.springframework.web.bind.annotation.RequestMapping;
            import org.springframework.web.bind.annotation.RequestParam;
            import org.springframework.web.bind.annotation.RestController;
            import reactor.core.publisher.Flux;
            /**
            * @Author Ysl
            * @Date 2024/5/11
            * @name SpringAi
            **/
            @RestController
            public class ChatController {
                /**
                 * OpenAi自動裝配,可以直接注入使用
                 */
                @Resource
                private OpenAiChatClient openAiChatClient;
                /**
                 * 調用OpenAi的接口,call方法爲同步的api
                 * @param msg 你要問的問題
                 * @return
                 */
                @RequestMapping ("/ai/chat")
                public String chat(@RequestParam("msg") String msg) {
                    String call = openAiChatClient.call(msg);
                    return call;
                }
                /**
                 * 調用OpenAi的接口
                 * @param msg 你要問的問題
                 * @return  Object--json對象
                 */
                @RequestMapping ("/ai/chat1")
                public Object chat1(@RequestParam("msg") String msg) {
                    ChatResponse response = openAiChatClient.call(new Prompt(msg));
                    return response;
            //        return response.getResult().getOutput().getContent();//隻拿到内容
                }
                /**
                 * 調用OpenAi的接口
                 * @param msg 你要問的問題
                 * @return
                 */
                @RequestMapping ("/ai/chat3")
                public String chat3(@RequestParam("msg") String msg) {
                    //可選參數在yml配置,同時在代碼中也配置,那麽會以代碼爲準
                    ChatResponse response = openAiChatClient.call(new Prompt(msg, OpenAiChatOptions.builder()
            //                .withModel("gpt-4")//使用的模型
                            .withTemperature(0.3F)//溫度越高回答越慢,溫度越低回答越快
                            .build()));
                    return response.getResult().getOutput().getContent();
                }
                /**
                 * 調用OpenAi的接口 stream是流式的api
                 * @param msg 你要問的問題
                 * @return
                 */
                @RequestMapping ("/ai/chat4")
                public Object chat4(@RequestParam("msg") String msg) {
                    //可選參數在yml配置,同時在代碼中也配置,那麽會以代碼爲準
                    Flux flux = openAiChatClient.stream(new Prompt(msg, OpenAiChatOptions.builder()
            //                .withModel("gpt-3.5")//使用的模型
                            .withTemperature(0.3F)//溫度越高回答越慢,溫度越低回答越快
                            .build()));
                    flux.toStream().forEach(chatResponse ->{
                        System.out.println(chatResponse.getResult().getOutput().getContent());
                            });
                    return flux.collectList();//數據的序列
                }
            }
            

            2、直接在浏覽器訪問

            • http://localhost:8080/ai/chat?msg=24年經濟形勢

              在這裏插入圖片描述

            • http://localhost:8080/ai/chat1?msg=24年經濟形勢

            • http://localhost:8080/ai/chat3?msg=java怎麽學

              在這裏插入圖片描述

              OpenAi聊天客戶端就寫到這裏,接下來是圖片客戶端。

              三、Ai畫圖程序代碼

              首先需要确保你的key支持繪圖可以使用DALL·E 模型

              1、創建一個子項目(pom文件的依賴和第一個項目一樣即可)

              在這裏插入圖片描述

              2、編寫yml配置文件

              在這裏插入圖片描述

              3、編寫controller層

              Python
              import jakarta.annotation.Resource;
              import org.springframework.ai.image.ImagePrompt;
              import org.springframework.ai.image.ImageResponse;
              import org.springframework.ai.openai.OpenAiImageClient;
              import org.springframework.ai.openai.OpenAiImageOptions;
              import org.springframework.web.bind.annotation.RequestMapping;
              import org.springframework.web.bind.annotation.RequestParam;
              import org.springframework.web.bind.annotation.RestController;
              /**
               * @Author Ysl
               * @Date 2024/5/12
               * @name SpringAi
               **/
              @RestController
              public class ImageController {
                  @Resource
                  private OpenAiImageClient openAiImageClient;
                  @RequestMapping("/ai/image")
                  public Object image(@RequestParam("msg") String msg) {
                      ImageResponse imageResponse = openAiImageClient.call(new ImagePrompt(msg));
              //        對圖片進行業務處理(拿到圖片的鏈接)
                      String url = imageResponse.getResult().getOutput().getUrl();
                      return imageResponse.getResult().getOutput();
                  }
                  @RequestMapping("/ai/image2")
                  public Object image2(@RequestParam("msg") String msg) {
                      //第二個參數是傳遞圖片的參數,同樣可在yml裏配置
                      ImageResponse imageResponse = openAiImageClient.call(new ImagePrompt(msg, OpenAiImageOptions.builder()
                              .withQuality("hd")//高清
                              .withN(1)//生成1張,可填數字1-10
                              .withHeight(1024)//高度
                              .withWidth(1024)//寬度
                              .build()
                      ));
              //        對圖片進行業務處理(拿到圖片的鏈接)
                      String url = imageResponse.getResult().getOutput().getUrl();
                      return imageResponse.getResult().getOutput();
                  }
              }
              

              3、訪問鏈接

              • http://localhost:8080/ai/image?msg=畫一隻蝴蝶
              • http://localhost:8080/ai/image2?msg=畫一隻蝴蝶

                4、結果

                在這裏插入圖片描述

                打開鏈接

                在這裏插入圖片描述

                Ai畫圖就講到這裏,下面是音頻翻譯

                四、Ai音頻翻譯代碼

                首先确保你的key可以使用whisper 模型

                1、創建子項目編寫配置文件

                在這裏插入圖片描述

                2、用到的工具類:将bytes[ ]字節數組寫入新建的文件中

                Python
                import java.io.*;
                /**
                 * @Author Ysl
                 * @Date 2024/5/12
                 * @name SpringAi
                 **/
                public class save2File {
                    /**
                     * 方法功能:将字節數組寫入到新建文件中。
                     * @param  fname
                     * @param  msg
                     * @return boolean
                     * */
                    public static boolean save2File(String fname, byte[] msg){
                        OutputStream fos = null;
                        try{
                            File file = new File(fname);
                            File parent = file.getParentFile();
                            boolean bool;
                            if ((!parent.exists()) &&
                                    (!parent.mkdirs())) {
                                return false;
                            }
                            fos = new FileOutputStream(file);
                            fos.write(msg);
                            fos.flush();
                            return true;
                        } catch (FileNotFoundException e) {
                            return false;
                        }catch (IOException e){
                            File parent;
                            return false;
                        }
                        finally{
                            if (fos != null) {
                                try{
                                    fos.close();
                                }catch (IOException e) {}
                            }
                        }
                    }
                }
                

                2、編寫controller層

                Python
                import jakarta.annotation.Resource;
                import org.springframework.ai.openai.OpenAiAudioSpeechClient;
                import org.springframework.ai.openai.OpenAiAudioTranscriptionClient;
                import org.springframework.core.io.ClassPathResource;
                import org.springframework.web.bind.annotation.RequestMapping;
                import org.springframework.web.bind.annotation.RestController;
                import static com.ysl.utisl.save2File.save2File;
                /**
                 * @Author Ysl
                 * @Date 2024/5/12
                 * @name SpringAi
                 **/
                @RestController
                public class TranscriptionController {
                    //将音頻轉文字時使用
                    @Resource
                    private OpenAiAudioTranscriptionClient transcriptionClient;
                    //将文字轉語音時使用
                    @Resource
                    private OpenAiAudioSpeechClient speechClient;
                    /**
                     * 将音頻轉文字
                     * @return
                     */
                    @RequestMapping("/ai/transcription")
                    public Object transcription() {
                    //讀取的是磁盤的路徑
                    //FileSystemResource audioFile = new FileSystemResource("C:\\Users\\DELL\\Desktop\\luyin.m4a");
                        //讀取的是classpath靜态資源下的文件
                        ClassPathResource audioFile = new ClassPathResource("luyin.m4a");
                        String call = transcriptionClient.call(audioFile);
                        System.out.println(call);
                        return call;
                    }
                    /**
                     * 将文字轉音頻
                     * @return
                     */
                    @RequestMapping("/ai/tts")
                    public Object tts() {
                        String text = "Spring AI 是 AI 工程的應用框架。其目标是将 Spring 生态系統設計原則(如可移植性和模塊化設計)應用于 AI,并推廣使用 POJO 作爲 AI 領域應用程序的構建塊。 跨 AI 提供商的可移植 API 支持,适用于聊天、文本到圖像和嵌入模型。支持同步和流 API 選項。還支持下拉以訪問特定于模型的功能";
                        byte[] bytes = speechClient.call(text);
                        save2File("C:\\Users\\DELL\\Desktop\\test.mp3",bytes);
                        return "OK";
                    }
                }
                

                3、訪問鏈接

                • 1、 http://localhost:8080/ai/transcription
                • 将音頻中的話轉化爲文字顯示在頁面中

                  在這裏插入圖片描述

                • 2、 http://localhost:8080/ai/tts
                • 将text中的文字轉爲語音後儲存在路徑C:\Users\DELL\Desktop\test.mp3
                • 打開mp3文件即可聽到代碼中text文本中的内容

                  在這裏插入圖片描述

微信掃一掃加客服

微信掃一掃加客服

點擊啓動AI問答
Draggable Icon