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

題目:SpringBoot + OpenAi

在這里獲取key和url:獲取免費key
在這里插入圖片描述
base-url為這兩個:
在這里插入圖片描述

在這里插入圖片描述
話不多說直接來!

一、簡介

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

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

二、Ai聊天程序代碼

1、 創建項目工程

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

在這里插入圖片描述

  • 勾選上依賴然后創建

在這里插入圖片描述

  • 具體的依賴如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.2.4</version><relativePath/> <!-- lookup parent from repository --></parent><!-- Generated by https://start.springboot.io --><!-- 優質的 spring/boot/data/security/cloud 框架中文文檔盡在 => https://springdoc.cn --><groupId>com.ysl</groupId><artifactId>SpringAi</artifactId><version>0.0.1-SNAPSHOT</version><packaging>pom</packaging><name>SpringAi</name><description>SpringAi</description><modules><module>spring-ai-01-chat</module></modules><properties><java.version>17</java.version>
<!--        快照版本--><spring-ai.version>1.0.0-SNAPSHOT</spring-ai.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai-spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
<!--    相當于繼承一個父項目:spring-ai-bom--><dependencyManagement><dependencies><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-bom</artifactId><version>${spring-ai.version}</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><image><builder>paketobuildpacks/builder-jammy-base:latest</builder></image><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build><!--~配置本項目的倉庫:因maven中心倉庫還設有更新spring ai的jar包--><repositories><repository>
<!--            里程碑版本releases的倉庫,改成快照版本的snapshot--><id>spring-snapshot</id><name>Spring Snapshots</name><url>https://repo.spring.io/snapshot</url><releases><enabled>false</enabled></releases></repository></repositories></project>
  • 編寫yml配置

在這里插入圖片描述

  • openai有自動配置類OpenAiAutoConfiguration
    在這里插入圖片描述
    其中有聊天客戶端,圖片客戶端…等(看下面源碼)
//聊天客戶端
@Bean@ConditionalOnMissingBean@ConditionalOnProperty(prefix = OpenAiChatProperties.CONFIG_PREFIX, name = "enabled", havingValue = "true",matchIfMissing = true)public OpenAiChatClient openAiChatClient(OpenAiConnectionProperties commonProperties,OpenAiChatProperties chatProperties, RestClient.Builder restClientBuilder,List<FunctionCallback> 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);}
//圖片客戶端
@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層就可以

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自動裝配,可以直接注入使用*/@Resourceprivate 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<ChatResponse> 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聊天客戶端就寫到這里,接下來是圖片客戶端。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/10419.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/10419.shtml
英文地址,請注明出處:http://en.pswp.cn/web/10419.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

暗區突圍pc資格 暗區突圍pc端測試資格獲取

《暗區突圍》的誕生&#xff0c;仿佛在游戲界投下了一枚深水炸彈&#xff0c;它不僅僅是射擊游戲的新標桿&#xff0c;更是對玩家策略思維、生存直覺與團隊協作能力的一次全面考驗。在這個精心構建的虛擬戰場中&#xff0c;每一次踏入暗區&#xff0c;都是對未知的探索&#xf…

【練習4】

1.兩數之和 暴力&#xff1a; class Solution { public:vector<int> twoSum(vector<int>& nums, int target) {int n nums.size();vector<int> res(2, -1); // 初始化結果為-1for (int i 0; i < n; i) {int temp nums[i];for (int j i 1; j <…

Python 技巧:滿意的逗號放置

當你在 Python 中添加或刪除列表、字典或集合中的項目時&#xff0c;記住總是將所有行結尾加一個逗號。這是一個非常有用的技巧&#xff0c;可以幫助你避免一些常見的問題。 不確定我所說的什么&#xff1f;讓我給你一個快速示例。假設你在代碼中有一個名單列表&#xff1a; …

銀行家算法簡易實現

這里寫目錄標題 實驗要求內容代碼main.cppmyfunc.hmyfunc.cpp 運行結果與分析 實驗要求 程序可以針對不同進程的請求進行判斷&#xff0c;并決定是否滿足其需求。算法程序需要設計合理的數據結構&#xff0c;對資源情況、進程相關數據進行存儲。 內容 隨機生成數據, 并校驗數據…

做視頻號小店,怎么找達人合作?這里有詳細講解

大家好&#xff0c;我是電商笨笨熊 做視頻號小店是沒有自然流量的&#xff0c;這點剛入駐的新玩家還不清楚&#xff1b; 因此很多老電商玩家們還想著繼續拿其他平臺動銷自然流的玩法去做視頻號&#xff1b; 只能說這種方式在視頻號是完全行不通的&#xff0c;當下想要推廣售…

設計模式2——原則篇:依賴倒轉原則、單一職責原則、合成|聚合復用原則、開放-封閉原則、迪米特法則、里氏代換原則

設計模式2——設計原則篇 目錄 一、依賴倒轉原則 二、單一職責原則&#xff08;SRP&#xff09; 三、合成|聚合復用原則&#xff08;CARP&#xff09; 四、開放-封閉原則 五、迪米特法則&#xff08;LoD&#xff09; 六、里氏代換原則 七、接口隔離原則 八、總結 一、依賴…

Python-VBA函數之旅-setattr函數

