題目: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聊天客戶端就寫到這里,接下來是圖片客戶端。