Spring AI 初學

来源:https://www.cnblogs.com/ytryhard/p/18216456
-Advertisement-
Play Games

Spring AI 初學 Spring AI 官方地址 ”spring 不生產 AI,只是 AI 工具的搬運工“ 項目可以查看gitee Open AI 前期準備 Open AI官方地址,需要使用魔法才能打開,同時購買很麻煩,建議淘寶進行購買,只需要購買 open ai 的 apikey 即可。 a ...


Spring AI 初學

Spring AI 官方地址

”spring 不生產 AI,只是 AI 工具的搬運工“

項目可以查看gitee

Open AI

前期準備

Open AI官方地址,需要使用魔法才能打開,同時購買很麻煩,建議淘寶進行購買,只需要購買 open ai 的 apikey 即可。

apikey 形如 sk-xxxxxxxxxxxxxxxxx

項目創建

Idea 創建 SpringBoot Maven 項目(基於1.0-SNAPSHOT版本,SpringBoot 3.2.6),依賴選擇Spring Web、 OpenAI。其他可以自行選擇

修改項目倉庫地址,中央倉庫暫時還沒 Spring AI 相關 jar 包。倉庫地址改成快照倉庫地址,官方說明

    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <releases>
            <enabled>false</enabled>
        </releases>
    </repository>

項目中找到 pom.xml 文件,將 <spring-ai.version>0.8.1</spring-ai.version> 改為 <spring-ai.version>1.0.0-SNAPSHOT</spring-ai.version>

yaml 配置文件中添加,openai 更多配置可以查看 org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration。

spring:
  ai:
    openai:
      # 購買的 api-key
      api-key: sk-xxxx
      # 如果是官方地址,則可以不填,預設為 https://api.openai.com
      base-url: 

聊天

基礎使用

主要類 org.springframework.ai.openai.OpenAiChatModel,快照版本不同,可能名字不一樣,可以查看 org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration 中的聊天類是哪個。

import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class ChatTest {

    @Resource
    private OpenAiChatModel chatModel;

    @Test
    public void chat1(){
        String msg = "你是誰?";
        //返回string數據
        String res = chatModel.call(msg);
        System.out.println(res);
    }
    
    @Test
    public void chat2(){
        String msg = "你是誰?";
        //返回對象
        ChatResponse res = chatModel.call(new Prompt(msg));
        System.out.println(res);
        //獲取對話返回結果
        System.out.println(res.getResult().getOutput().getContent());
    }

}

配置屬性

    @Test
    public void test3(){
        String msg = "你是誰";
        //採用 gpt-4-turbo 模型
        ChatResponse res = chatModel.call(new Prompt(msg, OpenAiChatOptions.builder()
                                                     .withModel("gpt-4-turbo")
                                                     .build()));
        System.out.println(res);
        //獲取對話返回結果
        System.out.println(res.getResult().getOutput().getContent());
    }

聊天模型配置屬性可以查看 org.springframework.ai.autoconfigure.openai.OpenAiChatProperties,也可以在官網查看更詳細的信息。配置屬性也可以放在 yml 配置文件中,如 OpenAiChatProperties 的註解,需要以 spring.ai.openai.chat 開頭,例如將 gpt-4-turbo 配置在配置文件中,就是 OpenAiChatProperties 中 options 中的屬性。

spring:
  ai:
    openai:
      chat:
        options:
          model: gpt-4-turbo

多模型

可以配合圖片等讓聊天模型進行回答。

    //給圖片來進行聊天
    @Test
    public void test4() {
        //獲取圖片資源
        ClassPathResource resource = new ClassPathResource("2024052701.png");
        UserMessage userMessage = new UserMessage("說說你看到了什麼", 
                List.of(new Media(MimeTypeUtils.IMAGE_PNG, resource)));
        ChatResponse res = chatModel.call(new Prompt(userMessage, OpenAiChatOptions.builder()
                .withModel("gpt-4-turbo")
                .build()));
        System.out.println(res);
        //獲取回答
        System.out.println(res.getResult().getOutput().getContent());
    }

圖像

