人工智能革命已经到来,随之而来的是不断增长的强大模型列表,这些模型可以生成文本、创建视觉效果并解决复杂问题。但让我们面对现实吧:有如此多的选择,找出最适合您的项目的模型可能会让人不知所措。如果有一种方法可以快速测试这些模型,查看它们的实际结果,并决定将哪个模型集成到您的生产系统中,会怎么样?
进入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 } } </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. 基于文本的端点:
2. 基于图像的端点:
?探索该项目
准备好潜水了吗?查看 QuickAI GitHub 存储库以查看完整代码并继续操作。如果您觉得有用,请给它⭐。
奖金 ?
想要进一步推进这个项目吗?
- 我已经为 API 文档配置了 Swagger UI,这将帮助您构建前端应用程序。
- 使用您最喜欢的前端框架(例如 React、Angular 或只是简单的 HTML/CSS/Vanilla JS)构建一个简单的前端应用程序。
?恭喜你已经走到这一步了。
现在你知道如何使用拥抱脸了吗?:
- 在您的应用程序中快速使用 AI 模型。
- 生成文本:根据提示创建创意内容。
- 生成图像:将文本描述转化为视觉效果。
?让我们联系吧!
想要合作或有任何建议可以在 LinkedIn 上找到我,Portfolio 也可以在 GitHub 上查看我的其他项目。
有问题或建议,请在下面发表评论,我很乐意解决。
快乐编码! ?
以上是轻松集成 AI 模型:构建和评估 AI 模型(Spring Boot 和 Hugging Face)的详细内容。更多信息请关注PHP中文网其他相关文章!

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

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

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

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

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

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

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

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

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

Atom编辑器mac版下载
最流行的的开源编辑器