輕鬆整合 AI 模型:建立和評估 AI 模型(Spring Boot 和 Hugging Face)
人工智慧革命已經到來,隨之而來的是不斷增長的強大模型列表,這些模型可以生成文字、創建視覺效果並解決複雜問題。但讓我們面對現實:有這麼多的選擇,找出最適合您的專案的模型可能會讓人不知所措。如果有一種方法可以快速測試這些模型,查看它們的實際結果,並決定將哪個模型整合到您的生產系統中,會怎麼樣?
進入Hugging Face 的推理 API-探索並利用最先進的人工智慧模式的捷徑。它透過提供即插即用的解決方案,消除了設定、託管或訓練模型的麻煩。無論您是在集思廣益新功能還是評估模型的功能,Hugging Face 都能讓 AI 整合變得比以往更簡單。
在本部落格中,我將引導您使用 Spring Boot 建立一個輕量級後端應用程序,讓您可以輕鬆測試和評估 AI 模型。以下是您可以期待的:
?你將學到什麼
- 存取 AI 模型:了解如何使用 Hugging Face 的推理 API 來探索和測試模型。
- 建立後端:建立一個 Spring Boot 應用程式來與這些模型互動。
- 測試模型:使用範例提示設定和測試文字和圖像產生的端點。
最後,您將擁有一個方便的工具來測試不同的人工智慧模型,並就它們是否適合您的專案需求做出明智的決定。如果您準備好彌合好奇心和實施之間的差距,那就開始吧!
?️ 為什麼要擁抱人臉推理 API?
這就是為什麼 Hugging Face 能夠改變 AI 整合的遊戲規則:
- 易於使用:無需訓練或部署模型 - 只需呼叫 API。
- 多樣性:存取超過 150,000 個模型來執行文字產生、圖像建立等任務。
- 可擴充性:非常適合原型設計和生產使用。
?你將建構什麼
我們將建立 QuickAI,一個 Spring Boot 應用程式:
- 產生文字:根據提示建立創意內容。
- 產生圖像:將文字描述轉換為視覺效果。
- 提供API文件:使用Swagger測試API並與API互動。
?入門
第 1 步:註冊擁抱臉
前往huggingface.co 並建立帳戶(如果您還沒有帳戶)。
步驟 2: 取得您的 API 金鑰
導覽至您的帳戶設定並產生 API 金鑰。此金鑰將允許您的 Spring Boot 應用程式與 Hugging Face 的 Inference API 進行互動。
第 3 步:探索模型
查看擁抱臉部模型中心,找到適合您需求的模型。在本教程中,我們將使用:
- 文字產生模型(例如 HuggingFaceH4/zephyr-7b-beta)。
- 影像產生模型(例如,stabilityai/stable-diffusion-xl-base-1.0)。
?️ 設定 Spring Boot 項目
步驟1:創建一個新的Spring Boot項目
使用 Spring Initializr 設定具有以下相依性的項目:
- Spring WebFlux:用於反應式、非阻塞 API 呼叫。
- Lombok:減少樣板程式碼。
- Swagger:API 文件。
步驟2:新增擁抱臉配置
將您的 Hugging Face API 金鑰和模型 URL 新增至 application.properties 檔案:
huggingface.text.api.url=https://api-inference.huggingface.co/models/your-text-model huggingface.api.key=your-api-key-here huggingface.image.api.url=https://api-inference.huggingface.co/models/your-image-model
?接下來是什麼?
讓我們深入研究程式碼並建立文字和圖像生成服務。請繼續關注!
1. 文字產生服務:
@Service public class LLMService { private final WebClient webClient; private static final Logger logger = LoggerFactory.getLogger(LLMService.class); // Constructor to initialize WebClient with Hugging Face API URL and API key public LLMService(@Value("${huggingface.text.api.url}") String apiUrl, @Value("${huggingface.api.key}") String apiKey) { this.webClient = WebClient.builder() .baseUrl(apiUrl) // Set the base URL for the API .defaultHeader("Authorization", "Bearer " + apiKey) // Add API key to the header .build(); } // Method to generate text using Hugging Face's Inference API public Mono<String> generateText(String prompt) { // Validate the input prompt if (prompt == null || prompt.trim().isEmpty()) { return Mono.error(new IllegalArgumentException("Prompt must not be null or empty")); } // Create the request body with the prompt Map<String, String> body = Collections.singletonMap("inputs", prompt); // Make a POST request to the Hugging Face API return webClient.post() .bodyValue(body) .retrieve() .bodyToMono(String.class) .doOnSuccess(response -> logger.info("Response received: {}", response)) // Log successful responses .doOnError(error -> logger.error("Error during API call", error)) // Log errors .retryWhen(Retry.backoff(3, Duration.ofMillis(500))) // Retry on failure with exponential backoff .timeout(Duration.ofSeconds(5)) // Set a timeout for the API call .onErrorResume(error -> Mono.just("Fallback response due to error: " + error.getMessage())); // Provide a fallback response on error } }
2.影像生成服務:
@Service public class ImageGenerationService { private static final Logger logger = LoggerFactory.getLogger(ImageGenerationService.class); private final WebClient webClient; public ImageGenerationService(@Value("${huggingface.image.api.url}") String apiUrl, @Value("${huggingface.api.key}") String apiKey) { this.webClient = WebClient.builder() .baseUrl(apiUrl) .defaultHeader("Authorization", "Bearer " + apiKey) .build(); } public Mono<byte[]> generateImage(String prompt) { if (prompt == null || prompt.trim().isEmpty()) { return Mono.error(new IllegalArgumentException("Prompt must not be null or empty")); } Map<String, String> body = Collections.singletonMap("inputs", prompt); return webClient.post() .bodyValue(body) .retrieve() .bodyToMono(byte[].class) / Convert the response to a Mono<byte[]> (image bytes) .timeout(Duration.ofSeconds(10)) // Timeout after 10 seconds .retryWhen(Retry.backoff(3, Duration.ofMillis(500))) // Retry logic .doOnSuccess(response -> logger.info("Image generated successfully for prompt: {}", prompt)) .doOnError(error -> logger.error("Error generating image for prompt: {}", prompt, error)) .onErrorResume(WebClientResponseException.class, ex -> { logger.error("HTTP error during image generation: {}", ex.getMessage(), ex); return Mono.error(new RuntimeException("Error generating image: " + ex.getMessage())); }) .onErrorResume(TimeoutException.class, ex -> { logger.error("Timeout while generating image for prompt: {}", prompt); return Mono.error(new RuntimeException("Request timed out")); }); } }
範例提示及其結果: ?
1. 基於文字的端點:
2. 基於影像的端點:
?探索該項目
準備好潛水了嗎?查看 QuickAI GitHub 儲存庫以查看完整程式碼並繼續操作。如果您覺得有用,請給它⭐。
獎金 ?
想要進一步推進這個計畫嗎?
- 我已經為 API 文件配置了 Swagger UI,這將幫助您建立前端應用程式。
- 使用您最喜歡的前端框架(例如 React、Angular 或只是簡單的 HTML/CSS/Vanilla JS)建立一個簡單的前端應用程式。
?恭喜你已經走到這一步了。
現在你知道如何使用擁抱臉了嗎? :
- 在您的應用程式中快速使用 AI 模型。
- 產生文字:根據提示建立創意內容。
- 產生圖像:將文字描述轉化為視覺效果。
?讓我們聯絡吧!
想要合作或有任何建議可以在 LinkedIn 上找到我,Portfolio 也可以在 GitHub 上查看我的其他項目。
有問題或建議,請在下面發表評論,我很樂意解決。
快樂編碼! ?
以上是輕鬆整合 AI 模型:建立和評估 AI 模型(Spring Boot 和 Hugging Face)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

公司安全軟件導致部分應用無法正常運行的排查與解決方法許多公司為了保障內部網絡安全,會部署安全軟件。 ...

將姓名轉換為數字以實現排序的解決方案在許多應用場景中,用戶可能需要在群組中進行排序,尤其是在一個用...

系統對接中的字段映射處理在進行系統對接時,常常會遇到一個棘手的問題:如何將A系統的接口字段有效地映�...

在使用IntelliJIDEAUltimate版本啟動Spring...

在使用MyBatis-Plus或其他ORM框架進行數據庫操作時,經常需要根據實體類的屬性名構造查詢條件。如果每次都手動...

Java對象與數組的轉換:深入探討強制類型轉換的風險與正確方法很多Java初學者會遇到將一個對象轉換成數組的�...

Redis緩存方案如何實現產品排行榜列表的需求?在開發過程中,我們常常需要處理排行榜的需求,例如展示一個�...

電商平台SKU和SPU表設計詳解本文將探討電商平台中SKU和SPU的數據庫設計問題,特別是如何處理用戶自定義銷售屬...