基礎使用

主要類 org.springframework.ai.openai.OpenAiImageModel,快照版本不同,可能類不一樣。可以查看 org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration 中具體的圖像類是哪個。

import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.ai.openai.OpenAiImageModel;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class ImageTest {

    @Resource
    private OpenAiImageModel imageModel;

    @Test
    public void test(){
        //調用 image 模型的 call 方法獲取圖片
        ImageResponse res = imageModel.call(new ImagePrompt("山水畫"));
        //AI 繪製的圖片路徑
        String url = res.getResult().getOutput().getUrl();
        System.out.println(url);
    }

}

配置屬性

    @Test
    public void test2(){
        //使用 dall-e-2 繪畫
        OpenAiImageOptions options = OpenAiImageOptions.builder()
            .withModel(OpenAiImageApi.ImageModel.DALL_E_2.getValue())
            .build();
        ImageResponse res = imageModel.call(new ImagePrompt("山水畫", options));
        //獲取 AI 繪畫路徑
        String url = res.getResult().getOutput().getUrl();
        System.out.println(url);
    }

圖像模型屬性配置可以查看 org.springframework.ai.autoconfigure.openai.OpenAiImageProperties,也可以查看官網獲取更詳細的信息。當然配置屬性也可以在 yml 中定義,如 OpenAiImageProperties 上的註解,需要以 spring.ai.openai.image 開頭,例如使用 dall-e-2 模型進行繪畫

 spring:
  ai:
    openai:
      image:
        options:
          model: dall-e-2

語音

語音轉文字

基礎使用

主要類 org.springframework.ai.openai.OpenAiAudioTranscriptionModel,快照版本不同,可能名字不一樣,可以查看 org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration 中的語音轉文字翻譯類是哪個。

import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.ai.openai.OpenAiAudioTranscriptionModel;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;

@SpringBootTest
public class AudioTest {

    //語音轉文字
    @Resource
    private OpenAiAudioTranscriptionModel transcriptionModel;

    @Test
    public void testTranscription1(){
        String res = transcriptionModel.call(new ClassPathResource("2024052702.mp3"));
        System.out.println(res);
    }

}
配置屬性
    @Test
    public void testTranscription2(){
        //創建模型屬性,採用 whisper-1 語音模型
        OpenAiAudioTranscriptionOptions options = new OpenAiAudioTranscriptionOptions().builder()
                .withModel(OpenAiAudioApi.WhisperModel.WHISPER_1.getValue())
                .build();
        AudioTranscriptionResponse res = transcriptionModel.call(
            new AudioTranscriptionPrompt(new ClassPathResource("2024052702.mp3"), options));
        //獲取翻譯內容
        String output = res.getResult().getOutput();
        System.out.println(output);
    }

語音轉文字模型屬性可以查看 org.springframework.ai.autoconfigure.openai.OpenAiAudioTranscriptionProperties,也可以在官網查看更詳細信息。當然可以在 yml 配置中配置屬性,如 OpenAiAudioTranscriptionProperties 上的註解,以 spring.ai.openai.audio.transcription 開頭,例如採用 whisper-1 模型

spring:
  ai:
    openai:
      audio:
        transcription:
          options:
            model: whisper-1

文字轉語音

基礎使用

主要類 org.springframework.ai.openai.OpenAiAudioSpeechModel,快照版本不同,可能名字不一樣,可以查看 org.springframework.ai.autoconfigure.openai.OpenAiAutoConfiguration 中的文字轉語音類是哪個。

import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.ai.openai.OpenAiAudioSpeechModel;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.FileOutputStream;
import java.io.IOException;

@SpringBootTest
public class AudioTest2 {

    @Resource
    private OpenAiAudioSpeechModel speechModel;

    //byte數組轉文件
    private void byteArrayToFile(byte[] byteArray, String filePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(filePath);
        fos.write(byteArray);
        fos.close();
    }

    @Test
    public void testSpeech() throws IOException {
        byte[] res = speechModel.call("我愛北京");
        byteArrayToFile(res,"D:\\project\\AI\\openai\\speech\\1.mp3");
    }

}