目錄 一、setattr函數的常見應用場景 二、setattr函數使用注意事項 三、如何用好setattr函數&#xff1f; 1、setattr函數&#xff1a; 1-1、Python&#xff1a; 1-2、VBA&#xff1a; 2、推薦閱讀&#xff1a; 個人主頁&#xff1a; https://blog.csdn.net/ygb_1024?…

宏集Panorama SCADA軟件獲BACnet BTL認證

Panorama 獲得BACnet BTL認證 建筑物的組件&#xff08;空調系統、照明傳感器等&#xff09;能否使用共同通訊協議&#xff1f;這正是標準化 BACnet協議&#xff08;Building Automation and Control Networks&#xff09;所提供的功能。該協議旨在實現建筑物中各種設備和系統…

【TS】入門

創建項目 vscode自動編譯ts 生成配置文件 tsc --init 然后發現終端也改變了&#xff1a;

SOCKET編程(3):相關結構體與函數

相關結構體與函數 sockaddr、sockaddr_in結構體 sockaddr和sockaddr_in詳解 struct sockaddr共16字節&#xff0c;協議族(family)占2字節&#xff0c;IP地址和端口號在sa_data字符數組中 /* Structure describing a generic socket address. */ struct sockaddr {__SOCKADDR…

抓大鵝教程電腦端秒通關……

大家好&#xff0c;我是小黃。 最近抓大鵝小程序游戲很火&#xff0c;抓大鵝小游戲是由青島藍飛互娛科技股份有限公司開發并推出的一款休閑益智類三消游戲。在游戲中&#xff0c;玩家需要在特定的“購物籃子”背景下&#xff0c;找到三個相同的物品并將其消除。游戲的玩法簡單…

社工庫信息查詢

此網站需要注冊賬號&#xff0c;新用戶注冊送3點券&#xff0c;每日簽到可獲得1.5點券。也可通過充值來查 我這里有方法可以利用缺陷來無限獲取點券查人

Python 實戰之量化交易

1. Python 實戰之量化交易 2..Python量化交易實戰-04.量化交易系統架構的設計 Python量化交易實戰-04.量化交易系統架構的設計 - 知乎 3.Python量化交易實戰-06.通過PythonAPI獲取股票數據 Python量化交易實戰-06.通過PythonAPI獲取股票數據 - 知乎 3.Python量化交易實戰…

程序員的歸宿。。

大家好&#xff0c;我是瑤琴呀。 相信每個進入職場的人都考慮過自己的職業生涯規劃&#xff0c;在不同的年齡段可能面臨不同挑戰&#xff0c;這點對于 35 的人應該更為感同身受。 對于程序員來說&#xff0c;大部分人的職業道路主要是下面三種&#xff1a;第一條&#xff0c;…

【Delphi 爬蟲庫 6】使用正則表達式提取貓眼電影排行榜top100

正則表達式庫的簡單介紹 正則表達式易于使用&#xff0c;功能強大&#xff0c;可用于復雜的搜索和替換以及基于模板的文本檢查。這對于輸入形式的用戶輸入驗證特別有用-驗證電子郵件地址等。您還可以從網頁或文檔中提取電話號碼&#xff0c;郵政編碼等&#xff0c;在日志文件中…

人生是曠野,不是軌道

最近看到一句話&#xff0c;很喜歡&#xff0c;分享一下。"人生是曠野&#xff0c;不是軌道"。人生不是固定的方程式&#xff0c;也沒有唯一答案&#xff0c;沒有誰生來就應該是什么樣。別太被太多世俗觀念束縛住手腳&#xff0c;每個人都有權利自由生長&#xff0c;…

用友暢捷通T+ keyEdit sql注入漏洞

產品介紹 暢捷通 T 是一款靈動&#xff0c;智慧&#xff0c;時尚的基于互聯網時代開發的管理軟件&#xff0c;主要針對中小型工貿與商貿企業&#xff0c;尤其適合有異地多組織機構&#xff08;多工廠&#xff0c;多倉庫&#xff0c;多辦事處&#xff0c;多經銷商&#xff09;的…

朋友圈刷屏的粘土風格照片,你體驗過了嗎?

Remini 的粘土風格真的丑萌丑萌的&#xff01; 從去年“妙鴨相機”的走紅&#xff0c;到今年Remini的刷屏&#xff0c;其實可以看出大眾對于圖片趣玩的興趣非常大&#xff01; 一張普通的照片經過工具的處理&#xff0c;一下子變成新風格&#xff0c;讓人眼前一亮。如果你也對…

GPT-SoVits:語音克隆,語音融合

首發網站 https://tianfeng.space 前言 零樣本文本到語音&#xff08;TTS&#xff09;&#xff1a; 輸入 5 秒的聲音樣本&#xff0c;即刻體驗文本到語音轉換。少樣本 TTS&#xff1a; 僅需 1 分鐘的訓練數據即可微調模型&#xff0c;提升聲音相似度和真實感。跨語言支持&…

信息收集方法合集 第1期

前言 在工作中&#xff0c;經常被問到某個文件怎么下載&#xff0c;原文來自哪里。索性把我知道的所有信息收集方法全部整理一遍&#xff0c;希望對大家有用&#xff0c;如果有幫助到你&#xff0c;非常榮幸&#xff0c;我會堅持分享我的學習、工作經驗。 信息種類&#xff1…