搜尋
首頁Javajava教程輕鬆整合 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 應用程式:

  1. 產生文字:根據提示建立創意內容。
  2. 產生圖像:將文字描述轉換為視覺效果。
  3. 提供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
    }
}
</string></string>

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"));
                });
    }
}
</byte></string></byte>

範例提示及其結果: ?

1. 基於文字的端點:

Effortless AI Model Integration: Build and Evaluate AI Models (Spring Boot and Hugging Face)

2. 基於影像的端點:

Effortless AI Model Integration: Build and Evaluate AI Models (Spring Boot and Hugging Face)

?探索該項目

準備好潛水了嗎?查看 QuickAI GitHub 儲存庫以查看完整程式碼並繼續操作。如果您覺得有用,請給它⭐。

獎金 ?

想要進一步推進這個計畫嗎?

  • 我已經為 API 文件配置了 Swagger UI,這將幫助您建立前端應用程式。
  • 使用您最喜歡的前端框架(例如 React、Angular 或只是簡單的 HTML/CSS/Vanilla JS)建立一個簡單的前端應用程式。

?恭喜你已經走到這一步了。

現在你知道如何使用擁抱臉了嗎? :

  1. 在您的應用程式中快速使用 AI 模型。
  2. 產生文字:根據提示建立創意內容。
  3. 產生圖像:將文字描述轉化為視覺效果。

?讓我們聯絡吧!

想要合作或有任何建議可以在 LinkedIn 上找到我,Portfolio 也可以在 GitHub 上查看我的其他項目。

有問題或建議,請在下面發表評論,我很樂意解決。

快樂編碼! ?

以上是輕鬆整合 AI 模型:建立和評估 AI 模型(Spring Boot 和 Hugging Face)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JVM性能與其他語言JVM性能與其他語言May 14, 2025 am 12:16 AM

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生產性。 1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

Java平台獨立性:使用示例Java平台獨立性:使用示例May 14, 2025 am 12:14 AM

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允許CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

JVM架構:深入研究Java虛擬機JVM架構:深入研究Java虛擬機May 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM:JVM與操作系統有關嗎?JVM:JVM與操作系統有關嗎?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java:寫一次,在任何地方跑步(WORA) - 深入了解平台獨立性Java:寫一次,在任何地方跑步(WORA) - 深入了解平台獨立性May 14, 2025 am 12:05 AM

Java實現“一次編寫,到處運行”通過編譯成字節碼並在Java虛擬機(JVM)上運行。 1)編寫Java代碼並編譯成字節碼。 2)字節碼在任何安裝了JVM的平台上運行。 3)使用Java原生接口(JNI)處理平台特定功能。儘管存在挑戰,如JVM一致性和平台特定庫的使用,但WORA大大提高了開發效率和部署靈活性。

Java平台獨立性:與不同的操作系統的兼容性Java平台獨立性:與不同的操作系統的兼容性May 13, 2025 am 12:11 AM

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允許Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

什麼功能使Java仍然強大什麼功能使Java仍然強大May 13, 2025 am 12:05 AM

JavaispoperfulduetoitsplatFormitiondence,對象與偏見,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

頂級Java功能:開發人員的綜合指南頂級Java功能:開發人員的綜合指南May 13, 2025 am 12:04 AM

Java的頂級功能包括:1)面向對象編程,支持多態性,提升代碼的靈活性和可維護性;2)異常處理機制,通過try-catch-finally塊提高代碼的魯棒性;3)垃圾回收,簡化內存管理;4)泛型,增強類型安全性;5)ambda表達式和函數式編程,使代碼更簡潔和表達性強;6)豐富的標準庫,提供優化過的數據結構和算法。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

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

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器