屬性配置
    @Test
    public void testSpeech2() throws IOException {
        //採用 tts-1-hd 模型
        OpenAiAudioSpeechOptions options = new OpenAiAudioSpeechOptions().builder()
                .withModel(OpenAiAudioApi.TtsModel.TTS_1_HD.getValue())
                .build();
        SpeechPrompt prompt = new SpeechPrompt("我愛北京", options);
        SpeechResponse res = speechModel.call(prompt);
        byte[] bytes = res.getResult().getOutput();
        byteArrayToFile(bytes,"D:\\project\\AI\\openai\\speech\\1-hd.mp3");
    }

文字轉語音模型屬性可以查看 org.springframework.ai.autoconfigure.openai.OpenAiAudioSpeechProperties,也可以在官網查看更詳細信息。當然可以在 yml 配置中配置屬性,如 OpenAiAudioSpeechProperties 上的註解,以 spring.ai.openai.audio.speech 開頭,例如採用 tts-1-hd 模型

spring:
  ai:
    openai:
      audio:
        speech:
          options:
            model: tts-1-hd

Ollama


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • title: Vue.js條件渲染與列表渲染指南 date: 2024/5/26 20:11:49 updated: 2024/5/26 20:11:49 categories: 前端開發 tags: VueJS 前端開發 數據綁定 列表渲染 狀態管理 路由配置 性能優化 第1章:Vue.js基礎與 ...
  • 從Vue開始較大範圍在前端應用開始,關於Vue一些基礎知識的討論和麵試問題就在開發圈子裡基本上就跟前幾年的股票和基金一樣,樓下擺攤賣醬香餅的阿姨都能說上幾句那種。找過前端開發工作或者正在找開發工作的前端都知道,面試官基本上都有那麼幾個常問的問題,而網上呢也有那麼一套可以用來背誦的“八股文”,自己懂多 ...
  • title: Vue 3指令與事件處理 date: 2024/5/25 18:53:37 updated: 2024/5/25 18:53:37 categories: 前端開發 tags: Vue3基礎 指令詳解 事件處理 高級事件 實戰案例 最佳實踐 性能優化 第1章 Vue 3基礎 1.1 V ...
  • Symbol 引用 iconfont icon圖標庫 Symbol 引用 這是一種全新的使用方式,應該說這才是未來的主流,也是平臺目前推薦的用法。相關介紹可以參考這篇文章 這種用法其實是做了一個 SVG 的集合,與另外兩種相比具有如下特點: 支持多色圖標了,不再受單色限制。 通過一些技巧,支持像字體 ...
  • 設計原則名稱 定義 使用頻率 單一職責原則 一個類只負責一個功能領域中的相應職責 四顆星 開閉原則 軟體實體應對擴展開發,而對修改關閉 五顆星 里氏代換原則 所有引用基類對象的地方能夠透明地使用其子類的對象 五顆星 依賴倒轉原則 抽象不應該依賴於細節,細節應該依賴於抽象 五顆星 介面隔離原則 使用多 ...
  • 中國程式員的特點 中國程式員的最大優點是非常勤奮。中國互聯網行業有句話叫:“they earn a lot of money but die early”(賺得多死得早)。由於工作強度大,經常有程式員突然去世的新聞報道。 996 工作制度:中國程式員通常實行“996”工作制度(即每天工作從早9點到晚 ...
  • 前言 大家好,我是老馬。很高興遇到你。 我們為 java 開發者實現了 java 版本的 nginx https://github.com/houbb/nginx4j 如果你想知道 servlet 如何處理的,可以參考我的另一個項目: 手寫從零實現簡易版 tomcat minicat 手寫 ngin ...
  • 二項分佈是描述固定次數獨立試驗中成功次數的概率分佈,常用於分析二元結果的事件,如拋硬幣。分佈由參數 n(試驗次數)、p(單次成功概率)和 k(成功次數)定義。概率質量函數 P(k) = C(n, k) * p^k * (1 - p)^(n - k)。NumPy 的 `random.binomial(... ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...