目錄
1. 配置
2 .搭建項目
3.?查看對應依賴
?3.1 OpenAI 依賴
3.2 配置 OpenAI API 密鑰
application.properties
application.yml
4. openai實戰
5. 運行和測試
6. 高級配置?
示例:配置模型和參數
解釋:
7. 處理異常和錯誤
示例:全局異常處理
8.監控和日志
示例:添加日志
9.性能優化
示例:異步調用
總結
1. 配置
- Project:Maven
- Language:Java
- SpringBoot:3.4.3
-
Dependencies:
-
Spring Web
-
Spring Boot DevTools(可選,用于開發熱部署)
-
2 .搭建項目
idea里面選擇File->New-Project
選擇SpringBoot 項目,Language選擇java,type選擇Maven
Jdk選擇對應的版本最低使用17,packaging類型根據自身部署習慣選擇jar或者war都可以
選擇完成后會跳轉如下界面,選擇AI,OpenAI勾選即可。
至此項目搭建完成
3.?查看對應依賴
?3.1 OpenAI 依賴
<dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-openai-spring-boot-starter</artifactId><version>1.0.0-M6</version>
</dependency>
3.2 配置 OpenAI API 密鑰
在?application.properties
?或?application.yml
?中配置 OpenAI 的 API 密鑰。
application.properties
spring.ai.openai.api-key=your-openai-api-key
application.yml
spring:
? ai:
? ? openai:
? ? ? api-key: your-openai-api-key
4. openai實戰
創建一個服務類來封裝與 OpenAI 的交互邏輯
public class ChatAiController {private static final Logger log = LogManager.getLogger(ChatAiController.class);private final ChatClient chatClient;public ChatAiController(ChatClient.Builder build) {this.chatClient = build.defaultSystem("測試").build();}@GetMapping("/chat")public String chatAI(@RequestParam(value = "message") String message){System.out.println(this.chatClient.prompt().user(message).call().content());return this.chatClient.prompt().user(message).call().content();}
}
5. 運行和測試
啟動 Spring Boot 應用程序,并通過 API 端點測試 OpenAI 功能
請求示例:
GET /chat?message=Hello, how are you?
響應示例:
?"I'm just a computer program, so I don't have feelings, but thanks for asking! How can I assist you today?"
6. 高級配置?
Spring AI 提供了多種配置選項,可以根據需求調整 OpenAI 的行為。
示例:配置模型和參數
解釋:
-
model
:指定使用的模型,如?gpt-3.5-turbo
?或?gpt-4
。 -
temperature
:控制生成文本的隨機性(0 到 1 之間,值越高越隨機)。 -
max-tokens
:限制生成文本的最大長度。
7. 處理異常和錯誤
在實際應用中,處理 API 調用中的異常和錯誤是非常重要的。你可以使用 Spring 的異常處理機制來捕獲和處理這些異常
示例:全局異常處理
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception ex) {return new ResponseEntity<>("An error occurred: " + ex.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);}
}
8.監控和日志
為了確保 API 調用的穩定性和可維護性,建議添加監控和日志記錄。
示例:添加日志
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;@Service
public class OpenAiService {private static final Logger logger = LoggerFactory.getLogger(OpenAiService.class);private final ChatClient chatClient;@Autowiredpublic OpenAiService(ChatClient chatClient) {this.chatClient = chatClient;}public String generateChatResponse(String message) {logger.info("Generating chat response for message: {}", message);return chatClient.call(message);}
}
9.性能優化
對于高并發的場景,可能需要考慮性能優化,如緩存、異步調用等。
示例:異步調用
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;@Service
public class OpenAiService {private final ChatClient chatClient;@Autowiredpublic OpenAiService(ChatClient chatClient) {this.chatClient = chatClient;}@Asyncpublic CompletableFuture<String> generateChatResponseAsync(String message) {return CompletableFuture.completedFuture(chatClient.call(message));}
}
總結
通過以上步驟,你可以快速創建一個 Spring Boot 項目并集成 OpenAI 的功能。根據實際需求,你可以進一步擴展和優化這些功能,例如添加日志、異常處理、性能優化等